src/Tools/Code/code_haskell.ML
author haftmann
Sat Jan 25 23:50:49 2014 +0100 (2014-01-25)
changeset 55147 bce3dbc11f95
parent 55145 2bb3cd36bcf7
child 55148 7e1b7cb54114
permissions -rw-r--r--
prefer explicit code symbol type over ad-hoc name mangling
haftmann@37745
     1
(*  Title:      Tools/Code/code_haskell.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@28054
     4
Serializer for Haskell.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@28054
     7
signature CODE_HASKELL =
haftmann@28054
     8
sig
noschinl@44926
     9
  val language_params: string
haftmann@37745
    10
  val target: string
haftmann@28054
    11
  val setup: theory -> theory
haftmann@28054
    12
end;
haftmann@28054
    13
haftmann@28054
    14
structure Code_Haskell : CODE_HASKELL =
haftmann@28054
    15
struct
haftmann@28054
    16
haftmann@28054
    17
val target = "Haskell";
haftmann@28054
    18
noschinl@44926
    19
val language_extensions =
noschinl@44940
    20
  ["EmptyDataDecls", "RankNTypes", "ScopedTypeVariables"];
noschinl@44926
    21
noschinl@44926
    22
val language_pragma =
noschinl@44940
    23
  "{-# LANGUAGE " ^ commas language_extensions ^ " #-}";
noschinl@44926
    24
noschinl@44926
    25
val language_params =
noschinl@44940
    26
  space_implode " " (map (prefix "-X") language_extensions);
noschinl@44926
    27
haftmann@28054
    28
open Basic_Code_Thingol;
haftmann@28054
    29
open Code_Printer;
haftmann@28054
    30
haftmann@28054
    31
infixr 5 @@;
haftmann@28054
    32
infixr 5 @|;
haftmann@28054
    33
haftmann@28054
    34
haftmann@28054
    35
(** Haskell serializer **)
haftmann@28054
    36
haftmann@47609
    37
fun print_haskell_stmt class_syntax tyco_syntax const_syntax
bulwahn@44793
    38
    reserved deresolve deriving_show =
haftmann@28054
    39
  let
haftmann@55147
    40
    val deresolve_const = deresolve o Code_Symbol.Constant;
haftmann@55147
    41
    val deresolve_tyco = deresolve o Code_Symbol.Type_Constructor;
haftmann@55147
    42
    val deresolve_class = deresolve o Code_Symbol.Type_Class;
haftmann@38923
    43
    fun class_name class = case class_syntax class
haftmann@55147
    44
     of NONE => deresolve_class class
haftmann@28687
    45
      | SOME class => class;
haftmann@33991
    46
    fun print_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@28054
    47
     of [] => []
haftmann@37384
    48
      | constraints => enum "," "(" ")" (
haftmann@28054
    49
          map (fn (v, class) =>
haftmann@37384
    50
            str (class_name class ^ " " ^ lookup_var tyvars v)) constraints)
haftmann@28054
    51
          @@ str " => ";
haftmann@33991
    52
    fun print_typforall tyvars vs = case map fst vs
haftmann@28054
    53
     of [] => []
haftmann@28054
    54
      | vnames => str "forall " :: Pretty.breaks
haftmann@32924
    55
          (map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
haftmann@33991
    56
    fun print_tyco_expr tyvars fxy (tyco, tys) =
haftmann@33991
    57
      brackify fxy (str tyco :: map (print_typ tyvars BR) tys)
haftmann@47609
    58
    and print_typ tyvars fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55147
    59
         of NONE => print_tyco_expr tyvars fxy (deresolve_tyco tyco, tys)
haftmann@47609
    60
          | SOME (_, print) => print (print_typ tyvars) fxy tys)
haftmann@33991
    61
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@48003
    62
    fun print_typdecl tyvars (tyco, vs) =
haftmann@48003
    63
      print_tyco_expr tyvars NOBR (tyco, map ITyVar vs);
haftmann@33991
    64
    fun print_typscheme tyvars (vs, ty) =
haftmann@33991
    65
      Pretty.block (print_typforall tyvars vs @ print_typcontext tyvars vs @| print_typ tyvars NOBR ty);
haftmann@48072
    66
    fun print_term tyvars some_thm vars fxy (IConst const) =
haftmann@48072
    67
          print_app tyvars some_thm vars fxy (const, [])
haftmann@35228
    68
      | print_term tyvars some_thm vars fxy (t as (t1 `$ t2)) =
haftmann@28054
    69
          (case Code_Thingol.unfold_const_app t
haftmann@35228
    70
           of SOME app => print_app tyvars some_thm vars fxy app
haftmann@28054
    71
            | _ =>
haftmann@28054
    72
                brackify fxy [
haftmann@35228
    73
                  print_term tyvars some_thm vars NOBR t1,
haftmann@35228
    74
                  print_term tyvars some_thm vars BR t2
haftmann@28054
    75
                ])
haftmann@35228
    76
      | print_term tyvars some_thm vars fxy (IVar NONE) =
haftmann@31889
    77
          str "_"
haftmann@35228
    78
      | print_term tyvars some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
    79
          (str o lookup_var vars) v
haftmann@35228
    80
      | print_term tyvars some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
    81
          let
haftmann@31874
    82
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
    83
            val (ps, vars') = fold_map (print_bind tyvars some_thm BR o fst) binds vars;
haftmann@35228
    84
          in brackets (str "\\" :: ps @ str "->" @@ print_term tyvars some_thm vars' NOBR t') end
haftmann@48072
    85
      | print_term tyvars some_thm vars fxy (ICase case_expr) =
haftmann@48072
    86
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55147
    87
           of SOME (app as ({ sym = Code_Symbol.Constant const, ... }, _)) =>
haftmann@55147
    88
                if is_none (const_syntax const)
haftmann@48072
    89
                then print_case tyvars some_thm vars fxy case_expr
haftmann@48072
    90
                else print_app tyvars some_thm vars fxy app
haftmann@48072
    91
            | NONE => print_case tyvars some_thm vars fxy case_expr)
haftmann@55147
    92
    and print_app_expr tyvars some_thm vars ({ sym, dom, range, annotate, ... }, ts) =
bulwahn@44792
    93
      let
haftmann@55147
    94
        val ty = Library.foldr (op `->) (dom, range)
bulwahn@45009
    95
        val printed_const =
bulwahn@45009
    96
          if annotate then
haftmann@55147
    97
            brackets [(str o deresolve) sym, str "::", print_typ tyvars NOBR ty]
bulwahn@45009
    98
          else
haftmann@55147
    99
            (str o deresolve) sym
bulwahn@44792
   100
      in 
bulwahn@45009
   101
        printed_const :: map (print_term tyvars some_thm vars BR) ts
bulwahn@44792
   102
      end
haftmann@38923
   103
    and print_app tyvars = gen_print_app (print_app_expr tyvars) (print_term tyvars) const_syntax
haftmann@35228
   104
    and print_bind tyvars some_thm fxy p = gen_print_bind (print_term tyvars) some_thm fxy p
haftmann@48072
   105
    and print_case tyvars some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   106
          (brackify fxy o Pretty.breaks o map str) ["error", "\"empty case\""]
haftmann@48072
   107
      | print_case tyvars some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   108
          let
haftmann@48072
   109
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47609
   110
            fun print_match ((pat, _), t) vars =
haftmann@28054
   111
              vars
haftmann@35228
   112
              |> print_bind tyvars some_thm BR pat
haftmann@35228
   113
              |>> (fn p => semicolon [p, str "=", print_term tyvars some_thm vars NOBR t])
haftmann@33991
   114
            val (ps, vars') = fold_map print_match binds vars;
haftmann@31665
   115
          in brackify_block fxy (str "let {")
haftmann@31665
   116
            ps
haftmann@35228
   117
            (concat [str "}", str "in", print_term tyvars some_thm vars' NOBR body])
haftmann@28054
   118
          end
haftmann@48072
   119
      | print_case tyvars some_thm vars fxy { term = t, typ = ty, clauses = clauses as _ :: _, ... } =
haftmann@28054
   120
          let
haftmann@33991
   121
            fun print_select (pat, body) =
haftmann@28054
   122
              let
haftmann@35228
   123
                val (p, vars') = print_bind tyvars some_thm NOBR pat vars;
haftmann@35228
   124
              in semicolon [p, str "->", print_term tyvars some_thm vars' NOBR body] end;
haftmann@36576
   125
          in Pretty.block_enclose
haftmann@36576
   126
            (concat [str "(case", print_term tyvars some_thm vars NOBR t, str "of", str "{"], str "})")
haftmann@33991
   127
            (map print_select clauses)
haftmann@48072
   128
          end;
haftmann@55147
   129
    fun print_stmt (Code_Symbol.Constant const, Code_Thingol.Fun (((vs, ty), raw_eqs), _)) =
haftmann@28054
   130
          let
haftmann@32924
   131
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@34269
   132
            fun print_err n =
haftmann@55147
   133
              (semicolon o map str) (
haftmann@55147
   134
                deresolve_const const
haftmann@55147
   135
                :: replicate n "_"
haftmann@55147
   136
                @ "="
haftmann@55147
   137
                :: "error"
haftmann@55147
   138
                @@ ML_Syntax.print_string const
haftmann@34269
   139
              );
haftmann@35228
   140
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   141
              let
haftmann@32924
   142
                val vars = reserved
haftmann@55145
   143
                  |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   144
                      deresolve (t :: ts)
haftmann@32924
   145
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@32925
   146
                      (insert (op =)) ts []);
haftmann@28054
   147
              in
haftmann@28054
   148
                semicolon (
haftmann@55147
   149
                  (str o deresolve_const) const
haftmann@35228
   150
                  :: map (print_term tyvars some_thm vars BR) ts
haftmann@28054
   151
                  @ str "="
haftmann@35228
   152
                  @@ print_term tyvars some_thm vars NOBR t
haftmann@28054
   153
                )
haftmann@28054
   154
              end;
haftmann@28054
   155
          in
haftmann@28054
   156
            Pretty.chunks (
haftmann@33991
   157
              semicolon [
haftmann@55147
   158
                (str o suffix " ::" o deresolve_const) const,
haftmann@33991
   159
                print_typscheme tyvars (vs, ty)
haftmann@28054
   160
              ]
haftmann@34269
   161
              :: (case filter (snd o snd) raw_eqs
haftmann@34269
   162
               of [] => [print_err ((length o fst o Code_Thingol.unfold_fun) ty)]
haftmann@34269
   163
                | eqs => map print_eqn eqs)
haftmann@28054
   164
            )
haftmann@28054
   165
          end
haftmann@55147
   166
      | print_stmt (Code_Symbol.Type_Constructor tyco, Code_Thingol.Datatype (vs, [])) =
haftmann@28054
   167
          let
haftmann@48003
   168
            val tyvars = intro_vars vs reserved;
haftmann@28054
   169
          in
haftmann@28054
   170
            semicolon [
haftmann@28054
   171
              str "data",
haftmann@55147
   172
              print_typdecl tyvars (deresolve_tyco tyco, vs)
haftmann@28054
   173
            ]
haftmann@28054
   174
          end
haftmann@55147
   175
      | print_stmt (Code_Symbol.Type_Constructor tyco, Code_Thingol.Datatype (vs, [((co, _), [ty])])) =
haftmann@28054
   176
          let
haftmann@48003
   177
            val tyvars = intro_vars vs reserved;
haftmann@28054
   178
          in
haftmann@28054
   179
            semicolon (
haftmann@28054
   180
              str "newtype"
haftmann@55147
   181
              :: print_typdecl tyvars (deresolve_tyco tyco, vs)
haftmann@28054
   182
              :: str "="
haftmann@55147
   183
              :: (str o deresolve_const) co
haftmann@33991
   184
              :: print_typ tyvars BR ty
haftmann@55147
   185
              :: (if deriving_show tyco then [str "deriving (Read, Show)"] else [])
haftmann@28054
   186
            )
haftmann@28054
   187
          end
haftmann@55147
   188
      | print_stmt (Code_Symbol.Type_Constructor tyco, Code_Thingol.Datatype (vs, co :: cos)) =
haftmann@28054
   189
          let
haftmann@48003
   190
            val tyvars = intro_vars vs reserved;
haftmann@37449
   191
            fun print_co ((co, _), tys) =
haftmann@28054
   192
              concat (
haftmann@55147
   193
                (str o deresolve_const) co
haftmann@33991
   194
                :: map (print_typ tyvars BR) tys
haftmann@28054
   195
              )
haftmann@28054
   196
          in
haftmann@28054
   197
            semicolon (
haftmann@28054
   198
              str "data"
haftmann@55147
   199
              :: print_typdecl tyvars (deresolve_tyco tyco, vs)
haftmann@28054
   200
              :: str "="
haftmann@33991
   201
              :: print_co co
haftmann@33991
   202
              :: map ((fn p => Pretty.block [str "| ", p]) o print_co) cos
haftmann@55147
   203
              @ (if deriving_show tyco then [str "deriving (Read, Show)"] else [])
haftmann@28054
   204
            )
haftmann@28054
   205
          end
haftmann@55147
   206
      | print_stmt (Code_Symbol.Type_Class class, Code_Thingol.Class (v, (classrels, classparams))) =
haftmann@28054
   207
          let
haftmann@32924
   208
            val tyvars = intro_vars [v] reserved;
haftmann@33991
   209
            fun print_classparam (classparam, ty) =
haftmann@28054
   210
              semicolon [
haftmann@55147
   211
                (str o deresolve_const) classparam,
haftmann@28054
   212
                str "::",
haftmann@33991
   213
                print_typ tyvars NOBR ty
haftmann@28054
   214
              ]
haftmann@28054
   215
          in
haftmann@28054
   216
            Pretty.block_enclose (
haftmann@28054
   217
              Pretty.block [
haftmann@28054
   218
                str "class ",
haftmann@55147
   219
                Pretty.block (print_typcontext tyvars [(v, map snd classrels)]),
haftmann@55147
   220
                str (deresolve_class class ^ " " ^ lookup_var tyvars v),
haftmann@28054
   221
                str " where {"
haftmann@28054
   222
              ],
haftmann@28054
   223
              str "};"
haftmann@33991
   224
            ) (map print_classparam classparams)
haftmann@28054
   225
          end
haftmann@48072
   226
      | print_stmt (_, Code_Thingol.Classinst { class, tyco, vs, inst_params, ... }) =
haftmann@28054
   227
          let
haftmann@32924
   228
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@38923
   229
            fun requires_args classparam = case const_syntax classparam
haftmann@39207
   230
             of NONE => NONE
haftmann@39207
   231
              | SOME (Code_Printer.Plain_const_syntax _) => SOME 0
haftmann@39207
   232
              | SOME (Code_Printer.Complex_const_syntax (k,_ )) => SOME k;
haftmann@52519
   233
            fun print_classparam_instance ((classparam, (const, _)), (thm, _)) =
haftmann@37881
   234
              case requires_args classparam
haftmann@39207
   235
               of NONE => semicolon [
haftmann@55147
   236
                      (str o Long_Name.base_name o deresolve_const) classparam,
haftmann@28687
   237
                      str "=",
haftmann@37881
   238
                      print_app tyvars (SOME thm) reserved NOBR (const, [])
haftmann@28687
   239
                    ]
haftmann@39207
   240
                | SOME k =>
haftmann@37881
   241
                    let
haftmann@55147
   242
                      val { sym = Code_Symbol.Constant c, dom, range, ... } = const;
haftmann@37881
   243
                      val (vs, rhs) = (apfst o map) fst
haftmann@37881
   244
                        (Code_Thingol.unfold_abs (Code_Thingol.eta_expand k (const, [])));
haftmann@38923
   245
                      val s = if (is_some o const_syntax) c
haftmann@55147
   246
                        then NONE else (SOME o Long_Name.base_name o deresolve_const) c;
haftmann@37881
   247
                      val vars = reserved
haftmann@37881
   248
                        |> intro_vars (map_filter I (s :: vs));
haftmann@55147
   249
                      val lhs = IConst { sym = Code_Symbol.Constant classparam, typargs = [],
haftmann@48072
   250
                        dicts = [], dom = dom, range = range, annotate = false } `$$ map IVar vs;
bulwahn@45009
   251
                        (*dictionaries are not relevant at this late stage,
bulwahn@45009
   252
                          and these consts never need type annotations for disambiguation *)
haftmann@37881
   253
                    in
haftmann@37881
   254
                      semicolon [
haftmann@37881
   255
                        print_term tyvars (SOME thm) vars NOBR lhs,
haftmann@37881
   256
                        str "=",
haftmann@37881
   257
                        print_term tyvars (SOME thm) vars NOBR rhs
haftmann@37881
   258
                      ]
haftmann@37881
   259
                    end;
haftmann@28054
   260
          in
haftmann@28054
   261
            Pretty.block_enclose (
haftmann@28054
   262
              Pretty.block [
haftmann@28054
   263
                str "instance ",
haftmann@33991
   264
                Pretty.block (print_typcontext tyvars vs),
haftmann@28054
   265
                str (class_name class ^ " "),
haftmann@33991
   266
                print_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@28054
   267
                str " where {"
haftmann@28054
   268
              ],
haftmann@28054
   269
              str "};"
haftmann@48072
   270
            ) (map print_classparam_instance inst_params)
haftmann@28054
   271
          end;
haftmann@33991
   272
  in print_stmt end;
haftmann@28054
   273
haftmann@55147
   274
fun haskell_program_of_program ctxt module_prefix module_name reserved identifiers =
haftmann@39202
   275
  let
haftmann@39202
   276
    fun namify_fun upper base (nsp_fun, nsp_typ) =
haftmann@39202
   277
      let
wenzelm@43326
   278
        val (base', nsp_fun') =
wenzelm@43326
   279
          Name.variant (if upper then first_upper base else base) nsp_fun;
haftmann@39202
   280
      in (base', (nsp_fun', nsp_typ)) end;
haftmann@39202
   281
    fun namify_typ base (nsp_fun, nsp_typ) =
haftmann@39202
   282
      let
wenzelm@43326
   283
        val (base', nsp_typ') = Name.variant (first_upper base) nsp_typ;
haftmann@39202
   284
      in (base', (nsp_fun, nsp_typ')) end;
haftmann@55147
   285
    fun namify_stmt (Code_Thingol.Fun (_, SOME _)) = pair
haftmann@39202
   286
      | namify_stmt (Code_Thingol.Fun _) = namify_fun false
haftmann@39202
   287
      | namify_stmt (Code_Thingol.Datatype _) = namify_typ
haftmann@39202
   288
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_fun true
haftmann@39202
   289
      | namify_stmt (Code_Thingol.Class _) = namify_typ
haftmann@39202
   290
      | namify_stmt (Code_Thingol.Classrel _) = pair
haftmann@39202
   291
      | namify_stmt (Code_Thingol.Classparam _) = namify_fun false
haftmann@39202
   292
      | namify_stmt (Code_Thingol.Classinst _) = pair;
haftmann@55147
   293
    fun select_stmt (Code_Thingol.Fun (_, SOME _)) = false
haftmann@39202
   294
      | select_stmt (Code_Thingol.Fun _) = true
haftmann@39202
   295
      | select_stmt (Code_Thingol.Datatype _) = true
haftmann@39202
   296
      | select_stmt (Code_Thingol.Datatypecons _) = false
haftmann@39202
   297
      | select_stmt (Code_Thingol.Class _) = true
haftmann@39202
   298
      | select_stmt (Code_Thingol.Classrel _) = false
haftmann@39202
   299
      | select_stmt (Code_Thingol.Classparam _) = false
haftmann@39202
   300
      | select_stmt (Code_Thingol.Classinst _) = true;
haftmann@39202
   301
  in
haftmann@55147
   302
    Code_Namespace.flat_program ctxt
haftmann@52138
   303
      { module_prefix = module_prefix, module_name = module_name, reserved = reserved,
haftmann@52138
   304
        identifiers = identifiers, empty_nsp = (reserved, reserved), namify_stmt = namify_stmt,
haftmann@39202
   305
        modify_stmt = fn stmt => if select_stmt stmt then SOME stmt else NONE }
haftmann@39202
   306
  end;
haftmann@39202
   307
haftmann@48431
   308
val prelude_import_operators = [
haftmann@48431
   309
  "==", "/=", "<", "<=", ">=", ">", "+", "-", "*", "/", "**", ">>=", ">>", "=<<", "&&", "||", "^", "^^", ".", "$", "$!", "++", "!!"
haftmann@48431
   310
];
haftmann@48431
   311
haftmann@48431
   312
val prelude_import_unqualified = [
haftmann@48431
   313
  "Eq",
haftmann@48431
   314
  "error",
haftmann@48431
   315
  "id",
haftmann@48431
   316
  "return",
haftmann@48431
   317
  "not",
haftmann@48431
   318
  "fst", "snd",
haftmann@48431
   319
  "map", "filter", "concat", "concatMap", "reverse", "zip", "null", "takeWhile", "dropWhile", "all", "any",
haftmann@48431
   320
  "Integer", "negate", "abs", "divMod",
haftmann@48431
   321
  "String"
haftmann@48431
   322
];
haftmann@48431
   323
haftmann@48431
   324
val prelude_import_unqualified_constr = [
haftmann@48431
   325
  ("Bool", ["True", "False"]),
haftmann@48431
   326
  ("Maybe", ["Nothing", "Just"])
haftmann@48431
   327
];
haftmann@48431
   328
haftmann@55147
   329
fun serialize_haskell module_prefix string_classes ctxt { module_name,
haftmann@52138
   330
    reserved_syms, identifiers, includes, class_syntax, tyco_syntax, const_syntax } program =
haftmann@28054
   331
  let
haftmann@39204
   332
haftmann@39204
   333
    (* build program *)
haftmann@38926
   334
    val reserved = fold (insert (op =) o fst) includes reserved_syms;
haftmann@39204
   335
    val { deresolver, flat_program = haskell_program } = haskell_program_of_program
haftmann@55147
   336
      ctxt module_prefix module_name (Name.make_context reserved) identifiers program;
haftmann@39204
   337
haftmann@39204
   338
    (* print statements *)
haftmann@28054
   339
    fun deriving_show tyco =
haftmann@28054
   340
      let
haftmann@28054
   341
        fun deriv _ "fun" = false
haftmann@55147
   342
          | deriv tycos tyco = member (op =) tycos tyco
haftmann@55147
   343
              orelse case try (Code_Symbol.Graph.get_node program) (Code_Symbol.Type_Constructor tyco)
haftmann@55147
   344
                of SOME (Code_Thingol.Datatype (_, cs)) => forall (deriv' (tyco :: tycos))
haftmann@28054
   345
                    (maps snd cs)
haftmann@55147
   346
                 | NONE => true
haftmann@28054
   347
        and deriv' tycos (tyco `%% tys) = deriv tycos tyco
haftmann@28054
   348
              andalso forall (deriv' tycos) tys
haftmann@28054
   349
          | deriv' _ (ITyVar _) = true
haftmann@28054
   350
      in deriv [] tyco end;
haftmann@47609
   351
    fun print_stmt deresolve = print_haskell_stmt
haftmann@39204
   352
      class_syntax tyco_syntax const_syntax (make_vars reserved)
bulwahn@45009
   353
      deresolve (if string_classes then deriving_show else K false);
haftmann@39204
   354
haftmann@39204
   355
    (* print modules *)
haftmann@39204
   356
    fun print_module_frame module_name ps =
haftmann@39204
   357
      (module_name, Pretty.chunks2 (
haftmann@39209
   358
        str ("module " ^ module_name ^ " where {")
haftmann@39204
   359
        :: ps
haftmann@39204
   360
        @| str "}"
haftmann@39204
   361
      ));
haftmann@48431
   362
    fun print_qualified_import module_name = semicolon [str "import qualified", str module_name];
haftmann@48431
   363
    val import_common_ps =
haftmann@48431
   364
      enclose "import Prelude (" ");" (commas (map str
haftmann@48431
   365
        (map (Library.enclose "(" ")") prelude_import_operators @ prelude_import_unqualified)
haftmann@48431
   366
          @ map (fn (tyco, constrs) => (enclose (tyco ^ "(") ")" o commas o map str) constrs) prelude_import_unqualified_constr))
haftmann@48431
   367
      :: print_qualified_import "Prelude"
haftmann@48431
   368
      :: map (print_qualified_import o fst) includes;
haftmann@39204
   369
    fun print_module module_name (gr, imports) =
haftmann@28054
   370
      let
haftmann@48431
   371
        val deresolve = deresolver module_name;
haftmann@39204
   372
        fun print_import module_name = (semicolon o map str) ["import qualified", module_name];
haftmann@48431
   373
        val import_ps = import_common_ps @ map (print_qualified_import o fst) imports;
haftmann@55147
   374
        fun print_stmt' sym = case Code_Symbol.Graph.get_node gr sym
haftmann@39204
   375
         of (_, NONE) => NONE
haftmann@55147
   376
          | (_, SOME stmt) => SOME (markup_stmt sym (print_stmt deresolve (sym, stmt)));
haftmann@55147
   377
        val body_ps = map_filter print_stmt' ((flat o rev o Code_Symbol.Graph.strong_conn) gr);
haftmann@39204
   378
      in
haftmann@39204
   379
        print_module_frame module_name
haftmann@39204
   380
          ((if null import_ps then [] else [Pretty.chunks import_ps]) @ body_ps)
haftmann@39204
   381
      end;
haftmann@39204
   382
haftmann@39204
   383
    (*serialization*)
haftmann@39204
   384
    fun write_module width (SOME destination) (module_name, content) =
haftmann@38915
   385
          let
wenzelm@42003
   386
            val _ = File.check_dir destination;
haftmann@39204
   387
            val filepath = (Path.append destination o Path.ext "hs" o Path.explode o implode
haftmann@39204
   388
              o separate "/" o Long_Name.explode) module_name;
haftmann@41246
   389
            val _ = Isabelle_System.mkdirs (Path.dir filepath);
haftmann@39209
   390
          in
haftmann@39209
   391
            (File.write filepath o format [] width o Pretty.chunks2)
noschinl@44926
   392
              [str language_pragma, content]
haftmann@39209
   393
          end
haftmann@39056
   394
      | write_module width NONE (_, content) = writeln (format [] width content);
haftmann@28054
   395
  in
haftmann@38916
   396
    Code_Target.serialization
haftmann@38915
   397
      (fn width => fn destination => K () o map (write_module width destination))
haftmann@40705
   398
      (fn present => fn width => rpair (try (deresolver ""))
haftmann@48568
   399
        o (map o apsnd) (format present width))
haftmann@39204
   400
      (map (uncurry print_module_frame o apsnd single) includes
haftmann@39204
   401
        @ map (fn module_name => print_module module_name (Graph.get_node haskell_program module_name))
haftmann@39204
   402
          ((flat o rev o Graph.strong_conn) haskell_program))
haftmann@28054
   403
  end;
haftmann@28054
   404
haftmann@38966
   405
val serializer : Code_Target.serializer =
haftmann@39206
   406
  Code_Target.parse_args (Scan.optional (Args.$$$ "root" -- Args.colon |-- Args.name) ""
haftmann@38966
   407
    -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@38966
   408
    >> (fn (module_prefix, string_classes) =>
haftmann@38966
   409
      serialize_haskell module_prefix string_classes));
haftmann@38966
   410
haftmann@28064
   411
val literals = let
haftmann@28064
   412
  fun char_haskell c =
haftmann@28064
   413
    let
haftmann@28064
   414
      val s = ML_Syntax.print_char c;
haftmann@28064
   415
    in if s = "'" then "\\'" else s end;
haftmann@34944
   416
  fun numeral_haskell k = if k >= 0 then string_of_int k
haftmann@34944
   417
    else Library.enclose "(" ")" (signed_string_of_int k);
haftmann@28064
   418
in Literals {
haftmann@34178
   419
  literal_char = Library.enclose "'" "'" o char_haskell,
haftmann@28064
   420
  literal_string = quote o translate_string char_haskell,
haftmann@34944
   421
  literal_numeral = numeral_haskell,
haftmann@34178
   422
  literal_list = enum "," "[" "]",
haftmann@28064
   423
  infix_cons = (5, ":")
haftmann@28064
   424
} end;
haftmann@28064
   425
haftmann@28054
   426
haftmann@28054
   427
(** optional monad syntax **)
haftmann@28054
   428
haftmann@28054
   429
fun pretty_haskell_monad c_bind =
haftmann@28054
   430
  let
haftmann@31874
   431
    fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2
haftmann@31889
   432
     of SOME ((pat, ty), t') =>
haftmann@31889
   433
          SOME ((SOME ((pat, ty), true), t1), t')
haftmann@28145
   434
      | NONE => NONE;
haftmann@55147
   435
    fun dest_monad c_bind_name (IConst { sym = Code_Symbol.Constant c, ... } `$ t1 `$ t2) =
haftmann@28663
   436
          if c = c_bind_name then dest_bind t1 t2
haftmann@28145
   437
          else NONE
haftmann@28663
   438
      | dest_monad _ t = case Code_Thingol.split_let t
haftmann@28145
   439
         of SOME (((pat, ty), tbind), t') =>
haftmann@31889
   440
              SOME ((SOME ((pat, ty), false), tbind), t')
haftmann@28145
   441
          | NONE => NONE;
haftmann@28663
   442
    fun implode_monad c_bind_name = Code_Thingol.unfoldr (dest_monad c_bind_name);
haftmann@33991
   443
    fun print_monad print_bind print_term (NONE, t) vars =
haftmann@33991
   444
          (semicolon [print_term vars NOBR t], vars)
haftmann@33991
   445
      | print_monad print_bind print_term (SOME ((bind, _), true), t) vars = vars
haftmann@33991
   446
          |> print_bind NOBR bind
haftmann@33991
   447
          |>> (fn p => semicolon [p, str "<-", print_term vars NOBR t])
haftmann@33991
   448
      | print_monad print_bind print_term (SOME ((bind, _), false), t) vars = vars
haftmann@33991
   449
          |> print_bind NOBR bind
haftmann@37832
   450
          |>> (fn p => semicolon [str "let", str "{", p, str "=", print_term vars NOBR t, str "}"]);
haftmann@33991
   451
    fun pretty _ [c_bind'] print_term thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
haftmann@28145
   452
     of SOME (bind, t') => let
haftmann@31054
   453
          val (binds, t'') = implode_monad c_bind' t'
haftmann@33991
   454
          val (ps, vars') = fold_map (print_monad (gen_print_bind (K print_term) thm) print_term)
haftmann@33991
   455
            (bind :: binds) vars;
haftmann@33991
   456
        in
haftmann@37833
   457
          (brackify fxy o single o enclose "do { " " }" o Pretty.breaks)
haftmann@33991
   458
            (ps @| print_term vars' NOBR t'')
haftmann@33991
   459
        end
haftmann@28145
   460
      | NONE => brackify_infix (1, L) fxy
haftmann@37242
   461
          (print_term vars (INFX (1, L)) t1, str ">>=", print_term vars (INFX (1, X)) t2)
haftmann@31054
   462
  in (2, ([c_bind], pretty)) end;
haftmann@28054
   463
haftmann@28145
   464
fun add_monad target' raw_c_bind thy =
haftmann@28054
   465
  let
haftmann@31156
   466
    val c_bind = Code.read_const thy raw_c_bind;
wenzelm@52801
   467
  in
wenzelm@52801
   468
    if target = target' then
wenzelm@52801
   469
      thy
wenzelm@52801
   470
      |> Code_Target.set_printings (Code_Symbol.Constant (c_bind, [(target,
wenzelm@52801
   471
        SOME (Code_Printer.complex_const_syntax (pretty_haskell_monad c_bind)))]))
wenzelm@52801
   472
    else error "Only Haskell target allows for monad syntax"
wenzelm@52801
   473
  end;
haftmann@28054
   474
haftmann@28054
   475
haftmann@28054
   476
(** Isar setup **)
haftmann@28054
   477
haftmann@28054
   478
val _ =
wenzelm@46961
   479
  Outer_Syntax.command @{command_spec "code_monad"} "define code syntax for monads"
wenzelm@52801
   480
    (Parse.term -- Parse.name >> (fn (raw_bind, target) =>
wenzelm@52801
   481
      Toplevel.theory (add_monad target raw_bind)));
haftmann@28054
   482
haftmann@28054
   483
val setup =
haftmann@37821
   484
  Code_Target.add_target
haftmann@38966
   485
    (target, { serializer = serializer, literals = literals,
wenzelm@41952
   486
      check = { env_var = "ISABELLE_GHC", make_destination = I,
wenzelm@41940
   487
        make_command = fn module_name =>
noschinl@44926
   488
          "\"$ISABELLE_GHC\" " ^ language_params  ^ " -odir build -hidir build -stubdir build -e \"\" " ^
wenzelm@41940
   489
            module_name ^ ".hs" } })
haftmann@52435
   490
  #> Code_Target.set_printings (Code_Symbol.Type_Constructor ("fun",
haftmann@52435
   491
    [(target, SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   492
      brackify_infix (1, R) fxy (
haftmann@33991
   493
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   494
        str "->",
haftmann@33991
   495
        print_typ (INFX (1, R)) ty2
haftmann@52435
   496
      )))]))
haftmann@28054
   497
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   498
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@28054
   499
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@28054
   500
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@28054
   501
    ]
haftmann@48431
   502
  #> fold (Code_Target.add_reserved target) prelude_import_unqualified
haftmann@48431
   503
  #> fold (Code_Target.add_reserved target o fst) prelude_import_unqualified_constr
haftmann@48431
   504
  #> fold (fold (Code_Target.add_reserved target) o snd) prelude_import_unqualified_constr;
haftmann@28054
   505
haftmann@28054
   506
end; (*struct*)