src/Tools/Code/code_haskell.ML
author haftmann
Mon Jan 04 14:09:56 2010 +0100 (2010-01-04)
changeset 34244 03f8dcab55f3
parent 34178 a78b8d5b91cb
child 34269 b5c99df2e4b1
permissions -rw-r--r--
code cache without copy; tuned
haftmann@28054
     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
haftmann@28054
     9
  val setup: theory -> theory
haftmann@28054
    10
end;
haftmann@28054
    11
haftmann@28054
    12
structure Code_Haskell : CODE_HASKELL =
haftmann@28054
    13
struct
haftmann@28054
    14
haftmann@28054
    15
val target = "Haskell";
haftmann@28054
    16
haftmann@28054
    17
open Basic_Code_Thingol;
haftmann@28054
    18
open Code_Printer;
haftmann@28054
    19
haftmann@28054
    20
infixr 5 @@;
haftmann@28054
    21
infixr 5 @|;
haftmann@28054
    22
haftmann@28054
    23
haftmann@28054
    24
(** Haskell serializer **)
haftmann@28054
    25
haftmann@33991
    26
fun print_haskell_stmt labelled_name syntax_class syntax_tyco syntax_const
haftmann@32924
    27
    reserved deresolve contr_classparam_typs deriving_show =
haftmann@28054
    28
  let
wenzelm@30364
    29
    val deresolve_base = Long_Name.base_name o deresolve;
haftmann@28054
    30
    fun class_name class = case syntax_class class
haftmann@28054
    31
     of NONE => deresolve class
haftmann@28687
    32
      | SOME class => class;
haftmann@33991
    33
    fun print_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@28054
    34
     of [] => []
haftmann@34178
    35
      | classbinds => enum "," "(" ")" (
haftmann@28054
    36
          map (fn (v, class) =>
haftmann@32924
    37
            str (class_name class ^ " " ^ lookup_var tyvars v)) classbinds)
haftmann@28054
    38
          @@ str " => ";
haftmann@33991
    39
    fun print_typforall tyvars vs = case map fst vs
haftmann@28054
    40
     of [] => []
haftmann@28054
    41
      | vnames => str "forall " :: Pretty.breaks
haftmann@32924
    42
          (map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
haftmann@33991
    43
    fun print_tyco_expr tyvars fxy (tyco, tys) =
haftmann@33991
    44
      brackify fxy (str tyco :: map (print_typ tyvars BR) tys)
haftmann@33991
    45
    and print_typ tyvars fxy (tycoexpr as tyco `%% tys) = (case syntax_tyco tyco
haftmann@33991
    46
         of NONE => print_tyco_expr tyvars fxy (deresolve tyco, tys)
haftmann@33991
    47
          | SOME (i, print) => print (print_typ tyvars) fxy tys)
haftmann@33991
    48
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@33991
    49
    fun print_typdecl tyvars (vs, tycoexpr) =
haftmann@33991
    50
      Pretty.block (print_typcontext tyvars vs @| print_tyco_expr tyvars NOBR tycoexpr);
haftmann@33991
    51
    fun print_typscheme tyvars (vs, ty) =
haftmann@33991
    52
      Pretty.block (print_typforall tyvars vs @ print_typcontext tyvars vs @| print_typ tyvars NOBR ty);
haftmann@33991
    53
    fun print_term tyvars thm vars fxy (IConst c) =
haftmann@33991
    54
          print_app tyvars thm vars fxy (c, [])
haftmann@33991
    55
      | print_term tyvars thm vars fxy (t as (t1 `$ t2)) =
haftmann@28054
    56
          (case Code_Thingol.unfold_const_app t
haftmann@33991
    57
           of SOME app => print_app tyvars thm vars fxy app
haftmann@28054
    58
            | _ =>
haftmann@28054
    59
                brackify fxy [
haftmann@33991
    60
                  print_term tyvars thm vars NOBR t1,
haftmann@33991
    61
                  print_term tyvars thm vars BR t2
haftmann@28054
    62
                ])
haftmann@33991
    63
      | print_term tyvars thm vars fxy (IVar NONE) =
haftmann@31889
    64
          str "_"
haftmann@33991
    65
      | print_term tyvars thm vars fxy (IVar (SOME v)) =
haftmann@32924
    66
          (str o lookup_var vars) v
