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