src/Tools/Code/code_ml.ML
author haftmann
Sat Jan 25 23:50:49 2014 +0100 (2014-01-25)
changeset 55147 bce3dbc11f95
parent 55145 2bb3cd36bcf7
child 55150 0940309ed8f1
permissions -rw-r--r--
prefer explicit code symbol type over ad-hoc name mangling
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@28054
    17
open Basic_Code_Thingol;
haftmann@28054
    18
open Code_Printer;
haftmann@28054
    19
haftmann@28054
    20
infixr 5 @@;
haftmann@28054
    21
infixr 5 @|;
haftmann@28054
    22
haftmann@33992
    23
haftmann@33992
    24
(** generic **)
haftmann@33992
    25
haftmann@28054
    26
val target_SML = "SML";
haftmann@28054
    27
val target_OCaml = "OCaml";
haftmann@28054
    28
haftmann@33636
    29
datatype ml_binding =
haftmann@35228
    30
    ML_Function of string * (typscheme * ((iterm list * iterm) * (thm option * bool)) list)
haftmann@55147
    31
  | ML_Instance of (string * class) * { class: class, tyco: string, vs: (vname * sort) list,
haftmann@55147
    32
        superinsts: (class * dict list list) list,
haftmann@52519
    33
        inst_params: ((string * (const * int)) * (thm * bool)) list,
haftmann@52519
    34
        superinst_params: ((string * (const * int)) * (thm * bool)) list };
haftmann@28054
    35
haftmann@33636
    36
datatype ml_stmt =
haftmann@33992
    37
    ML_Exc of string * (typscheme * int)
haftmann@33636
    38
  | ML_Val of ml_binding
haftmann@55147
    39
  | ML_Funs of ml_binding list * Code_Symbol.symbol list
haftmann@48003
    40
  | ML_Datas of (string * (vname list * ((string * vname list) * itype list) list)) list
haftmann@55147
    41
  | ML_Class of string * (vname * ((class * class) list * (string * itype) list));
haftmann@33636
    42
haftmann@33992
    43
fun print_product _ [] = NONE
haftmann@33992
    44
  | print_product print [x] = SOME (print x)
haftmann@34178
    45
  | print_product print xs = (SOME o enum " *" "" "") (map print xs);
haftmann@28054
    46
haftmann@38922
    47
fun tuplify _ _ [] = NONE
haftmann@38922
    48
  | tuplify print fxy [x] = SOME (print fxy x)
haftmann@38922
    49
  | tuplify print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
haftmann@28054
    50
haftmann@33992
    51
haftmann@33992
    52
(** SML serializer **)
haftmann@33992
    53
haftmann@50625
    54
fun print_sml_stmt tyco_syntax const_syntax reserved is_constr deresolve =
haftmann@28054
    55
  let
haftmann@55147
    56
    val deresolve_const = deresolve o Code_Symbol.Constant;
haftmann@55147
    57
    val deresolve_tyco = deresolve o Code_Symbol.Type_Constructor;
haftmann@55147
    58
    val deresolve_class = deresolve o Code_Symbol.Type_Class;
haftmann@55147
    59
    val deresolve_classrel = deresolve o Code_Symbol.Class_Relation;