haftmann@33991
    67
      | print_term tyvars thm vars fxy (t as _ `|=> _) =
haftmann@28054
    68
          let
haftmann@31874
    69
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33991
    70
            val (ps, vars') = fold_map (print_bind tyvars thm BR o fst) binds vars;
haftmann@33991
    71
          in brackets (str "\\" :: ps @ str "->" @@ print_term tyvars thm vars' NOBR t') end
haftmann@33991
    72
      | print_term tyvars thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
    73
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
    74
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@33991
    75
                then print_case tyvars thm vars fxy cases
haftmann@33991
    76
                else print_app tyvars thm vars fxy c_ts
haftmann@33991
    77
            | NONE => print_case tyvars thm vars fxy cases)
haftmann@33991
    78
    and print_app_expr tyvars thm vars ((c, (_, tys)), ts) = case contr_classparam_typs c
haftmann@33991
    79
     of [] => (str o deresolve) c :: map (print_term tyvars thm vars BR) ts
haftmann@28054
    80
      | fingerprint => let
haftmann@33957
    81
          val ts_fingerprint = ts ~~ take (length ts) fingerprint;
haftmann@28054
    82
          val needs_annotation = forall (fn (_, NONE) => true | (t, SOME _) =>
haftmann@28054
    83
            (not o Code_Thingol.locally_monomorphic) t) ts_fingerprint;
haftmann@33991
    84
          fun print_term_anno (t, NONE) _ = print_term tyvars thm vars BR t
haftmann@33991
    85
            | print_term_anno (t, SOME _) ty =
haftmann@33991
    86
                brackets [print_term tyvars thm vars NOBR t, str "::", print_typ tyvars NOBR ty];
haftmann@28054
    87
        in
haftmann@28054
    88
          if needs_annotation then
haftmann@33994
    89
            (str o deresolve) c :: map2 print_term_anno ts_fingerprint (take (length ts) tys)
haftmann@33991
    90
          else (str o deresolve) c :: map (print_term tyvars thm vars BR) ts
haftmann@28054
    91
        end
haftmann@33991
    92
    and print_app tyvars = gen_print_app (print_app_expr tyvars) (print_term tyvars) syntax_const
haftmann@33991
    93
    and print_bind tyvars thm fxy p = gen_print_bind (print_term tyvars) thm fxy p
haftmann@33991
    94
    and print_case tyvars thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
    95
          let
haftmann@29952
    96
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33991
    97
            fun print_match ((pat, ty), t) vars =
haftmann@28054
    98
              vars
haftmann@33991
    99
              |> print_bind tyvars thm BR pat
haftmann@33991
   100
              |>> (fn p => semicolon [p, str "=", print_term tyvars thm vars NOBR t])
haftmann@33991
   101
            val (ps, vars') = fold_map print_match binds vars;
haftmann@31665
   102
          in brackify_block fxy (str "let {")
haftmann@31665
   103
            ps
haftmann@33991
   104
            (concat [str "}", str "in", print_term tyvars thm vars' NOBR body])
haftmann@28054
   105
          end
haftmann@33991
   106
      | print_case tyvars thm vars fxy (((t, ty), clauses as _ :: _), _) =
haftmann@28054
   107
          let
haftmann@33991
   108
            fun print_select (pat, body) =
haftmann@28054
   109
              let
haftmann@33991
   110
                val (p, vars') = print_bind tyvars thm NOBR pat vars;
haftmann@33991
   111
              in semicolon [p, str "->", print_term tyvars thm vars' NOBR body] end;
haftmann@31665
   112
          in brackify_block fxy
haftmann@33991
   113
            (concat [str "case", print_term tyvars thm vars NOBR t, str "of", str "{"])
haftmann@33991
   114
            (map print_select clauses)
haftmann@31665
   115
            (str "}") 
haftmann@28054
   116
          end
haftmann@33991
   117
      | print_case tyvars thm vars fxy ((_, []), _) =
haftmann@31376
   118
          (brackify fxy o Pretty.breaks o map str) ["error", "\"empty case\""];
haftmann@33991
   119
    fun print_stmt (name, Code_Thingol.Fun (_, ((vs, ty), []))) =
haftmann@28054
   120
          let
haftmann@32924
   121
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   122
            val n = (length o fst o Code_Thingol.unfold_fun) ty;
haftmann@28054
   123
          in
haftmann@28054
   124
            Pretty.chunks [
haftmann@33991
   125
              semicolon [
haftmann@28054
   126
                (str o suffix " ::" o deresolve_base) name,
haftmann@33991
   127
                print_typscheme tyvars (vs, ty)
haftmann@28054
   128
              ],
haftmann@33991
   129
              semicolon (
haftmann@28054
   130
                (str o deresolve_base) name
haftmann@28054
   131
                :: map str (replicate n "_")
haftmann@28054
   132
                @ str "="
haftmann@28054
   133
                :: str "error"
haftmann@33991
   134
                @@ (str o ML_Syntax.print_string
wenzelm@30364
   135
                    o Long_Name.base_name o Long_Name.qualifier) name
haftmann@28054
   136
              )
haftmann@28054
   137
            ]
haftmann@28054
   138
          end
haftmann@33991
   139
      | print_stmt (name, Code_Thingol.Fun (_, ((vs, ty), raw_eqs))) =
haftmann@28054
   140
          let
haftmann@28350
   141
            val eqs = filter (snd o snd) raw_eqs;
haftmann@32924
   142
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@33991
   143
            fun print_eqn ((ts, t), (thm, _)) =
haftmann@28054
   144
              let
haftmann@32913
   145
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   146
                val vars = reserved
haftmann@32924
   147
                  |> intro_base_names
haftmann@32913
   148
                      (is_none o syntax_const) deresolve consts
haftmann@32924
   149
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@32925
   150
                      (insert (op =)) ts []);
haftmann@28054
   151
              in
haftmann@28054
   152
                semicolon (
haftmann@28054
   153
                  (str o deresolve_base) name
haftmann@33991
   154
                  :: map (print_term tyvars thm vars BR) ts
haftmann@28054
   155
                  @ str "="
haftmann@33991
   156
                  @@ print_term tyvars thm vars NOBR t
haftmann@28054
   157
                )
haftmann@28054
   158
              end;
haftmann@28054
   159
          in
haftmann@28054
   160
            Pretty.chunks (
haftmann@33991
   161
              semicolon [
haftmann@28054
   162
                (str o suffix " ::" o deresolve_base) name,
haftmann@33991
   163
                print_typscheme tyvars (vs, ty)
haftmann@28054
   164
              ]
haftmann@33991
   165
              :: map print_eqn eqs
haftmann@28054
   166
            )
haftmann@28054
   167
          end
haftmann@33991
   168
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, []))) =
haftmann@28054
   169
          let
haftmann@32924
   170
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   171
          in
haftmann@28054
   172
            semicolon [
haftmann@28054
   173
              str "data",
haftmann@33991
   174
              print_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   175
            ]
haftmann@28054
   176
          end
haftmann@33991
   177
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, [(co, [ty])]))) =
haftmann@28054
   178
          let
haftmann@32924
   179
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   180
          in
haftmann@28054
   181
            semicolon (
haftmann@28054
   182
              str "newtype"
haftmann@33991
   183
              :: print_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   184
              :: str "="
haftmann@28054
   185
              :: (str o deresolve_base) co
haftmann@33991
   186
              :: print_typ tyvars BR ty
haftmann@28054
   187
              :: (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   188
            )
haftmann@28054
   189
          end
haftmann@33991
   190
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, co :: cos))) =
haftmann@28054
   191
          let
haftmann@32924
   192
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@33991
   193
            fun print_co (co, tys) =
haftmann@28054
   194
              concat (
haftmann@28054
   195
                (str o deresolve_base) co
haftmann@33991
   196
                :: map (print_typ tyvars BR) tys
haftmann@28054
   197
              )
haftmann@28054
   198
          in
haftmann@28054
   199
            semicolon (
haftmann@28054
   200
              str "data"
haftmann@33991
   201
              :: print_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   202
              :: str "="
haftmann@33991
   203
              :: print_co co
haftmann@33991
   204
              :: map ((fn p => Pretty.block [str "| ", p]) o print_co) cos
haftmann@28054
   205
              @ (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   206
            )
haftmann@28054
   207
          end
haftmann@33991
   208
      | print_stmt (name, Code_Thingol.Class (_, (v, (superclasses, classparams)))) =
haftmann@28054
   209
          let
haftmann@32924
   210
            val tyvars = intro_vars [v] reserved;
haftmann@33991
   211
            fun print_classparam (classparam, ty) =
haftmann@28054
   212
              semicolon [
haftmann@28687
   213
                (str o deresolve_base) classparam,
haftmann@28054
   214
                str "::",
haftmann@33991
   215
                print_typ tyvars NOBR ty
haftmann@28054
   216
              ]
haftmann@28054
   217
          in
haftmann@28054
   218
            Pretty.block_enclose (
haftmann@28054
   219
              Pretty.block [
haftmann@28054
   220
                str "class ",
haftmann@33991
   221
                Pretty.block (print_typcontext tyvars [(v, map fst superclasses)]),
haftmann@32924
   222
                str (deresolve_base name ^ " " ^ lookup_var tyvars v),
haftmann@28054
   223
                str " where {"
haftmann@28054
   224
              ],
haftmann@28054
   225
              str "};"
haftmann@33991
   226
            ) (map print_classparam classparams)
haftmann@28054
   227
          end
haftmann@33991
   228
      | print_stmt (_, Code_Thingol.Classinst ((class, (tyco, vs)), (_, classparam_insts))) =
haftmann@28054
   229
          let
haftmann@32924
   230
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@33991
   231
            fun print_instdef ((classparam, c_inst), (thm, _)) = case syntax_const classparam
haftmann@28687
   232
             of NONE => semicolon [
haftmann@28687
   233
                    (str o deresolve_base) classparam,
haftmann@28687
   234
                    str "=",
haftmann@33991
   235
                    print_app tyvars thm reserved NOBR (c_inst, [])
haftmann@28687
   236
                  ]
haftmann@28687
   237
              | SOME (k, pr) =>
haftmann@28687
   238
                  let
haftmann@28687
   239
                    val (c_inst_name, (_, tys)) = c_inst;
haftmann@28687
   240
                    val const = if (is_some o syntax_const) c_inst_name
wenzelm@30364
   241
                      then NONE else (SOME o Long_Name.base_name o deresolve) c_inst_name;
haftmann@28687
   242
                    val proto_rhs = Code_Thingol.eta_expand k (c_inst, []);
haftmann@31874
   243
                    val (vs, rhs) = (apfst o map) fst (Code_Thingol.unfold_abs proto_rhs);
haftmann@32924
   244
                    val vars = reserved
haftmann@32924
   245
                      |> intro_vars (the_list const)
haftmann@32924
   246
                      |> intro_vars (map_filter I vs);
haftmann@31889
   247
                    val lhs = IConst (classparam, (([], []), tys)) `$$ map IVar vs;
haftmann@28687
   248
                      (*dictionaries are not relevant at this late stage*)
haftmann@28687
   249
                  in
haftmann@28687
   250
                    semicolon [
haftmann@33991
   251
                      print_term tyvars thm vars NOBR lhs,
haftmann@28687
   252
                      str "=",
haftmann@33991
   253
                      print_term tyvars thm vars NOBR rhs
haftmann@28687
   254
                    ]
haftmann@28687
   255
                  end;
haftmann@28054
   256
          in
haftmann@28054
   257
            Pretty.block_enclose (
haftmann@28054
   258
              Pretty.block [
haftmann@28054
   259
                str "instance ",
haftmann@33991
   260
                Pretty.block (print_typcontext tyvars vs),
haftmann@28054
   261
                str (class_name class ^ " "),
haftmann@33991
   262
                print_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@28054
   263
                str " where {"
haftmann@28054
   264
              ],
haftmann@28054
   265
              str "};"
haftmann@33991
   266
            ) (map print_instdef classparam_insts)
haftmann@28054
   267
          end;
haftmann@33991
   268
  in print_stmt end;
haftmann@28054
   269
haftmann@32924
   270
fun haskell_program_of_program labelled_name module_name module_prefix reserved raw_module_alias program =
haftmann@28054
   271
  let
haftmann@28054
   272
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@32924
   273
    val reserved = Name.make_context reserved;
haftmann@32924
   274
    val mk_name_module = mk_name_module reserved module_prefix module_alias program;
haftmann@28054
   275
    fun add_stmt (name, (stmt, deps)) =
haftmann@28054
   276
      let
haftmann@32924
   277
        val (module_name, base) = dest_name name;
haftmann@28054
   278
        val module_name' = mk_name_module module_name;
haftmann@28054
   279
        val mk_name_stmt = yield_singleton Name.variants;
haftmann@28054
   280
        fun add_fun upper (nsp_fun, nsp_typ) =
haftmann@28054
   281
          let
haftmann@28054
   282
            val (base', nsp_fun') =
haftmann@32924
   283
              mk_name_stmt (if upper then first_upper base else base) nsp_fun
haftmann@28054
   284
          in (base', (nsp_fun', nsp_typ)) end;
