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