src/Tools/Code/code_ml.ML
author haftmann
Wed, 01 Sep 2010 08:52:49 +0200
changeset 39192 68853347ba37
parent 39159 bd77e092f67c
child 39272 0dd6c5a0beef
permissions -rw-r--r--
tuned internally and made smlnj happy
haftmann@37744
     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@34026
     9
  val target_SML: string
haftmann@37744
    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@33989
    23
haftmann@33989
    24
(** generic **)
haftmann@33989
    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@37420
    32
        * ((class * (string * (string * dict list list))) list
haftmann@37424
    33
      * (((string * const) * (thm * bool)) list * ((string * const) * (thm * bool)) list)));
haftmann@28054
    34
haftmann@33636
    35
datatype ml_stmt =
haftmann@33989
    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@37424
    39
  | ML_Datas of (string * ((vname * sort) list * ((string * vname list) * itype list) list)) list
haftmann@37422
    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@33989
    51
fun print_product _ [] = NONE
haftmann@33989
    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@39148
    55
fun tuplify _ _ [] = NONE
haftmann@39148
    56
  | tuplify print fxy [x] = SOME (print fxy x)
haftmann@39148
    57
  | tuplify print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
haftmann@28054
    58
haftmann@33989
    59
haftmann@33989
    60
(** SML serializer **)
haftmann@33989
    61
haftmann@39149
    62
fun print_sml_stmt labelled_name tyco_syntax const_syntax reserved is_cons deresolve =
haftmann@28054
    63
  let
haftmann@33989
    64
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33989
    65
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33989
    66
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33989
    67
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
    68
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@39149
    69
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@33989
    70
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33989
    71
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33989
    72
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33989
    73
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
    74
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33989
    75
      (map_filter (fn (v, sort) =>
haftmann@33989
    76
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33989
    77
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33989
    78
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33989
    79
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33989
    80
          brackify fxy ((str o deresolve) inst ::
haftmann@33989
    81
            (if is_pseudo_fun inst then [str "()"]
haftmann@33989
    82
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33989
    83
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33989
    84
          let
haftmann@33989
    85
            val v_p = str (if k = 1 then first_upper v ^ "_"
haftmann@33989
    86
              else first_upper v ^ string_of_int (i+1) ^ "_");
haftmann@33989
    87
          in case classrels
haftmann@33989
    88
           of [] => v_p
haftmann@33989
    89
            | [classrel] => brackets [(str o deresolve) classrel, v_p]
haftmann@33989
    90
            | classrels => brackets
haftmann@34178
    91
                [enum " o" "(" ")" (map (str o deresolve) classrels), v_p]
haftmann@33989
    92
          end
haftmann@39148
    93
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33989
    94
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33989
    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@31873
   109
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33989
   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@33989
   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@39149
   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@37424
   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@37424
   123
        let val k = length function_typs in
haftmann@33989
   124
          if k < 2 orelse length ts = k
haftmann@33989
   125
          then (str o deresolve) c
haftmann@39148
   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@33989
   128
        end
haftmann@33636
   129
      else if is_pseudo_fun c
haftmann@29175
   130
        then (str o deresolve) c @@ str "()"
haftmann@33989
   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@39149
   134
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33989
   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@29889
   138
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33989
   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@33989
   142
              |>> (fn p => semicolon [str "val", p, str "=",
haftmann@35228
   143
                    print_term is_pseudo_fun some_thm vars NOBR t])
haftmann@33989
   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@33989
   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@33989
   164
              :: print_select "of" clause
haftmann@33989
   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@33989
   170
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33989
   171
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33989
   172
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33989
   173
      let
haftmann@37424
   174
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37424
   175
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   176
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33989
   177
      in
haftmann@33989
   178
        concat (
haftmann@33989
   179
          str definer
haftmann@33989
   180
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33989
   181
          :: str "="
haftmann@33989
   182
          :: separate (str "|") (map print_co cos)
haftmann@33989
   183
        )
haftmann@33989
   184
      end;
haftmann@33989
   185
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33989
   186
          (ML_Function (name, (vs_ty as (vs, ty), eq :: eqs))) =
haftmann@28054
   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@39149
   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@33989
   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@33989
   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@33989
   209
            val shift = if null eqs then I else
haftmann@33989
   210
              map (Pretty.block o single o Pretty.block o single);
haftmann@33989
   211
          in pair
haftmann@33989
   212
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33989
   213
            ((Pretty.block o Pretty.fbreaks o shift) (
haftmann@33989
   214
              print_eqn definer eq
haftmann@33989
   215
              :: map (print_eqn "|") eqs
haftmann@33989
   216
            ))
haftmann@29189
   217
          end
haftmann@33989
   218
      | print_def is_pseudo_fun _ definer
haftmann@37424
   219
          (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@29189
   220
          let
haftmann@37359
   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@33989
   225
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   226
              ];
haftmann@37359
   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@37359
   231
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   232
              ];
haftmann@33989
   233
          in pair
haftmann@33989
   234
            (print_val_decl print_dicttypscheme
haftmann@33989
   235
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33989
   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@33989
   240
                  else print_dict_args vs)
haftmann@33636
   241
              @ str "="
haftmann@34178
   242
              :: enum "," "{" "}"
haftmann@37359
   243
                (map print_super_instance super_instances
haftmann@37359
   244
                  @ map print_classparam_instance classparam_instances)
haftmann@33636
   245
              :: str ":"
haftmann@33989
   246
              @@ print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33989
   247
            ))
haftmann@33636
   248
          end;
haftmann@33989
   249
    fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33989
   250
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33989
   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@33989
   258
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33989
   259
          ))
