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