haftmann@28054
   285
        fun add_typ (nsp_fun, nsp_typ) =
haftmann@28054
   286
          let
haftmann@32924
   287
            val (base', nsp_typ') = mk_name_stmt (first_upper base) nsp_typ
haftmann@28054
   288
          in (base', (nsp_fun, nsp_typ')) end;
haftmann@28054
   289
        val add_name = case stmt
haftmann@28054
   290
         of Code_Thingol.Fun _ => add_fun false
haftmann@28054
   291
          | Code_Thingol.Datatype _ => add_typ
haftmann@28054
   292
          | Code_Thingol.Datatypecons _ => add_fun true
haftmann@28054
   293
          | Code_Thingol.Class _ => add_typ
haftmann@28054
   294
          | Code_Thingol.Classrel _ => pair base
haftmann@28054
   295
          | Code_Thingol.Classparam _ => add_fun false
haftmann@28054
   296
          | Code_Thingol.Classinst _ => pair base;
haftmann@28054
   297
        fun add_stmt' base' = case stmt
haftmann@28054
   298
         of Code_Thingol.Datatypecons _ =>
wenzelm@30364
   299
              cons (name, (Long_Name.append module_name' base', NONE))
haftmann@28054
   300
          | Code_Thingol.Classrel _ => I
haftmann@28054
   301
          | Code_Thingol.Classparam _ =>