haftmann@55147
    60
    val deresolve_inst = deresolve o Code_Symbol.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@55147
    67
         of NONE => print_tyco_expr (Code_Symbol.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@55147
    70
    fun print_dicttyp (class, ty) = print_tyco_expr (Code_Symbol.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@55147
    84
            (if is_pseudo_fun (Code_Symbol.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@55147
   113
           of SOME (app as ({ sym = Code_Symbol.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@55147
   177
          :: print_tyco_expr (Code_Symbol.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@55147
   198
                  :: (if is_pseudo_fun (Code_Symbol.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@55147
   208
            (print_val_decl print_typscheme (Code_Symbol.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@55147
   231
              (Code_Symbol.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@55147
   235
              :: (if is_pseudo_fun (Code_Symbol.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@55147
   246
          [print_val_decl print_typscheme (Code_Symbol.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@55147
   282
            val ty_p = print_tyco_expr (Code_Symbol.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@55147
   304
                (Code_Symbol.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@55147
   312
                (Code_Symbol.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@38933
   338
fun print_sml_module name some_decls body =
haftmann@38933
   339
  Pretty.chunks2 (
haftmann@33992
   340
    Pretty.chunks (
haftmann@33992
   341
      str ("structure " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   342
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   343
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   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@55147
   362
    val deresolve_const = deresolve o Code_Symbol.Constant;
haftmann@55147
   363
    val deresolve_tyco = deresolve o Code_Symbol.Type_Constructor;
haftmann@55147
   364
    val deresolve_class = deresolve o Code_Symbol.Type_Class;
haftmann@55147
   365
    val deresolve_classrel = deresolve o Code_Symbol.Class_Relation;
haftmann@55147
   366
    val deresolve_inst = deresolve o Code_Symbol.Class_Instance;
haftmann@55147
   367
    fun print_tyco_expr (sym, []) = (str o deresolve) sym
haftmann@55147
   368
      | print_tyco_expr (sym, [ty]) =
haftmann@55147
   369
          concat [print_typ BR ty, (str o deresolve) sym]
haftmann@55147
   370
      | print_tyco_expr (sym, tys) =
haftmann@55147
   371
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) sym]
haftmann@38923
   372
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55147
   373
         of NONE => print_tyco_expr (Code_Symbol.Type_Constructor tyco, tys)
haftmann@47576
   374
          | SOME (_, print) => print print_typ fxy tys)
haftmann@33992
   375
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@55147
   376
    fun print_dicttyp (class, ty) = print_tyco_expr (Code_Symbol.Type_Class class, [ty]);
haftmann@34178
   377
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
   378
      (map_filter (fn (v, sort) =>
haftmann@33992
   379
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
   380
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
   381
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@41100
   382
    val print_classrels =
haftmann@55147
   383
      fold_rev (fn classrel => fn p => Pretty.block [p, str ".", (str o deresolve_classrel) classrel])
haftmann@41118
   384
    fun print_dict is_pseudo_fun fxy (Dict (classrels, x)) =
haftmann@41118
   385
      print_plain_dict is_pseudo_fun fxy x
haftmann@41118
   386
      |> print_classrels classrels
haftmann@41118
   387
    and print_plain_dict is_pseudo_fun fxy (Dict_Const (inst, dss)) =
haftmann@55147
   388
          brackify BR ((str o deresolve_inst) inst ::
haftmann@55147
   389
            (if is_pseudo_fun (Code_Symbol.Class_Instance inst) then [str "()"]
haftmann@33992
   390
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@41118
   391
      | print_plain_dict is_pseudo_fun fxy (Dict_Var (v, (i, k))) =
haftmann@33992
   392
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   393
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@38922
   394
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
   395
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@41118
   396
      (map_index (fn (i, _) => Dict ([], Dict_Var (v, (i, length sort)))) sort));
haftmann@48072
   397
    fun print_term is_pseudo_fun some_thm vars fxy (IConst const) =
haftmann@48072
   398
          print_app is_pseudo_fun some_thm vars fxy (const, [])
haftmann@35228
   399
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   400
          str "_"
haftmann@35228
   401
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   402
          str (lookup_var vars v)
haftmann@35228
   403
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   404
          (case Code_Thingol.unfold_const_app t
haftmann@48072
   405
           of SOME app => print_app is_pseudo_fun some_thm vars fxy app
haftmann@35228
   406
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   407
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   408
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   409
          let
haftmann@31874
   410
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
   411
            val (ps, vars') = fold_map (print_bind is_pseudo_fun some_thm BR o fst) binds vars;
haftmann@35228
   412
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun some_thm vars' NOBR t') end
haftmann@48072
   413
      | print_term is_pseudo_fun some_thm vars fxy (ICase case_expr) =
haftmann@48072
   414
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55147
   415
           of SOME (app as ({ sym = Code_Symbol.Constant const, ... }, _)) =>
haftmann@55147
   416
                if is_none (const_syntax const)
haftmann@48072
   417
                then print_case is_pseudo_fun some_thm vars fxy case_expr
haftmann@48072
   418
                else print_app is_pseudo_fun some_thm vars fxy app
haftmann@48072
   419
            | NONE => print_case is_pseudo_fun some_thm vars fxy case_expr)
haftmann@55147
   420
    and print_app_expr is_pseudo_fun some_thm vars (app as ({ sym, dicts = dss, dom = dom, ... }, ts)) =
haftmann@55147
   421
      if is_constr sym then
haftmann@48072
   422
        let val k = length dom in
haftmann@33992
   423
          if length ts = k
haftmann@55147
   424
          then (str o deresolve) sym
haftmann@38922
   425
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   426
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   427
        end
haftmann@55147
   428
      else if is_pseudo_fun sym
haftmann@55147
   429
        then (str o deresolve) sym @@ str "()"
haftmann@55147
   430
      else (str o deresolve) sym :: map_filter (print_dicts is_pseudo_fun BR) dss
haftmann@35228
   431
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   432
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   433
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   434
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@48072
   435
    and print_case is_pseudo_fun some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   436
          (concat o map str) ["failwith", "\"empty case\""]
haftmann@48072
   437
      | print_case is_pseudo_fun some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   438
          let
haftmann@48072
   439
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47576
   440
            fun print_let ((pat, _), t) vars =
haftmann@28054
   441
              vars
haftmann@35228
   442
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   443
              |>> (fn p => concat
haftmann@35228
   444
                  [str "let", p, str "=", print_term is_pseudo_fun some_thm vars NOBR t, str "in"])
haftmann@33992
   445
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   446
          in
haftmann@31665
   447
            brackify_block fxy (Pretty.chunks ps) []
haftmann@35228
   448
              (print_term is_pseudo_fun some_thm vars' NOBR body)
haftmann@31665
   449
          end
haftmann@48072
   450
      | print_case is_pseudo_fun some_thm vars fxy { term = t, typ = ty, clauses = clause :: clauses, ... } =
haftmann@28054
   451
          let
haftmann@33992
   452
            fun print_select delim (pat, body) =
haftmann@28054
   453
              let
haftmann@35228
   454
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@35228
   455
              in concat [str delim, p, str "->", print_term is_pseudo_fun some_thm vars' NOBR body] end;
haftmann@28054
   456
          in
haftmann@31665
   457
            brackets (
haftmann@28054
   458
              str "match"
haftmann@35228
   459
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   460
              :: print_select "with" clause
haftmann@33992
   461
              :: map (print_select "|") clauses
haftmann@28054
   462
            )
haftmann@48072
   463
          end;
haftmann@55147
   464
    fun print_val_decl print_typscheme (sym, typscheme) = concat
haftmann@55147
   465
      [str "val", str (deresolve sym), str ":", print_typscheme typscheme];
haftmann@33992
   466
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   467
      let
haftmann@55147
   468
        fun print_co ((co, _), []) = str (deresolve_const co)
haftmann@55147
   469
          | print_co ((co, _), tys) = concat [str (deresolve_const co), str "of",
haftmann@34178
   470
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   471
      in
haftmann@33992
   472
        concat (
haftmann@33992
   473
          str definer
haftmann@55147
   474
          :: print_tyco_expr (Code_Symbol.Type_Constructor tyco, map ITyVar vs)
haftmann@33992
   475
          :: str "="
haftmann@33992
   476
          :: separate (str "|") (map print_co cos)
haftmann@33992
   477
        )
haftmann@33992
   478
      end;
haftmann@33992
   479
    fun print_def is_pseudo_fun needs_typ definer
haftmann@55147
   480
          (ML_Function (const, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   481
          let
haftmann@35228
   482
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   483
              let
haftmann@32924
   484
                val vars = reserved
haftmann@55145
   485
                  |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   486
                      deresolve (t :: ts)
haftmann@32924
   487
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   488
                      (insert (op =)) ts []);
haftmann@28054
   489
              in concat [
haftmann@38778
   490
                (Pretty.block o commas)
haftmann@35228
   491
                  (map (print_term is_pseudo_fun some_thm vars NOBR) ts),
haftmann@28054
   492
                str "->",
haftmann@35228
   493
                print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   494
              ] end;
haftmann@35228
   495
            fun print_eqns is_pseudo [((ts, t), (some_thm, _))] =
haftmann@28054
   496
                  let
haftmann@32924
   497
                    val vars = reserved
haftmann@55145
   498
                      |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   499
                          deresolve (t :: ts)
haftmann@32924
   500
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   501
                          (insert (op =)) ts []);
haftmann@28054
   502
                  in
haftmann@28054
   503
                    concat (
haftmann@29189
   504
                      (if is_pseudo then [str "()"]
haftmann@35228
   505
                        else map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@28054
   506
                      @ str "="
haftmann@35228
   507
                      @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   508
                    )
haftmann@28054
   509
                  end
haftmann@33992
   510
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   511
                  Pretty.block (
haftmann@28054
   512
                    str "="
haftmann@28054
   513
                    :: Pretty.brk 1
haftmann@28054
   514
                    :: str "function"
haftmann@28054
   515
                    :: Pretty.brk 1
haftmann@33992
   516
                    :: print_eqn eq
haftmann@28054
   517
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   518
                          o single o print_eqn) eqs
haftmann@28054
   519
                  )
haftmann@33992
   520
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   521
                  let
haftmann@32924
   522
                    val vars = reserved
haftmann@55145
   523
                      |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   524
                           deresolve (map (snd o fst) eqs)
haftmann@32924
   525
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   526
                  in
haftmann@28054
   527
                    Pretty.block (
haftmann@28054
   528
                      Pretty.breaks dummy_parms
haftmann@28054
   529
                      @ Pretty.brk 1
haftmann@28054
   530
                      :: str "="
haftmann@28054
   531
                      :: Pretty.brk 1
haftmann@28054
   532
                      :: str "match"
haftmann@28054
   533
                      :: Pretty.brk 1
haftmann@38778
   534
                      :: (Pretty.block o commas) dummy_parms
haftmann@28054
   535
                      :: Pretty.brk 1
haftmann@28054
   536
                      :: str "with"
haftmann@28054
   537
                      :: Pretty.brk 1
haftmann@33992
   538
                      :: print_eqn eq
haftmann@28054
   539
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   540
                           o single o print_eqn) eqs'
haftmann@28054
   541
                    )
haftmann@28054
   542
                  end;
haftmann@33636
   543
            val prolog = if needs_typ then
haftmann@55147
   544
              concat [str definer, (str o deresolve_const) const, str ":", print_typ NOBR ty]
haftmann@55147
   545
                else (concat o map str) [definer, deresolve_const const];
haftmann@33992
   546
          in pair
haftmann@55147
   547
            (print_val_decl print_typscheme (Code_Symbol.Constant const, vs_ty))
haftmann@33992
   548
            (concat (
haftmann@33636
   549
              prolog
haftmann@33992
   550
              :: print_dict_args vs
haftmann@55147
   551
              @| print_eqns (is_pseudo_fun (Code_Symbol.Constant const)) eqs
haftmann@33992
   552
            ))
haftmann@33636
   553
          end
haftmann@37384
   554
      | print_def is_pseudo_fun _ definer
haftmann@55147
   555
          (ML_Instance (inst as (tyco, class), { vs, superinsts, inst_params, ... })) =
haftmann@33636
   556
          let
haftmann@55147
   557
            fun print_super_instance (super_class, x) =
haftmann@33636
   558
              concat [
haftmann@55147
   559
                (str o deresolve_classrel) (class, super_class),
haftmann@33636
   560
                str "=",
haftmann@55147
   561
                print_dict is_pseudo_fun NOBR (Dict ([], Dict_Const ((tyco, super_class), x)))
haftmann@33636
   562
              ];
haftmann@52519
   563
            fun print_classparam_instance ((classparam, (const, _)), (thm, _)) =
haftmann@33636
   564
              concat [
haftmann@55147
   565
                (str o deresolve_const) classparam,
haftmann@33636
   566
                str "=",
haftmann@37384
   567
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   568
              ];
haftmann@33992
   569
          in pair
haftmann@33992
   570
            (print_val_decl print_dicttypscheme
haftmann@55147
   571
              (Code_Symbol.Class_Instance inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   572
            (concat (
haftmann@33636
   573
              str definer
haftmann@55147
   574
              :: (str o deresolve_inst) inst
haftmann@55147
   575
              :: (if is_pseudo_fun (Code_Symbol.Class_Instance inst) then [str "()"]
bulwahn@43343
   576
                  else print_dict_args vs)
haftmann@33636
   577
              @ str "="
haftmann@33636
   578
              @@ brackets [
haftmann@48072
   579
                enum_default "()" ";" "{" "}" (map print_super_instance superinsts
haftmann@48072
   580
                  @ map print_classparam_instance inst_params),
haftmann@33636
   581
                str ":",
haftmann@55147
   582
                print_dicttyp (class, tyco `%% map (ITyVar o fst) vs)
haftmann@33636
   583
              ]
haftmann@33992
   584
            ))
haftmann@33636
   585
          end;
haftmann@55147
   586
     fun print_stmt (ML_Exc (const, (vs_ty, n))) = pair
haftmann@55147
   587
          [print_val_decl print_typscheme (Code_Symbol.Constant const, vs_ty)]
haftmann@33992
   588
          ((doublesemicolon o map str) (
haftmann@33636
   589
            "let"
haftmann@55147
   590
            :: deresolve_const const
haftmann@33636
   591
            :: replicate n "_"
haftmann@33636
   592
            @ "="
haftmann@33636
   593
            :: "failwith"
haftmann@55147
   594
            @@ ML_Syntax.print_string const
haftmann@33992
   595
          ))
haftmann@33992
   596
      | print_stmt (ML_Val binding) =
haftmann@33636
   597
          let
haftmann@33992
   598
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   599
          in pair
haftmann@33992
   600
            [sig_p]
haftmann@33992
   601
            (doublesemicolon [p])
haftmann@33992
   602
          end
haftmann@33992
   603
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   604
          let
haftmann@33992
   605
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@55147
   606
            fun print_pseudo_fun sym = concat [
haftmann@29189
   607
                str "let",
haftmann@55147
   608
                (str o deresolve) sym,
haftmann@29189
   609
                str "=",
haftmann@55147
   610
                (str o deresolve) sym,
haftmann@29189
   611
                str "();;"
haftmann@29189
   612
              ];
haftmann@33992
   613
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   614
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   615
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   616
          in pair
haftmann@33992
   617
            sig_ps
haftmann@33992
   618
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   619
          end
haftmann@33992
   620
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   621
          let
haftmann@55147
   622
            val ty_p = print_tyco_expr (Code_Symbol.Type_Constructor tyco, map ITyVar vs);
haftmann@33992
   623
          in
haftmann@33992
   624
            pair
haftmann@33992
   625
            [concat [str "type", ty_p]]
haftmann@33992
   626
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   627
          end
haftmann@33992
   628
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   629
          let
haftmann@33992
   630
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   631
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   632
            val (ps, p) = split_last sig_ps;
haftmann@33992
   633
          in pair
haftmann@33992
   634
            sig_ps
haftmann@33992
   635
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   636
          end
haftmann@55147
   637
     | print_stmt (ML_Class (class, (v, (classrels, classparams)))) =
haftmann@28054
   638
          let
haftmann@33992
   639
            fun print_field s p = concat [str s, str ":", p];
haftmann@55147
   640
            fun print_super_class_field (classrel as (_, super_class)) =
haftmann@55147
   641
              print_field (deresolve_classrel classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33992
   642
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   643
              print_val_decl print_typscheme
haftmann@55147
   644
                (Code_Symbol.Constant classparam, ([(v, [class])], ty));
haftmann@33992
   645
            fun print_classparam_field (classparam, ty) =
haftmann@55147
   646
              print_field (deresolve_const classparam) (print_typ NOBR ty);
haftmann@32924
   647
            val w = "_" ^ first_upper v;
haftmann@33992
   648
            fun print_classparam_proj (classparam, _) =
haftmann@55147
   649
              (concat o map str) ["let", deresolve_const classparam, w, "=",
haftmann@55147
   650
                w ^ "." ^ deresolve_const classparam ^ ";;"];
haftmann@33992
   651
            val type_decl_p = concat [
haftmann@33992
   652
                str ("type '" ^ v),
haftmann@55147
   653
                (str o deresolve_class) class,
haftmann@28054
   654
                str "=",
haftmann@33992
   655
                enum_default "unit" ";" "{" "}" (
haftmann@55147
   656
                  map print_super_class_field classrels
haftmann@33992
   657
                  @ map print_classparam_field classparams
haftmann@33992
   658
                )
haftmann@28054
   659
              ];
haftmann@33992
   660
          in pair
haftmann@33992
   661
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   662
            (Pretty.chunks (
haftmann@33992
   663
              doublesemicolon [type_decl_p]
haftmann@33992
   664
              :: map print_classparam_proj classparams
haftmann@33992
   665
            ))
haftmann@33992
   666
          end;
haftmann@33992
   667
  in print_stmt end;
haftmann@28054
   668
haftmann@38933
   669
fun print_ocaml_module name some_decls body =
haftmann@38933
   670
  Pretty.chunks2 (
haftmann@33992
   671
    Pretty.chunks (
haftmann@33992
   672
      str ("module " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   673
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   674
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   675
    )
haftmann@33992
   676
    :: body
haftmann@33992
   677
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   678
  );
haftmann@28054
   679
haftmann@28064
   680
val literals_ocaml = let
haftmann@28064
   681
  fun chr i =
haftmann@28064
   682
    let
haftmann@28064
   683
      val xs = string_of_int i;
wenzelm@40627
   684
      val ys = replicate_string (3 - length (raw_explode xs)) "0";
haftmann@28064
   685
    in "\\" ^ ys ^ xs end;
haftmann@28064
   686
  fun char_ocaml c =
haftmann@28064
   687
    let
haftmann@28064
   688
      val i = ord c;
haftmann@28064
   689
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   690
        then chr i else c
haftmann@28064
   691
    in s end;
haftmann@34944
   692
  fun numeral_ocaml k = if k < 0
haftmann@34944
   693
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34944
   694
    else if k <= 1073741823
haftmann@34944
   695
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34944
   696
      else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   697
in Literals {
haftmann@34178
   698
  literal_char = Library.enclose "'" "'" o char_ocaml,
haftmann@28064
   699
  literal_string = quote o translate_string char_ocaml,
haftmann@34944
   700
  literal_numeral = numeral_ocaml,
haftmann@34178
   701
  literal_list = enum ";" "[" "]",
haftmann@28064
   702
  infix_cons = (6, "::")
haftmann@28064
   703
} end;
haftmann@28064
   704
haftmann@28064
   705
haftmann@28054
   706
haftmann@28054
   707
(** SML/OCaml generic part **)
haftmann@28054
   708
haftmann@55147
   709
fun ml_program_of_program ctxt module_name reserved identifiers program =
haftmann@39028
   710
  let
haftmann@39028
   711
    fun namify_const upper base (nsp_const, nsp_type) =
haftmann@39028
   712
      let
wenzelm@43326
   713
        val (base', nsp_const') =
wenzelm@43326
   714
          Name.variant (if upper then first_upper base else base) nsp_const
haftmann@39028
   715
      in (base', (nsp_const', nsp_type)) end;
haftmann@39028
   716
    fun namify_type base (nsp_const, nsp_type) =
haftmann@39028
   717
      let
wenzelm@43326
   718
        val (base', nsp_type') = Name.variant base nsp_type
haftmann@39028
   719
      in (base', (nsp_const, nsp_type')) end;
haftmann@39028
   720
    fun namify_stmt (Code_Thingol.Fun _) = namify_const false
haftmann@39028
   721
      | namify_stmt (Code_Thingol.Datatype _) = namify_type
haftmann@39028
   722
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_const true
haftmann@39028
   723
      | namify_stmt (Code_Thingol.Class _) = namify_type
haftmann@39028
   724
      | namify_stmt (Code_Thingol.Classrel _) = namify_const false
haftmann@39028
   725
      | namify_stmt (Code_Thingol.Classparam _) = namify_const false
haftmann@39028
   726
      | namify_stmt (Code_Thingol.Classinst _) = namify_const false;
haftmann@55147
   727
    fun ml_binding_of_stmt (sym as Code_Symbol.Constant const, Code_Thingol.Fun ((tysm as (vs, ty), raw_eqs), _)) =
haftmann@39028
   728
          let
haftmann@39028
   729
            val eqs = filter (snd o snd) raw_eqs;
haftmann@55147
   730
            val (eqs', some_sym) = if null (filter_out (null o snd) vs) then case eqs
haftmann@39028
   731
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@39028
   732
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@55147
   733
                  else (eqs, SOME (sym, member (op =) (Code_Thingol.add_constsyms t []) sym))
haftmann@39028
   734
                | _ => (eqs, NONE)
haftmann@39028
   735
              else (eqs, NONE)
haftmann@55147
   736
          in (ML_Function (const, (tysm, eqs')), some_sym) end
haftmann@55147
   737
      | ml_binding_of_stmt (sym as Code_Symbol.Class_Instance inst, Code_Thingol.Classinst (stmt as { vs, ... })) =
haftmann@55147
   738
          (ML_Instance (inst, stmt), if forall (null o snd) vs then SOME (sym, false) else NONE)
haftmann@55147
   739
      | ml_binding_of_stmt (sym, _) =
haftmann@52138
   740
          error ("Binding block containing illegal statement: " ^ 
haftmann@55147
   741
            Code_Symbol.quote ctxt sym)
haftmann@55147
   742
    fun modify_fun (sym, stmt) =
haftmann@39028
   743
      let
haftmann@55147
   744
        val (binding, some_value_sym) = ml_binding_of_stmt (sym, stmt);
haftmann@39028
   745
        val ml_stmt = case binding
haftmann@55147
   746
         of ML_Function (const, ((vs, ty), [])) =>
haftmann@55147
   747
              ML_Exc (const, ((vs, ty),
haftmann@39028
   748
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@55147
   749
          | _ => case some_value_sym
haftmann@39028
   750
             of NONE => ML_Funs ([binding], [])
haftmann@55147
   751
              | SOME (sym, true) => ML_Funs ([binding], [sym])
haftmann@55147
   752
              | SOME (sym, false) => ML_Val binding
haftmann@39028
   753
      in SOME ml_stmt end;
haftmann@39031
   754
    fun modify_funs stmts = single (SOME
haftmann@39031
   755
      (ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst)))
haftmann@39031
   756
    fun modify_datatypes stmts = single (SOME
haftmann@39031
   757
      (ML_Datas (map_filter
haftmann@55147
   758
        (fn (Code_Symbol.Type_Constructor tyco, Code_Thingol.Datatype stmt) => SOME (tyco, stmt) | _ => NONE) stmts)))
haftmann@39031
   759
    fun modify_class stmts = single (SOME
haftmann@39031
   760
      (ML_Class (the_single (map_filter
haftmann@55147
   761
        (fn (Code_Symbol.Type_Class class, Code_Thingol.Class stmt) => SOME (class, stmt) | _ => NONE) stmts))))
haftmann@47576
   762
    fun modify_stmts ([stmt as (_, stmt' as Code_Thingol.Fun _)]) =
haftmann@39059
   763
          if Code_Thingol.is_case stmt' then [] else [modify_fun stmt]
haftmann@55147
   764
      | modify_stmts ((stmts as (_, Code_Thingol.Fun _) :: _)) =
haftmann@39061
   765
          modify_funs (filter_out (Code_Thingol.is_case o snd) stmts)
haftmann@55147
   766
      | modify_stmts ((stmts as (_, Code_Thingol.Datatypecons _) :: _)) =
haftmann@39028
   767
          modify_datatypes stmts
haftmann@55147
   768
      | modify_stmts ((stmts as (_, Code_Thingol.Datatype _) :: _)) =
haftmann@39028
   769
          modify_datatypes stmts
haftmann@55147
   770
      | modify_stmts ((stmts as (_, Code_Thingol.Class _) :: _)) =
haftmann@39028
   771
          modify_class stmts
haftmann@55147
   772
      | modify_stmts ((stmts as (_, Code_Thingol.Classrel _) :: _)) =
haftmann@39028
   773
          modify_class stmts
haftmann@55147
   774
      | modify_stmts ((stmts as (_, Code_Thingol.Classparam _) :: _)) =
haftmann@39028
   775
          modify_class stmts
haftmann@39028
   776
      | modify_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@39028
   777
          [modify_fun stmt]
haftmann@55147
   778
      | modify_stmts ((stmts as (_, Code_Thingol.Classinst _) :: _)) =
haftmann@39028
   779
          modify_funs stmts
haftmann@39028
   780
      | modify_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@55147
   781
          (Library.commas o map (Code_Symbol.quote ctxt o fst)) stmts);
haftmann@39028
   782
  in
haftmann@55147
   783
    Code_Namespace.hierarchical_program ctxt {
haftmann@52138
   784
      module_name = module_name, reserved = reserved, identifiers = identifiers,
haftmann@39028
   785
      empty_nsp = (reserved, reserved), namify_module = pair, namify_stmt = namify_stmt,
haftmann@39028
   786
      cyclic_modules = false, empty_data = (), memorize_data = K I, modify_stmts = modify_stmts } program
haftmann@39028
   787
  end;
haftmann@39028
   788
haftmann@52138
   789
fun serialize_ml print_ml_module print_ml_stmt with_signatures ctxt
haftmann@55147
   790
    { module_name, reserved_syms, identifiers, includes,
haftmann@41343
   791
      class_syntax, tyco_syntax, const_syntax } program =
haftmann@28054
   792
  let
haftmann@39147
   793
haftmann@39147
   794
    (* build program *)
haftmann@39028
   795
    val { deresolver, hierarchical_program = ml_program } =
haftmann@55147
   796
      ml_program_of_program ctxt module_name (Name.make_context reserved_syms) identifiers program;
haftmann@39147
   797
haftmann@39147
   798
    (* print statements *)
haftmann@39147
   799
    fun print_stmt prefix_fragments (_, stmt) = print_ml_stmt
haftmann@47576
   800
      tyco_syntax const_syntax (make_vars reserved_syms)
haftmann@50625
   801
      (Code_Thingol.is_constr program) (deresolver prefix_fragments) stmt
haftmann@39147
   802
      |> apfst SOME;
haftmann@39147
   803
haftmann@39147
   804
    (* print modules *)
haftmann@47576
   805
    fun print_module _ base _ xs =
haftmann@39147
   806
      let
haftmann@39147
   807
        val (raw_decls, body) = split_list xs;
haftmann@39147
   808
        val decls = if with_signatures then SOME (maps these raw_decls) else NONE 
haftmann@39147
   809
      in (NONE, print_ml_module base decls body) end;
haftmann@39147
   810
haftmann@39147
   811
    (* serialization *)
haftmann@39147
   812
    val p = Pretty.chunks2 (map snd includes
haftmann@39147
   813
      @ map snd (Code_Namespace.print_hierarchical {
haftmann@39147
   814
        print_module = print_module, print_stmt = print_stmt,
haftmann@39147
   815
        lift_markup = apsnd } ml_program));
haftmann@39056
   816
    fun write width NONE = writeln o format [] width
haftmann@39056
   817
      | write width (SOME p) = File.write p o format [] width;
haftmann@55147
   818
    fun prepare syms width p = ([("", format syms width p)], try (deresolver []));
haftmann@28054
   819
  in
haftmann@48568
   820
    Code_Target.serialization write prepare p
haftmann@28054
   821
  end;
haftmann@28054
   822
haftmann@38966
   823
val serializer_sml : Code_Target.serializer =
haftmann@33992
   824
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@47576
   825
  >> (fn with_signatures => serialize_ml print_sml_module print_sml_stmt with_signatures));
haftmann@28054
   826
haftmann@38966
   827
val serializer_ocaml : Code_Target.serializer =
haftmann@33992
   828
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@47576
   829
  >> (fn with_signatures => serialize_ml print_ocaml_module print_ocaml_stmt with_signatures));
haftmann@28054
   830
haftmann@38966
   831
haftmann@38966
   832
(** Isar setup **)
haftmann@38966
   833
haftmann@52435
   834
fun fun_syntax print_typ fxy [ty1, ty2] =
haftmann@52435
   835
  brackify_infix (1, R) fxy (
haftmann@52435
   836
    print_typ (INFX (1, X)) ty1,
haftmann@52435
   837
    str "->",
haftmann@52435
   838
    print_typ (INFX (1, R)) ty2
haftmann@52435
   839
  );
haftmann@52435
   840
haftmann@28054
   841
val setup =
haftmann@37821
   842
  Code_Target.add_target
haftmann@38966
   843
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
wenzelm@41940
   844
      check = { env_var = "ISABELLE_PROCESS",
wenzelm@41940
   845
        make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@50022
   846
        make_command = fn _ =>
haftmann@51091
   847
          "\"$ISABELLE_PROCESS\" -r -q -e 'datatype ref = datatype Unsynchronized.ref; use \"ROOT.ML\" handle _ => exit 1' Pure" } })
haftmann@37821
   848
  #> Code_Target.add_target
haftmann@38966
   849
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
wenzelm@41952
   850
      check = { env_var = "ISABELLE_OCAML",
wenzelm@41940
   851
        make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
wenzelm@41952
   852
        make_command = fn _ => "\"$ISABELLE_OCAML\" -w pu nums.cma ROOT.ocaml" } })
haftmann@52435
   853
  #> Code_Target.set_printings (Code_Symbol.Type_Constructor ("fun",
haftmann@52435
   854
    [(target_SML, SOME (2, fun_syntax)), (target_OCaml, SOME (2, fun_syntax))]))
haftmann@28054
   855
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   856
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
   857
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
   858
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   859
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   860
      "and", "as", "assert", "begin", "class",
haftmann@28054
   861
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   862
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   863
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   864
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   865
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   866
      "virtual", "when", "while", "with"
haftmann@28054
   867
    ]
haftmann@34944
   868
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
   869
haftmann@28054
   870
end; (*struct*)