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