wenzelm@30364
   302
              cons (name, (Long_Name.append module_name' base', NONE))
wenzelm@30364
   303
          | _ => cons (name, (Long_Name.append module_name' base', SOME stmt));
haftmann@28054
   304
      in
haftmann@32924
   305
        Symtab.map_default (module_name', ([], ([], (reserved, reserved))))
haftmann@28054
   306
              (apfst (fold (insert (op = : string * string -> bool)) deps))
haftmann@28054
   307
        #> `(fn program => add_name ((snd o snd o the o Symtab.lookup program) module_name'))
haftmann@28054
   308
        #-> (fn (base', names) =>
haftmann@28054
   309
              (Symtab.map_entry module_name' o apsnd) (fn (stmts, _) =>
haftmann@28054
   310
              (add_stmt' base' stmts, names)))
haftmann@28054
   311
      end;
haftmann@28054
   312
    val hs_program = fold add_stmt (AList.make (fn name =>
haftmann@28054
   313
      (Graph.get_node program name, Graph.imm_succs program name))
haftmann@28054
   314
      (Graph.strong_conn program |> flat)) Symtab.empty;
haftmann@28663
   315
    fun deresolver name = (fst o the o AList.lookup (op =) ((fst o snd o the
haftmann@32924
   316
      o Symtab.lookup hs_program) ((mk_name_module o fst o dest_name) name))) name
