src/Tools/Code/code_ml.ML
author haftmann
Thu Sep 02 10:33:13 2010 +0200 (2010-09-02)
changeset 39031 b27d6643591c
parent 39028 0dd6c5a0beef
child 39034 ebeb48fd653b
permissions -rw-r--r--
dropped dead code; tuned
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@39031
   754
    fun modify_funs stmts = single (SOME
haftmann@39031
   755
      (ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst)))
haftmann@39031
   756
    fun modify_datatypes stmts = single (SOME
haftmann@39031
   757
      (ML_Datas (map_filter
haftmann@39031
   758
        (fn (name, Code_Thingol.Datatype (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts)))
haftmann@39031
   759
    fun modify_class stmts = single (SOME
haftmann@39031
   760
      (ML_Class (the_single (map_filter
haftmann@39031
   761
        (fn (name, Code_Thingol.Class (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts))))
haftmann@39028
   762
    fun modify_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@39028
   763
          [modify_fun stmt]
haftmann@39028
   764
      | modify_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@39028
   765
          modify_funs stmts
haftmann@39028
   766
      | modify_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@39028
   767
          modify_datatypes stmts
haftmann@39028
   768
      | modify_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@39028
   769
          modify_datatypes stmts
haftmann@39028
   770
      | modify_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@39028
   771
          modify_class stmts
haftmann@39028
   772
      | modify_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@39028
   773
          modify_class stmts
haftmann@39028
   774
      | modify_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@39028
   775
          modify_class stmts
haftmann@39028
   776
      | modify_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@39028
   777
          [modify_fun stmt]
haftmann@39028
   778
      | modify_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@39028
   779
          modify_funs stmts
haftmann@39028
   780
      | modify_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@39028
   781
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@39028
   782
  in
haftmann@39028
   783
    Code_Namespace.hierarchical_program labelled_name { module_alias = module_alias, reserved = reserved,
haftmann@39028
   784
      empty_nsp = (reserved, reserved), namify_module = pair, namify_stmt = namify_stmt,
haftmann@39028
   785
      cyclic_modules = false, empty_data = (), memorize_data = K I, modify_stmts = modify_stmts } program
haftmann@39028
   786
  end;
haftmann@39028
   787
haftmann@38926
   788
fun serialize_ml target print_module print_stmt with_signatures { labelled_name,
haftmann@38928
   789
  reserved_syms, includes, module_alias, class_syntax, tyco_syntax,
haftmann@38926
   790
  const_syntax, program, names, presentation_names } =
haftmann@28054
   791
  let
haftmann@28054
   792
    val is_cons = Code_Thingol.is_cons program;
haftmann@38926
   793
    val is_presentation = not (null presentation_names);
haftmann@39028
   794
    val { deresolver, hierarchical_program = ml_program } =
haftmann@39028
   795
      ml_program_of_program labelled_name (Name.make_context reserved_syms) module_alias program;
haftmann@39028
   796
    fun print_node _ (_, Code_Namespace.Dummy) =
haftmann@28054
   797
          NONE
haftmann@39028
   798
      | print_node prefix_fragments (_, Code_Namespace.Stmt stmt) =
haftmann@39028
   799
          if is_presentation andalso
haftmann@39028
   800
            (null o filter (member (op =) presentation_names) o stmt_names_of) stmt
haftmann@30962
   801
          then NONE
haftmann@39028
   802
          else SOME (print_stmt labelled_name tyco_syntax const_syntax (make_vars reserved_syms)
haftmann@39028
   803
            is_cons (deresolver prefix_fragments) stmt)
haftmann@39028
   804
      | print_node prefix_fragments (name_fragment, Code_Namespace.Module (_, nodes)) =
haftmann@33992
   805
          let
haftmann@39028
   806
            val (decls, body) = print_nodes (prefix_fragments @ [name_fragment]) nodes;
haftmann@33992
   807
            val p = if is_presentation then Pretty.chunks2 body
haftmann@39028
   808
              else print_module name_fragment
haftmann@39028
   809
                (if with_signatures then SOME decls else NONE) body;
haftmann@33992
   810
          in SOME ([], p) end
haftmann@39028
   811
    and print_nodes prefix_fragments nodes = (map_filter
haftmann@39028
   812
        (fn name => print_node prefix_fragments (name, snd (Graph.get_node nodes name)))
haftmann@33992
   813
        o rev o flat o Graph.strong_conn) nodes
haftmann@33992
   814
      |> split_list
haftmann@33992
   815
      |> (fn (decls, body) => (flat decls, body))
haftmann@38928
   816
    val names' = map (try (deresolver [])) names;
haftmann@39028
   817
    val p = Pretty.chunks2 (map snd includes @ snd (print_nodes [] ml_program));
haftmann@38915
   818
    fun write width NONE = writeln_pretty width
haftmann@38915
   819
      | write width (SOME p) = File.write p o string_of_pretty width;
haftmann@28054
   820
  in
haftmann@38926
   821
    Code_Target.serialization write (fn width => (rpair names' o string_of_pretty width)) p
haftmann@28054
   822
  end;
haftmann@28054
   823
haftmann@38966
   824
val serializer_sml : Code_Target.serializer =
haftmann@33992
   825
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33992
   826
  >> (fn with_signatures => serialize_ml target_SML
haftmann@38924
   827
      print_sml_module print_sml_stmt with_signatures));
haftmann@28054
   828
haftmann@38966
   829
val serializer_ocaml : Code_Target.serializer =
haftmann@33992
   830
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@37748
   831
  >> (fn with_signatures => serialize_ml target_OCaml
haftmann@38924
   832
      print_ocaml_module print_ocaml_stmt with_signatures));
haftmann@28054
   833
haftmann@38966
   834
haftmann@38966
   835
(** Isar setup **)
haftmann@38966
   836
haftmann@28054
   837
val setup =
haftmann@37821
   838
  Code_Target.add_target
haftmann@38966
   839
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
haftmann@37822
   840
      check = { env_var = "ISABELLE_PROCESS", make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@38863
   841
        make_command = fn isabelle => fn _ => isabelle ^ " -r -q -u Pure" } })
haftmann@37821
   842
  #> Code_Target.add_target
haftmann@38966
   843
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
haftmann@37822
   844
      check = { env_var = "EXEC_OCAML", make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
haftmann@38863
   845
        make_command = fn ocaml => fn _ => ocaml ^ " -w pu nums.cma ROOT.ocaml" } })
haftmann@38923
   846
  #> Code_Target.add_tyco_syntax target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   847
      brackify_infix (1, R) fxy (
haftmann@33992
   848
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   849
        str "->",
haftmann@33992
   850
        print_typ (INFX (1, R)) ty2
haftmann@37242
   851
      )))
haftmann@38923
   852
  #> Code_Target.add_tyco_syntax target_OCaml "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   853
      brackify_infix (1, R) fxy (
haftmann@33992
   854
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   855
        str "->",
haftmann@33992
   856
        print_typ (INFX (1, R)) ty2
haftmann@37242
   857
      )))
haftmann@28054
   858
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   859
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
   860
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
   861
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   862
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   863
      "and", "as", "assert", "begin", "class",
haftmann@28054
   864
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   865
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   866
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   867
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   868
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   869
      "virtual", "when", "while", "with"
haftmann@28054
   870
    ]
haftmann@34944
   871
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
   872
haftmann@28054
   873
end; (*struct*)