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