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