src/Tools/Code/code_haskell.ML
author haftmann
Tue Jun 05 07:05:56 2012 +0200 (2012-06-05)
changeset 48072 ace701efe203
parent 48003 1d11af40b106
child 48431 6efff142bb54
permissions -rw-r--r--
prefer records with speaking labels over deeply nested tuples
haftmann@37745
     1
(*  Title:      Tools/Code/code_haskell.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@28054
     4
Serializer for Haskell.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@28054
     7
signature CODE_HASKELL =
haftmann@28054
     8
sig
noschinl@44926
     9
  val language_params: string
haftmann@37745
    10
  val target: string
haftmann@28054
    11
  val setup: theory -> theory
haftmann@28054
    12
end;
haftmann@28054
    13
haftmann@28054
    14
structure Code_Haskell : CODE_HASKELL =
haftmann@28054
    15
struct
haftmann@28054
    16
haftmann@28054
    17
val target = "Haskell";
haftmann@28054
    18
noschinl@44926
    19
val language_extensions =
noschinl@44940
    20
  ["EmptyDataDecls", "RankNTypes", "ScopedTypeVariables"];
noschinl@44926
    21
noschinl@44926
    22
val language_pragma =
noschinl@44940
    23
  "{-# LANGUAGE " ^ commas language_extensions ^ " #-}";
noschinl@44926
    24
noschinl@44926
    25
val language_params =
noschinl@44940
    26
  space_implode " " (map (prefix "-X") language_extensions);
noschinl@44926
    27
haftmann@28054
    28
open Basic_Code_Thingol;
haftmann@28054
    29
open Code_Printer;
haftmann@28054
    30
haftmann@28054
    31
infixr 5 @@;
haftmann@28054
    32
infixr 5 @|;
haftmann@28054
    33
haftmann@28054
    34
haftmann@28054
    35
(** Haskell serializer **)
haftmann@28054
    36
haftmann@47609
    37
fun print_haskell_stmt class_syntax tyco_syntax const_syntax
bulwahn@44793
    38
    reserved deresolve deriving_show =
haftmann@28054
    39
  let
haftmann@38923
    40
    fun class_name class = case class_syntax class
haftmann@28054
    41
     of NONE => deresolve class
haftmann@28687
    42
      | SOME class => class;
haftmann@33991
    43
    fun print_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@28054
    44
     of [] => []
haftmann@37384
    45
      | constraints => enum "," "(" ")" (
haftmann@28054
    46
          map (fn (v, class) =>
haftmann@37384
    47
            str (class_name class ^ " " ^ lookup_var tyvars v)) constraints)
haftmann@28054
    48
          @@ str " => ";
haftmann@33991
    49
    fun print_typforall tyvars vs = case map fst vs
haftmann@28054
    50
     of [] => []
haftmann@28054
    51
      | vnames => str "forall " :: Pretty.breaks
haftmann@32924
    52
          (map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
haftmann@33991
    53
    fun print_tyco_expr tyvars fxy (tyco, tys) =
haftmann@33991
    54
      brackify fxy (str tyco :: map (print_typ tyvars BR) tys)
haftmann@47609
    55
    and print_typ tyvars fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@33991
    56
         of NONE => print_tyco_expr tyvars fxy (deresolve tyco, tys)
haftmann@47609
    57
          | SOME (_, print) => print (print_typ tyvars) fxy tys)
haftmann@33991
    58
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@48003
    59
    fun print_typdecl tyvars (tyco, vs) =
haftmann@48003
    60
      print_tyco_expr tyvars NOBR (tyco, map ITyVar vs);
haftmann@33991
    61
    fun print_typscheme tyvars (vs, ty) =
haftmann@33991
    62
      Pretty.block (print_typforall tyvars vs @ print_typcontext tyvars vs @| print_typ tyvars NOBR ty);
haftmann@48072
    63
    fun print_term tyvars some_thm vars fxy (IConst const) =
haftmann@48072
    64
          print_app tyvars some_thm vars fxy (const, [])
haftmann@35228
    65
      | print_term tyvars some_thm vars fxy (t as (t1 `$ t2)) =
haftmann@28054
    66
          (case Code_Thingol.unfold_const_app t
haftmann@35228
    67
           of SOME app => print_app tyvars some_thm vars fxy app
haftmann@28054
    68
            | _ =>
haftmann@28054
    69
                brackify fxy [
haftmann@35228
    70
                  print_term tyvars some_thm vars NOBR t1,
haftmann@35228
    71
                  print_term tyvars some_thm vars BR t2
haftmann@28054
    72
                ])
haftmann@35228
    73
      | print_term tyvars some_thm vars fxy (IVar NONE) =
haftmann@31889
    74
          str "_"
haftmann@35228
    75
      | print_term tyvars some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
    76
          (str o lookup_var vars) v
haftmann@35228
    77
      | print_term tyvars some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
    78
          let
haftmann@31874
    79
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
    80
            val (ps, vars') = fold_map (print_bind tyvars some_thm BR o fst) binds vars;
haftmann@35228
    81
          in brackets (str "\\" :: ps @ str "->" @@ print_term tyvars some_thm vars' NOBR t') end
haftmann@48072
    82
      | print_term tyvars some_thm vars fxy (ICase case_expr) =
haftmann@48072
    83
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@48072
    84
           of SOME (app as ({ name = c, ... }, _)) => if is_none (const_syntax c)
haftmann@48072
    85
                then print_case tyvars some_thm vars fxy case_expr
haftmann@48072
    86
                else print_app tyvars some_thm vars fxy app
haftmann@48072
    87
            | NONE => print_case tyvars some_thm vars fxy case_expr)
haftmann@48072
    88
    and print_app_expr tyvars some_thm vars ({ name = c, dom, range, annotate, ... }, ts) =
bulwahn@44792
    89
      let
haftmann@48072
    90
        val ty = Library.foldr (fn (ty1, ty2) => Code_Thingol.fun_tyco `%% [ty1, ty2]) (dom, range)
bulwahn@45009
    91
        val printed_const =
bulwahn@45009
    92
          if annotate then
bulwahn@45009
    93
            brackets [(str o deresolve) c, str "::", print_typ tyvars NOBR ty]
bulwahn@45009
    94
          else
bulwahn@45009
    95
            (str o deresolve) c
bulwahn@44792
    96
      in 
bulwahn@45009
    97
        printed_const :: map (print_term tyvars some_thm vars BR) ts
bulwahn@44792
    98
      end
haftmann@38923
    99
    and print_app tyvars = gen_print_app (print_app_expr tyvars) (print_term tyvars) const_syntax
haftmann@35228
   100
    and print_bind tyvars some_thm fxy p = gen_print_bind (print_term tyvars) some_thm fxy p
haftmann@48072
   101
    and print_case tyvars some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   102
          (brackify fxy o Pretty.breaks o map str) ["error", "\"empty case\""]
haftmann@48072
   103
      | print_case tyvars some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   104
          let
haftmann@48072
   105
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47609
   106
            fun print_match ((pat, _), t) vars =
haftmann@28054
   107
              vars
haftmann@35228
   108
              |> print_bind tyvars some_thm BR pat
haftmann@35228
   109
              |>> (fn p => semicolon [p, str "=", print_term tyvars some_thm vars NOBR t])
haftmann@33991
   110
            val (ps, vars') = fold_map print_match binds vars;
haftmann@31665
   111
          in brackify_block fxy (str "let {")
haftmann@31665
   112
            ps
haftmann@35228
   113
            (concat [str "}", str "in", print_term tyvars some_thm vars' NOBR body])
haftmann@28054
   114
          end
haftmann@48072
   115
      | print_case tyvars some_thm vars fxy { term = t, typ = ty, clauses = clauses as _ :: _, ... } =
haftmann@28054
   116
          let
haftmann@33991
   117
            fun print_select (pat, body) =
haftmann@28054
   118
              let
haftmann@35228
   119
                val (p, vars') = print_bind tyvars some_thm NOBR pat vars;
haftmann@35228
   120
              in semicolon [p, str "->", print_term tyvars some_thm vars' NOBR body] end;
haftmann@36576
   121
          in Pretty.block_enclose
haftmann@36576
   122
            (concat [str "(case", print_term tyvars some_thm vars NOBR t, str "of", str "{"], str "})")
haftmann@33991
   123
            (map print_select clauses)
haftmann@48072
   124
          end;
haftmann@37437
   125
    fun print_stmt (name, Code_Thingol.Fun (_, (((vs, ty), raw_eqs), _))) =
haftmann@28054
   126
          let
haftmann@32924
   127
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@34269
   128
            fun print_err n =
haftmann@33991
   129
              semicolon (
haftmann@39207
   130
                (str o deresolve) 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@34269
   136
              );
haftmann@35228
   137
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   138
              let
haftmann@32913
   139
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   140
                val vars = reserved
haftmann@32924
   141
                  |> intro_base_names
haftmann@38923
   142
                      (is_none o const_syntax) deresolve consts
haftmann@32924
   143
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@32925
   144
                      (insert (op =)) ts []);
haftmann@28054
   145
              in
haftmann@28054
   146
                semicolon (
haftmann@39207
   147
                  (str o deresolve) name
haftmann@35228
   148
                  :: map (print_term tyvars some_thm vars BR) ts
haftmann@28054
   149
                  @ str "="
haftmann@35228
   150
                  @@ print_term tyvars some_thm vars NOBR t
haftmann@28054
   151
                )
haftmann@28054
   152
              end;
haftmann@28054
   153
          in
haftmann@28054
   154
            Pretty.chunks (
haftmann@33991
   155
              semicolon [
haftmann@39207
   156
                (str o suffix " ::" o deresolve) name,
haftmann@33991
   157
                print_typscheme tyvars (vs, ty)
haftmann@28054
   158
              ]
haftmann@34269
   159
              :: (case filter (snd o snd) raw_eqs
haftmann@34269
   160
               of [] => [print_err ((length o fst o Code_Thingol.unfold_fun) ty)]
haftmann@34269
   161
                | eqs => map print_eqn eqs)
haftmann@28054
   162
            )
haftmann@28054
   163
          end
haftmann@33991
   164
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, []))) =
haftmann@28054
   165
          let
haftmann@48003
   166
            val tyvars = intro_vars vs reserved;
haftmann@28054
   167
          in
haftmann@28054
   168
            semicolon [
haftmann@28054
   169
              str "data",
haftmann@48003
   170
              print_typdecl tyvars (deresolve name, vs)
haftmann@28054
   171
            ]
haftmann@28054
   172
          end
haftmann@37449
   173
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, [((co, _), [ty])]))) =
haftmann@28054
   174
          let
