src/Tools/Code/code_ml.ML
author haftmann
Thu Sep 02 10:29:48 2010 +0200 (2010-09-02)
changeset 39028 0dd6c5a0beef
parent 38966 68853347ba37
child 39031 b27d6643591c
permissions -rw-r--r--
use code_namespace module for SML and OCaml code
haftmann@37745
     1
(*  Title:      Tools/Code/code_ml.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@28054
     4
Serializer for SML and OCaml.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@28054
     7
signature CODE_ML =
haftmann@28054
     8
sig
haftmann@34028
     9
  val target_SML: string
haftmann@37745
    10
  val target_OCaml: string
haftmann@28054
    11
  val setup: theory -> theory
haftmann@28054
    12
end;
haftmann@28054
    13
haftmann@28054
    14
structure Code_ML : CODE_ML =
haftmann@28054
    15
struct
haftmann@28054
    16
haftmann@28054
    17
open Basic_Code_Thingol;
haftmann@28054
    18
open Code_Printer;
haftmann@28054
    19
haftmann@28054
    20
infixr 5 @@;
haftmann@28054
    21
infixr 5 @|;
haftmann@28054
    22
haftmann@33992
    23
haftmann@33992
    24
(** generic **)
haftmann@33992
    25
haftmann@28054
    26
val target_SML = "SML";
haftmann@28054
    27
val target_OCaml = "OCaml";
haftmann@28054
    28
haftmann@33636
    29
datatype ml_binding =
haftmann@35228
    30
    ML_Function of string * (typscheme * ((iterm list * iterm) * (thm option * bool)) list)
haftmann@33636
    31
  | ML_Instance of string * ((class * (string * (vname * sort) list))
haftmann@37445
    32
        * ((class * (string * (string * dict list list))) list
haftmann@37449
    33
      * (((string * const) * (thm * bool)) list * ((string * const) * (thm * bool)) list)));
haftmann@28054
    34
haftmann@33636
    35
datatype ml_stmt =
haftmann@33992
    36
    ML_Exc of string * (typscheme * int)
haftmann@33636
    37
  | ML_Val of ml_binding
haftmann@33636
    38
  | ML_Funs of ml_binding list * string list
haftmann@37449
    39
  | ML_Datas of (string * ((vname * sort) list * ((string * vname list) * itype list) list)) list
haftmann@37447
    40
  | ML_Class of string * (vname * ((class * string) list * (string * itype) list));
haftmann@33636
    41
haftmann@33636
    42
fun stmt_name_of_binding (ML_Function (name, _)) = name
haftmann@33636
    43
  | stmt_name_of_binding (ML_Instance (name, _)) = name;
haftmann@33636
    44
haftmann@33636
    45
fun stmt_names_of (ML_Exc (name, _)) = [name]
haftmann@33636
    46
  | stmt_names_of (ML_Val binding) = [stmt_name_of_binding binding]
haftmann@33636
    47
  | stmt_names_of (ML_Funs (bindings, _)) = map stmt_name_of_binding bindings
haftmann@33636
    48
  | stmt_names_of (ML_Datas ds) = map fst ds
haftmann@33636
    49
  | stmt_names_of (ML_Class (name, _)) = [name];
haftmann@28054
    50
haftmann@33992
    51
fun print_product _ [] = NONE
haftmann@33992
    52
  | print_product print [x] = SOME (print x)
haftmann@34178
    53
  | print_product print xs = (SOME o enum " *" "" "") (map print xs);
haftmann@28054
    54
haftmann@38922
    55
fun tuplify _ _ [] = NONE
haftmann@38922
    56
  | tuplify print fxy [x] = SOME (print fxy x)
haftmann@38922
    57
  | tuplify print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
haftmann@28054
    58
haftmann@33992
    59
haftmann@33992
    60
(** SML serializer **)
haftmann@33992
    61
haftmann@38923
    62
fun print_sml_stmt labelled_name tyco_syntax const_syntax reserved is_cons deresolve =
haftmann@28054
    63
  let
haftmann@33992
    64
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33992
    65
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33992
    66
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33992
    67
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
    68
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@38923
    69
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@33992
    70
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33992
    71
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33992
    72
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33992
    73
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
    74
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
    75
      (map_filter (fn (v, sort) =>
haftmann@33992
    76
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
    77
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
    78
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33992
    79
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
    80
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
    81
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
    82
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
    83
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
    84
          let
haftmann@33992
    85
            val v_p = str (if k = 1 then first_upper v ^ "_"
haftmann@33992
    86
              else first_upper v ^ string_of_int (i+1) ^ "_");
haftmann@33992
    87
          in case classrels
haftmann@33992
    88
           of [] => v_p
haftmann@33992
    89
            | [classrel] => brackets [(str o deresolve) classrel, v_p]
haftmann@33992
    90
            | classrels => brackets
haftmann@34178
    91
                [enum " o" "(" ")" (map (str o deresolve) classrels), v_p]
haftmann@33992
    92
          end
haftmann@38922
    93
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
    94
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
    95
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@35228
    96
    fun print_term is_pseudo_fun some_thm vars fxy (IConst c) =
haftmann@35228
    97
          print_app is_pseudo_fun some_thm vars fxy (c, [])
haftmann@35228
    98
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
    99
          str "_"
haftmann@35228
   100
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   101
          str (lookup_var vars v)
haftmann@35228
   102
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   103
          (case Code_Thingol.unfold_const_app t
haftmann@35228
   104
           of SOME c_ts => print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   105
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   106
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   107
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   108
          let
haftmann@31874
   109
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33992
   110
            fun print_abs (pat, ty) =
haftmann@35228
   111
              print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   112
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@33992
   113
            val (ps, vars') = fold_map print_abs binds vars;
haftmann@35228
   114
          in brackets (ps @ [print_term is_pseudo_fun some_thm vars' NOBR t']) end
haftmann@35228
   115
      | print_term is_pseudo_fun some_thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
   116
          (case Code_Thingol.unfold_const_app t0
haftmann@38923
   117
           of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c)
haftmann@35228
   118
                then print_case is_pseudo_fun some_thm vars fxy cases
haftmann@35228
   119
                else print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   120
            | NONE => print_case is_pseudo_fun some_thm vars fxy cases)
haftmann@37449
   121
    and print_app_expr is_pseudo_fun some_thm vars (app as ((c, ((_, iss), function_typs)), ts)) =
haftmann@29175
   122
      if is_cons c then
haftmann@37449
   123
        let val k = length function_typs in
haftmann@33992
   124
          if k < 2 orelse length ts = k
haftmann@33992
   125
          then (str o deresolve) c
haftmann@38922
   126
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   127
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   128
        end
haftmann@33636
   129
      else if is_pseudo_fun c
haftmann@29175
   130
        then (str o deresolve) c @@ str "()"
haftmann@33992
   131
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@35228
   132
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   133
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   134
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   135
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@35228
   136
    and print_case is_pseudo_fun some_thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   137
          let
haftmann@29952
   138
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   139
            fun print_match ((pat, ty), 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@35228
   152
      | print_case is_pseudo_fun some_thm vars fxy (((t, ty), 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@28054
   167
          end
haftmann@35228
   168
      | print_case is_pseudo_fun some_thm vars fxy ((_, []), _) =
haftmann@31121
   169
          (concat o map str) ["raise", "Fail", "\"empty case\""];
haftmann@33992
   170
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   171
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   172
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   173
      let
haftmann@37449
   174
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37449
   175
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   176
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   177
      in
haftmann@33992
   178
        concat (
haftmann@33992
   179
          str definer
haftmann@33992
   180
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   181
          :: str "="
haftmann@33992
   182
          :: separate (str "|") (map print_co cos)
haftmann@33992
   183
        )
haftmann@33992
   184
      end;
haftmann@33992
   185
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   186
          (ML_Function (name, (vs_ty as (vs, ty), eq :: eqs))) =
haftmann@29189
   187
          let
haftmann@35228
   188
            fun print_eqn definer ((ts, t), (some_thm, _)) =
haftmann@33636
   189
              let
haftmann@33636
   190
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@33636
   191
                val vars = reserved
haftmann@33636
   192
                  |> intro_base_names
haftmann@38923
   193
                       (is_none o const_syntax) deresolve consts
haftmann@33636
   194
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@33636
   195
                       (insert (op =)) ts []);
haftmann@33636
   196
                val prolog = if needs_typ then
haftmann@33992
   197
                  concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@34178
   198
                    else (concat o map str) [definer, deresolve name];
haftmann@33636
   199
              in
haftmann@33636
   200
                concat (
haftmann@33636
   201
                  prolog
haftmann@33636
   202
                  :: (if is_pseudo_fun name then [str "()"]
haftmann@33992
   203
                      else print_dict_args vs
haftmann@35228
   204
                        @ map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@33636
   205
                  @ str "="
haftmann@35228
   206
                  @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33636
   207
                )
haftmann@33636
   208
              end
haftmann@33992
   209
            val shift = if null eqs then I else
haftmann@33992
   210
              map (Pretty.block o single o Pretty.block o single);
haftmann@33992
   211
          in pair
haftmann@33992
   212
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   213
            ((Pretty.block o Pretty.fbreaks o shift) (
haftmann@33992
   214
              print_eqn definer eq
haftmann@33992
   215
              :: map (print_eqn "|") eqs
haftmann@33992
   216
            ))
haftmann@29189
   217
          end
haftmann@33992
   218
      | print_def is_pseudo_fun _ definer
haftmann@37449
   219
          (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@29189
   220
          let
haftmann@37384
   221
            fun print_super_instance (_, (classrel, dss)) =
haftmann@33636
   222
              concat [
haftmann@33636
   223
                (str o Long_Name.base_name o deresolve) classrel,
haftmann@33636
   224
                str "=",
haftmann@33992
   225
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   226
              ];
haftmann@37384
   227
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   228
              concat [
haftmann@33636
   229
                (str o Long_Name.base_name o deresolve) classparam,
haftmann@33636
   230
                str "=",
haftmann@37384
   231
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   232
              ];
haftmann@33992
   233
          in pair
haftmann@33992
   234
            (print_val_decl print_dicttypscheme
haftmann@33992
   235
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   236
            (concat (
haftmann@33636
   237
              str definer
haftmann@33636
   238
              :: (str o deresolve) inst
haftmann@33636
   239
              :: (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   240
                  else print_dict_args vs)
haftmann@33636
   241
              @ str "="
haftmann@34178
   242
              :: enum "," "{" "}"
haftmann@37384
   243
                (map print_super_instance super_instances
haftmann@37384
   244
                  @ map print_classparam_instance classparam_instances)
haftmann@33636
   245
              :: str ":"
haftmann@33992
   246
              @@ print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33992
   247
            ))
haftmann@33636
   248
          end;
haftmann@33992
   249
    fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   250
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   251
          ((semicolon o map str) (
haftmann@33636
   252
            (if n = 0 then "val" else "fun")
haftmann@33636
   253
            :: deresolve name
haftmann@33636
   254
            :: replicate n "_"
haftmann@33636
   255
            @ "="
haftmann@33636
   256
            :: "raise"
haftmann@33636
   257
            :: "Fail"
haftmann@33992
   258
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   259
          ))
haftmann@33992
   260
      | print_stmt (ML_Val binding) =
haftmann@33636
   261
          let
haftmann@33992
   262
            val (sig_p, p) = print_def (K false) true "val" binding
haftmann@33992
   263
          in pair
haftmann@33992
   264
            [sig_p]
haftmann@33992
   265
            (semicolon [p])
haftmann@33992
   266
          end
haftmann@33992
   267
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   268
          let
haftmann@33992
   269
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   270
            fun print_pseudo_fun name = concat [
haftmann@29189
   271
                str "val",
haftmann@29189
   272
                (str o deresolve) name,
haftmann@29189
   273
                str "=",
haftmann@29189
   274
                (str o deresolve) name,
haftmann@29189
   275
                str "();"
haftmann@29189
   276
              ];
haftmann@33992
   277
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   278
              (print_def' "fun" binding :: map (print_def' "and") bindings);
haftmann@33992
   279
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   280
          in pair
haftmann@33992
   281
            sig_ps
haftmann@33992
   282
            (Pretty.chunks (ps @ semicolon [p] :: pseudo_ps))
haftmann@33992
   283
          end
haftmann@33992
   284
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   285
          let
haftmann@33992
   286
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   287
          in
haftmann@33992
   288
            pair
haftmann@33992
   289
            [concat [str "type", ty_p]]
haftmann@33992
   290
            (concat [str "datatype", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   291
          end
haftmann@33992
   292
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   293
          let
haftmann@33992
   294
            val sig_ps = print_datatype_decl "datatype" data
haftmann@33992
   295
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   296
            val (ps, p) = split_last sig_ps;
haftmann@33992
   297
          in pair
haftmann@33992
   298
            sig_ps
haftmann@33992
   299
            (Pretty.chunks (ps @| semicolon [p]))
haftmann@33992
   300
          end
haftmann@37447
   301
     | print_stmt (ML_Class (class, (v, (super_classes, 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@37384
   306
            fun print_super_class_decl (super_class, classrel) =
haftmann@33992
   307
              print_val_decl print_dicttypscheme
haftmann@37384
   308
                (classrel, ([(v, [class])], (super_class, ITyVar v)));
haftmann@37384
   309
            fun print_super_class_field (super_class, classrel) =
haftmann@37384
   310
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@37384
   311
            fun print_super_class_proj (super_class, classrel) =
haftmann@33992
   312
              print_proj (deresolve 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@33992
   316
                (classparam, ([(v, [class])], ty));
haftmann@33992
   317
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   318
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@33992
   319
            fun print_classparam_proj (classparam, ty) =
haftmann@33992
   320
              print_proj (deresolve 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@37384
   324
              :: map print_super_class_decl super_classes
haftmann@33992
   325
              @ map print_classparam_decl classparams)
haftmann@33992
   326
            (Pretty.chunks (
haftmann@28054
   327
              concat [
haftmann@28054
   328
                str ("type '" ^ v),
haftmann@28054
   329
                (str o deresolve) class,
haftmann@28054
   330
                str "=",
haftmann@34178
   331
                enum "," "{" "};" (
haftmann@37384
   332
                  map print_super_class_field super_classes
haftmann@33992
   333
                  @ map print_classparam_field classparams
haftmann@28054
   334
                )
haftmann@28054
   335
              ]
haftmann@37384
   336
              :: map print_super_class_proj super_classes
haftmann@33992
   337
              @ map print_classparam_proj classparams
haftmann@33992
   338
            ))
haftmann@28054
   339
          end;
haftmann@33992
   340
  in print_stmt end;
haftmann@28054
   341
haftmann@38933
   342
fun print_sml_module name some_decls body =
haftmann@38933
   343
  Pretty.chunks2 (
haftmann@33992
   344
    Pretty.chunks (
haftmann@33992
   345
      str ("structure " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   346
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   347
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   348
    )
haftmann@33992
   349
    :: body
haftmann@33992
   350
    @| str ("end; (*struct " ^ name ^ "*)")
haftmann@28054
   351
  );
haftmann@28054
   352
haftmann@28064
   353
val literals_sml = Literals {
haftmann@28064
   354
  literal_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@28064
   355
  literal_string = quote o translate_string ML_Syntax.print_char,
haftmann@34944
   356
  literal_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34944
   357
  literal_positive_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@37958
   358
  literal_alternative_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34944
   359
  literal_naive_numeral = string_of_int,
haftmann@34178
   360
  literal_list = enum "," "[" "]",
haftmann@28064
   361
  infix_cons = (7, "::")
haftmann@28064
   362
};
haftmann@28064
   363
haftmann@28054
   364
haftmann@28054
   365
(** OCaml serializer **)
haftmann@28054
   366
haftmann@38923
   367
fun print_ocaml_stmt labelled_name tyco_syntax const_syntax reserved is_cons deresolve =
haftmann@28054
   368
  let
haftmann@33992
   369
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33992
   370
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33992
   371
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33992
   372
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
   373
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@38923
   374
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@33992
   375
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33992
   376
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33992
   377
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33992
   378
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
   379
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
   380
      (map_filter (fn (v, sort) =>
haftmann@33992
   381
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
   382
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
   383
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33992
   384
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
   385
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
   386
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   387
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
   388
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
   389
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   390
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@33992
   391
          |> fold_rev (fn classrel => fn p =>
haftmann@33992
   392
               Pretty.block [p, str ".", (str o deresolve) classrel]) classrels
haftmann@38922
   393
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
   394
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
   395
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@35228
   396
    fun print_term is_pseudo_fun some_thm vars fxy (IConst c) =
haftmann@35228
   397
          print_app is_pseudo_fun some_thm vars fxy (c, [])
haftmann@35228
   398
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   399
          str "_"
haftmann@35228
   400
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   401
          str (lookup_var vars v)
haftmann@35228
   402
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   403
          (case Code_Thingol.unfold_const_app t
haftmann@35228
   404
           of SOME c_ts => print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   405
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   406
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   407
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   408
          let
haftmann@31874
   409
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
   410
            val (ps, vars') = fold_map (print_bind is_pseudo_fun some_thm BR o fst) binds vars;
haftmann@35228
   411
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun some_thm vars' NOBR t') end
haftmann@35228
   412
      | print_term is_pseudo_fun some_thm vars fxy (ICase (cases as (_, t0))) =
haftmann@33992
   413
          (case Code_Thingol.unfold_const_app t0
haftmann@38923
   414
           of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c)
haftmann@35228
   415
                then print_case is_pseudo_fun some_thm vars fxy cases
haftmann@35228
   416
                else print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   417
            | NONE => print_case is_pseudo_fun some_thm vars fxy cases)
haftmann@35228
   418
    and print_app_expr is_pseudo_fun some_thm vars (app as ((c, ((_, iss), tys)), ts)) =
haftmann@28054
   419
      if is_cons c then
haftmann@33992
   420
        let val k = length tys in
haftmann@33992
   421
          if length ts = k
haftmann@33992
   422
          then (str o deresolve) c
haftmann@38922
   423
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   424
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   425
        end
haftmann@33636
   426
      else if is_pseudo_fun c
haftmann@29175
   427
        then (str o deresolve) c @@ str "()"
haftmann@33992
   428
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@35228
   429
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   430
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   431
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   432
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@35228
   433
    and print_case is_pseudo_fun some_thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   434
          let
haftmann@29952
   435
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   436
            fun print_let ((pat, ty), t) vars =
haftmann@28054
   437
              vars
haftmann@35228
   438
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   439
              |>> (fn p => concat
haftmann@35228
   440
                  [str "let", p, str "=", print_term is_pseudo_fun some_thm vars NOBR t, str "in"])
haftmann@33992
   441
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   442
          in
haftmann@31665
   443
            brackify_block fxy (Pretty.chunks ps) []
haftmann@35228
   444
              (print_term is_pseudo_fun some_thm vars' NOBR body)
haftmann@31665
   445
          end
haftmann@35228
   446
      | print_case is_pseudo_fun some_thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   447
          let
haftmann@33992
   448
            fun print_select delim (pat, body) =
haftmann@28054
   449
              let
haftmann@35228
   450
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@35228
   451
              in concat [str delim, p, str "->", print_term is_pseudo_fun some_thm vars' NOBR body] end;
haftmann@28054
   452
          in
haftmann@31665
   453
            brackets (
haftmann@28054
   454
              str "match"
haftmann@35228
   455
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   456
              :: print_select "with" clause
haftmann@33992
   457
              :: map (print_select "|") clauses
haftmann@28054
   458
            )
haftmann@28054
   459
          end
haftmann@35228
   460
      | print_case is_pseudo_fun some_thm vars fxy ((_, []), _) =
haftmann@31121
   461
          (concat o map str) ["failwith", "\"empty case\""];
haftmann@33992
   462
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   463
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   464
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   465
      let
haftmann@37449
   466
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37449
   467
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   468
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   469
      in
haftmann@33992
   470
        concat (
haftmann@33992
   471
          str definer
haftmann@33992
   472
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   473
          :: str "="
haftmann@33992
   474
          :: separate (str "|") (map print_co cos)
haftmann@33992
   475
        )
haftmann@33992
   476
      end;
haftmann@33992
   477
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   478
          (ML_Function (name, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   479
          let
haftmann@35228
   480
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   481
              let
haftmann@32913
   482
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   483
                val vars = reserved
haftmann@32924
   484
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   485
                      (insert (op =)) ts []);
haftmann@28054
   486
              in concat [
haftmann@38778
   487
                (Pretty.block o commas)
haftmann@35228
   488
                  (map (print_term is_pseudo_fun some_thm vars NOBR) ts),
haftmann@28054
   489
                str "->",
haftmann@35228
   490
                print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   491
              ] end;
haftmann@35228
   492
            fun print_eqns is_pseudo [((ts, t), (some_thm, _))] =
haftmann@28054
   493
                  let
haftmann@32913
   494
                    val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   495
                    val vars = reserved
haftmann@32924
   496
                      |> intro_base_names
haftmann@38923
   497
                          (is_none o const_syntax) deresolve consts
haftmann@32924
   498
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   499
                          (insert (op =)) ts []);
haftmann@28054
   500
                  in
haftmann@28054
   501
                    concat (
haftmann@29189
   502
                      (if is_pseudo then [str "()"]
haftmann@35228
   503
                        else map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@28054
   504
                      @ str "="
haftmann@35228
   505
                      @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   506
                    )
haftmann@28054
   507
                  end
haftmann@33992
   508
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   509
                  Pretty.block (
haftmann@28054
   510
                    str "="
haftmann@28054
   511
                    :: Pretty.brk 1
haftmann@28054
   512
                    :: str "function"
haftmann@28054
   513
                    :: Pretty.brk 1
haftmann@33992
   514
                    :: print_eqn eq
haftmann@28054
   515
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   516
                          o single o print_eqn) eqs
haftmann@28054
   517
                  )
haftmann@33992
   518
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   519
                  let
haftmann@32913
   520
                    val consts = fold Code_Thingol.add_constnames (map (snd o fst) eqs) [];
haftmann@32924
   521
                    val vars = reserved
haftmann@32924
   522
                      |> intro_base_names
haftmann@38923
   523
                          (is_none o const_syntax) deresolve consts;
haftmann@32924
   524
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   525
                  in
haftmann@28054
   526
                    Pretty.block (
haftmann@28054
   527
                      Pretty.breaks dummy_parms
haftmann@28054
   528
                      @ Pretty.brk 1
haftmann@28054
   529
                      :: str "="
haftmann@28054
   530
                      :: Pretty.brk 1
haftmann@28054
   531
                      :: str "match"
haftmann@28054
   532
                      :: Pretty.brk 1
haftmann@38778
   533
                      :: (Pretty.block o commas) dummy_parms
haftmann@28054
   534
                      :: Pretty.brk 1
haftmann@28054
   535
                      :: str "with"
haftmann@28054
   536
                      :: Pretty.brk 1
haftmann@33992
   537
                      :: print_eqn eq
haftmann@28054
   538
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   539
                           o single o print_eqn) eqs'
haftmann@28054
   540
                    )
haftmann@28054
   541
                  end;
haftmann@33636
   542
            val prolog = if needs_typ then
haftmann@33992
   543
              concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@34178
   544
                else (concat o map str) [definer, deresolve name];
haftmann@33992
   545
          in pair
haftmann@33992
   546
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   547
            (concat (
haftmann@33636
   548
              prolog
haftmann@33992
   549
              :: print_dict_args vs
haftmann@33992
   550
              @| print_eqns (is_pseudo_fun name) eqs
haftmann@33992
   551
            ))
haftmann@33636
   552
          end
haftmann@37384
   553
      | print_def is_pseudo_fun _ definer
haftmann@37449
   554
            (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@33636
   555
          let
haftmann@37384
   556
            fun print_super_instance (_, (classrel, dss)) =
haftmann@33636
   557
              concat [
haftmann@33636
   558
                (str o deresolve) classrel,
haftmann@33636
   559
                str "=",
haftmann@33992
   560
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   561
              ];
haftmann@37384
   562
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   563
              concat [
haftmann@33636
   564
                (str o deresolve) classparam,
haftmann@33636
   565
                str "=",
haftmann@37384
   566
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   567
              ];
haftmann@33992
   568
          in pair
haftmann@33992
   569
            (print_val_decl print_dicttypscheme
haftmann@33992
   570
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   571
            (concat (
haftmann@33636
   572
              str definer
haftmann@33636
   573
              :: (str o deresolve) inst
haftmann@33992
   574
              :: print_dict_args vs
haftmann@33636
   575
              @ str "="
haftmann@33636
   576
              @@ brackets [
haftmann@37384
   577
                enum_default "()" ";" "{" "}" (map print_super_instance super_instances
haftmann@37384
   578
                  @ map print_classparam_instance classparam_instances),
haftmann@33636
   579
                str ":",
haftmann@33992
   580
                print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33636
   581
              ]
haftmann@33992
   582
            ))
haftmann@33636
   583
          end;
haftmann@33992
   584
     fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   585
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   586
          ((doublesemicolon o map str) (
haftmann@33636
   587
            "let"
haftmann@33636
   588
            :: deresolve name
haftmann@33636
   589
            :: replicate n "_"
haftmann@33636
   590
            @ "="
haftmann@33636
   591
            :: "failwith"
haftmann@33992
   592
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   593
          ))
haftmann@33992
   594
      | print_stmt (ML_Val binding) =
haftmann@33636
   595
          let
haftmann@33992
   596
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   597
          in pair
haftmann@33992
   598
            [sig_p]
haftmann@33992
   599
            (doublesemicolon [p])
haftmann@33992
   600
          end
haftmann@33992
   601
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   602
          let
haftmann@33992
   603
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   604
            fun print_pseudo_fun name = concat [
haftmann@29189
   605
                str "let",
haftmann@29189
   606
                (str o deresolve) name,
haftmann@29189
   607
                str "=",
haftmann@29189
   608
                (str o deresolve) name,
haftmann@29189
   609
                str "();;"
haftmann@29189
   610
              ];
haftmann@33992
   611
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   612
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   613
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   614
          in pair
haftmann@33992
   615
            sig_ps
haftmann@33992
   616
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   617
          end
haftmann@33992
   618
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   619
          let
haftmann@33992
   620
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   621
          in
haftmann@33992
   622
            pair
haftmann@33992
   623
            [concat [str "type", ty_p]]
haftmann@33992
   624
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   625
          end
haftmann@33992
   626
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   627
          let
haftmann@33992
   628
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   629
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   630
            val (ps, p) = split_last sig_ps;
haftmann@33992
   631
          in pair
haftmann@33992
   632
            sig_ps
haftmann@33992
   633
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   634
          end
haftmann@37447
   635
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@28054
   636
          let
haftmann@33992
   637
            fun print_field s p = concat [str s, str ":", p];
haftmann@37384
   638
            fun print_super_class_field (super_class, classrel) =
haftmann@37384
   639
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33992
   640
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   641
              print_val_decl print_typscheme
haftmann@33992
   642
                (classparam, ([(v, [class])], ty));
haftmann@33992
   643
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   644
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@32924
   645
            val w = "_" ^ first_upper v;
haftmann@33992
   646
            fun print_classparam_proj (classparam, _) =
haftmann@33992
   647
              (concat o map str) ["let", deresolve classparam, w, "=",
haftmann@33992
   648
                w ^ "." ^ deresolve classparam ^ ";;"];
haftmann@33992
   649
            val type_decl_p = concat [
haftmann@33992
   650
                str ("type '" ^ v),
haftmann@33992
   651
                (str o deresolve) class,
haftmann@28054
   652
                str "=",
haftmann@33992
   653
                enum_default "unit" ";" "{" "}" (
haftmann@37384
   654
                  map print_super_class_field super_classes
haftmann@33992
   655
                  @ map print_classparam_field classparams
haftmann@33992
   656
                )
haftmann@28054
   657
              ];
haftmann@33992
   658
          in pair
haftmann@33992
   659
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   660
            (Pretty.chunks (
haftmann@33992
   661
              doublesemicolon [type_decl_p]
haftmann@33992
   662
              :: map print_classparam_proj classparams
haftmann@33992
   663
            ))
haftmann@33992
   664
          end;
haftmann@33992
   665
  in print_stmt end;
haftmann@28054
   666
haftmann@38933
   667
fun print_ocaml_module name some_decls body =
haftmann@38933
   668
  Pretty.chunks2 (
haftmann@33992
   669
    Pretty.chunks (
haftmann@33992
   670
      str ("module " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   671
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   672
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   673
    )
haftmann@33992
   674
    :: body
haftmann@33992
   675
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   676
  );
haftmann@28054
   677
haftmann@28064
   678
val literals_ocaml = let
haftmann@28064
   679
  fun chr i =
haftmann@28064
   680
    let
haftmann@28064
   681
      val xs = string_of_int i;
haftmann@28064
   682
      val ys = replicate_string (3 - length (explode xs)) "0";
haftmann@28064
   683
    in "\\" ^ ys ^ xs end;
haftmann@28064
   684
  fun char_ocaml c =
haftmann@28064
   685
    let
haftmann@28064
   686
      val i = ord c;
haftmann@28064
   687
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   688
        then chr i else c
haftmann@28064
   689
    in s end;
haftmann@34944
   690
  fun numeral_ocaml k = if k < 0
haftmann@34944
   691
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34944
   692
    else if k <= 1073741823
haftmann@34944
   693
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34944
   694
      else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   695
in Literals {
haftmann@34178
   696
  literal_char = Library.enclose "'" "'" o char_ocaml,
haftmann@28064
   697
  literal_string = quote o translate_string char_ocaml,
haftmann@34944
   698
  literal_numeral = numeral_ocaml,
haftmann@34944
   699
  literal_positive_numeral = numeral_ocaml,
haftmann@37958
   700
  literal_alternative_numeral = numeral_ocaml,
haftmann@34944
   701
  literal_naive_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@39028
   710
fun ml_program_of_program labelled_name reserved module_alias program =
haftmann@39028
   711
  let
haftmann@39028
   712
    fun namify_const upper base (nsp_const, nsp_type) =
haftmann@39028
   713
      let
haftmann@39028
   714
        val (base', nsp_const') = yield_singleton Name.variants
haftmann@39028
   715
          (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
haftmann@39028
   719
        val (base', nsp_type') = yield_singleton Name.variants 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@39028
   728
    fun ml_binding_of_stmt (name, 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@39028
   731
            val (eqs', some_value_name) = 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@39028
   734
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@39028
   735
                | _ => (eqs, NONE)
haftmann@39028
   736
              else (eqs, NONE)
haftmann@39028
   737
          in (ML_Function (name, (tysm, eqs')), some_value_name) end
haftmann@39028
   738
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as ((_, (_, vs)), _))) =
haftmann@39028
   739
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@39028
   740
      | ml_binding_of_stmt (name, _) =
haftmann@39028
   741
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@39028
   742
    fun modify_fun (name, stmt) =
haftmann@39028
   743
      let
haftmann@39028
   744
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@39028
   745
        val ml_stmt = case binding
haftmann@39028
   746
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@39028
   747
              ML_Exc (name, ((vs, ty),
haftmann@39028
   748
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@39028
   749
          | _ => case some_value_name
haftmann@39028
   750
             of NONE => ML_Funs ([binding], [])
haftmann@39028
   751
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@39028
   752
              | SOME (name, false) => ML_Val binding
haftmann@39028
   753
      in SOME ml_stmt end;
haftmann@39028
   754
    fun modify_funs stmts =
haftmann@39028
   755
      (SOME (ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst))
haftmann@39028
   756
        :: replicate (length stmts - 1) NONE)
haftmann@39028
   757
    fun modify_datatypes stmts =
haftmann@39028
   758
      (SOME (ML_Datas (map_filter
haftmann@39028
   759
        (fn (name, Code_Thingol.Datatype (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts))
haftmann@39028
   760
        :: replicate (length stmts - 1) NONE)
haftmann@39028
   761
    fun modify_class stmts =
haftmann@39028
   762
      (SOME (ML_Class (the_single (map_filter
haftmann@39028
   763
        (fn (name, Code_Thingol.Class (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts)))
haftmann@39028
   764
        :: replicate (length stmts - 1) NONE)
haftmann@39028
   765
    fun modify_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@39028
   766
          [modify_fun stmt]
haftmann@39028
   767
      | modify_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@39028
   768
          modify_funs stmts
haftmann@39028
   769
      | modify_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@39028
   770
          modify_datatypes stmts
haftmann@39028
   771
      | modify_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@39028
   772
          modify_datatypes stmts
haftmann@39028
   773
      | modify_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@39028
   774
          modify_class stmts
haftmann@39028
   775
      | modify_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@39028
   776
          modify_class stmts
haftmann@39028
   777
      | modify_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@39028
   778
          modify_class stmts
haftmann@39028
   779
      | modify_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@39028
   780
          [modify_fun stmt]
haftmann@39028
   781
      | modify_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@39028
   782
          modify_funs stmts
haftmann@39028
   783
      | modify_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@39028
   784
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@39028
   785
  in
haftmann@39028
   786
    Code_Namespace.hierarchical_program labelled_name { module_alias = module_alias, reserved = reserved,
haftmann@39028
   787
      empty_nsp = (reserved, reserved), namify_module = pair, namify_stmt = namify_stmt,
haftmann@39028
   788
      cyclic_modules = false, empty_data = (), memorize_data = K I, modify_stmts = modify_stmts } program
haftmann@39028
   789
  end;
haftmann@39028
   790
haftmann@28054
   791
local
haftmann@28054
   792
haftmann@28054
   793
datatype ml_node =
haftmann@28054
   794
    Dummy of string
haftmann@28054
   795
  | Stmt of string * ml_stmt
haftmann@28054
   796
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   797
haftmann@28054
   798
in
haftmann@28054
   799
haftmann@38924
   800
fun ml_node_of_program labelled_name reserved module_alias program =
haftmann@28054
   801
  let
haftmann@32924
   802
    val reserved = Name.make_context reserved;
haftmann@32924
   803
    val empty_module = ((reserved, reserved), Graph.empty);
haftmann@28054
   804
    fun map_node [] f = f
haftmann@28054
   805
      | map_node (m::ms) f =
haftmann@28054
   806
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   807
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   808
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   809
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   810
          let
haftmann@28054
   811
            val (x, nsp') = f nsp
haftmann@28054
   812
          in (x, (nsp', nodes)) end
haftmann@28054
   813
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   814
          let
haftmann@28054
   815
            val (x, nodes') =
haftmann@28054
   816
              nodes
haftmann@28054
   817
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   818
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   819
                  let
haftmann@28054
   820
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   821
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   822
          in (x, (nsp, nodes')) end;
haftmann@28054
   823
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   824
      let
haftmann@28054
   825
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   826
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   827
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   828
      let
haftmann@28054
   829
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   830
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@32924
   831
    val mk_name_module = mk_name_module reserved NONE module_alias program;
haftmann@28054
   832
    fun mk_name_stmt upper name nsp =
haftmann@28054
   833
      let
haftmann@32924
   834
        val (_, base) = dest_name name;
haftmann@32924
   835
        val base' = if upper then first_upper base else base;
haftmann@28054
   836
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   837
      in (base'', nsp') end;
haftmann@37439
   838
    fun deps_of names =
haftmann@37439
   839
      []
haftmann@37439
   840
      |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@37439
   841
      |> subtract (op =) names
haftmann@37439
   842
      |> filter_out (Code_Thingol.is_case o Graph.get_node program);
haftmann@37437
   843
    fun ml_binding_of_stmt (name, Code_Thingol.Fun (_, ((tysm as (vs, ty), raw_eqs), _))) =
haftmann@33636
   844
          let
haftmann@33636
   845
            val eqs = filter (snd o snd) raw_eqs;
haftmann@33636
   846
            val (eqs', is_value) = if null (filter_out (null o snd) vs) then case eqs
haftmann@35228
   847
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@35228
   848
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@33636
   849
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@33636
   850
                | _ => (eqs, NONE)
haftmann@33636
   851
              else (eqs, NONE)
haftmann@33636
   852
          in (ML_Function (name, (tysm, eqs')), is_value) end
haftmann@33992
   853
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as ((_, (_, vs)), _))) =
haftmann@33992
   854
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@33636
   855
      | ml_binding_of_stmt (name, _) =
haftmann@33636
   856
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@33636
   857
    fun add_fun (name, stmt) =
haftmann@29189
   858
      let
haftmann@33636
   859
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@33636
   860
        val ml_stmt = case binding
haftmann@33636
   861
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@33992
   862
              ML_Exc (name, ((vs, ty),
haftmann@33992
   863
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@33636
   864
          | _ => case some_value_name
haftmann@33636
   865
             of NONE => ML_Funs ([binding], [])
haftmann@33636
   866
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@33636
   867
              | SOME (name, false) => ML_Val binding
haftmann@33636
   868
      in
haftmann@33636
   869
        map_nsp_fun_yield (mk_name_stmt false name)
haftmann@33636
   870
        #>> (fn name' => ([name'], ml_stmt))
haftmann@33636
   871
      end;
haftmann@33636
   872
    fun add_funs stmts =
haftmann@33636
   873
      let
haftmann@33636
   874
        val ml_stmt = ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst);
haftmann@33636
   875
      in
haftmann@33636
   876
        fold_map (fn (name, _) => map_nsp_fun_yield (mk_name_stmt false name)) stmts
haftmann@33636
   877
        #>> rpair ml_stmt
haftmann@33636
   878
      end;
haftmann@28054
   879
    fun add_datatypes stmts =
haftmann@28054
   880
      fold_map
haftmann@28663
   881
        (fn (name, Code_Thingol.Datatype (_, stmt)) =>
haftmann@28054
   882
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   883
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   884
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   885
          | (name, _) =>
haftmann@28054
   886
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   887
        ) stmts
haftmann@28054
   888
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   889
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@38778
   890
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   891
             | stmts => ML_Datas stmts)));
haftmann@28054
   892
    fun add_class stmts =
haftmann@28054
   893
      fold_map
haftmann@28663
   894
        (fn (name, Code_Thingol.Class (_, stmt)) =>
haftmann@28663
   895
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   896
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   897
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   898
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   899
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   900
          | (name, _) =>
haftmann@28054
   901
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   902
        ) stmts
haftmann@28054
   903
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   904
        #> (fn [] => error ("Class block without class statement: "
haftmann@38778
   905
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   906
             | [stmt] => ML_Class stmt)));
haftmann@33636
   907
    fun add_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@33636
   908
          add_fun stmt
haftmann@33636
   909
      | add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   910
          add_funs stmts
haftmann@28054
   911
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   912
          add_datatypes stmts
haftmann@28054
   913
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   914
          add_datatypes stmts
haftmann@28054
   915
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   916
          add_class stmts
haftmann@28054
   917
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   918
          add_class stmts
haftmann@28054
   919
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   920
          add_class stmts
haftmann@33636
   921
      | add_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@33636
   922
          add_fun stmt
haftmann@33636
   923
      | add_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@33636
   924
          add_funs stmts
haftmann@28054
   925
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@38778
   926
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@28054
   927
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   928
      let
haftmann@28054
   929
        val names as (name :: names') = map fst stmts;
haftmann@37439
   930
        val deps = deps_of names;
haftmann@32924
   931
        val (module_names, _) = (split_list o map dest_name) names;
haftmann@28054
   932
        val module_name = (the_single o distinct (op =) o map mk_name_module) module_names
haftmann@28054
   933
          handle Empty =>
haftmann@28054
   934
            error ("Different namespace prefixes for mutual dependencies:\n"
haftmann@38778
   935
              ^ Library.commas (map labelled_name names)
haftmann@28054
   936
              ^ "\n"
haftmann@38778
   937
              ^ Library.commas module_names);
wenzelm@30364
   938
        val module_name_path = Long_Name.explode module_name;
haftmann@28054
   939
        fun add_dep name name' =
haftmann@28054
   940
          let
haftmann@32924
   941
            val module_name' = (mk_name_module o fst o dest_name) name';
haftmann@28054
   942
          in if module_name = module_name' then
haftmann@28054
   943
            map_node module_name_path (Graph.add_edge (name, name'))
haftmann@28054
   944
          else let
haftmann@28705
   945
            val (common, (diff1 :: _, diff2 :: _)) = chop_prefix (op =)
wenzelm@30364
   946
              (module_name_path, Long_Name.explode module_name');
haftmann@28054
   947
          in
haftmann@28054
   948
            map_node common
haftmann@28054
   949
              (fn node => Graph.add_edge_acyclic (diff1, diff2) node
haftmann@28054
   950
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@28054
   951
                  ^ quote name ^ " -> " ^ quote name'
haftmann@28054
   952
                  ^ " would result in module dependency cycle"))
haftmann@28054
   953
          end end;
haftmann@28054
   954
      in
haftmann@28054
   955
        nsp_nodes
haftmann@28054
   956
        |> map_nsp_yield module_name_path (add_stmts stmts)
haftmann@28054
   957
        |-> (fn (base' :: bases', stmt') =>
haftmann@28054
   958
           apsnd (map_node module_name_path (Graph.new_node (name, (Stmt (base', stmt')))
haftmann@28054
   959
              #> fold2 (fn name' => fn base' =>
haftmann@28054
   960
                   Graph.new_node (name', (Dummy base'))) names' bases')))
haftmann@28054
   961
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@28054
   962
        |> apsnd (fold_product (curry (map_node module_name_path o Graph.add_edge)) names names)
haftmann@28054
   963
      end;
haftmann@37439
   964
    val stmts = map (AList.make (Graph.get_node program)) (rev (Graph.strong_conn program))
haftmann@37439
   965
      |> filter_out (fn [(_, stmt)] => Code_Thingol.is_case stmt | _ => false);
haftmann@37439
   966
    val (_, nodes) = fold add_stmts' stmts empty_module;
haftmann@28054
   967
    fun deresolver prefix name = 
haftmann@28054
   968
      let
haftmann@32924
   969
        val module_name = (fst o dest_name) name;
wenzelm@30364
   970
        val module_name' = (Long_Name.explode o mk_name_module) module_name;
haftmann@28054
   971
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, module_name');
haftmann@28054
   972
        val stmt_name =
haftmann@28054
   973
          nodes
haftmann@28054
   974
          |> fold (fn name => fn node => case Graph.get_node node name
haftmann@28054
   975
              of Module (_, (_, node)) => node) module_name'
haftmann@28054
   976
          |> (fn node => case Graph.get_node node name of Stmt (stmt_name, _) => stmt_name
haftmann@28054
   977
               | Dummy stmt_name => stmt_name);
haftmann@28054
   978
      in
wenzelm@30364
   979
        Long_Name.implode (remainder @ [stmt_name])
haftmann@28054
   980
      end handle Graph.UNDEF _ =>
haftmann@28054
   981
        error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   982
  in (deresolver, nodes) end;
haftmann@28054
   983
haftmann@38926
   984
fun serialize_ml target print_module print_stmt with_signatures { labelled_name,
haftmann@38928
   985
  reserved_syms, includes, module_alias, class_syntax, tyco_syntax,
haftmann@38926
   986
  const_syntax, program, names, presentation_names } =
haftmann@28054
   987
  let
haftmann@28054
   988
    val is_cons = Code_Thingol.is_cons program;
haftmann@38926
   989
    val is_presentation = not (null presentation_names);
haftmann@39028
   990
    val { deresolver, hierarchical_program = ml_program } =
haftmann@39028
   991
      ml_program_of_program labelled_name (Name.make_context reserved_syms) module_alias program;
haftmann@39028
   992
    fun print_node _ (_, Code_Namespace.Dummy) =
haftmann@28054
   993
          NONE
haftmann@39028
   994
      | print_node prefix_fragments (_, Code_Namespace.Stmt stmt) =
haftmann@39028
   995
          if is_presentation andalso
haftmann@39028
   996
            (null o filter (member (op =) presentation_names) o stmt_names_of) stmt
haftmann@30962
   997
          then NONE
haftmann@39028
   998
          else SOME (print_stmt labelled_name tyco_syntax const_syntax (make_vars reserved_syms)
haftmann@39028
   999
            is_cons (deresolver prefix_fragments) stmt)
haftmann@39028
  1000
      | print_node prefix_fragments (name_fragment, Code_Namespace.Module (_, nodes)) =
haftmann@33992
  1001
          let
haftmann@39028
  1002
            val (decls, body) = print_nodes (prefix_fragments @ [name_fragment]) nodes;
haftmann@33992
  1003
            val p = if is_presentation then Pretty.chunks2 body
haftmann@39028
  1004
              else print_module name_fragment
haftmann@39028
  1005
                (if with_signatures then SOME decls else NONE) body;
haftmann@33992
  1006
          in SOME ([], p) end
haftmann@39028
  1007
    and print_nodes prefix_fragments nodes = (map_filter
haftmann@39028
  1008
        (fn name => print_node prefix_fragments (name, snd (Graph.get_node nodes name)))
haftmann@33992
  1009
        o rev o flat o Graph.strong_conn) nodes
haftmann@33992
  1010
      |> split_list
haftmann@33992
  1011
      |> (fn (decls, body) => (flat decls, body))
haftmann@38928
  1012
    val names' = map (try (deresolver [])) names;
haftmann@39028
  1013
    val p = Pretty.chunks2 (map snd includes @ snd (print_nodes [] ml_program));
haftmann@38915
  1014
    fun write width NONE = writeln_pretty width
haftmann@38915
  1015
      | write width (SOME p) = File.write p o string_of_pretty width;
haftmann@28054
  1016
  in
haftmann@38926
  1017
    Code_Target.serialization write (fn width => (rpair names' o string_of_pretty width)) p
haftmann@28054
  1018
  end;
haftmann@28054
  1019
haftmann@28054
  1020
end; (*local*)
haftmann@28054
  1021
haftmann@38966
  1022
val serializer_sml : Code_Target.serializer =
haftmann@33992
  1023
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33992
  1024
  >> (fn with_signatures => serialize_ml target_SML
haftmann@38924
  1025
      print_sml_module print_sml_stmt with_signatures));
haftmann@28054
  1026
haftmann@38966
  1027
val serializer_ocaml : Code_Target.serializer =
haftmann@33992
  1028
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@37748
  1029
  >> (fn with_signatures => serialize_ml target_OCaml
haftmann@38924
  1030
      print_ocaml_module print_ocaml_stmt with_signatures));
haftmann@28054
  1031
haftmann@38966
  1032
haftmann@38966
  1033
(** Isar setup **)
haftmann@38966
  1034
haftmann@28054
  1035
val setup =
haftmann@37821
  1036
  Code_Target.add_target
haftmann@38966
  1037
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
haftmann@37822
  1038
      check = { env_var = "ISABELLE_PROCESS", make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@38863
  1039
        make_command = fn isabelle => fn _ => isabelle ^ " -r -q -u Pure" } })
haftmann@37821
  1040
  #> Code_Target.add_target
haftmann@38966
  1041
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
haftmann@37822
  1042
      check = { env_var = "EXEC_OCAML", make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
haftmann@38863
  1043
        make_command = fn ocaml => fn _ => ocaml ^ " -w pu nums.cma ROOT.ocaml" } })
haftmann@38923
  1044
  #> Code_Target.add_tyco_syntax target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
  1045
      brackify_infix (1, R) fxy (
haftmann@33992
  1046
        print_typ (INFX (1, X)) ty1,
haftmann@28054
  1047
        str "->",
haftmann@33992
  1048
        print_typ (INFX (1, R)) ty2
haftmann@37242
  1049
      )))
haftmann@38923
  1050
  #> Code_Target.add_tyco_syntax target_OCaml "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
  1051
      brackify_infix (1, R) fxy (
haftmann@33992
  1052
        print_typ (INFX (1, X)) ty1,
haftmann@28054
  1053
        str "->",
haftmann@33992
  1054
        print_typ (INFX (1, R)) ty2
haftmann@37242
  1055
      )))
haftmann@28054
  1056
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
  1057
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
  1058
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
  1059
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
  1060
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
  1061
      "and", "as", "assert", "begin", "class",
haftmann@28054
  1062
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
  1063
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
  1064
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
  1065
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
  1066
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
  1067
      "virtual", "when", "while", "with"
haftmann@28054
  1068
    ]
haftmann@34944
  1069
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
  1070
haftmann@28054
  1071
end; (*struct*)