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