haftmann@48003
   175
            val tyvars = intro_vars vs reserved;
haftmann@28054
   176
          in
haftmann@28054
   177
            semicolon (
haftmann@28054
   178
              str "newtype"
haftmann@48003
   179
              :: print_typdecl tyvars (deresolve name, vs)
haftmann@28054
   180
              :: str "="
haftmann@39207
   181
              :: (str o deresolve) co
haftmann@33991
   182
              :: print_typ tyvars BR ty
haftmann@28054
   183
              :: (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   184
            )
haftmann@28054
   185
          end
haftmann@33991
   186
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, co :: cos))) =
haftmann@28054
   187
          let
haftmann@48003
   188
            val tyvars = intro_vars vs reserved;
haftmann@37449
   189
            fun print_co ((co, _), tys) =
haftmann@28054
   190
              concat (
haftmann@39207
   191
                (str o deresolve) co
haftmann@33991
   192
                :: map (print_typ tyvars BR) tys
haftmann@28054
   193
              )
haftmann@28054
   194
          in
haftmann@28054
   195
            semicolon (
haftmann@28054
   196
              str "data"
haftmann@48003
   197
              :: print_typdecl tyvars (deresolve name, vs)
haftmann@28054
   198
              :: str "="
haftmann@33991
   199
              :: print_co co
haftmann@33991
   200
              :: map ((fn p => Pretty.block [str "| ", p]) o print_co) cos
haftmann@28054
   201
              @ (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   202
            )
haftmann@28054
   203
          end
haftmann@37447
   204
      | print_stmt (name, Code_Thingol.Class (_, (v, (super_classes, classparams)))) =
haftmann@28054
   205
          let
haftmann@32924
   206
            val tyvars = intro_vars [v] reserved;
haftmann@33991
   207
            fun print_classparam (classparam, ty) =
haftmann@28054
   208
              semicolon [
haftmann@39207
   209
                (str o deresolve) classparam,
haftmann@28054
   210
                str "::",
haftmann@33991
   211
                print_typ tyvars NOBR ty
haftmann@28054
   212
              ]
haftmann@28054
   213
          in
haftmann@28054
   214
            Pretty.block_enclose (
haftmann@28054
   215
              Pretty.block [
haftmann@28054
   216
                str "class ",
haftmann@37384
   217
                Pretty.block (print_typcontext tyvars [(v, map fst super_classes)]),
haftmann@39207
   218
                str (deresolve name ^ " " ^ lookup_var tyvars v),
haftmann@28054
   219
                str " where {"
haftmann@28054
   220
              ],
haftmann@28054
   221
              str "};"
haftmann@33991
   222
            ) (map print_classparam classparams)
haftmann@28054
   223
          end
haftmann@48072
   224
      | print_stmt (_, Code_Thingol.Classinst { class, tyco, vs, inst_params, ... }) =
haftmann@28054
   225
          let
haftmann@32924
   226
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@38923
   227
            fun requires_args classparam = case const_syntax classparam
haftmann@39207
   228
             of NONE => NONE
haftmann@39207
   229
              | SOME (Code_Printer.Plain_const_syntax _) => SOME 0
haftmann@39207
   230
              | SOME (Code_Printer.Complex_const_syntax (k,_ )) => SOME k;
haftmann@37881
   231
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@37881
   232
              case requires_args classparam
haftmann@39207
   233
               of NONE => semicolon [
haftmann@39207
   234
                      (str o Long_Name.base_name o deresolve) classparam,
haftmann@28687
   235
                      str "=",
haftmann@37881
   236
                      print_app tyvars (SOME thm) reserved NOBR (const, [])
haftmann@28687
   237
                    ]
haftmann@39207
   238
                | SOME k =>
haftmann@37881
   239
                    let
haftmann@48072
   240
                      val { name = c, dom, range, ... } = const;
haftmann@37881
   241
                      val (vs, rhs) = (apfst o map) fst
haftmann@37881
   242
                        (Code_Thingol.unfold_abs (Code_Thingol.eta_expand k (const, [])));
haftmann@38923
   243
                      val s = if (is_some o const_syntax) c
haftmann@37881
   244
                        then NONE else (SOME o Long_Name.base_name o deresolve) c;
haftmann@37881
   245
                      val vars = reserved
haftmann@37881
   246
                        |> intro_vars (map_filter I (s :: vs));
haftmann@48072
   247
                      val lhs = IConst { name = classparam, typargs = [],
haftmann@48072
   248
                        dicts = [], dom = dom, range = range, annotate = false } `$$ map IVar vs;
bulwahn@45009
   249
                        (*dictionaries are not relevant at this late stage,
bulwahn@45009
   250
                          and these consts never need type annotations for disambiguation *)
haftmann@37881
   251
                    in
haftmann@37881
   252
                      semicolon [
haftmann@37881
   253
                        print_term tyvars (SOME thm) vars NOBR lhs,
haftmann@37881
   254
                        str "=",
haftmann@37881
   255
                        print_term tyvars (SOME thm) vars NOBR rhs
haftmann@37881
   256
                      ]
haftmann@37881
   257
                    end;
haftmann@28054
   258
          in
haftmann@28054
   259
            Pretty.block_enclose (
haftmann@28054
   260
              Pretty.block [
haftmann@28054
   261
                str "instance ",
haftmann@33991
   262
                Pretty.block (print_typcontext tyvars vs),
haftmann@28054
   263
                str (class_name class ^ " "),
haftmann@33991
   264
                print_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@28054
   265
                str " where {"
haftmann@28054
   266
              ],
haftmann@28054
   267
              str "};"
haftmann@48072
   268
            ) (map print_classparam_instance inst_params)
haftmann@28054
   269
          end;
haftmann@33991
   270
  in print_stmt end;
haftmann@28054
   271
haftmann@39202
   272
fun haskell_program_of_program labelled_name module_alias module_prefix reserved =
haftmann@39202
   273
  let
haftmann@39202
   274
    fun namify_fun upper base (nsp_fun, nsp_typ) =
haftmann@39202
   275
      let
wenzelm@43326
   276
        val (base', nsp_fun') =
wenzelm@43326
   277
          Name.variant (if upper then first_upper base else base) nsp_fun;
haftmann@39202
   278
      in (base', (nsp_fun', nsp_typ)) end;
haftmann@39202
   279
    fun namify_typ base (nsp_fun, nsp_typ) =
haftmann@39202
   280
      let
wenzelm@43326
   281
        val (base', nsp_typ') = Name.variant (first_upper base) nsp_typ;
haftmann@39202
   282
      in (base', (nsp_fun, nsp_typ')) end;
haftmann@39202
   283
    fun namify_stmt (Code_Thingol.Fun (_, (_, SOME _))) = pair
haftmann@39202
   284
      | namify_stmt (Code_Thingol.Fun _) = namify_fun false
haftmann@39202
   285
      | namify_stmt (Code_Thingol.Datatype _) = namify_typ
haftmann@39202
   286
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_fun true
haftmann@39202
   287
      | namify_stmt (Code_Thingol.Class _) = namify_typ
haftmann@39202
   288
      | namify_stmt (Code_Thingol.Classrel _) = pair
haftmann@39202
   289
      | namify_stmt (Code_Thingol.Classparam _) = namify_fun false
haftmann@39202
   290
      | namify_stmt (Code_Thingol.Classinst _) = pair;
haftmann@39202
   291
    fun select_stmt (Code_Thingol.Fun (_, (_, SOME _))) = false
haftmann@39202
   292
      | select_stmt (Code_Thingol.Fun _) = true
haftmann@39202
   293
      | select_stmt (Code_Thingol.Datatype _) = true
haftmann@39202
   294
      | select_stmt (Code_Thingol.Datatypecons _) = false
haftmann@39202
   295
      | select_stmt (Code_Thingol.Class _) = true
haftmann@39202
   296
      | select_stmt (Code_Thingol.Classrel _) = false
haftmann@39202
   297
      | select_stmt (Code_Thingol.Classparam _) = false
haftmann@39202
   298
      | select_stmt (Code_Thingol.Classinst _) = true;
haftmann@39202
   299
  in
haftmann@39206
   300
    Code_Namespace.flat_program labelled_name
haftmann@39202
   301
      { module_alias = module_alias, module_prefix = module_prefix,
haftmann@39202
   302
        reserved = reserved, empty_nsp = (reserved, reserved), namify_stmt = namify_stmt,
haftmann@39202
   303
        modify_stmt = fn stmt => if select_stmt stmt then SOME stmt else NONE }
haftmann@39202
   304
  end;
haftmann@39202
   305
haftmann@39142
   306
fun serialize_haskell module_prefix string_classes { labelled_name, reserved_syms,
haftmann@41343
   307
    includes, module_alias, class_syntax, tyco_syntax, const_syntax } program =
haftmann@28054
   308
  let
haftmann@39204
   309
haftmann@39204
   310
    (* build program *)
haftmann@38926
   311
    val reserved = fold (insert (op =) o fst) includes reserved_syms;
haftmann@39204
   312
    val { deresolver, flat_program = haskell_program } = haskell_program_of_program
haftmann@39204
   313
      labelled_name module_alias module_prefix (Name.make_context reserved) program;
haftmann@39204
   314
haftmann@39204
   315
    (* print statements *)
haftmann@28054
   316
    fun deriving_show tyco =
haftmann@28054
   317
      let
haftmann@28054
   318
        fun deriv _ "fun" = false
haftmann@34085
   319
          | deriv tycos tyco = not (tyco = Code_Thingol.fun_tyco)
haftmann@34085
   320
              andalso (member (op =) tycos tyco
haftmann@34085
   321
              orelse case try (Graph.get_node program) tyco
haftmann@28663
   322
                of SOME (Code_Thingol.Datatype (_, (_, cs))) => forall (deriv' (tyco :: tycos))
haftmann@28054
   323
                    (maps snd cs)
haftmann@34085
   324
                 | NONE => true)
haftmann@28054
   325
        and deriv' tycos (tyco `%% tys) = deriv tycos tyco
