src/Tools/Code/code_ml.ML
author haftmann
Sun Feb 23 10:33:43 2014 +0100 (2014-02-23)
changeset 55677 1f89921f3e75
parent 55657 d5ad50aea356
child 55679 59244fc1a7ca
permissions -rw-r--r--
dropped long-unused option
haftmann@37745
     1
(*  Title:      Tools/Code/code_ml.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@28054
     4
Serializer for SML and OCaml.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@28054
     7
signature CODE_ML =
haftmann@28054
     8
sig
haftmann@34028
     9
  val target_SML: string
haftmann@37745
    10
  val target_OCaml: string
haftmann@28054
    11
  val setup: theory -> theory
haftmann@28054
    12
end;
haftmann@28054
    13
haftmann@28054
    14
structure Code_ML : CODE_ML =
haftmann@28054
    15
struct
haftmann@28054
    16
haftmann@55150
    17
open Basic_Code_Symbol;
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@33992
    24
haftmann@33992
    25
(** generic **)
haftmann@33992
    26
haftmann@28054
    27
val target_SML = "SML";
haftmann@28054
    28
val target_OCaml = "OCaml";
haftmann@28054
    29
haftmann@33636
    30
datatype ml_binding =
haftmann@35228
    31
    ML_Function of string * (typscheme * ((iterm list * iterm) * (thm option * bool)) list)
haftmann@55147
    32
  | ML_Instance of (string * class) * { class: class, tyco: string, vs: (vname * sort) list,
haftmann@55147
    33
        superinsts: (class * dict list list) list,
haftmann@52519
    34
        inst_params: ((string * (const * int)) * (thm * bool)) list,
haftmann@52519
    35
        superinst_params: ((string * (const * int)) * (thm * bool)) list };
haftmann@28054
    36
haftmann@33636
    37
datatype ml_stmt =
haftmann@33992
    38
    ML_Exc of string * (typscheme * int)
haftmann@33636
    39
  | ML_Val of ml_binding
haftmann@55150
    40
  | ML_Funs of ml_binding list * Code_Symbol.T list
haftmann@48003
    41
  | ML_Datas of (string * (vname list * ((string * vname list) * itype list) list)) list
haftmann@55147
    42
  | ML_Class of string * (vname * ((class * class) list * (string * itype) list));
haftmann@33636
    43
haftmann@33992
    44
fun print_product _ [] = NONE
haftmann@33992
    45
  | print_product print [x] = SOME (print x)
haftmann@34178
    46
  | print_product print xs = (SOME o enum " *" "" "") (map print xs);
haftmann@28054
    47
haftmann@38922
    48
fun tuplify _ _ [] = NONE
haftmann@38922
    49
  | tuplify print fxy [x] = SOME (print fxy x)
haftmann@38922
    50
  | tuplify print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
haftmann@28054
    51
haftmann@33992
    52
haftmann@33992
    53
(** SML serializer **)
haftmann@33992
    54
haftmann@50625
    55
fun print_sml_stmt tyco_syntax const_syntax reserved is_constr deresolve =
haftmann@28054
    56
  let
haftmann@55150
    57
    val deresolve_const = deresolve o Constant;
haftmann@55150
    58
    val deresolve_class = deresolve o Type_Class;
haftmann@55150
    59
    val deresolve_classrel = deresolve o Class_Relation;
haftmann@55150
    60
    val deresolve_inst = deresolve o Class_Instance;
haftmann@55147
    61
    fun print_tyco_expr (sym, []) = (str o deresolve) sym
haftmann@55147
    62
      | print_tyco_expr (sym, [ty]) =
haftmann@55147
    63
          concat [print_typ BR ty, (str o deresolve) sym]
haftmann@55147
    64
      | print_tyco_expr (sym, tys) =
haftmann@55147
    65
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) sym]
haftmann@38923
    66
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55150
    67
         of NONE => print_tyco_expr (Type_Constructor tyco, tys)
haftmann@47609
    68
          | SOME (_, print) => print print_typ fxy tys)
haftmann@33992
    69
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@55150
    70
    fun print_dicttyp (class, ty) = print_tyco_expr (Type_Class class, [ty]);
