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