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