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