haftmann@33989
   260
      | print_stmt (ML_Val binding) =
haftmann@29189
   261
          let
haftmann@33989
   262
            val (sig_p, p) = print_def (K false) true "val" binding
haftmann@33989
   263
          in pair
haftmann@33989
   264
            [sig_p]
haftmann@33989
   265
            (semicolon [p])
haftmann@33989
   266
          end
haftmann@33989
   267
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33989
   268
          let
haftmann@33989
   269
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33989
   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@33989
   277
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33989
   278
              (print_def' "fun" binding :: map (print_def' "and") bindings);
haftmann@33989
   279
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33989
   280
          in pair
haftmann@33989
   281
            sig_ps
haftmann@33989
   282
            (Pretty.chunks (ps @ semicolon [p] :: pseudo_ps))
haftmann@33989
   283
          end
haftmann@33989
   284
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@28054
   285
          let
haftmann@33989
   286
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33989
   287
          in
haftmann@33989
   288
            pair
haftmann@33989
   289
            [concat [str "type", ty_p]]
haftmann@33989
   290
            (concat [str "datatype", ty_p, str "=", str "EMPTY__"])
haftmann@33989
   291
          end
haftmann@33989
   292
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   293
          let
haftmann@33989
   294
            val sig_ps = print_datatype_decl "datatype" data
haftmann@33989
   295
              :: map (print_datatype_decl "and") datas;
haftmann@33989
   296
            val (ps, p) = split_last sig_ps;
haftmann@33989
   297
          in pair
haftmann@33989
   298
            sig_ps
haftmann@33989
   299
            (Pretty.chunks (ps @| semicolon [p]))
haftmann@33989
   300
          end
haftmann@37422
   301
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@33989
   302
          let
haftmann@33989
   303
            fun print_field s p = concat [str s, str ":", p];
haftmann@33989
   304
            fun print_proj s p = semicolon
haftmann@33989
   305
              (map str ["val", s, "=", "#" ^ s, ":"] @| p);
haftmann@37359
   306
            fun print_super_class_decl (super_class, classrel) =
haftmann@33989
   307
              print_val_decl print_dicttypscheme
haftmann@37359
   308
                (classrel, ([(v, [class])], (super_class, ITyVar v)));
haftmann@37359
   309
            fun print_super_class_field (super_class, classrel) =
haftmann@37359
   310
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@37359
   311
            fun print_super_class_proj (super_class, classrel) =
haftmann@33989
   312
              print_proj (deresolve classrel)
haftmann@37359
   313
                (print_dicttypscheme ([(v, [class])], (super_class, ITyVar v)));
haftmann@33989
   314
            fun print_classparam_decl (classparam, ty) =