haftmann@34178
    71
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
    72
      (map_filter (fn (v, sort) =>
haftmann@33992
    73
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
    74
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
    75
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@41100
    76
    fun print_classrels fxy [] ps = brackify fxy ps
haftmann@55147
    77
      | print_classrels fxy [classrel] ps = brackify fxy [(str o deresolve_classrel) classrel, brackify BR ps]
haftmann@41100
    78
      | print_classrels fxy classrels ps =
haftmann@55147
    79
          brackify fxy [enum " o" "(" ")" (map (str o deresolve_classrel) classrels), brackify BR ps]
haftmann@41118
    80
    fun print_dict is_pseudo_fun fxy (Dict (classrels, x)) =
haftmann@41118
    81
      print_classrels fxy classrels (print_plain_dict is_pseudo_fun fxy x)
haftmann@41118
    82
    and print_plain_dict is_pseudo_fun fxy (Dict_Const (inst, dss)) =
haftmann@55147
    83
          ((str o deresolve_inst) inst ::
haftmann@55150
    84
            (if is_pseudo_fun (Class_Instance inst) then [str "()"]
haftmann@33992
    85
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@41118
    86
      | print_plain_dict is_pseudo_fun fxy (Dict_Var (v, (i, k))) =
haftmann@41118
    87
          [str (if k = 1 then first_upper v ^ "_"
haftmann@41100
    88
            else first_upper v ^ string_of_int (i+1) ^ "_")]
haftmann@38922
    89
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
    90
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@41118
    91
      (map_index (fn (i, _) => Dict ([], Dict_Var (v, (i, length sort)))) sort));
haftmann@48072
    92
    fun print_term is_pseudo_fun some_thm vars fxy (IConst const) =
haftmann@48072
    93
          print_app is_pseudo_fun some_thm vars fxy (const, [])
haftmann@35228
    94
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
    95
          str "_"
haftmann@35228
    96
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
    97
          str (lookup_var vars v)
haftmann@35228
    98
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
    99
          (case Code_Thingol.unfold_const_app t
haftmann@48072
   100
           of SOME app => print_app is_pseudo_fun some_thm vars fxy app
haftmann@35228
   101
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   102
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   103
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   104
          let
haftmann@31874
   105
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33992
   106
            fun print_abs (pat, ty) =
haftmann@35228
   107
              print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   108
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@33992
   109
            val (ps, vars') = fold_map print_abs binds vars;
haftmann@35228
   110
          in brackets (ps @ [print_term is_pseudo_fun some_thm vars' NOBR t']) end
haftmann@48072
   111
      | print_term is_pseudo_fun some_thm vars fxy (ICase case_expr) =
haftmann@48072
   112
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55150
   113
           of SOME (app as ({ sym = Constant const, ... }, _)) =>
haftmann@55147
   114
                if is_none (const_syntax const)
haftmann@48072
   115
                then print_case is_pseudo_fun some_thm vars fxy case_expr
haftmann@48072
   116
                else print_app is_pseudo_fun some_thm vars fxy app
haftmann@48072
   117
            | NONE => print_case is_pseudo_fun some_thm vars fxy case_expr)
haftmann@55147
   118
    and print_app_expr is_pseudo_fun some_thm vars (app as ({ sym, dicts = dss, dom = dom, ... }, ts)) =
haftmann@55147
   119
      if is_constr sym then
haftmann@48072
   120
        let val k = length dom in
haftmann@33992
   121
          if k < 2 orelse length ts = k
haftmann@55147
   122
          then (str o deresolve) sym
haftmann@38922
   123
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   124
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   125
        end
haftmann@55147
   126
      else if is_pseudo_fun sym
haftmann@55147
   127
        then (str o deresolve) sym @@ str "()"
haftmann@55147
   128
      else (str o deresolve) sym :: map_filter (print_dicts is_pseudo_fun BR) dss
haftmann@35228
   129
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   130
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   131
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   132
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@48072
   133
    and print_case is_pseudo_fun some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   134
          (concat o map str) ["raise", "Fail", "\"empty case\""]
haftmann@48072
   135
      | print_case is_pseudo_fun some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   136
          let
haftmann@48072
   137
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47609
   138
            fun print_match ((pat, _), t) vars =
haftmann@28054
   139
              vars
haftmann@35228
   140
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@33992
   141
              |>> (fn p => semicolon [str "val", p, str "=",
haftmann@35228
   142
                    print_term is_pseudo_fun some_thm vars NOBR t])
haftmann@33992
   143
            val (ps, vars') = fold_map print_match binds vars;
haftmann@28054
   144
          in
haftmann@28054
   145
            Pretty.chunks [
haftmann@34178
   146
              Pretty.block [str "let", Pretty.fbrk, Pretty.chunks ps],
haftmann@35228
   147
              Pretty.block [str "in", Pretty.fbrk, print_term is_pseudo_fun some_thm vars' NOBR body],
haftmann@34178
   148
              str "end"
haftmann@28054
   149
            ]
haftmann@28054
   150
          end
haftmann@48072
   151
      | print_case is_pseudo_fun some_thm vars fxy { term = t, typ = ty, clauses = clause :: clauses, ... } =
haftmann@28054
   152
          let
haftmann@33992
   153
            fun print_select delim (pat, body) =
haftmann@28054
   154
              let
haftmann@35228
   155
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@28054
   156
              in
haftmann@35228
   157
                concat [str delim, p, str "=>", print_term is_pseudo_fun some_thm vars' NOBR body]
haftmann@28054
   158
              end;
haftmann@28054
   159
          in
haftmann@31665
   160
            brackets (
haftmann@28054
   161
              str "case"
haftmann@35228
   162
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   163
              :: print_select "of" clause
haftmann@33992
   164
              :: map (print_select "|") clauses
haftmann@28054
   165
            )
haftmann@48072
   166
          end;
haftmann@55147
   167
    fun print_val_decl print_typscheme (sym, typscheme) = concat
haftmann@55147
   168
      [str "val", str (deresolve sym), str ":", print_typscheme typscheme];
haftmann@33992
   169
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   170
      let
haftmann@55147
   171
        fun print_co ((co, _), []) = str (deresolve_const co)
haftmann@55147
   172
          | print_co ((co, _), tys) = concat [str (deresolve_const co), str "of",
haftmann@34178
   173
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   174
      in
haftmann@33992
   175
        concat (
haftmann@33992
   176
          str definer
haftmann@55150
   177
          :: print_tyco_expr (Type_Constructor tyco, map ITyVar vs)
haftmann@33992
   178
          :: str "="
haftmann@33992
   179
          :: separate (str "|") (map print_co cos)
haftmann@33992
   180
        )
haftmann@33992
   181
      end;
haftmann@33992
   182
    fun print_def is_pseudo_fun needs_typ definer
haftmann@55147
   183
          (ML_Function (const, (vs_ty as (vs, ty), eq :: eqs))) =
haftmann@29189
   184
          let
haftmann@35228
   185
            fun print_eqn definer ((ts, t), (some_thm, _)) =
haftmann@33636
   186
              let
haftmann@33636
   187
                val vars = reserved
haftmann@55145
   188
                  |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   189
                       deresolve (t :: ts)
haftmann@33636
   190
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@33636
   191
                       (insert (op =)) ts []);
haftmann@33636
   192
                val prolog = if needs_typ then
haftmann@55147
   193
                  concat [str definer, (str o deresolve_const) const, str ":", print_typ NOBR ty]
haftmann@55147
   194
                    else (concat o map str) [definer, deresolve_const const];
haftmann@33636
   195
              in
haftmann@33636
   196
                concat (
haftmann@33636
   197
                  prolog
haftmann@55150
   198
                  :: (if is_pseudo_fun (Constant const) then [str "()"]
haftmann@33992
   199
                      else print_dict_args vs
haftmann@35228
   200
                        @ map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@33636
   201
                  @ str "="
haftmann@35228
   202
                  @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33636
   203
                )
haftmann@33636
   204
              end
haftmann@33992
   205
            val shift = if null eqs then I else
haftmann@33992
   206
              map (Pretty.block o single o Pretty.block o single);
haftmann@33992
   207
          in pair
haftmann@55150
   208
            (print_val_decl print_typscheme (Constant const, vs_ty))
haftmann@33992
   209
            ((Pretty.block o Pretty.fbreaks o shift) (
haftmann@33992
   210
              print_eqn definer eq
haftmann@33992
   211
              :: map (print_eqn "|") eqs
haftmann@33992
   212
            ))
haftmann@29189
   213
          end
haftmann@33992
   214
      | print_def is_pseudo_fun _ definer
haftmann@55147
   215
          (ML_Instance (inst as (tyco, class), { vs, superinsts, inst_params, ... })) =
haftmann@29189
   216
          let
haftmann@55147
   217
            fun print_super_instance (super_class, x) =
haftmann@33636
   218
              concat [
haftmann@55147
   219
                (str o Long_Name.base_name o deresolve_classrel) (class, super_class),
haftmann@33636
   220
                str "=",
haftmann@55147
   221
                print_dict is_pseudo_fun NOBR (Dict ([], Dict_Const ((tyco, super_class), x)))
haftmann@33636
   222
              ];
haftmann@52519
   223
            fun print_classparam_instance ((classparam, (const, _)), (thm, _)) =
haftmann@33636
   224
              concat [
haftmann@55147
   225
                (str o Long_Name.base_name o deresolve_const) classparam,
haftmann@33636
   226
                str "=",
haftmann@37384
   227
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   228
              ];
haftmann@33992
   229
          in pair
haftmann@33992
   230
            (print_val_decl print_dicttypscheme
haftmann@55150
   231
              (Class_Instance inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   232
            (concat (
haftmann@33636
   233
              str definer
haftmann@55147
   234
              :: (str o deresolve_inst) inst
haftmann@55150
   235
              :: (if is_pseudo_fun (Class_Instance inst) then [str "()"]
haftmann@33992
   236
                  else print_dict_args vs)
haftmann@33636
   237
              @ str "="
haftmann@34178
   238
              :: enum "," "{" "}"
haftmann@48072
   239
                (map print_super_instance superinsts
haftmann@48072
   240
                  @ map print_classparam_instance inst_params)
haftmann@33636
   241
              :: str ":"
haftmann@55147
   242
              @@ print_dicttyp (class, tyco `%% map (ITyVar o fst) vs)
haftmann@33992
   243
            ))
haftmann@33636
   244
          end;
haftmann@55147
   245
    fun print_stmt (ML_Exc (const, (vs_ty, n))) = pair
haftmann@55150
   246
          [print_val_decl print_typscheme (Constant const, vs_ty)]
haftmann@33992
   247
          ((semicolon o map str) (
haftmann@33636
   248
            (if n = 0 then "val" else "fun")
haftmann@55147
   249
            :: deresolve_const const
haftmann@33636
   250
            :: replicate n "_"
haftmann@33636
   251
            @ "="
haftmann@33636
   252
            :: "raise"
haftmann@33636
   253
            :: "Fail"
haftmann@55147
   254
            @@ ML_Syntax.print_string const
haftmann@33992
   255
          ))
haftmann@33992
   256
      | print_stmt (ML_Val binding) =
haftmann@33636
   257
          let
haftmann@33992
   258
            val (sig_p, p) = print_def (K false) true "val" binding
haftmann@33992
   259
          in pair
haftmann@33992
   260
            [sig_p]
haftmann@33992
   261
            (semicolon [p])
haftmann@33992
   262
          end
haftmann@33992
   263
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   264
          let
haftmann@33992
   265
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@55147
   266
            fun print_pseudo_fun sym = concat [
haftmann@29189
   267
                str "val",
haftmann@55147
   268
                (str o deresolve) sym,
haftmann@29189
   269
                str "=",
haftmann@55147
   270
                (str o deresolve) sym,
haftmann@29189
   271
                str "();"
haftmann@29189
   272
              ];
haftmann@33992
   273
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   274
              (print_def' "fun" binding :: map (print_def' "and") bindings);
haftmann@33992
   275
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   276
          in pair
haftmann@33992
   277
            sig_ps
haftmann@33992
   278
            (Pretty.chunks (ps @ semicolon [p] :: pseudo_ps))
haftmann@33992
   279
          end
haftmann@33992
   280
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   281
          let
haftmann@55150
   282
            val ty_p = print_tyco_expr (Type_Constructor tyco, map ITyVar vs);
haftmann@33992
   283
          in
haftmann@33992
   284
            pair
haftmann@33992
   285
            [concat [str "type", ty_p]]
haftmann@33992
   286
            (concat [str "datatype", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   287
          end
haftmann@33992
   288
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   289
          let
haftmann@33992
   290
            val sig_ps = print_datatype_decl "datatype" data
haftmann@33992
   291
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   292
            val (ps, p) = split_last sig_ps;
haftmann@33992
   293
          in pair
haftmann@33992
   294
            sig_ps
haftmann@33992
   295
            (Pretty.chunks (ps @| semicolon [p]))
haftmann@33992
   296
          end
haftmann@55147
   297
     | print_stmt (ML_Class (class, (v, (classrels, classparams)))) =
haftmann@28054
   298
          let
haftmann@33992
   299
            fun print_field s p = concat [str s, str ":", p];
haftmann@33992
   300
            fun print_proj s p = semicolon
haftmann@33992
   301
              (map str ["val", s, "=", "#" ^ s, ":"] @| p);
haftmann@55147
   302
            fun print_super_class_decl (classrel as (_, super_class)) =
haftmann@33992
   303
              print_val_decl print_dicttypscheme
haftmann@55150
   304
                (Class_Relation classrel, ([(v, [class])], (super_class, ITyVar v)));
haftmann@55147
   305
            fun print_super_class_field (classrel as (_, super_class)) =
haftmann@55147
   306
              print_field (deresolve_classrel classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@55147
   307
            fun print_super_class_proj (classrel as (_, super_class)) =
haftmann@55147
   308
              print_proj (deresolve_classrel classrel)
haftmann@37384
   309
                (print_dicttypscheme ([(v, [class])], (super_class, ITyVar v)));
haftmann@33992
   310
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   311
              print_val_decl print_typscheme
haftmann@55150
   312
                (Constant classparam, ([(v, [class])], ty));
haftmann@33992
   313
            fun print_classparam_field (classparam, ty) =
haftmann@55147
   314
              print_field (deresolve_const classparam) (print_typ NOBR ty);
haftmann@33992
   315
            fun print_classparam_proj (classparam, ty) =
haftmann@55147
   316
              print_proj (deresolve_const classparam)
haftmann@33992
   317
                (print_typscheme ([(v, [class])], ty));
haftmann@33992
   318
          in pair
haftmann@33992
   319
            (concat [str "type", print_dicttyp (class, ITyVar v)]
haftmann@55147
   320
              :: map print_super_class_decl classrels
haftmann@33992
   321
              @ map print_classparam_decl classparams)
haftmann@33992
   322
            (Pretty.chunks (
haftmann@28054
   323
              concat [
haftmann@28054
   324
                str ("type '" ^ v),
haftmann@55147
   325
                (str o deresolve_class) class,
haftmann@28054
   326
                str "=",
haftmann@34178
   327
                enum "," "{" "};" (
haftmann@55147
   328
                  map print_super_class_field classrels
haftmann@33992
   329
                  @ map print_classparam_field classparams
haftmann@28054
   330
                )
haftmann@28054
   331
              ]
haftmann@55147
   332
              :: map print_super_class_proj classrels
haftmann@33992
   333
              @ map print_classparam_proj classparams
haftmann@33992
   334
            ))
haftmann@28054
   335
          end;
haftmann@33992
   336
  in print_stmt end;
haftmann@28054
   337
haftmann@55677
   338
fun print_sml_module name decls body =
haftmann@38933
   339
  Pretty.chunks2 (
haftmann@55677
   340
    Pretty.chunks [
haftmann@55677
   341
      str ("structure " ^ name ^ " : sig"),
haftmann@55677
   342
      (indent 2 o Pretty.chunks) decls,
haftmann@55677
   343
      str "end = struct"
haftmann@55677
   344
    ]
haftmann@33992
   345
    :: body
haftmann@33992
   346
    @| str ("end; (*struct " ^ name ^ "*)")
haftmann@28054
   347
  );
haftmann@28054
   348
haftmann@28064
   349
val literals_sml = Literals {
haftmann@28064
   350
  literal_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@28064
   351
  literal_string = quote o translate_string ML_Syntax.print_char,
haftmann@34944
   352
  literal_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34178
   353
  literal_list = enum "," "[" "]",
haftmann@28064
   354
  infix_cons = (7, "::")
haftmann@28064
   355
};
haftmann@28064
   356
haftmann@28054
   357
haftmann@28054
   358
(** OCaml serializer **)
haftmann@28054
   359
haftmann@50625
   360
fun print_ocaml_stmt tyco_syntax const_syntax reserved is_constr deresolve =
haftmann@28054
   361
  let
haftmann@55150
   362
    val deresolve_const = deresolve o Constant;
haftmann@55150
   363
    val deresolve_class = deresolve o Type_Class;
haftmann@55150
   364
    val deresolve_classrel = deresolve o Class_Relation;
haftmann@55150
   365
    val deresolve_inst = deresolve o Class_Instance;
haftmann@55147
   366
    fun print_tyco_expr (sym, []) = (str o deresolve) sym
haftmann@55147
   367
      | print_tyco_expr (sym, [ty]) =
haftmann@55147
   368
          concat [print_typ BR ty, (str o deresolve) sym]
haftmann@55147
   369
      | print_tyco_expr (sym, tys) =
haftmann@55147
   370
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) sym]
haftmann@38923
   371
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55150
   372
         of NONE => print_tyco_expr (Type_Constructor tyco, tys)
haftmann@47576
   373
          | SOME (_, print) => print print_typ fxy tys)
haftmann@33992
   374
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@55150
   375
    fun print_dicttyp (class, ty) = print_tyco_expr (Type_Class class, [ty]);
haftmann@34178
   376
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
   377
      (map_filter (fn (v, sort) =>
haftmann@33992
   378
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
   379
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
   380
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@41100
   381
    val print_classrels =
haftmann@55147
   382
      fold_rev (fn classrel => fn p => Pretty.block [p, str ".", (str o deresolve_classrel) classrel])
haftmann@41118
   383
    fun print_dict is_pseudo_fun fxy (Dict (classrels, x)) =
haftmann@41118
   384
      print_plain_dict is_pseudo_fun fxy x
haftmann@41118
   385
      |> print_classrels classrels
haftmann@41118
   386
    and print_plain_dict is_pseudo_fun fxy (Dict_Const (inst, dss)) =
haftmann@55147
   387
          brackify BR ((str o deresolve_inst) inst ::
haftmann@55150
   388
            (if is_pseudo_fun (Class_Instance inst) then [str "()"]
haftmann@33992
   389
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@41118
   390
      | print_plain_dict is_pseudo_fun fxy (Dict_Var (v, (i, k))) =
haftmann@33992
   391
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   392
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@38922
   393
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
   394
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@41118
   395
      (map_index (fn (i, _) => Dict ([], Dict_Var (v, (i, length sort)))) sort));
haftmann@48072
   396
    fun print_term is_pseudo_fun some_thm vars fxy (IConst const) =
haftmann@48072
   397
          print_app is_pseudo_fun some_thm vars fxy (const, [])
haftmann@35228
   398
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   399
          str "_"
haftmann@35228
   400
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   401
          str (lookup_var vars v)
haftmann@35228
   402
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   403
          (case Code_Thingol.unfold_const_app t
haftmann@48072
   404
           of SOME app => print_app is_pseudo_fun some_thm vars fxy app
haftmann@35228
   405
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   406
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   407
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   408
          let
haftmann@31874
   409
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
   410
            val (ps, vars') = fold_map (print_bind is_pseudo_fun some_thm BR o fst) binds vars;
haftmann@35228
   411
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun some_thm vars' NOBR t') end
haftmann@48072
   412
      | print_term is_pseudo_fun some_thm vars fxy (ICase case_expr) =
haftmann@48072
   413
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55150
   414
           of SOME (app as ({ sym = Constant const, ... }, _)) =>
haftmann@55147
   415
                if is_none (const_syntax const)
haftmann@48072
   416
                then print_case is_pseudo_fun some_thm vars fxy case_expr
haftmann@48072
   417
                else print_app is_pseudo_fun some_thm vars fxy app
haftmann@48072
   418
            | NONE => print_case is_pseudo_fun some_thm vars fxy case_expr)
haftmann@55147
   419
    and print_app_expr is_pseudo_fun some_thm vars (app as ({ sym, dicts = dss, dom = dom, ... }, ts)) =
haftmann@55147
   420
      if is_constr sym then
haftmann@48072
   421
        let val k = length dom in
haftmann@33992
   422
          if length ts = k
haftmann@55147
   423
          then (str o deresolve) sym
haftmann@38922
   424
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   425
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   426
        end
haftmann@55147
   427
      else if is_pseudo_fun sym
haftmann@55147
   428
        then (str o deresolve) sym @@ str "()"
haftmann@55147
   429
      else (str o deresolve) sym :: map_filter (print_dicts is_pseudo_fun BR) dss
haftmann@35228
   430
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   431
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   432
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   433
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@48072
   434
    and print_case is_pseudo_fun some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   435
          (concat o map str) ["failwith", "\"empty case\""]
haftmann@48072
   436
      | print_case is_pseudo_fun some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   437
          let
haftmann@48072
   438
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47576
   439
            fun print_let ((pat, _), t) vars =
haftmann@28054
   440
              vars
haftmann@35228
   441
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   442
              |>> (fn p => concat
haftmann@35228
   443
                  [str "let", p, str "=", print_term is_pseudo_fun some_thm vars NOBR t, str "in"])
haftmann@33992
   444
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   445
          in
haftmann@31665
   446
            brackify_block fxy (Pretty.chunks ps) []
haftmann@35228
   447
              (print_term is_pseudo_fun some_thm vars' NOBR body)
haftmann@31665
   448
          end
haftmann@48072
   449
      | print_case is_pseudo_fun some_thm vars fxy { term = t, typ = ty, clauses = clause :: clauses, ... } =
haftmann@28054
   450
          let
haftmann@33992
   451
            fun print_select delim (pat, body) =
haftmann@28054
   452
              let
haftmann@35228
   453
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@35228
   454
              in concat [str delim, p, str "->", print_term is_pseudo_fun some_thm vars' NOBR body] end;
haftmann@28054
   455
          in
haftmann@31665
   456
            brackets (
haftmann@28054
   457
              str "match"
haftmann@35228
   458
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   459
              :: print_select "with" clause
haftmann@33992
   460
              :: map (print_select "|") clauses
haftmann@28054
   461
            )
haftmann@48072
   462
          end;
haftmann@55147
   463
    fun print_val_decl print_typscheme (sym, typscheme) = concat
haftmann@55147
   464
      [str "val", str (deresolve sym), str ":", print_typscheme typscheme];
haftmann@33992
   465
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   466
      let
haftmann@55147
   467
        fun print_co ((co, _), []) = str (deresolve_const co)
haftmann@55147
   468
          | print_co ((co, _), tys) = concat [str (deresolve_const co), str "of",
haftmann@34178
   469
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   470
      in
haftmann@33992
   471
        concat (
haftmann@33992
   472
          str definer
haftmann@55150
   473
          :: print_tyco_expr (Type_Constructor tyco, map ITyVar vs)
haftmann@33992
   474
          :: str "="
haftmann@33992
   475
          :: separate (str "|") (map print_co cos)
haftmann@33992
   476
        )
haftmann@33992
   477
      end;
haftmann@33992
   478
    fun print_def is_pseudo_fun needs_typ definer
haftmann@55147
   479
          (ML_Function (const, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   480
          let
haftmann@35228
   481
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   482
              let
haftmann@32924
   483
                val vars = reserved
haftmann@55145
   484
                  |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   485
                      deresolve (t :: ts)
haftmann@32924
   486
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   487
                      (insert (op =)) ts []);
haftmann@28054
   488
              in concat [
haftmann@38778
   489
                (Pretty.block o commas)
haftmann@35228
   490
                  (map (print_term is_pseudo_fun some_thm vars NOBR) ts),
haftmann@28054
   491
                str "->",
haftmann@35228
   492
                print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   493
              ] end;
haftmann@35228
   494
            fun print_eqns is_pseudo [((ts, t), (some_thm, _))] =
haftmann@28054
   495
                  let
haftmann@32924
   496
                    val vars = reserved
haftmann@55145
   497
                      |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   498
                          deresolve (t :: ts)
haftmann@32924
   499
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   500
                          (insert (op =)) ts []);
haftmann@28054
   501
                  in
haftmann@28054
   502
                    concat (
haftmann@29189
   503
                      (if is_pseudo then [str "()"]
haftmann@35228
   504
                        else map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@28054
   505
                      @ str "="
haftmann@35228
   506
                      @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   507
                    )
haftmann@28054
   508
                  end
haftmann@33992
   509
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   510
                  Pretty.block (
haftmann@28054
   511
                    str "="
haftmann@28054
   512
                    :: Pretty.brk 1
haftmann@28054
   513
                    :: str "function"
haftmann@28054
   514
                    :: Pretty.brk 1
haftmann@33992
   515
                    :: print_eqn eq
haftmann@28054
   516
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   517
                          o single o print_eqn) eqs
haftmann@28054
   518
                  )
haftmann@33992
   519
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   520
                  let
haftmann@32924
   521
                    val vars = reserved
haftmann@55145
   522
                      |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   523
                           deresolve (map (snd o fst) eqs)
haftmann@32924
   524
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   525
                  in
haftmann@28054
   526
                    Pretty.block (
haftmann@28054
   527
                      Pretty.breaks dummy_parms
haftmann@28054
   528
                      @ Pretty.brk 1
haftmann@28054
   529
                      :: str "="
haftmann@28054
   530
                      :: Pretty.brk 1
haftmann@28054
   531
                      :: str "match"
haftmann@28054
   532
                      :: Pretty.brk 1
haftmann@38778
   533
                      :: (Pretty.block o commas) dummy_parms
haftmann@28054
   534
                      :: Pretty.brk 1
haftmann@28054
   535
                      :: str "with"
haftmann@28054
   536
                      :: Pretty.brk 1
haftmann@33992
   537
                      :: print_eqn eq
haftmann@28054
   538
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   539
                           o single o print_eqn) eqs'
haftmann@28054
   540
                    )
haftmann@28054
   541
                  end;
haftmann@33636
   542
            val prolog = if needs_typ then
haftmann@55147
   543
              concat [str definer, (str o deresolve_const) const, str ":", print_typ NOBR ty]
haftmann@55147
   544
                else (concat o map str) [definer, deresolve_const const];
haftmann@33992
   545
          in pair
haftmann@55150
   546
            (print_val_decl print_typscheme (Constant const, vs_ty))
haftmann@33992
   547
            (concat (
haftmann@33636
   548
              prolog
haftmann@33992
   549
              :: print_dict_args vs
haftmann@55150
   550
              @| print_eqns (is_pseudo_fun (Constant const)) eqs
haftmann@33992
   551
            ))
haftmann@33636
   552
          end
haftmann@37384
   553
      | print_def is_pseudo_fun _ definer
haftmann@55147
   554
          (ML_Instance (inst as (tyco, class), { vs, superinsts, inst_params, ... })) =
haftmann@33636
   555
          let
haftmann@55147
   556
            fun print_super_instance (super_class, x) =
haftmann@33636
   557
              concat [
haftmann@55147
   558
                (str o deresolve_classrel) (class, super_class),
haftmann@33636
   559
                str "=",
haftmann@55147
   560
                print_dict is_pseudo_fun NOBR (Dict ([], Dict_Const ((tyco, super_class), x)))
haftmann@33636
   561
              ];
haftmann@52519
   562
            fun print_classparam_instance ((classparam, (const, _)), (thm, _)) =
haftmann@33636
   563
              concat [
haftmann@55147
   564
                (str o deresolve_const) classparam,
haftmann@33636
   565
                str "=",
haftmann@37384
   566
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   567
              ];
haftmann@33992
   568
          in pair
haftmann@33992
   569
            (print_val_decl print_dicttypscheme
haftmann@55150
   570
              (Class_Instance inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   571
            (concat (
haftmann@33636
   572
              str definer
haftmann@55147
   573
              :: (str o deresolve_inst) inst
haftmann@55150
   574
              :: (if is_pseudo_fun (Class_Instance inst) then [str "()"]
bulwahn@43343
   575
                  else print_dict_args vs)
haftmann@33636
   576
              @ str "="
haftmann@33636
   577
              @@ brackets [
haftmann@48072
   578
                enum_default "()" ";" "{" "}" (map print_super_instance superinsts
haftmann@48072
   579
                  @ map print_classparam_instance inst_params),
haftmann@33636
   580
                str ":",
haftmann@55147
   581
                print_dicttyp (class, tyco `%% map (ITyVar o fst) vs)
haftmann@33636
   582
              ]
haftmann@33992
   583
            ))
haftmann@33636
   584
          end;
haftmann@55147
   585
     fun print_stmt (ML_Exc (const, (vs_ty, n))) = pair
haftmann@55150
   586
          [print_val_decl print_typscheme (Constant const, vs_ty)]
haftmann@33992
   587
          ((doublesemicolon o map str) (
haftmann@33636
   588
            "let"
haftmann@55147
   589
            :: deresolve_const const
haftmann@33636
   590
            :: replicate n "_"
haftmann@33636
   591
            @ "="
haftmann@33636
   592
            :: "failwith"
haftmann@55147
   593
            @@ ML_Syntax.print_string const
haftmann@33992
   594
          ))
haftmann@33992
   595
      | print_stmt (ML_Val binding) =
haftmann@33636
   596
          let
haftmann@33992
   597
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   598
          in pair
haftmann@33992
   599
            [sig_p]
haftmann@33992
   600
            (doublesemicolon [p])
haftmann@33992
   601
          end
haftmann@33992
   602
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   603
          let
haftmann@33992
   604
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@55147
   605
            fun print_pseudo_fun sym = concat [
haftmann@29189
   606
                str "let",
haftmann@55147
   607
                (str o deresolve) sym,
haftmann@29189
   608
                str "=",
haftmann@55147
   609
                (str o deresolve) sym,
haftmann@29189
   610
                str "();;"
haftmann@29189
   611
              ];
haftmann@33992
   612
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   613
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   614
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   615
          in pair
haftmann@33992
   616
            sig_ps
haftmann@33992
   617
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   618
          end
haftmann@33992
   619
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   620
          let
haftmann@55150
   621
            val ty_p = print_tyco_expr (Type_Constructor tyco, map ITyVar vs);
haftmann@33992
   622
          in
haftmann@33992
   623
            pair
haftmann@33992
   624
            [concat [str "type", ty_p]]
haftmann@33992
   625
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   626
          end
haftmann@33992
   627
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   628
          let
haftmann@33992
   629
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   630
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   631
            val (ps, p) = split_last sig_ps;
haftmann@33992
   632
          in pair
haftmann@33992
   633
            sig_ps
haftmann@33992
   634
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   635
          end
haftmann@55147
   636
     | print_stmt (ML_Class (class, (v, (classrels, classparams)))) =
haftmann@28054
   637
          let
haftmann@33992
   638
            fun print_field s p = concat [str s, str ":", p];
haftmann@55147
   639
            fun print_super_class_field (classrel as (_, super_class)) =
haftmann@55147
   640
              print_field (deresolve_classrel classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33992
   641
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   642
              print_val_decl print_typscheme
haftmann@55150
   643
                (Constant classparam, ([(v, [class])], ty));
haftmann@33992
   644
            fun print_classparam_field (classparam, ty) =
haftmann@55147
   645
              print_field (deresolve_const classparam) (print_typ NOBR ty);
haftmann@32924
   646
            val w = "_" ^ first_upper v;
haftmann@33992
   647
            fun print_classparam_proj (classparam, _) =
haftmann@55147
   648
              (concat o map str) ["let", deresolve_const classparam, w, "=",
haftmann@55147
   649
                w ^ "." ^ deresolve_const classparam ^ ";;"];
haftmann@33992
   650
            val type_decl_p = concat [
haftmann@33992
   651
                str ("type '" ^ v),
haftmann@55147
   652
                (str o deresolve_class) class,
haftmann@28054
   653
                str "=",
haftmann@33992
   654
                enum_default "unit" ";" "{" "}" (
haftmann@55147
   655
                  map print_super_class_field classrels
haftmann@33992
   656
                  @ map print_classparam_field classparams
haftmann@33992
   657
                )
haftmann@28054
   658
              ];
haftmann@33992
   659
          in pair
haftmann@33992
   660
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   661
            (Pretty.chunks (
haftmann@33992
   662
              doublesemicolon [type_decl_p]
haftmann@33992
   663
              :: map print_classparam_proj classparams
haftmann@33992
   664
            ))
haftmann@33992
   665
          end;
haftmann@33992
   666
  in print_stmt end;
haftmann@28054
   667
haftmann@55677
   668
fun print_ocaml_module name decls body =
haftmann@38933
   669
  Pretty.chunks2 (
haftmann@55677
   670
    Pretty.chunks [
haftmann@55677
   671
      str ("module " ^ name ^ " : sig"),
haftmann@55677
   672
      (indent 2 o Pretty.chunks) decls,
haftmann@55677
   673
      str "end = struct"
haftmann@55677
   674
    ]
haftmann@33992
   675
    :: body
haftmann@33992
   676
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   677
  );
haftmann@28054
   678
haftmann@28064
   679
val literals_ocaml = let
haftmann@28064
   680
  fun chr i =
haftmann@28064
   681
    let
haftmann@28064
   682
      val xs = string_of_int i;
wenzelm@40627
   683
      val ys = replicate_string (3 - length (raw_explode xs)) "0";
haftmann@28064
   684
    in "\\" ^ ys ^ xs end;
haftmann@28064
   685
  fun char_ocaml c =
haftmann@28064
   686
    let
haftmann@28064
   687
      val i = ord c;
haftmann@28064
   688
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   689
        then chr i else c
haftmann@28064
   690
    in s end;
haftmann@34944
   691
  fun numeral_ocaml k = if k < 0
haftmann@34944
   692
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34944
   693
    else if k <= 1073741823
haftmann@34944
   694
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34944
   695
      else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   696
in Literals {
haftmann@34178
   697
  literal_char = Library.enclose "'" "'" o char_ocaml,
haftmann@28064
   698
  literal_string = quote o translate_string char_ocaml,
haftmann@34944
   699
  literal_numeral = numeral_ocaml,
haftmann@34178
   700
  literal_list = enum ";" "[" "]",
haftmann@28064
   701
  infix_cons = (6, "::")
haftmann@28064
   702
} end;
haftmann@28064
   703
haftmann@28064
   704
haftmann@28054
   705
haftmann@28054
   706
(** SML/OCaml generic part **)
haftmann@28054
   707
haftmann@55147
   708
fun ml_program_of_program ctxt module_name reserved identifiers program =
haftmann@39028
   709
  let
haftmann@39028
   710
    fun namify_const upper base (nsp_const, nsp_type) =
haftmann@39028
   711
      let
wenzelm@43326
   712
        val (base', nsp_const') =
wenzelm@43326
   713
          Name.variant (if upper then first_upper base else base) nsp_const
haftmann@39028
   714
      in (base', (nsp_const', nsp_type)) end;
haftmann@39028
   715
    fun namify_type base (nsp_const, nsp_type) =
haftmann@39028
   716
      let
wenzelm@43326
   717
        val (base', nsp_type') = Name.variant base nsp_type
haftmann@39028
   718
      in (base', (nsp_const, nsp_type')) end;
haftmann@39028
   719
    fun namify_stmt (Code_Thingol.Fun _) = namify_const false
haftmann@39028
   720
      | namify_stmt (Code_Thingol.Datatype _) = namify_type
haftmann@39028
   721
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_const true
haftmann@39028
   722
      | namify_stmt (Code_Thingol.Class _) = namify_type
haftmann@39028
   723
      | namify_stmt (Code_Thingol.Classrel _) = namify_const false
haftmann@39028
   724
      | namify_stmt (Code_Thingol.Classparam _) = namify_const false
haftmann@39028
   725
      | namify_stmt (Code_Thingol.Classinst _) = namify_const false;
haftmann@55150
   726
    fun ml_binding_of_stmt (sym as Constant const, Code_Thingol.Fun ((tysm as (vs, ty), raw_eqs), _)) =
haftmann@39028
   727
          let
haftmann@39028
   728
            val eqs = filter (snd o snd) raw_eqs;
haftmann@55147
   729
            val (eqs', some_sym) = if null (filter_out (null o snd) vs) then case eqs
haftmann@39028
   730
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@39028
   731
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@55147
   732
                  else (eqs, SOME (sym, member (op =) (Code_Thingol.add_constsyms t []) sym))
haftmann@39028
   733
                | _ => (eqs, NONE)
haftmann@39028
   734
              else (eqs, NONE)
haftmann@55147
   735
          in (ML_Function (const, (tysm, eqs')), some_sym) end
haftmann@55150
   736
      | ml_binding_of_stmt (sym as Class_Instance inst, Code_Thingol.Classinst (stmt as { vs, ... })) =
haftmann@55147
   737
          (ML_Instance (inst, stmt), if forall (null o snd) vs then SOME (sym, false) else NONE)
haftmann@55147
   738
      | ml_binding_of_stmt (sym, _) =
haftmann@52138
   739
          error ("Binding block containing illegal statement: " ^ 
haftmann@55147
   740
            Code_Symbol.quote ctxt sym)
haftmann@55147
   741
    fun modify_fun (sym, stmt) =
haftmann@39028
   742
      let
haftmann@55147
   743
        val (binding, some_value_sym) = ml_binding_of_stmt (sym, stmt);
haftmann@39028
   744
        val ml_stmt = case binding
haftmann@55147
   745
         of ML_Function (const, ((vs, ty), [])) =>
haftmann@55147
   746
              ML_Exc (const, ((vs, ty),
haftmann@39028
   747
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@55147
   748
          | _ => case some_value_sym
haftmann@39028
   749
             of NONE => ML_Funs ([binding], [])
haftmann@55147
   750
              | SOME (sym, true) => ML_Funs ([binding], [sym])
haftmann@55147
   751
              | SOME (sym, false) => ML_Val binding
haftmann@39028
   752
      in SOME ml_stmt end;
haftmann@39031
   753
    fun modify_funs stmts = single (SOME
haftmann@39031
   754
      (ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst)))
haftmann@39031
   755
    fun modify_datatypes stmts = single (SOME
haftmann@39031
   756
      (ML_Datas (map_filter
haftmann@55150
   757
        (fn (Type_Constructor tyco, Code_Thingol.Datatype stmt) => SOME (tyco, stmt) | _ => NONE) stmts)))
haftmann@39031
   758
    fun modify_class stmts = single (SOME
haftmann@39031
   759
      (ML_Class (the_single (map_filter
haftmann@55150
   760
        (fn (Type_Class class, Code_Thingol.Class stmt) => SOME (class, stmt) | _ => NONE) stmts))))
haftmann@47576
   761
    fun modify_stmts ([stmt as (_, stmt' as Code_Thingol.Fun _)]) =
haftmann@39059
   762
          if Code_Thingol.is_case stmt' then [] else [modify_fun stmt]
haftmann@55147
   763
      | modify_stmts ((stmts as (_, Code_Thingol.Fun _) :: _)) =
haftmann@39061
   764
          modify_funs (filter_out (Code_Thingol.is_case o snd) stmts)
haftmann@55147
   765
      | modify_stmts ((stmts as (_, Code_Thingol.Datatypecons _) :: _)) =
haftmann@39028
   766
          modify_datatypes stmts
haftmann@55147
   767
      | modify_stmts ((stmts as (_, Code_Thingol.Datatype _) :: _)) =
haftmann@39028
   768
          modify_datatypes stmts
haftmann@55147
   769
      | modify_stmts ((stmts as (_, Code_Thingol.Class _) :: _)) =
haftmann@39028
   770
          modify_class stmts
haftmann@55147
   771
      | modify_stmts ((stmts as (_, Code_Thingol.Classrel _) :: _)) =
haftmann@39028
   772
          modify_class stmts
haftmann@55147
   773
      | modify_stmts ((stmts as (_, Code_Thingol.Classparam _) :: _)) =
haftmann@39028
   774
          modify_class stmts
haftmann@39028
   775
      | modify_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@39028
   776
          [modify_fun stmt]
haftmann@55147
   777
      | modify_stmts ((stmts as (_, Code_Thingol.Classinst _) :: _)) =
haftmann@39028
   778
          modify_funs stmts
haftmann@39028
   779
      | modify_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@55147
   780
          (Library.commas o map (Code_Symbol.quote ctxt o fst)) stmts);
haftmann@39028
   781
  in
haftmann@55147
   782
    Code_Namespace.hierarchical_program ctxt {
haftmann@52138
   783
      module_name = module_name, reserved = reserved, identifiers = identifiers,
haftmann@39028
   784
      empty_nsp = (reserved, reserved), namify_module = pair, namify_stmt = namify_stmt,
haftmann@39028
   785
      cyclic_modules = false, empty_data = (), memorize_data = K I, modify_stmts = modify_stmts } program
haftmann@39028
   786
  end;
haftmann@39028
   787
haftmann@55677
   788
fun serialize_ml print_ml_module print_ml_stmt ctxt
haftmann@55147
   789
    { module_name, reserved_syms, identifiers, includes,
haftmann@41343
   790
      class_syntax, tyco_syntax, const_syntax } program =
haftmann@28054
   791
  let
haftmann@39147
   792
haftmann@39147
   793
    (* build program *)
haftmann@39028
   794
    val { deresolver, hierarchical_program = ml_program } =
haftmann@55147
   795
      ml_program_of_program ctxt module_name (Name.make_context reserved_syms) identifiers program;
haftmann@39147
   796
haftmann@39147
   797
    (* print statements *)
haftmann@39147
   798
    fun print_stmt prefix_fragments (_, stmt) = print_ml_stmt
haftmann@47576
   799
      tyco_syntax const_syntax (make_vars reserved_syms)
haftmann@50625
   800
      (Code_Thingol.is_constr program) (deresolver prefix_fragments) stmt
haftmann@39147
   801
      |> apfst SOME;
haftmann@39147
   802
haftmann@39147
   803
    (* print modules *)
haftmann@47576
   804
    fun print_module _ base _ xs =
haftmann@39147
   805
      let
haftmann@39147
   806
        val (raw_decls, body) = split_list xs;
haftmann@55677
   807
        val decls = maps these raw_decls
haftmann@39147
   808
      in (NONE, print_ml_module base decls body) end;
haftmann@39147
   809
haftmann@39147
   810
    (* serialization *)
haftmann@39147
   811
    val p = Pretty.chunks2 (map snd includes
haftmann@39147
   812
      @ map snd (Code_Namespace.print_hierarchical {
haftmann@39147
   813
        print_module = print_module, print_stmt = print_stmt,
haftmann@39147
   814
        lift_markup = apsnd } ml_program));
haftmann@39056
   815
    fun write width NONE = writeln o format [] width
haftmann@39056
   816
      | write width (SOME p) = File.write p o format [] width;
haftmann@55147
   817
    fun prepare syms width p = ([("", format syms width p)], try (deresolver []));
haftmann@28054
   818
  in
haftmann@48568
   819
    Code_Target.serialization write prepare p
haftmann@28054
   820
  end;
haftmann@28054
   821
haftmann@38966
   822
val serializer_sml : Code_Target.serializer =
haftmann@55677
   823
  Code_Target.parse_args (Scan.succeed ()) #> K (serialize_ml print_sml_module print_sml_stmt);
haftmann@28054
   824
haftmann@38966
   825
val serializer_ocaml : Code_Target.serializer =
haftmann@55677
   826
  Code_Target.parse_args (Scan.succeed ()) #> K (serialize_ml print_ocaml_module print_ocaml_stmt);
haftmann@28054
   827
haftmann@38966
   828
haftmann@38966
   829
(** Isar setup **)
haftmann@38966
   830
haftmann@52435
   831
fun fun_syntax print_typ fxy [ty1, ty2] =
haftmann@52435
   832
  brackify_infix (1, R) fxy (
haftmann@52435
   833
    print_typ (INFX (1, X)) ty1,
haftmann@52435
   834
    str "->",
haftmann@52435
   835
    print_typ (INFX (1, R)) ty2
haftmann@52435
   836
  );
haftmann@52435
   837
haftmann@28054
   838
val setup =
haftmann@37821
   839
  Code_Target.add_target
haftmann@38966
   840
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
wenzelm@41940
   841
      check = { env_var = "ISABELLE_PROCESS",
wenzelm@41940
   842
        make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@50022
   843
        make_command = fn _ =>
haftmann@51091
   844
          "\"$ISABELLE_PROCESS\" -r -q -e 'datatype ref = datatype Unsynchronized.ref; use \"ROOT.ML\" handle _ => exit 1' Pure" } })
haftmann@37821
   845
  #> Code_Target.add_target
haftmann@38966
   846
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
wenzelm@41952
   847
      check = { env_var = "ISABELLE_OCAML",
wenzelm@41940
   848
        make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
wenzelm@41952
   849
        make_command = fn _ => "\"$ISABELLE_OCAML\" -w pu nums.cma ROOT.ocaml" } })
haftmann@55150
   850
  #> Code_Target.set_printings (Type_Constructor ("fun",
haftmann@52435
   851
    [(target_SML, SOME (2, fun_syntax)), (target_OCaml, SOME (2, fun_syntax))]))
haftmann@28054
   852
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   853
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
   854
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
   855
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   856
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   857
      "and", "as", "assert", "begin", "class",
haftmann@28054
   858
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   859
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   860
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   861
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   862
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   863
      "virtual", "when", "while", "with"
haftmann@28054
   864
    ]
haftmann@34944
   865
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
   866
haftmann@28054
   867
end; (*struct*)