haftmann@28054
   326
              andalso forall (deriv' tycos) tys
haftmann@28054
   327
          | deriv' _ (ITyVar _) = true
haftmann@28054
   328
      in deriv [] tyco end;
haftmann@47609
   329
    fun print_stmt deresolve = print_haskell_stmt
haftmann@39204
   330
      class_syntax tyco_syntax const_syntax (make_vars reserved)
bulwahn@45009
   331
      deresolve (if string_classes then deriving_show else K false);
haftmann@39204
   332
haftmann@39204
   333
    (* print modules *)
haftmann@39204
   334
    val import_includes_ps =
haftmann@39204
   335
      map (fn (name, _) => str ("import qualified " ^ name ^ ";")) includes;
haftmann@39204
   336
    fun print_module_frame module_name ps =
haftmann@39204
   337
      (module_name, Pretty.chunks2 (
haftmann@39209
   338
        str ("module " ^ module_name ^ " where {")
haftmann@39204
   339
        :: ps
haftmann@39204
   340
        @| str "}"
haftmann@39204
   341
      ));
haftmann@39204
   342
    fun print_module module_name (gr, imports) =
haftmann@28054
   343
      let
haftmann@39204
   344
        val deresolve = deresolver module_name
haftmann@39204
   345
        fun print_import module_name = (semicolon o map str) ["import qualified", module_name];
haftmann@39204
   346
        val import_ps = import_includes_ps @ map (print_import o fst) imports;
haftmann@39204
   347
        fun print_stmt' gr name = case Graph.get_node gr name
haftmann@39204
   348
         of (_, NONE) => NONE
haftmann@39204
   349
          | (_, SOME stmt) => SOME (markup_stmt name (print_stmt deresolve (name, stmt)));
haftmann@39204
   350
        val body_ps = map_filter (print_stmt' gr) ((flat o rev o Graph.strong_conn) gr);
haftmann@39204
   351
      in
haftmann@39204
   352
        print_module_frame module_name
haftmann@39204
   353
          ((if null import_ps then [] else [Pretty.chunks import_ps]) @ body_ps)
haftmann@39204
   354
      end;
haftmann@39204
   355
haftmann@39204
   356
    (*serialization*)
haftmann@39204
   357
    fun write_module width (SOME destination) (module_name, content) =
haftmann@38915
   358
          let
wenzelm@42003
   359
            val _ = File.check_dir destination;
haftmann@39204
   360
            val filepath = (Path.append destination o Path.ext "hs" o Path.explode o implode
haftmann@39204
   361
              o separate "/" o Long_Name.explode) module_name;
haftmann@41246
   362
            val _ = Isabelle_System.mkdirs (Path.dir filepath);
haftmann@39209
   363
          in
haftmann@39209
   364
            (File.write filepath o format [] width o Pretty.chunks2)
noschinl@44926
   365
              [str language_pragma, content]
haftmann@39209
   366
          end
haftmann@39056
   367
      | write_module width NONE (_, content) = writeln (format [] width content);
haftmann@28054
   368
  in
haftmann@38916
   369
    Code_Target.serialization
haftmann@38915
   370
      (fn width => fn destination => K () o map (write_module width destination))
haftmann@40705
   371
      (fn present => fn width => rpair (try (deresolver ""))
haftmann@39204
   372
        o format present width o Pretty.chunks o map snd)
haftmann@39204
   373
      (map (uncurry print_module_frame o apsnd single) includes
haftmann@39204
   374
        @ map (fn module_name => print_module module_name (Graph.get_node haskell_program module_name))
haftmann@39204
   375
          ((flat o rev o Graph.strong_conn) haskell_program))
haftmann@28054
   376
  end;
haftmann@28054
   377
haftmann@38966
   378
val serializer : Code_Target.serializer =
haftmann@39206
   379
  Code_Target.parse_args (Scan.optional (Args.$$$ "root" -- Args.colon |-- Args.name) ""
haftmann@38966
   380
    -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@38966
   381
    >> (fn (module_prefix, string_classes) =>
haftmann@38966
   382
      serialize_haskell module_prefix string_classes));
haftmann@38966
   383
haftmann@28064
   384
val literals = let
haftmann@28064
   385
  fun char_haskell c =
haftmann@28064
   386
    let
haftmann@28064
   387
      val s = ML_Syntax.print_char c;
haftmann@28064
   388
    in if s = "'" then "\\'" else s end;
haftmann@34944
   389
  fun numeral_haskell k = if k >= 0 then string_of_int k
haftmann@34944
   390
    else Library.enclose "(" ")" (signed_string_of_int k);
haftmann@28064
   391
in Literals {
haftmann@34178
   392
  literal_char = Library.enclose "'" "'" o char_haskell,
haftmann@28064
   393
  literal_string = quote o translate_string char_haskell,
haftmann@34944
   394
  literal_numeral = numeral_haskell,
haftmann@34944
   395
  literal_positive_numeral = numeral_haskell,
haftmann@37958
   396
  literal_alternative_numeral = numeral_haskell,
haftmann@34944
   397
  literal_naive_numeral = numeral_haskell,
haftmann@34178
   398
  literal_list = enum "," "[" "]",
haftmann@28064
   399
  infix_cons = (5, ":")
haftmann@28064
   400
} end;
haftmann@28064
   401
haftmann@28054
   402
haftmann@28054
   403
(** optional monad syntax **)
haftmann@28054
   404
haftmann@28054
   405
fun pretty_haskell_monad c_bind =
haftmann@28054
   406
  let
haftmann@31874
   407
    fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2
haftmann@31889
   408
     of SOME ((pat, ty), t') =>
haftmann@31889
   409
          SOME ((SOME ((pat, ty), true), t1), t')
haftmann@28145
   410
      | NONE => NONE;
haftmann@48072
   411
    fun dest_monad c_bind_name (IConst { name = c, ... } `$ t1 `$ t2) =
haftmann@28663
   412
          if c = c_bind_name then dest_bind t1 t2
haftmann@28145
   413
          else NONE
haftmann@28663
   414
      | dest_monad _ t = case Code_Thingol.split_let t
haftmann@28145
   415
         of SOME (((pat, ty), tbind), t') =>
haftmann@31889
   416
              SOME ((SOME ((pat, ty), false), tbind), t')
haftmann@28145
   417
          | NONE => NONE;
haftmann@28663
   418
    fun implode_monad c_bind_name = Code_Thingol.unfoldr (dest_monad c_bind_name);
haftmann@33991
   419
    fun print_monad print_bind print_term (NONE, t) vars =
haftmann@33991
   420
          (semicolon [print_term vars NOBR t], vars)
haftmann@33991
   421
      | print_monad print_bind print_term (SOME ((bind, _), true), t) vars = vars
haftmann@33991
   422
          |> print_bind NOBR bind
haftmann@33991
   423
          |>> (fn p => semicolon [p, str "<-", print_term vars NOBR t])
haftmann@33991
   424
      | print_monad print_bind print_term (SOME ((bind, _), false), t) vars = vars
haftmann@33991
   425
          |> print_bind NOBR bind
haftmann@37832
   426
          |>> (fn p => semicolon [str "let", str "{", p, str "=", print_term vars NOBR t, str "}"]);
haftmann@33991
   427
    fun pretty _ [c_bind'] print_term thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
haftmann@28145
   428
     of SOME (bind, t') => let
haftmann@31054
   429
          val (binds, t'') = implode_monad c_bind' t'
haftmann@33991
   430
          val (ps, vars') = fold_map (print_monad (gen_print_bind (K print_term) thm) print_term)
haftmann@33991
   431
            (bind :: binds) vars;
haftmann@33991
   432
        in
haftmann@37833
   433
          (brackify fxy o single o enclose "do { " " }" o Pretty.breaks)
haftmann@33991
   434
            (ps @| print_term vars' NOBR t'')
haftmann@33991
   435
        end
haftmann@28145
   436
      | NONE => brackify_infix (1, L) fxy
haftmann@37242
   437
          (print_term vars (INFX (1, L)) t1, str ">>=", print_term vars (INFX (1, X)) t2)
haftmann@31054
   438
  in (2, ([c_bind], pretty)) end;
haftmann@28054
   439
haftmann@28145
   440
fun add_monad target' raw_c_bind thy =
haftmann@28054
   441
  let
haftmann@31156
   442
    val c_bind = Code.read_const thy raw_c_bind;
haftmann@28054
   443
  in if target = target' then
haftmann@28054
   444
    thy
haftmann@38923
   445
    |> Code_Target.add_const_syntax target c_bind
haftmann@37881
   446
        (SOME (Code_Printer.complex_const_syntax (pretty_haskell_monad c_bind)))
haftmann@28054
   447
  else error "Only Haskell target allows for monad syntax" end;
haftmann@28054
   448
haftmann@28054
   449
haftmann@28054
   450
(** Isar setup **)
haftmann@28054
   451
haftmann@28054
   452
val _ =
wenzelm@46961
   453
  Outer_Syntax.command @{command_spec "code_monad"} "define code syntax for monads"
wenzelm@46961
   454
    (Parse.term_group -- Parse.name >> (fn (raw_bind, target) =>
wenzelm@46961
   455
      Toplevel.theory  (add_monad target raw_bind)));
haftmann@28054
   456
haftmann@28054
   457
val setup =
haftmann@37821
   458
  Code_Target.add_target
haftmann@38966
   459
    (target, { serializer = serializer, literals = literals,
wenzelm@41952
   460
      check = { env_var = "ISABELLE_GHC", make_destination = I,
wenzelm@41940
   461
        make_command = fn module_name =>
noschinl@44926
   462
          "\"$ISABELLE_GHC\" " ^ language_params  ^ " -odir build -hidir build -stubdir build -e \"\" " ^
wenzelm@41940
   463
            module_name ^ ".hs" } })
haftmann@38923
   464
  #> Code_Target.add_tyco_syntax target "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   465
      brackify_infix (1, R) fxy (
haftmann@33991
   466
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   467
        str "->",
haftmann@33991
   468
        print_typ (INFX (1, R)) ty2
haftmann@37242
   469
      )))
haftmann@28054
   470
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   471
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@28054
   472
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@28054
   473
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@28054
   474
    ]
haftmann@28054
   475
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   476
      "Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int",
haftmann@28054
   477
      "Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded",
haftmann@28054
   478
      "Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor",
haftmann@28054
   479
      "AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException",
haftmann@28054
   480
      "BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException",
haftmann@28054
   481
      "Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure",
haftmann@28054
   482
      "ExitSuccess", "False", "GT", "HeapOverflow",
haftmann@28054
   483
      "IOError", "IOException", "IllegalOperation",
haftmann@28054
   484
      "IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError",
haftmann@28054
   485
      "NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow",
haftmann@28054
   486
      "PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError",
haftmann@28054
   487
      "RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow",
haftmann@28054
   488
      "ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow",
haftmann@28054
   489
      "UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all",
haftmann@28054
   490
      "and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan",
haftmann@28054
   491
      "atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen",
haftmann@28054
   492
      "boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break",
haftmann@28054
   493
      "catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const",
haftmann@28054
   494
      "cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod",
haftmann@28054
   495
      "doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem",
haftmann@28054
   496
      "emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
haftmann@28054
   497
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip",
haftmann@28054
   498
      "floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational",
haftmann@28054
   499
      "floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble",
haftmann@28054
   500
      "fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj",
haftmann@28054
   501
      "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head",
haftmann@28054
   502
      "id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha",
haftmann@28054
   503
      "isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite",
haftmann@28054
   504
      "isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'",
haftmann@28054
   505
      "last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log",
haftmann@28054
   506
      "logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum",
haftmann@28054
   507
      "maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem",
haftmann@28054
   508
      "null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo",
haftmann@28054
   509
      "numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred", 
haftmann@28054
   510
      "print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn",
haftmann@28054
   511
      "quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat",
haftmann@28054
   512
      "rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile",
haftmann@28054
   513
      "readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn",
haftmann@28054
   514
      "readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational",
haftmann@28054
   515
      "realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse",
haftmann@28054
   516
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence",
haftmann@28054
   517
      "sequence_", "show", "showChar", "showException", "showField", "showList",
haftmann@28054
   518
      "showLitChar", "showParen", "showString", "shows", "showsPrec", "significand",
haftmann@28054
   519
      "signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract",
haftmann@28054
   520
      "succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult",
haftmann@28054
   521
      "throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry",
haftmann@28054
   522
      "undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords",
haftmann@28054
   523
      "unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"
haftmann@28054
   524
    ] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*);
haftmann@28054
   525
haftmann@28054
   526
end; (*struct*)