src/Tools/Code/code_haskell.ML
author haftmann
Thu Sep 18 18:48:54 2014 +0200 (2014-09-18)
changeset 58400 d0d3c30806b4
parent 58397 1c036d6216d3
child 58454 271829a473ed
permissions -rw-r--r--
always annotate potentially polymorphic Haskell numerals
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@58400
    11
  val print_numeral: string -> int -> string
haftmann@28054
    12
  val setup: theory -> theory
haftmann@28054
    13
end;
haftmann@28054
    14
haftmann@28054
    15
structure Code_Haskell : CODE_HASKELL =
haftmann@28054
    16
struct
haftmann@28054
    17
haftmann@28054
    18
val target = "Haskell";
haftmann@28054
    19
noschinl@44926
    20
val language_extensions =
noschinl@44940
    21
  ["EmptyDataDecls", "RankNTypes", "ScopedTypeVariables"];
noschinl@44926
    22
noschinl@44926
    23
val language_pragma =
noschinl@44940
    24
  "{-# LANGUAGE " ^ commas language_extensions ^ " #-}";
noschinl@44926
    25
noschinl@44926
    26
val language_params =
noschinl@44940
    27
  space_implode " " (map (prefix "-X") language_extensions);
noschinl@44926
    28
haftmann@55150
    29
open Basic_Code_Symbol;
haftmann@28054
    30
open Basic_Code_Thingol;
haftmann@28054
    31
open Code_Printer;
haftmann@28054
    32
haftmann@28054
    33
infixr 5 @@;
haftmann@28054
    34
infixr 5 @|;
haftmann@28054
    35
haftmann@28054
    36
haftmann@28054
    37
(** Haskell serializer **)
haftmann@28054
    38
haftmann@47609
    39
fun print_haskell_stmt class_syntax tyco_syntax const_syntax
bulwahn@44793
    40
    reserved deresolve deriving_show =
haftmann@28054
    41
  let
haftmann@55150
    42
    val deresolve_const = deresolve o Constant;
haftmann@55150
    43
    val deresolve_tyco = deresolve o Type_Constructor;
haftmann@55150
    44
    val deresolve_class = deresolve o Type_Class;
haftmann@38923
    45
    fun class_name class = case class_syntax class
haftmann@55147
    46
     of NONE => deresolve_class class
haftmann@28687
    47
      | SOME class => class;
haftmann@33991
    48
    fun print_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@28054
    49
     of [] => []
haftmann@37384
    50
      | constraints => enum "," "(" ")" (
haftmann@28054
    51
          map (fn (v, class) =>
haftmann@37384
    52
            str (class_name class ^ " " ^ lookup_var tyvars v)) constraints)
haftmann@28054
    53
          @@ str " => ";
haftmann@33991
    54
    fun print_typforall tyvars vs = case map fst vs
haftmann@28054
    55
     of [] => []
haftmann@28054
    56
      | vnames => str "forall " :: Pretty.breaks
haftmann@32924
    57
          (map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
haftmann@33991
    58
    fun print_tyco_expr tyvars fxy (tyco, tys) =
haftmann@33991
    59
      brackify fxy (str tyco :: map (print_typ tyvars BR) tys)
haftmann@47609
    60
    and print_typ tyvars fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55147
    61
         of NONE => print_tyco_expr tyvars fxy (deresolve_tyco tyco, tys)
haftmann@47609
    62
          | SOME (_, print) => print (print_typ tyvars) fxy tys)
haftmann@33991
    63
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@48003
    64
    fun print_typdecl tyvars (tyco, vs) =
haftmann@48003
    65
      print_tyco_expr tyvars NOBR (tyco, map ITyVar vs);
haftmann@33991
    66
    fun print_typscheme tyvars (vs, ty) =
haftmann@33991
    67
      Pretty.block (print_typforall tyvars vs @ print_typcontext tyvars vs @| print_typ tyvars NOBR ty);
haftmann@48072
    68
    fun print_term tyvars some_thm vars fxy (IConst const) =
haftmann@48072
    69
          print_app tyvars some_thm vars fxy (const, [])
