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