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