haftmann@28663
   317
      handle Option => error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   318
  in (deresolver, hs_program) end;
haftmann@28054
   319
haftmann@28054
   320
fun serialize_haskell module_prefix raw_module_name string_classes labelled_name
haftmann@32924
   321
    raw_reserved includes raw_module_alias
haftmann@34073
   322
    syntax_class syntax_tyco syntax_const (code_of_pretty, code_writeln) program cs destination =
haftmann@28054
   323
  let
haftmann@28054
   324
    val stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@28054
   325
    val module_name = if null stmt_names then raw_module_name else SOME "Code";
haftmann@32924
   326
    val reserved = fold (insert (op =) o fst) includes raw_reserved;
haftmann@28054
   327
    val (deresolver, hs_program) = haskell_program_of_program labelled_name
haftmann@32924
   328
      module_name module_prefix reserved raw_module_alias program;
haftmann@28054
   329
    val contr_classparam_typs = Code_Thingol.contr_classparam_typs program;
haftmann@28054
   330
    fun deriving_show tyco =
haftmann@28054
   331
      let
haftmann@28054
   332
        fun deriv _ "fun" = false
haftmann@34085
   333
          | deriv tycos tyco = not (tyco = Code_Thingol.fun_tyco)
haftmann@34085
   334
              andalso (member (op =) tycos tyco
haftmann@34085
   335
              orelse case try (Graph.get_node program) tyco
haftmann@28663
   336
                of SOME (Code_Thingol.Datatype (_, (_, cs))) => forall (deriv' (tyco :: tycos))
haftmann@28054
   337
                    (maps snd cs)
haftmann@34085
   338
                 | NONE => true)
haftmann@28054
   339
        and deriv' tycos (tyco `%% tys) = deriv tycos tyco
haftmann@28054
   340
              andalso forall (deriv' tycos) tys
haftmann@28054
   341
          | deriv' _ (ITyVar _) = true
haftmann@28054
   342
      in deriv [] tyco end;
haftmann@32924
   343
    val reserved = make_vars reserved;
haftmann@33991
   344
    fun print_stmt qualified = print_haskell_stmt labelled_name
haftmann@32924
   345
      syntax_class syntax_tyco syntax_const reserved
wenzelm@30364
   346
      (if qualified then deresolver else Long_Name.base_name o deresolver)
haftmann@32903
   347
      contr_classparam_typs
haftmann@28054
   348
      (if string_classes then deriving_show else K false);
haftmann@33991
   349
    fun print_module name content =
haftmann@28054
   350
      (name, Pretty.chunks [
haftmann@28054
   351
        str ("module " ^ name ^ " where {"),
haftmann@28054
   352
        str "",
haftmann@28054
   353
        content,
haftmann@28054
   354
        str "",
haftmann@28054
   355
        str "}"
haftmann@28054
   356
      ]);
haftmann@28054
   357
    fun serialize_module1 (module_name', (deps, (stmts, _))) =
haftmann@28054
   358
      let
haftmann@28054
   359
        val stmt_names = map fst stmts;
haftmann@33421
   360
        val qualified = is_none module_name;
haftmann@33421
   361
        val imports = subtract (op =) stmt_names deps
haftmann@28054
   362
          |> distinct (op =)
haftmann@33421
   363
          |> map_filter (try deresolver)
wenzelm@30364
   364
          |> map Long_Name.qualifier
haftmann@28054
   365
          |> distinct (op =);
haftmann@33991
   366
        fun print_import_include (name, _) = str ("import qualified " ^ name ^ ";");
haftmann@34049
   367
        fun print_import_module name = str ((if qualified
haftmann@34049
   368
          then "import qualified "
haftmann@34049
   369
          else "import ") ^ name ^ ";");
haftmann@33991
   370
        val import_ps = map print_import_include includes @ map print_import_module imports
haftmann@34073
   371
        val content = Pretty.chunks2 ((if null import_ps then [] else [Pretty.chunks import_ps])
haftmann@33991
   372
            @ map_filter
haftmann@33991
   373
              (fn (name, (_, SOME stmt)) => SOME (print_stmt qualified (name, stmt))
haftmann@33991
   374
                | (_, (_, NONE)) => NONE) stmts
haftmann@33991
   375
          );
haftmann@33991
   376
      in print_module module_name' content end;
haftmann@33991
   377
    fun serialize_module2 (_, (_, (stmts, _))) = Pretty.chunks2 (map_filter
haftmann@28054
   378
        (fn (name, (_, SOME stmt)) => if null stmt_names
haftmann@28054
   379
              orelse member (op =) stmt_names name
haftmann@33991
   380
              then SOME (print_stmt false (name, stmt))
haftmann@28054
   381
              else NONE
haftmann@33991
   382
          | (_, (_, NONE)) => NONE) stmts);
haftmann@28054
   383
    val serialize_module =
haftmann@28054
   384
      if null stmt_names then serialize_module1 else pair "" o serialize_module2;
haftmann@29832
   385
    fun check_destination destination =
haftmann@29832
   386
      (File.check destination; destination);
haftmann@28054
   387
    fun write_module destination (modlname, content) =
haftmann@28054
   388
      let
haftmann@28054
   389
        val filename = case modlname
haftmann@28054
   390
         of "" => Path.explode "Main.hs"
haftmann@28054
   391
          | _ => (Path.ext "hs" o Path.explode o implode o separate "/"
wenzelm@30364
   392
                o Long_Name.explode) modlname;
haftmann@28054
   393
        val pathname = Path.append destination filename;
haftmann@28054
   394
        val _ = File.mkdir (Path.dir pathname);
haftmann@29135
   395
      in File.write pathname
haftmann@29135
   396
        ("{-# OPTIONS_GHC -fglasgow-exts #-}\n\n"
haftmann@34073
   397
          ^ code_of_pretty content)
haftmann@29135
   398
      end
haftmann@28054
   399
  in
haftmann@28054
   400
    Code_Target.mk_serialization target NONE
haftmann@34073
   401
      (fn NONE => K () o map (code_writeln o snd) | SOME file => K () o map
haftmann@29832
   402
        (write_module (check_destination file)))
haftmann@34073
   403
      (rpair [] o cat_lines o map (code_of_pretty o snd))
haftmann@33991
   404
      (map (uncurry print_module) includes
haftmann@28054
   405
        @ map serialize_module (Symtab.dest hs_program))
haftmann@28054
   406
      destination
haftmann@28054
   407
  end;
haftmann@28054
   408
haftmann@28064
   409
val literals = let
haftmann@28064
   410
  fun char_haskell c =
haftmann@28064
   411
    let
haftmann@28064
   412
      val s = ML_Syntax.print_char c;
haftmann@28064
   413
    in if s = "'" then "\\'" else s end;
haftmann@28064
   414
in Literals {
haftmann@34178
   415
  literal_char = Library.enclose "'" "'" o char_haskell,
haftmann@28064
   416
  literal_string = quote o translate_string char_haskell,
haftmann@28064
   417
  literal_numeral = fn unbounded => fn k => if k >= 0 then string_of_int k
haftmann@34178
   418
    else Library.enclose "(" ")" (signed_string_of_int k),
haftmann@34178
   419
  literal_list = enum "," "[" "]",
haftmann@28064
   420
  infix_cons = (5, ":")
haftmann@28064
   421
} end;
haftmann@28064
   422
haftmann@28054
   423
haftmann@28054
   424
(** optional monad syntax **)
haftmann@28054
   425
haftmann@28054
   426
fun pretty_haskell_monad c_bind =
haftmann@28054
   427
  let
haftmann@31874
   428
    fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2
haftmann@31889
   429
     of SOME ((pat, ty), t') =>
haftmann@31889
   430
          SOME ((SOME ((pat, ty), true), t1), t')
haftmann@28145
   431
      | NONE => NONE;
haftmann@28663
   432
    fun dest_monad c_bind_name (IConst (c, _) `$ t1 `$ t2) =
haftmann@28663
   433
          if c = c_bind_name then dest_bind t1 t2
haftmann@28145
   434
          else NONE
haftmann@28663
   435
      | dest_monad _ t = case Code_Thingol.split_let t
haftmann@28145
   436
         of SOME (((pat, ty), tbind), t') =>
haftmann@31889
   437
              SOME ((SOME ((pat, ty), false), tbind), t')
haftmann@28145
   438
          | NONE => NONE;
haftmann@28663
   439
    fun implode_monad c_bind_name = Code_Thingol.unfoldr (dest_monad c_bind_name);
haftmann@33991
   440
    fun print_monad print_bind print_term (NONE, t) vars =
haftmann@33991
   441
          (semicolon [print_term vars NOBR t], vars)
haftmann@33991
   442
      | print_monad print_bind print_term (SOME ((bind, _), true), t) vars = vars
haftmann@33991
   443
          |> print_bind NOBR bind
haftmann@33991
   444
          |>> (fn p => semicolon [p, str "<-", print_term vars NOBR t])
haftmann@33991
   445
      | print_monad print_bind print_term (SOME ((bind, _), false), t) vars = vars
haftmann@33991
   446
          |> print_bind NOBR bind
haftmann@33991
   447
          |>> (fn p => semicolon [str "let", p, str "=", print_term vars NOBR t]);
haftmann@33991
   448
    fun pretty _ [c_bind'] print_term thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
haftmann@28145
   449
     of SOME (bind, t') => let
haftmann@31054
   450
          val (binds, t'') = implode_monad c_bind' t'
haftmann@33991
   451
          val (ps, vars') = fold_map (print_monad (gen_print_bind (K print_term) thm) print_term)
haftmann@33991
   452
            (bind :: binds) vars;
haftmann@33991
   453
        in
haftmann@34178
   454
          (brackify fxy o single o enclose "do {" "}" o Pretty.breaks)
haftmann@33991
   455
            (ps @| print_term vars' NOBR t'')
haftmann@33991
   456
        end
haftmann@28145
   457
      | NONE => brackify_infix (1, L) fxy
haftmann@33991
   458
          [print_term vars (INFX (1, L)) t1, str ">>=", print_term vars (INFX (1, X)) t2]
haftmann@31054
   459
  in (2, ([c_bind], pretty)) end;
haftmann@28054
   460
haftmann@28145
   461
fun add_monad target' raw_c_bind thy =
haftmann@28054
   462
  let
haftmann@31156
   463
    val c_bind = Code.read_const thy raw_c_bind;
haftmann@28054
   464
  in if target = target' then
haftmann@28054
   465
    thy
haftmann@28145
   466
    |> Code_Target.add_syntax_const target c_bind
haftmann@28663
   467
        (SOME (pretty_haskell_monad c_bind))
haftmann@28054
   468
  else error "Only Haskell target allows for monad syntax" end;
haftmann@28054
   469
haftmann@28054
   470
haftmann@28054
   471
(** Isar setup **)
haftmann@28054
   472
haftmann@33991
   473
fun isar_seri_haskell module_name =
haftmann@28054
   474
  Code_Target.parse_args (Scan.option (Args.$$$ "root" -- Args.colon |-- Args.name)
haftmann@28054
   475
    -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@28054
   476
    >> (fn (module_prefix, string_classes) =>
haftmann@33991
   477
      serialize_haskell module_prefix module_name string_classes));
haftmann@28054
   478
haftmann@28054
   479
val _ =
haftmann@28054
   480
  OuterSyntax.command "code_monad" "define code syntax for monads" OuterKeyword.thy_decl (
haftmann@28145
   481
    OuterParse.term_group -- OuterParse.name >> (fn (raw_bind, target) =>
haftmann@28145
   482
      Toplevel.theory  (add_monad target raw_bind))
haftmann@28054
   483
  );
haftmann@28054
   484
haftmann@28054
   485
val setup =
haftmann@28064
   486
  Code_Target.add_target (target, (isar_seri_haskell, literals))
haftmann@33991
   487
  #> Code_Target.add_syntax_tyco target "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
   488
      brackify_infix (1, R) fxy [
haftmann@33991
   489
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   490
        str "->",
haftmann@33991
   491
        print_typ (INFX (1, R)) ty2
haftmann@28054
   492
      ]))
haftmann@28054
   493
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   494
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@28054
   495
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@28054
   496
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@28054
   497
    ]
haftmann@28054
   498
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   499
      "Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int",
haftmann@28054
   500
      "Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded",
haftmann@28054
   501
      "Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor",
haftmann@28054
   502
      "AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException",
haftmann@28054
   503
      "BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException",
haftmann@28054
   504
      "Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure",
haftmann@28054
   505
      "ExitSuccess", "False", "GT", "HeapOverflow",
haftmann@28054
   506
      "IOError", "IOException", "IllegalOperation",
haftmann@28054
   507
      "IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError",
haftmann@28054
   508
      "NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow",
haftmann@28054
   509
      "PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError",
haftmann@28054
   510
      "RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow",
haftmann@28054
   511
      "ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow",
haftmann@28054
   512
      "UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all",
haftmann@28054
   513
      "and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan",
haftmann@28054
   514
      "atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen",
haftmann@28054
   515
      "boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break",
haftmann@28054
   516
      "catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const",
haftmann@28054
   517
      "cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod",
haftmann@28054
   518
      "doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem",
haftmann@28054
   519
      "emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
haftmann@28054
   520
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip",
haftmann@28054
   521
      "floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational",
haftmann@28054
   522
      "floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble",
haftmann@28054
   523
      "fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj",
haftmann@28054
   524
      "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head",
haftmann@28054
   525
      "id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha",
haftmann@28054
   526
      "isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite",
haftmann@28054
   527
      "isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'",
haftmann@28054
   528
      "last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log",
haftmann@28054
   529
      "logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum",
haftmann@28054
   530
      "maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem",
haftmann@28054
   531
      "null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo",
haftmann@28054
   532
      "numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred", 
haftmann@28054
   533
      "print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn",
haftmann@28054
   534
      "quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat",
haftmann@28054
   535
      "rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile",
haftmann@28054
   536
      "readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn",
haftmann@28054
   537
      "readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational",
haftmann@28054
   538
      "realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse",
haftmann@28054
   539
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence",
haftmann@28054
   540
      "sequence_", "show", "showChar", "showException", "showField", "showList",
haftmann@28054
   541
      "showLitChar", "showParen", "showString", "shows", "showsPrec", "significand",
haftmann@28054
   542
      "signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract",
haftmann@28054
   543
      "succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult",
haftmann@28054
   544
      "throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry",
haftmann@28054
   545
      "undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords",
haftmann@28054
   546
      "unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"
haftmann@28054
   547
    ] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*);
haftmann@28054
   548
haftmann@28054
   549
end; (*struct*)