haftmann@35228
    70
      | print_term tyvars some_thm vars fxy (t as (t1 `$ t2)) =
haftmann@28054
    71
          (case Code_Thingol.unfold_const_app t
haftmann@35228
    72
           of SOME app => print_app tyvars some_thm vars fxy app
haftmann@28054
    73
            | _ =>
haftmann@28054
    74
                brackify fxy [
haftmann@35228
    75
                  print_term tyvars some_thm vars NOBR t1,
haftmann@35228
    76
                  print_term tyvars some_thm vars BR t2
haftmann@28054
    77
                ])
haftmann@35228
    78
      | print_term tyvars some_thm vars fxy (IVar NONE) =
haftmann@31889
    79
          str "_"
haftmann@35228
    80
      | print_term tyvars some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
    81
          (str o lookup_var vars) v
haftmann@35228
    82
      | print_term tyvars some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
    83
          let
haftmann@31874
    84
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
    85
            val (ps, vars') = fold_map (print_bind tyvars some_thm BR o fst) binds vars;
haftmann@35228
    86
          in brackets (str "\\" :: ps @ str "->" @@ print_term tyvars some_thm vars' NOBR t') end
haftmann@48072
    87
      | print_term tyvars some_thm vars fxy (ICase case_expr) =
haftmann@48072
    88
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55150
    89
           of SOME (app as ({ sym = Constant const, ... }, _)) =>
haftmann@55147
    90
                if is_none (const_syntax const)
haftmann@48072
    91
                then print_case tyvars some_thm vars fxy case_expr
haftmann@48072
    92
                else print_app tyvars some_thm vars fxy app
haftmann@48072
    93
            | NONE => print_case tyvars some_thm vars fxy case_expr)
haftmann@58397
    94
    and print_app_expr tyvars some_thm vars ({ sym, annotation, ... }, ts) =
bulwahn@44792
    95
      let
bulwahn@45009
    96
        val printed_const =
haftmann@58397
    97
          case annotation of
haftmann@58397
    98
            SOME ty => brackets [(str o deresolve) sym, str "::", print_typ tyvars NOBR ty]
haftmann@58397
    99
          | NONE => (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@55150
   129
    fun print_stmt (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@55150
   166
      | print_stmt (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@55150
   175
      | print_stmt (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@55374
   185
              :: (if deriving_show tyco then [str "deriving (Prelude.Read, Prelude.Show)"] else [])
haftmann@28054
   186
            )
haftmann@28054
   187
          end
haftmann@55150
   188
      | print_stmt (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@55374
   203
              @ (if deriving_show tyco then [str "deriving (Prelude.Read, Prelude.Show)"] else [])
haftmann@28054
   204
            )
haftmann@28054
   205
          end
haftmann@55150
   206
      | print_stmt (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@52519
   229
            fun print_classparam_instance ((classparam, (const, _)), (thm, _)) =
haftmann@55373
   230
              case const_syntax classparam of
haftmann@55373
   231
                NONE => semicolon [
haftmann@55373
   232
                    (str o Long_Name.base_name o deresolve_const) classparam,
haftmann@55373
   233
                    str "=",
haftmann@55373
   234
                    print_app tyvars (SOME thm) reserved NOBR (const, [])
haftmann@55373
   235
                  ]
haftmann@55373
   236
              | SOME (_, Code_Printer.Plain_printer s) => semicolon [
haftmann@55373
   237
                    (str o Long_Name.base_name) s,
haftmann@55373
   238
                    str "=",
haftmann@55373
   239
                    print_app tyvars (SOME thm) reserved NOBR (const, [])
haftmann@55373
   240
                  ]
haftmann@55373
   241
              | SOME (k, Code_Printer.Complex_printer _) =>
haftmann@55373
   242
                  let
haftmann@58397
   243
                    val { sym = Constant c, dom, ... } = const;
haftmann@55373
   244
                    val (vs, rhs) = (apfst o map) fst
haftmann@55373
   245
                      (Code_Thingol.unfold_abs (Code_Thingol.eta_expand k (const, [])));
haftmann@55373
   246
                    val s = if (is_some o const_syntax) c
haftmann@55373
   247
                      then NONE else (SOME o Long_Name.base_name o deresolve_const) c;
haftmann@55373
   248
                    val vars = reserved
haftmann@55373
   249
                      |> intro_vars (map_filter I (s :: vs));
haftmann@55373
   250
                    val lhs = IConst { sym = Constant classparam, typargs = [],
haftmann@58397
   251
                      dicts = [], dom = dom, annotation = NONE } `$$ map IVar vs;
haftmann@55373
   252
                      (*dictionaries are not relevant at this late stage,
haftmann@55373
   253
                        and these consts never need type annotations for disambiguation *)
haftmann@55373
   254
                  in
haftmann@55373
   255
                    semicolon [
haftmann@55373
   256
                      print_term tyvars (SOME thm) vars NOBR lhs,
haftmann@28687
   257
                      str "=",
haftmann@55373
   258
                      print_term tyvars (SOME thm) vars NOBR rhs
haftmann@28687
   259
                    ]
haftmann@55373
   260
                  end;
haftmann@28054
   261
          in
haftmann@28054
   262
            Pretty.block_enclose (
haftmann@28054
   263
              Pretty.block [
haftmann@28054
   264
                str "instance ",
haftmann@33991
   265
                Pretty.block (print_typcontext tyvars vs),
haftmann@28054
   266
                str (class_name class ^ " "),
haftmann@33991
   267
                print_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@28054
   268
                str " where {"
haftmann@28054
   269
              ],
haftmann@28054
   270
              str "};"
haftmann@48072
   271
            ) (map print_classparam_instance inst_params)
haftmann@28054
   272
          end;
haftmann@33991
   273
  in print_stmt end;
haftmann@28054
   274
haftmann@55147
   275
fun haskell_program_of_program ctxt module_prefix module_name reserved identifiers =
haftmann@39202
   276
  let
haftmann@39202
   277
    fun namify_fun upper base (nsp_fun, nsp_typ) =
haftmann@39202
   278
      let
haftmann@56826
   279
        val (base', nsp_fun') = Name.variant (Name.enforce_case upper 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
haftmann@56812
   283
        val (base', nsp_typ') = Name.variant (Name.enforce_case true 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@55683
   330
    reserved_syms, identifiers, includes, class_syntax, tyco_syntax, const_syntax } exports 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@55683
   336
      ctxt module_prefix module_name (Name.make_context reserved) identifiers exports 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@55150
   343
              orelse case try (Code_Symbol.Graph.get_node program) (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@55679
   356
    fun print_module_frame module_name exports ps =
haftmann@39204
   357
      (module_name, Pretty.chunks2 (
haftmann@55679
   358
        concat [str "module",
haftmann@55679
   359
          case exports of
haftmann@55679
   360
            SOME ps => Pretty.block [str module_name, enclose "(" ")" (commas ps)]
haftmann@55679
   361
          | NONE => str module_name,
haftmann@55679
   362
          str "where {"
haftmann@55679
   363
        ]
haftmann@39204
   364
        :: ps
haftmann@39204
   365
        @| str "}"
haftmann@39204
   366
      ));
haftmann@55679
   367
    fun print_qualified_import module_name =
haftmann@55679
   368
      semicolon [str "import qualified", str module_name];
haftmann@48431
   369
    val import_common_ps =
haftmann@48431
   370
      enclose "import Prelude (" ");" (commas (map str
haftmann@48431
   371
        (map (Library.enclose "(" ")") prelude_import_operators @ prelude_import_unqualified)
haftmann@48431
   372
          @ map (fn (tyco, constrs) => (enclose (tyco ^ "(") ")" o commas o map str) constrs) prelude_import_unqualified_constr))
haftmann@48431
   373
      :: print_qualified_import "Prelude"
haftmann@48431
   374
      :: map (print_qualified_import o fst) includes;
haftmann@39204
   375
    fun print_module module_name (gr, imports) =
haftmann@28054
   376
      let
haftmann@48431
   377
        val deresolve = deresolver module_name;
haftmann@55679
   378
        val deresolve_import = SOME o str o deresolve;
haftmann@55679
   379
        val deresolve_import_attached = SOME o str o suffix "(..)" o deresolve;
haftmann@55681
   380
        fun print_import (sym, (_, Code_Thingol.Fun _)) = deresolve_import sym
haftmann@55681
   381
          | print_import (sym, (Code_Namespace.Public, Code_Thingol.Datatype _)) = deresolve_import_attached sym
haftmann@55681
   382
          | print_import (sym, (Code_Namespace.Opaque, Code_Thingol.Datatype _)) = deresolve_import sym
haftmann@55681
   383
          | print_import (sym, (Code_Namespace.Public, Code_Thingol.Class _)) = deresolve_import_attached sym
haftmann@55681
   384
          | print_import (sym, (Code_Namespace.Opaque, Code_Thingol.Class _)) = deresolve_import sym
haftmann@55681
   385
          | print_import (sym, (_, Code_Thingol.Classinst _)) = NONE;
haftmann@48431
   386
        val import_ps = import_common_ps @ map (print_qualified_import o fst) imports;
haftmann@55147
   387
        fun print_stmt' sym = case Code_Symbol.Graph.get_node gr sym
haftmann@39204
   388
         of (_, NONE) => NONE
haftmann@55679
   389
          | (_, SOME (export, stmt)) =>
haftmann@55681
   390
              SOME (if Code_Namespace.not_private export then print_import (sym, (export, stmt)) else NONE, markup_stmt sym (print_stmt deresolve (sym, stmt)));
haftmann@55679
   391
        val (export_ps, body_ps) = (flat o rev o Code_Symbol.Graph.strong_conn) gr
haftmann@55679
   392
          |> map_filter print_stmt'
haftmann@55679
   393
          |> split_list
haftmann@55679
   394
          |> apfst (map_filter I);
haftmann@39204
   395
      in
haftmann@55679
   396
        print_module_frame module_name (SOME export_ps)
haftmann@39204
   397
          ((if null import_ps then [] else [Pretty.chunks import_ps]) @ body_ps)
haftmann@39204
   398
      end;
haftmann@39204
   399
haftmann@39204
   400
    (*serialization*)
haftmann@39204
   401
    fun write_module width (SOME destination) (module_name, content) =
haftmann@38915
   402
          let
wenzelm@42003
   403
            val _ = File.check_dir destination;
haftmann@39204
   404
            val filepath = (Path.append destination o Path.ext "hs" o Path.explode o implode
haftmann@39204
   405
              o separate "/" o Long_Name.explode) module_name;
haftmann@41246
   406
            val _ = Isabelle_System.mkdirs (Path.dir filepath);
haftmann@39209
   407
          in
haftmann@39209
   408
            (File.write filepath o format [] width o Pretty.chunks2)
noschinl@44926
   409
              [str language_pragma, content]
haftmann@39209
   410
          end
haftmann@39056
   411
      | write_module width NONE (_, content) = writeln (format [] width content);
haftmann@28054
   412
  in
haftmann@38916
   413
    Code_Target.serialization
haftmann@38915
   414
      (fn width => fn destination => K () o map (write_module width destination))
haftmann@40705
   415
      (fn present => fn width => rpair (try (deresolver ""))
haftmann@48568
   416
        o (map o apsnd) (format present width))
haftmann@55679
   417
      (map (fn (module_name, content) => print_module_frame module_name NONE [content]) includes
haftmann@39204
   418
        @ map (fn module_name => print_module module_name (Graph.get_node haskell_program module_name))
haftmann@39204
   419
          ((flat o rev o Graph.strong_conn) haskell_program))
haftmann@28054
   420
  end;
haftmann@28054
   421
haftmann@38966
   422
val serializer : Code_Target.serializer =
haftmann@39206
   423
  Code_Target.parse_args (Scan.optional (Args.$$$ "root" -- Args.colon |-- Args.name) ""
haftmann@38966
   424
    -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@38966
   425
    >> (fn (module_prefix, string_classes) =>
haftmann@38966
   426
      serialize_haskell module_prefix string_classes));
haftmann@38966
   427
haftmann@58400
   428
fun print_numeral typ = Library.enclose "(" (" :: " ^ typ ^ ")") o signed_string_of_int;
haftmann@58400
   429
haftmann@28064
   430
val literals = let
haftmann@28064
   431
  fun char_haskell c =
haftmann@28064
   432
    let
haftmann@28064
   433
      val s = ML_Syntax.print_char c;
haftmann@28064
   434
    in if s = "'" then "\\'" else s end;
haftmann@28064
   435
in Literals {
haftmann@34178
   436
  literal_char = Library.enclose "'" "'" o char_haskell,
haftmann@28064
   437
  literal_string = quote o translate_string char_haskell,
haftmann@58400
   438
  literal_numeral = print_numeral "Integer",
haftmann@34178
   439
  literal_list = enum "," "[" "]",
haftmann@28064
   440
  infix_cons = (5, ":")
haftmann@28064
   441
} end;
haftmann@28064
   442
haftmann@28054
   443
haftmann@28054
   444
(** optional monad syntax **)
haftmann@28054
   445
haftmann@28054
   446
fun pretty_haskell_monad c_bind =
haftmann@28054
   447
  let
haftmann@31874
   448
    fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2
haftmann@31889
   449
     of SOME ((pat, ty), t') =>
haftmann@31889
   450
          SOME ((SOME ((pat, ty), true), t1), t')
haftmann@28145
   451
      | NONE => NONE;
haftmann@55150
   452
    fun dest_monad (IConst { sym = Constant c, ... } `$ t1 `$ t2) =
haftmann@55148
   453
          if c = c_bind then dest_bind t1 t2
haftmann@28145
   454
          else NONE
haftmann@55148
   455
      | dest_monad t = case Code_Thingol.split_let t
haftmann@28145
   456
         of SOME (((pat, ty), tbind), t') =>
haftmann@31889
   457
              SOME ((SOME ((pat, ty), false), tbind), t')
haftmann@28145
   458
          | NONE => NONE;
haftmann@55148
   459
    val implode_monad = Code_Thingol.unfoldr dest_monad;
haftmann@33991
   460
    fun print_monad print_bind print_term (NONE, t) vars =
haftmann@33991
   461
          (semicolon [print_term vars NOBR t], vars)
haftmann@33991
   462
      | print_monad print_bind print_term (SOME ((bind, _), true), t) vars = vars
haftmann@33991
   463
          |> print_bind NOBR bind
haftmann@33991
   464
          |>> (fn p => semicolon [p, str "<-", print_term vars NOBR t])
haftmann@33991
   465
      | print_monad print_bind print_term (SOME ((bind, _), false), t) vars = vars
haftmann@33991
   466
          |> print_bind NOBR bind
haftmann@37832
   467
          |>> (fn p => semicolon [str "let", str "{", p, str "=", print_term vars NOBR t, str "}"]);
haftmann@55148
   468
    fun pretty _ print_term thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
haftmann@28145
   469
     of SOME (bind, t') => let
haftmann@55148
   470
          val (binds, t'') = implode_monad t'
haftmann@33991
   471
          val (ps, vars') = fold_map (print_monad (gen_print_bind (K print_term) thm) print_term)
haftmann@33991
   472
            (bind :: binds) vars;
haftmann@33991
   473
        in
haftmann@37833
   474
          (brackify fxy o single o enclose "do { " " }" o Pretty.breaks)
haftmann@33991
   475
            (ps @| print_term vars' NOBR t'')
haftmann@33991
   476
        end
haftmann@28145
   477
      | NONE => brackify_infix (1, L) fxy
haftmann@37242
   478
          (print_term vars (INFX (1, L)) t1, str ">>=", print_term vars (INFX (1, X)) t2)
haftmann@55148
   479
  in (2, pretty) end;
haftmann@28054
   480
haftmann@28145
   481
fun add_monad target' raw_c_bind thy =
haftmann@28054
   482
  let
haftmann@31156
   483
    val c_bind = Code.read_const thy raw_c_bind;
wenzelm@52801
   484
  in
wenzelm@52801
   485
    if target = target' then
wenzelm@52801
   486
      thy
haftmann@55150
   487
      |> Code_Target.set_printings (Constant (c_bind, [(target,
wenzelm@52801
   488
        SOME (Code_Printer.complex_const_syntax (pretty_haskell_monad c_bind)))]))
wenzelm@52801
   489
    else error "Only Haskell target allows for monad syntax"
wenzelm@52801
   490
  end;
haftmann@28054
   491
haftmann@28054
   492
haftmann@28054
   493
(** Isar setup **)
haftmann@28054
   494
haftmann@28054
   495
val _ =
wenzelm@46961
   496
  Outer_Syntax.command @{command_spec "code_monad"} "define code syntax for monads"
wenzelm@52801
   497
    (Parse.term -- Parse.name >> (fn (raw_bind, target) =>
wenzelm@52801
   498
      Toplevel.theory (add_monad target raw_bind)));
haftmann@28054
   499
haftmann@28054
   500
val setup =
haftmann@37821
   501
  Code_Target.add_target
haftmann@38966
   502
    (target, { serializer = serializer, literals = literals,
wenzelm@41952
   503
      check = { env_var = "ISABELLE_GHC", make_destination = I,
wenzelm@41940
   504
        make_command = fn module_name =>
noschinl@44926
   505
          "\"$ISABELLE_GHC\" " ^ language_params  ^ " -odir build -hidir build -stubdir build -e \"\" " ^
wenzelm@41940
   506
            module_name ^ ".hs" } })
haftmann@55150
   507
  #> Code_Target.set_printings (Type_Constructor ("fun",
haftmann@52435
   508
    [(target, SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   509
      brackify_infix (1, R) fxy (
haftmann@33991
   510
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   511
        str "->",
haftmann@33991
   512
        print_typ (INFX (1, R)) ty2
haftmann@52435
   513
      )))]))
haftmann@28054
   514
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   515
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@28054
   516
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@28054
   517
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@28054
   518
    ]
haftmann@48431
   519
  #> fold (Code_Target.add_reserved target) prelude_import_unqualified
haftmann@48431
   520
  #> fold (Code_Target.add_reserved target o fst) prelude_import_unqualified_constr
haftmann@48431
   521
  #> fold (fold (Code_Target.add_reserved target) o snd) prelude_import_unqualified_constr;
haftmann@28054
   522
haftmann@28054
   523
end; (*struct*)