haftmann@33989
   315
              print_val_decl print_typscheme
haftmann@33989
   316
                (classparam, ([(v, [class])], ty));
haftmann@33989
   317
            fun print_classparam_field (classparam, ty) =
haftmann@33989
   318
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@33989
   319
            fun print_classparam_proj (classparam, ty) =
haftmann@33989
   320
              print_proj (deresolve classparam)
haftmann@33989
   321
                (print_typscheme ([(v, [class])], ty));
haftmann@33989
   322
          in pair
haftmann@33989
   323
            (concat [str "type", print_dicttyp (class, ITyVar v)]
haftmann@37359
   324
              :: map print_super_class_decl super_classes
haftmann@33989
   325
              @ map print_classparam_decl classparams)
haftmann@33989
   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@37359
   332
                  map print_super_class_field super_classes
haftmann@33989
   333
                  @ map print_classparam_field classparams
haftmann@28054
   334
                )
haftmann@28054
   335
              ]
haftmann@37359
   336
              :: map print_super_class_proj super_classes
haftmann@33989
   337
              @ map print_classparam_proj classparams
haftmann@33989
   338
            ))
haftmann@28054
   339
          end;
haftmann@33989
   340
  in print_stmt end;
haftmann@28054
   341
haftmann@39159
   342
fun print_sml_module name some_decls body =
haftmann@39159
   343
  Pretty.chunks2 (
haftmann@33989
   344
    Pretty.chunks (
haftmann@33989
   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@33989
   347
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33989
   348
    )
haftmann@33989
   349
    :: body
haftmann@33989
   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@34931
   356
  literal_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34931
   357
  literal_positive_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@38195
   358
  literal_alternative_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34931
   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@39149
   367
fun print_ocaml_stmt labelled_name tyco_syntax const_syntax reserved is_cons deresolve =
haftmann@28054
   368
  let
haftmann@33989
   369
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33989
   370
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33989
   371
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33989
   372
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
   373
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@39149
   374
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@33989
   375
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33989
   376
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33989
   377
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33989
   378
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
   379
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33989
   380
      (map_filter (fn (v, sort) =>
haftmann@33989
   381
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33989
   382
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33989
   383
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33989
   384
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33989
   385
          brackify fxy ((str o deresolve) inst ::
haftmann@33989
   386
            (if is_pseudo_fun inst then [str "()"]
haftmann@33989
   387
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33989
   388
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33989
   389
          str (if k = 1 then "_" ^ first_upper v
haftmann@33989
   390
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@33989
   391
          |> fold_rev (fn classrel => fn p =>
haftmann@33989
   392
               Pretty.block [p, str ".", (str o deresolve) classrel]) classrels
haftmann@39148
   393
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33989
   394
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33989
   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@31873
   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@33989
   413
          (case Code_Thingol.unfold_const_app t0
haftmann@39149
   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@33989
   420
        let val k = length tys in
haftmann@33989
   421
          if length ts = k
haftmann@33989
   422
          then (str o deresolve) c
haftmann@39148
   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@33989
   425
        end
haftmann@33636
   426
      else if is_pseudo_fun c
haftmann@29175
   427
        then (str o deresolve) c @@ str "()"
haftmann@33989
   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@39149
   431
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33989
   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@29889
   435
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33989
   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@33989
   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@33989
   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@33989
   456
              :: print_select "with" clause
haftmann@33989
   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@33989
   462
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33989
   463
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33989
   464
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33989
   465
      let
haftmann@37424
   466
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37424
   467
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   468
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33989
   469
      in
haftmann@33989
   470
        concat (
haftmann@33989
   471
          str definer
haftmann@33989
   472
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33989
   473
          :: str "="
haftmann@33989
   474
          :: separate (str "|") (map print_co cos)
haftmann@33989
   475
        )
haftmann@33989
   476
      end;
haftmann@33989
   477
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33989
   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@39011
   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@39149
   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@33989
   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@33989
   514
                    :: print_eqn eq
haftmann@28054
   515
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33989
   516
                          o single o print_eqn) eqs
haftmann@28054
   517
                  )
haftmann@33989
   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@39149
   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@39011
   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@33989
   537
                      :: print_eqn eq
haftmann@28054
   538
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33989
   539
                           o single o print_eqn) eqs'
haftmann@28054
   540
                    )
haftmann@28054
   541
                  end;
haftmann@33636
   542
            val prolog = if needs_typ then
haftmann@33989
   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@33989
   545
          in pair
haftmann@33989
   546
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33989
   547
            (concat (
haftmann@33636
   548
              prolog
haftmann@33989
   549
              :: print_dict_args vs
haftmann@33989
   550
              @| print_eqns (is_pseudo_fun name) eqs
haftmann@33989
   551
            ))
haftmann@33636
   552
          end
haftmann@37359
   553
      | print_def is_pseudo_fun _ definer
haftmann@37424
   554
            (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@33636
   555
          let
haftmann@37359
   556
            fun print_super_instance (_, (classrel, dss)) =
haftmann@33636
   557
              concat [
haftmann@33636
   558
                (str o deresolve) classrel,
haftmann@33636
   559
                str "=",
haftmann@33989
   560
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   561
              ];
haftmann@37359
   562
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   563
              concat [
haftmann@33636
   564
                (str o deresolve) classparam,
haftmann@33636
   565
                str "=",
haftmann@37359
   566
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   567
              ];
haftmann@33989
   568
          in pair
haftmann@33989
   569
            (print_val_decl print_dicttypscheme
haftmann@33989
   570
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33989
   571
            (concat (
haftmann@33636
   572
              str definer
haftmann@33636
   573
              :: (str o deresolve) inst
haftmann@33989
   574
              :: print_dict_args vs
haftmann@33636
   575
              @ str "="
haftmann@33636
   576
              @@ brackets [
haftmann@37359
   577
                enum_default "()" ";" "{" "}" (map print_super_instance super_instances
haftmann@37359
   578
                  @ map print_classparam_instance classparam_instances),
haftmann@33636
   579
                str ":",
haftmann@33989
   580
                print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33636
   581
              ]
haftmann@33989
   582
            ))
haftmann@33636
   583
          end;
haftmann@33989
   584
     fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33989
   585
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33989
   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@33989
   592
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33989
   593
          ))
haftmann@33989
   594
      | print_stmt (ML_Val binding) =
haftmann@33636
   595
          let
haftmann@33989
   596
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33989
   597
          in pair
haftmann@33989
   598
            [sig_p]
haftmann@33989
   599
            (doublesemicolon [p])
haftmann@33989
   600
          end
haftmann@33989
   601
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33989
   602
          let
haftmann@33989
   603
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33989
   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@33989
   611
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33989
   612
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33989
   613
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33989
   614
          in pair
haftmann@33989
   615
            sig_ps
haftmann@33989
   616
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33989
   617
          end
haftmann@33989
   618
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@28054
   619
          let
haftmann@33989
   620
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33989
   621
          in
haftmann@33989
   622
            pair
haftmann@33989
   623
            [concat [str "type", ty_p]]
haftmann@33989
   624
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33989
   625
          end
haftmann@33989
   626
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   627
          let
haftmann@33989
   628
            val sig_ps = print_datatype_decl "type" data
haftmann@33989
   629
              :: map (print_datatype_decl "and") datas;
haftmann@33989
   630
            val (ps, p) = split_last sig_ps;
haftmann@33989
   631
          in pair
haftmann@33989
   632
            sig_ps
haftmann@33989
   633
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33989
   634
          end
haftmann@37422
   635
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@33989
   636
          let
haftmann@33989
   637
            fun print_field s p = concat [str s, str ":", p];
haftmann@37359
   638
            fun print_super_class_field (super_class, classrel) =
haftmann@37359
   639
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33989
   640
            fun print_classparam_decl (classparam, ty) =
haftmann@33989
   641
              print_val_decl print_typscheme
haftmann@33989
   642
                (classparam, ([(v, [class])], ty));
haftmann@33989
   643
            fun print_classparam_field (classparam, ty) =
haftmann@33989
   644
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@32924
   645
            val w = "_" ^ first_upper v;
haftmann@33989
   646
            fun print_classparam_proj (classparam, _) =
haftmann@33989
   647
              (concat o map str) ["let", deresolve classparam, w, "=",
haftmann@33989
   648
                w ^ "." ^ deresolve classparam ^ ";;"];
haftmann@33989
   649
            val type_decl_p = concat [
haftmann@33989
   650
                str ("type '" ^ v),
haftmann@33989
   651
                (str o deresolve) class,
haftmann@33989
   652
                str "=",
haftmann@33989
   653
                enum_default "unit" ";" "{" "}" (
haftmann@37359
   654
                  map print_super_class_field super_classes
haftmann@33989
   655
                  @ map print_classparam_field classparams
haftmann@33989
   656
                )
haftmann@28054
   657
              ];
haftmann@33989
   658
          in pair
haftmann@33989
   659
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33989
   660
            (Pretty.chunks (
haftmann@33989
   661
              doublesemicolon [type_decl_p]
haftmann@33989
   662
              :: map print_classparam_proj classparams
haftmann@33989
   663
            ))
haftmann@33989
   664
          end;
haftmann@33989
   665
  in print_stmt end;
haftmann@28054
   666
haftmann@39159
   667
fun print_ocaml_module name some_decls body =
haftmann@39159
   668
  Pretty.chunks2 (
haftmann@33989
   669
    Pretty.chunks (
haftmann@33989
   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@33989
   672
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33989
   673
    )
haftmann@33989
   674
    :: body
haftmann@33989
   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@34931
   690
  fun numeral_ocaml k = if k < 0
haftmann@34931
   691
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34931
   692
    else if k <= 1073741823
haftmann@34931
   693
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34931
   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@34931
   698
  literal_numeral = numeral_ocaml,
haftmann@34931
   699
  literal_positive_numeral = numeral_ocaml,
haftmann@38195
   700
  literal_alternative_numeral = numeral_ocaml,
haftmann@34931
   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@28054
   710
local
haftmann@28054
   711
haftmann@28054
   712
datatype ml_node =
haftmann@28054
   713
    Dummy of string
haftmann@28054
   714
  | Stmt of string * ml_stmt
haftmann@28054
   715
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   716
haftmann@28054
   717
in
haftmann@28054
   718
haftmann@39150
   719
fun ml_node_of_program labelled_name reserved module_alias program =
haftmann@28054
   720
  let
haftmann@32924
   721
    val reserved = Name.make_context reserved;
haftmann@32924
   722
    val empty_module = ((reserved, reserved), Graph.empty);
haftmann@28054
   723
    fun map_node [] f = f
haftmann@28054
   724
      | map_node (m::ms) f =
haftmann@28054
   725
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   726
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   727
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   728
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   729
          let
haftmann@28054
   730
            val (x, nsp') = f nsp
haftmann@28054
   731
          in (x, (nsp', nodes)) end
haftmann@28054
   732
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   733
          let
haftmann@28054
   734
            val (x, nodes') =
haftmann@28054
   735
              nodes
haftmann@28054
   736
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   737
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   738
                  let
haftmann@28054
   739
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   740
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   741
          in (x, (nsp, nodes')) end;
haftmann@28054
   742
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   743
      let
haftmann@28054
   744
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   745
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   746
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   747
      let
haftmann@28054
   748
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   749
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@32924
   750
    val mk_name_module = mk_name_module reserved NONE module_alias program;
haftmann@28054
   751
    fun mk_name_stmt upper name nsp =
haftmann@28054
   752
      let
haftmann@32924
   753
        val (_, base) = dest_name name;
haftmann@32924
   754
        val base' = if upper then first_upper base else base;
haftmann@28054
   755
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   756
      in (base'', nsp') end;
haftmann@37414
   757
    fun deps_of names =
haftmann@37414
   758
      []
haftmann@37414
   759
      |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@37414
   760
      |> subtract (op =) names
haftmann@37414
   761
      |> filter_out (Code_Thingol.is_case o Graph.get_node program);
haftmann@37412
   762
    fun ml_binding_of_stmt (name, Code_Thingol.Fun (_, ((tysm as (vs, ty), raw_eqs), _))) =
haftmann@33636
   763
          let
haftmann@33636
   764
            val eqs = filter (snd o snd) raw_eqs;
haftmann@33636
   765
            val (eqs', is_value) = if null (filter_out (null o snd) vs) then case eqs
haftmann@35228
   766
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@35228
   767
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@33636
   768
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@33636
   769
                | _ => (eqs, NONE)
haftmann@33636
   770
              else (eqs, NONE)
haftmann@33636
   771
          in (ML_Function (name, (tysm, eqs')), is_value) end
haftmann@33989
   772
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as ((_, (_, vs)), _))) =
haftmann@33989
   773
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@33636
   774
      | ml_binding_of_stmt (name, _) =
haftmann@33636
   775
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@33636
   776
    fun add_fun (name, stmt) =
haftmann@29189
   777
      let
haftmann@33636
   778
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@33636
   779
        val ml_stmt = case binding
haftmann@33636
   780
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@33989
   781
              ML_Exc (name, ((vs, ty),
haftmann@33989
   782
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@33636
   783
          | _ => case some_value_name
haftmann@33636
   784
             of NONE => ML_Funs ([binding], [])
haftmann@33636
   785
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@33636
   786
              | SOME (name, false) => ML_Val binding
haftmann@33636
   787
      in
haftmann@33636
   788
        map_nsp_fun_yield (mk_name_stmt false name)
haftmann@33636
   789
        #>> (fn name' => ([name'], ml_stmt))
haftmann@33636
   790
      end;
haftmann@33636
   791
    fun add_funs stmts =
haftmann@33636
   792
      let
haftmann@33636
   793
        val ml_stmt = ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst);
haftmann@33636
   794
      in
haftmann@33636
   795
        fold_map (fn (name, _) => map_nsp_fun_yield (mk_name_stmt false name)) stmts
haftmann@33636
   796
        #>> rpair ml_stmt
haftmann@33636
   797
      end;
haftmann@28054
   798
    fun add_datatypes stmts =
haftmann@28054
   799
      fold_map
haftmann@28663
   800
        (fn (name, Code_Thingol.Datatype (_, stmt)) =>
haftmann@28054
   801
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   802
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   803
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   804
          | (name, _) =>
haftmann@28054
   805
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   806
        ) stmts
haftmann@28054
   807
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   808
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@39011
   809
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   810
             | stmts => ML_Datas stmts)));
haftmann@28054
   811
    fun add_class stmts =
haftmann@28054
   812
      fold_map
haftmann@28663
   813
        (fn (name, Code_Thingol.Class (_, stmt)) =>
haftmann@28663
   814
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   815
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   816
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   817
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   818
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   819
          | (name, _) =>
haftmann@28054
   820
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   821
        ) stmts
haftmann@28054
   822
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   823
        #> (fn [] => error ("Class block without class statement: "
haftmann@39011
   824
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   825
             | [stmt] => ML_Class stmt)));
haftmann@33636
   826
    fun add_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@33636
   827
          add_fun stmt
haftmann@33636
   828
      | add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   829
          add_funs stmts
haftmann@28054
   830
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   831
          add_datatypes stmts
haftmann@28054
   832
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   833
          add_datatypes stmts
haftmann@28054
   834
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   835
          add_class stmts
haftmann@28054
   836
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   837
          add_class stmts
haftmann@28054
   838
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   839
          add_class stmts
haftmann@33636
   840
      | add_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@33636
   841
          add_fun stmt
haftmann@33636
   842
      | add_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@33636
   843
          add_funs stmts
haftmann@28054
   844
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@39011
   845
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@28054
   846
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   847
      let
haftmann@28054
   848
        val names as (name :: names') = map fst stmts;
haftmann@37414
   849
        val deps = deps_of names;
haftmann@32924
   850
        val (module_names, _) = (split_list o map dest_name) names;
haftmann@28054
   851
        val module_name = (the_single o distinct (op =) o map mk_name_module) module_names
haftmann@28054
   852
          handle Empty =>
haftmann@28054
   853
            error ("Different namespace prefixes for mutual dependencies:\n"
haftmann@39011
   854
              ^ Library.commas (map labelled_name names)
haftmann@28054
   855
              ^ "\n"
haftmann@39011
   856
              ^ Library.commas module_names);
wenzelm@30364
   857
        val module_name_path = Long_Name.explode module_name;
haftmann@28054
   858
        fun add_dep name name' =
haftmann@28054
   859
          let
haftmann@32924
   860
            val module_name' = (mk_name_module o fst o dest_name) name';
haftmann@28054
   861
          in if module_name = module_name' then
haftmann@28054
   862
            map_node module_name_path (Graph.add_edge (name, name'))
haftmann@28054
   863
          else let
haftmann@28705
   864
            val (common, (diff1 :: _, diff2 :: _)) = chop_prefix (op =)
wenzelm@30364
   865
              (module_name_path, Long_Name.explode module_name');
haftmann@28054
   866
          in
haftmann@28054
   867
            map_node common
haftmann@28054
   868
              (fn node => Graph.add_edge_acyclic (diff1, diff2) node
haftmann@28054
   869
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@28054
   870
                  ^ quote name ^ " -> " ^ quote name'
haftmann@28054
   871
                  ^ " would result in module dependency cycle"))
haftmann@28054
   872
          end end;
haftmann@28054
   873
      in
haftmann@28054
   874
        nsp_nodes
haftmann@28054
   875
        |> map_nsp_yield module_name_path (add_stmts stmts)
haftmann@28054
   876
        |-> (fn (base' :: bases', stmt') =>
haftmann@28054
   877
           apsnd (map_node module_name_path (Graph.new_node (name, (Stmt (base', stmt')))
haftmann@28054
   878
              #> fold2 (fn name' => fn base' =>
haftmann@28054
   879
                   Graph.new_node (name', (Dummy base'))) names' bases')))
haftmann@28054
   880
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@28054
   881
        |> apsnd (fold_product (curry (map_node module_name_path o Graph.add_edge)) names names)
haftmann@28054
   882
      end;
haftmann@37414
   883
    val stmts = map (AList.make (Graph.get_node program)) (rev (Graph.strong_conn program))
haftmann@37414
   884
      |> filter_out (fn [(_, stmt)] => Code_Thingol.is_case stmt | _ => false);
haftmann@37414
   885
    val (_, nodes) = fold add_stmts' stmts empty_module;
haftmann@28054
   886
    fun deresolver prefix name = 
haftmann@28054
   887
      let
haftmann@32924
   888
        val module_name = (fst o dest_name) name;
wenzelm@30364
   889
        val module_name' = (Long_Name.explode o mk_name_module) module_name;
haftmann@28054
   890
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, module_name');
haftmann@28054
   891
        val stmt_name =
haftmann@28054
   892
          nodes
haftmann@28054
   893
          |> fold (fn name => fn node => case Graph.get_node node name
haftmann@28054
   894
              of Module (_, (_, node)) => node) module_name'
haftmann@28054
   895
          |> (fn node => case Graph.get_node node name of Stmt (stmt_name, _) => stmt_name
haftmann@28054
   896
               | Dummy stmt_name => stmt_name);
haftmann@28054
   897
      in
wenzelm@30364
   898
        Long_Name.implode (remainder @ [stmt_name])
haftmann@28054
   899
      end handle Graph.UNDEF _ =>
haftmann@28054
   900
        error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   901
  in (deresolver, nodes) end;
haftmann@28054
   902
haftmann@39152
   903
fun serialize_ml target print_module print_stmt with_signatures { labelled_name,
haftmann@39154
   904
  reserved_syms, includes, module_alias, class_syntax, tyco_syntax,
haftmann@39152
   905
  const_syntax, program, names, presentation_names } =
haftmann@28054
   906
  let
haftmann@28054
   907
    val is_cons = Code_Thingol.is_cons program;
haftmann@39152
   908
    val is_presentation = not (null presentation_names);
haftmann@39150
   909
    val (deresolver, nodes) = ml_node_of_program labelled_name
haftmann@39152
   910
      reserved_syms module_alias program;
haftmann@39152
   911
    val reserved = make_vars reserved_syms;
haftmann@33989
   912
    fun print_node prefix (Dummy _) =
haftmann@28054
   913
          NONE
haftmann@33989
   914
      | print_node prefix (Stmt (_, stmt)) = if is_presentation andalso
haftmann@39152
   915
          (null o filter (member (op =) presentation_names) o stmt_names_of) stmt
haftmann@30962
   916
          then NONE
haftmann@39149
   917
          else SOME (print_stmt labelled_name tyco_syntax const_syntax reserved is_cons (deresolver prefix) stmt)
haftmann@33989
   918
      | print_node prefix (Module (module_name, (_, nodes))) =
haftmann@33989
   919
          let
haftmann@33989
   920
            val (decls, body) = print_nodes (prefix @ [module_name]) nodes;
haftmann@33989
   921
            val p = if is_presentation then Pretty.chunks2 body
haftmann@33989
   922
              else print_module module_name (if with_signatures then SOME decls else NONE) body;
haftmann@33989
   923
          in SOME ([], p) end
haftmann@33989
   924
    and print_nodes prefix nodes = (map_filter (print_node prefix o Graph.get_node nodes)
haftmann@33989
   925
        o rev o flat o Graph.strong_conn) nodes
haftmann@33989
   926
      |> split_list
haftmann@33989
   927
      |> (fn (decls, body) => (flat decls, body))
haftmann@39154
   928
    val names' = map (try (deresolver [])) names;
haftmann@33989
   929
    val p = Pretty.chunks2 (map snd includes @ snd (print_nodes [] nodes));
haftmann@39141
   930
    fun write width NONE = writeln_pretty width
haftmann@39141
   931
      | write width (SOME p) = File.write p o string_of_pretty width;
haftmann@28054
   932
  in
haftmann@39152
   933
    Code_Target.serialization write (fn width => (rpair names' o string_of_pretty width)) p
haftmann@28054
   934
  end;
haftmann@28054
   935
haftmann@28054
   936
end; (*local*)
haftmann@28054
   937
haftmann@39192
   938
val serializer_sml : Code_Target.serializer =
haftmann@33989
   939
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33989
   940
  >> (fn with_signatures => serialize_ml target_SML
haftmann@39150
   941
      print_sml_module print_sml_stmt with_signatures));
haftmann@28054
   942
haftmann@39192
   943
val serializer_ocaml : Code_Target.serializer =
haftmann@33989
   944
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@37747
   945
  >> (fn with_signatures => serialize_ml target_OCaml
haftmann@39150
   946
      print_ocaml_module print_ocaml_stmt with_signatures));
haftmann@28054
   947
haftmann@39192
   948
haftmann@39192
   949
(** Isar setup **)
haftmann@39192
   950
haftmann@28054
   951
val setup =
haftmann@37821
   952
  Code_Target.add_target
haftmann@39192
   953
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
haftmann@37822
   954
      check = { env_var = "ISABELLE_PROCESS", make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@39092
   955
        make_command = fn isabelle => fn _ => isabelle ^ " -r -q -u Pure" } })
haftmann@37821
   956
  #> Code_Target.add_target
haftmann@39192
   957
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
haftmann@37822
   958
      check = { env_var = "EXEC_OCAML", make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
haftmann@39092
   959
        make_command = fn ocaml => fn _ => ocaml ^ " -w pu nums.cma ROOT.ocaml" } })
haftmann@39149
   960
  #> Code_Target.add_tyco_syntax target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37239
   961
      brackify_infix (1, R) fxy (
haftmann@33989
   962
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   963
        str "->",
haftmann@33989
   964
        print_typ (INFX (1, R)) ty2
haftmann@37239
   965
      )))
haftmann@39149
   966
  #> Code_Target.add_tyco_syntax target_OCaml "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37239
   967
      brackify_infix (1, R) fxy (
haftmann@33989
   968
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   969
        str "->",
haftmann@33989
   970
        print_typ (INFX (1, R)) ty2
haftmann@37239
   971
      )))
haftmann@28054
   972
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   973
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38316
   974
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38316
   975
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   976
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   977
      "and", "as", "assert", "begin", "class",
haftmann@28054
   978
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   979
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   980
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   981
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   982
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   983
      "virtual", "when", "while", "with"
haftmann@28054
   984
    ]
haftmann@34931
   985
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
   986
haftmann@28054
   987
end; (*struct*)