src/Tools/Code/code_ml.ML
author haftmann
Fri Feb 15 08:31:31 2013 +0100 (2013-02-15)
changeset 51143 0a2371e7ced3
parent 51091 c007c6bf4a35
child 52138 e21426f244aa
permissions -rw-r--r--
two target language numeral types: integer and natural, as replacement for code_numeral;
former theory HOL/Library/Code_Numeral_Types replaces HOL/Code_Numeral;
refined stack of theories implementing int and/or nat by target language numerals;
reduced number of target language numeral types to exactly one
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@50625
    54
fun print_sml_stmt tyco_syntax const_syntax reserved is_constr 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@50625
   113
      if is_constr 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@34178
   348
  literal_list = enum "," "[" "]",
haftmann@28064
   349
  infix_cons = (7, "::")
haftmann@28064
   350
};
haftmann@28064
   351
haftmann@28054
   352
haftmann@28054
   353
(** OCaml serializer **)
haftmann@28054
   354
haftmann@50625
   355
fun print_ocaml_stmt tyco_syntax const_syntax reserved is_constr deresolve =
haftmann@28054
   356
  let
haftmann@47609
   357
    fun print_tyco_expr (tyco, []) = (str o deresolve) tyco
haftmann@47609
   358
      | print_tyco_expr (tyco, [ty]) =
haftmann@33992
   359
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@47609
   360
      | print_tyco_expr (tyco, tys) =
haftmann@34178
   361
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@38923
   362
    and print_typ fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@47609
   363
         of NONE => print_tyco_expr (tyco, tys)
haftmann@47576
   364
          | SOME (_, print) => print print_typ fxy tys)
haftmann@33992
   365
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@47609
   366
    fun print_dicttyp (class, ty) = print_tyco_expr (class, [ty]);
haftmann@34178
   367
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
   368
      (map_filter (fn (v, sort) =>
haftmann@33992
   369
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
   370
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
   371
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@41100
   372
    val print_classrels =
haftmann@41100
   373
      fold_rev (fn classrel => fn p => Pretty.block [p, str ".", (str o deresolve) classrel])
haftmann@41118
   374
    fun print_dict is_pseudo_fun fxy (Dict (classrels, x)) =
haftmann@41118
   375
      print_plain_dict is_pseudo_fun fxy x
haftmann@41118
   376
      |> print_classrels classrels
haftmann@41118
   377
    and print_plain_dict is_pseudo_fun fxy (Dict_Const (inst, dss)) =
haftmann@41100
   378
          brackify BR ((str o deresolve) inst ::
haftmann@33992
   379
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   380
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@41118
   381
      | print_plain_dict is_pseudo_fun fxy (Dict_Var (v, (i, k))) =
haftmann@33992
   382
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   383
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@38922
   384
    and print_dicts is_pseudo_fun = tuplify (print_dict is_pseudo_fun);
haftmann@33992
   385
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@41118
   386
      (map_index (fn (i, _) => Dict ([], Dict_Var (v, (i, length sort)))) sort));
haftmann@48072
   387
    fun print_term is_pseudo_fun some_thm vars fxy (IConst const) =
haftmann@48072
   388
          print_app is_pseudo_fun some_thm vars fxy (const, [])
haftmann@35228
   389
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   390
          str "_"
haftmann@35228
   391
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   392
          str (lookup_var vars v)
haftmann@35228
   393
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   394
          (case Code_Thingol.unfold_const_app t
haftmann@48072
   395
           of SOME app => print_app is_pseudo_fun some_thm vars fxy app
haftmann@35228
   396
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   397
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   398
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   399
          let
haftmann@31874
   400
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
   401
            val (ps, vars') = fold_map (print_bind is_pseudo_fun some_thm BR o fst) binds vars;
haftmann@35228
   402
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun some_thm vars' NOBR t') end
haftmann@48072
   403
      | print_term is_pseudo_fun some_thm vars fxy (ICase case_expr) =
haftmann@48072
   404
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@48072
   405
           of SOME (app as ({ name = c, ... }, _)) => if is_none (const_syntax c)
haftmann@48072
   406
                then print_case is_pseudo_fun some_thm vars fxy case_expr
haftmann@48072
   407
                else print_app is_pseudo_fun some_thm vars fxy app
haftmann@48072
   408
            | NONE => print_case is_pseudo_fun some_thm vars fxy case_expr)
haftmann@48072
   409
    and print_app_expr is_pseudo_fun some_thm vars (app as ({ name = c, dicts = dss, dom = dom, ... }, ts)) =
haftmann@50625
   410
      if is_constr c then
haftmann@48072
   411
        let val k = length dom in
haftmann@33992
   412
          if length ts = k
haftmann@33992
   413
          then (str o deresolve) c
haftmann@38922
   414
            :: the_list (tuplify (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   415
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   416
        end
haftmann@33636
   417
      else if is_pseudo_fun c
haftmann@29175
   418
        then (str o deresolve) c @@ str "()"
haftmann@48072
   419
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) dss
haftmann@35228
   420
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   421
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@38923
   422
      (print_term is_pseudo_fun) const_syntax some_thm vars
haftmann@33992
   423
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@48072
   424
    and print_case is_pseudo_fun some_thm vars fxy { clauses = [], ... } =
haftmann@48072
   425
          (concat o map str) ["failwith", "\"empty case\""]
haftmann@48072
   426
      | print_case is_pseudo_fun some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@28054
   427
          let
haftmann@48072
   428
            val (binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@47576
   429
            fun print_let ((pat, _), t) vars =
haftmann@28054
   430
              vars
haftmann@35228
   431
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   432
              |>> (fn p => concat
haftmann@35228
   433
                  [str "let", p, str "=", print_term is_pseudo_fun some_thm vars NOBR t, str "in"])
haftmann@33992
   434
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   435
          in
haftmann@31665
   436
            brackify_block fxy (Pretty.chunks ps) []
haftmann@35228
   437
              (print_term is_pseudo_fun some_thm vars' NOBR body)
haftmann@31665
   438
          end
haftmann@48072
   439
      | print_case is_pseudo_fun some_thm vars fxy { term = t, typ = ty, clauses = clause :: clauses, ... } =
haftmann@28054
   440
          let
haftmann@33992
   441
            fun print_select delim (pat, body) =
haftmann@28054
   442
              let
haftmann@35228
   443
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@35228
   444
              in concat [str delim, p, str "->", print_term is_pseudo_fun some_thm vars' NOBR body] end;
haftmann@28054
   445
          in
haftmann@31665
   446
            brackets (
haftmann@28054
   447
              str "match"
haftmann@35228
   448
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   449
              :: print_select "with" clause
haftmann@33992
   450
              :: map (print_select "|") clauses
haftmann@28054
   451
            )
haftmann@48072
   452
          end;
haftmann@33992
   453
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   454
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   455
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   456
      let
haftmann@37449
   457
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37449
   458
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   459
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   460
      in
haftmann@33992
   461
        concat (
haftmann@33992
   462
          str definer
haftmann@48003
   463
          :: print_tyco_expr (tyco, map ITyVar vs)
haftmann@33992
   464
          :: str "="
haftmann@33992
   465
          :: separate (str "|") (map print_co cos)
haftmann@33992
   466
        )
haftmann@33992
   467
      end;
haftmann@33992
   468
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   469
          (ML_Function (name, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   470
          let
haftmann@35228
   471
            fun print_eqn ((ts, t), (some_thm, _)) =
haftmann@28054
   472
              let
haftmann@32913
   473
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   474
                val vars = reserved
bulwahn@42599
   475
                  |> intro_base_names
bulwahn@42599
   476
                      (is_none o const_syntax) deresolve consts
haftmann@32924
   477
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   478
                      (insert (op =)) ts []);
haftmann@28054
   479
              in concat [
haftmann@38778
   480
                (Pretty.block o commas)
haftmann@35228
   481
                  (map (print_term is_pseudo_fun some_thm vars NOBR) ts),
haftmann@28054
   482
                str "->",
haftmann@35228
   483
                print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   484
              ] end;
haftmann@35228
   485
            fun print_eqns is_pseudo [((ts, t), (some_thm, _))] =
haftmann@28054
   486
                  let
haftmann@32913
   487
                    val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   488
                    val vars = reserved
haftmann@32924
   489
                      |> intro_base_names
haftmann@38923
   490
                          (is_none o const_syntax) deresolve consts
haftmann@32924
   491
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   492
                          (insert (op =)) ts []);
haftmann@28054
   493
                  in
haftmann@28054
   494
                    concat (
haftmann@29189
   495
                      (if is_pseudo then [str "()"]
haftmann@35228
   496
                        else map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@28054
   497
                      @ str "="
haftmann@35228
   498
                      @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   499
                    )
haftmann@28054
   500
                  end
haftmann@33992
   501
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   502
                  Pretty.block (
haftmann@28054
   503
                    str "="
haftmann@28054
   504
                    :: Pretty.brk 1
haftmann@28054
   505
                    :: str "function"
haftmann@28054
   506
                    :: Pretty.brk 1
haftmann@33992
   507
                    :: print_eqn eq
haftmann@28054
   508
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   509
                          o single o print_eqn) eqs
haftmann@28054
   510
                  )
haftmann@33992
   511
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   512
                  let
haftmann@32913
   513
                    val consts = fold Code_Thingol.add_constnames (map (snd o fst) eqs) [];
haftmann@32924
   514
                    val vars = reserved
haftmann@32924
   515
                      |> intro_base_names
haftmann@38923
   516
                          (is_none o const_syntax) deresolve consts;
haftmann@32924
   517
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   518
                  in
haftmann@28054
   519
                    Pretty.block (
haftmann@28054
   520
                      Pretty.breaks dummy_parms
haftmann@28054
   521
                      @ Pretty.brk 1
haftmann@28054
   522
                      :: str "="
haftmann@28054
   523
                      :: Pretty.brk 1
haftmann@28054
   524
                      :: str "match"
haftmann@28054
   525
                      :: Pretty.brk 1
haftmann@38778
   526
                      :: (Pretty.block o commas) dummy_parms
haftmann@28054
   527
                      :: Pretty.brk 1
haftmann@28054
   528
                      :: str "with"
haftmann@28054
   529
                      :: Pretty.brk 1
haftmann@33992
   530
                      :: print_eqn eq
haftmann@28054
   531
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   532
                           o single o print_eqn) eqs'
haftmann@28054
   533
                    )
haftmann@28054
   534
                  end;
haftmann@33636
   535
            val prolog = if needs_typ then
haftmann@33992
   536
              concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@34178
   537
                else (concat o map str) [definer, deresolve name];
haftmann@33992
   538
          in pair
haftmann@33992
   539
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   540
            (concat (
haftmann@33636
   541
              prolog
haftmann@33992
   542
              :: print_dict_args vs
haftmann@33992
   543
              @| print_eqns (is_pseudo_fun name) eqs
haftmann@33992
   544
            ))
haftmann@33636
   545
          end
haftmann@37384
   546
      | print_def is_pseudo_fun _ definer
haftmann@48072
   547
          (ML_Instance (inst, { class, tyco, vs, superinsts, inst_params, ... })) =
haftmann@33636
   548
          let
haftmann@41100
   549
            fun print_super_instance (_, (classrel, x)) =
haftmann@33636
   550
              concat [
haftmann@33636
   551
                (str o deresolve) classrel,
haftmann@33636
   552
                str "=",
haftmann@41118
   553
                print_dict is_pseudo_fun NOBR (Dict ([], Dict_Const x))
haftmann@33636
   554
              ];
haftmann@37384
   555
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   556
              concat [
haftmann@33636
   557
                (str o deresolve) classparam,
haftmann@33636
   558
                str "=",
haftmann@37384
   559
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   560
              ];
haftmann@33992
   561
          in pair
haftmann@33992
   562
            (print_val_decl print_dicttypscheme
haftmann@33992
   563
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   564
            (concat (
haftmann@33636
   565
              str definer
haftmann@33636
   566
              :: (str o deresolve) inst
bulwahn@43343
   567
              :: (if is_pseudo_fun inst then [str "()"]
bulwahn@43343
   568
                  else print_dict_args vs)
haftmann@33636
   569
              @ str "="
haftmann@33636
   570
              @@ brackets [
haftmann@48072
   571
                enum_default "()" ";" "{" "}" (map print_super_instance superinsts
haftmann@48072
   572
                  @ map print_classparam_instance inst_params),
haftmann@33636
   573
                str ":",
haftmann@47609
   574
                print_tyco_expr (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33636
   575
              ]
haftmann@33992
   576
            ))
haftmann@33636
   577
          end;
haftmann@33992
   578
     fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   579
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   580
          ((doublesemicolon o map str) (
haftmann@33636
   581
            "let"
haftmann@33636
   582
            :: deresolve name
haftmann@33636
   583
            :: replicate n "_"
haftmann@33636
   584
            @ "="
haftmann@33636
   585
            :: "failwith"
haftmann@33992
   586
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   587
          ))
haftmann@33992
   588
      | print_stmt (ML_Val binding) =
haftmann@33636
   589
          let
haftmann@33992
   590
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   591
          in pair
haftmann@33992
   592
            [sig_p]
haftmann@33992
   593
            (doublesemicolon [p])
haftmann@33992
   594
          end
haftmann@33992
   595
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   596
          let
haftmann@33992
   597
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   598
            fun print_pseudo_fun name = concat [
haftmann@29189
   599
                str "let",
haftmann@29189
   600
                (str o deresolve) name,
haftmann@29189
   601
                str "=",
haftmann@29189
   602
                (str o deresolve) name,
haftmann@29189
   603
                str "();;"
haftmann@29189
   604
              ];
haftmann@33992
   605
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   606
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   607
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   608
          in pair
haftmann@33992
   609
            sig_ps
haftmann@33992
   610
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   611
          end
haftmann@33992
   612
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   613
          let
haftmann@48003
   614
            val ty_p = print_tyco_expr (tyco, map ITyVar vs);
haftmann@33992
   615
          in
haftmann@33992
   616
            pair
haftmann@33992
   617
            [concat [str "type", ty_p]]
haftmann@33992
   618
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   619
          end
haftmann@33992
   620
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   621
          let
haftmann@33992
   622
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   623
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   624
            val (ps, p) = split_last sig_ps;
haftmann@33992
   625
          in pair
haftmann@33992
   626
            sig_ps
haftmann@33992
   627
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   628
          end
haftmann@37447
   629
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@28054
   630
          let
haftmann@33992
   631
            fun print_field s p = concat [str s, str ":", p];
haftmann@37384
   632
            fun print_super_class_field (super_class, classrel) =
haftmann@37384
   633
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33992
   634
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   635
              print_val_decl print_typscheme
haftmann@33992
   636
                (classparam, ([(v, [class])], ty));
haftmann@33992
   637
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   638
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@32924
   639
            val w = "_" ^ first_upper v;
haftmann@33992
   640
            fun print_classparam_proj (classparam, _) =
haftmann@33992
   641
              (concat o map str) ["let", deresolve classparam, w, "=",
haftmann@33992
   642
                w ^ "." ^ deresolve classparam ^ ";;"];
haftmann@33992
   643
            val type_decl_p = concat [
haftmann@33992
   644
                str ("type '" ^ v),
haftmann@33992
   645
                (str o deresolve) class,
haftmann@28054
   646
                str "=",
haftmann@33992
   647
                enum_default "unit" ";" "{" "}" (
haftmann@37384
   648
                  map print_super_class_field super_classes
haftmann@33992
   649
                  @ map print_classparam_field classparams
haftmann@33992
   650
                )
haftmann@28054
   651
              ];
haftmann@33992
   652
          in pair
haftmann@33992
   653
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   654
            (Pretty.chunks (
haftmann@33992
   655
              doublesemicolon [type_decl_p]
haftmann@33992
   656
              :: map print_classparam_proj classparams
haftmann@33992
   657
            ))
haftmann@33992
   658
          end;
haftmann@33992
   659
  in print_stmt end;
haftmann@28054
   660
haftmann@38933
   661
fun print_ocaml_module name some_decls body =
haftmann@38933
   662
  Pretty.chunks2 (
haftmann@33992
   663
    Pretty.chunks (
haftmann@33992
   664
      str ("module " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   665
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   666
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   667
    )
haftmann@33992
   668
    :: body
haftmann@33992
   669
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   670
  );
haftmann@28054
   671
haftmann@28064
   672
val literals_ocaml = let
haftmann@28064
   673
  fun chr i =
haftmann@28064
   674
    let
haftmann@28064
   675
      val xs = string_of_int i;
wenzelm@40627
   676
      val ys = replicate_string (3 - length (raw_explode xs)) "0";
haftmann@28064
   677
    in "\\" ^ ys ^ xs end;
haftmann@28064
   678
  fun char_ocaml c =
haftmann@28064
   679
    let
haftmann@28064
   680
      val i = ord c;
haftmann@28064
   681
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   682
        then chr i else c
haftmann@28064
   683
    in s end;
haftmann@34944
   684
  fun numeral_ocaml k = if k < 0
haftmann@34944
   685
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34944
   686
    else if k <= 1073741823
haftmann@34944
   687
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34944
   688
      else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   689
in Literals {
haftmann@34178
   690
  literal_char = Library.enclose "'" "'" o char_ocaml,
haftmann@28064
   691
  literal_string = quote o translate_string char_ocaml,
haftmann@34944
   692
  literal_numeral = numeral_ocaml,
haftmann@34178
   693
  literal_list = enum ";" "[" "]",
haftmann@28064
   694
  infix_cons = (6, "::")
haftmann@28064
   695
} end;
haftmann@28064
   696
haftmann@28064
   697
haftmann@28054
   698
haftmann@28054
   699
(** SML/OCaml generic part **)
haftmann@28054
   700
haftmann@39028
   701
fun ml_program_of_program labelled_name reserved module_alias program =
haftmann@39028
   702
  let
haftmann@39028
   703
    fun namify_const upper base (nsp_const, nsp_type) =
haftmann@39028
   704
      let
wenzelm@43326
   705
        val (base', nsp_const') =
wenzelm@43326
   706
          Name.variant (if upper then first_upper base else base) nsp_const
haftmann@39028
   707
      in (base', (nsp_const', nsp_type)) end;
haftmann@39028
   708
    fun namify_type base (nsp_const, nsp_type) =
haftmann@39028
   709
      let
wenzelm@43326
   710
        val (base', nsp_type') = Name.variant base nsp_type
haftmann@39028
   711
      in (base', (nsp_const, nsp_type')) end;
haftmann@39028
   712
    fun namify_stmt (Code_Thingol.Fun _) = namify_const false
haftmann@39028
   713
      | namify_stmt (Code_Thingol.Datatype _) = namify_type
haftmann@39028
   714
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_const true
haftmann@39028
   715
      | namify_stmt (Code_Thingol.Class _) = namify_type
haftmann@39028
   716
      | namify_stmt (Code_Thingol.Classrel _) = namify_const false
haftmann@39028
   717
      | namify_stmt (Code_Thingol.Classparam _) = namify_const false
haftmann@39028
   718
      | namify_stmt (Code_Thingol.Classinst _) = namify_const false;
haftmann@39028
   719
    fun ml_binding_of_stmt (name, Code_Thingol.Fun (_, ((tysm as (vs, ty), raw_eqs), _))) =
haftmann@39028
   720
          let
haftmann@39028
   721
            val eqs = filter (snd o snd) raw_eqs;
haftmann@39028
   722
            val (eqs', some_value_name) = if null (filter_out (null o snd) vs) then case eqs
haftmann@39028
   723
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@39028
   724
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@39028
   725
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@39028
   726
                | _ => (eqs, NONE)
haftmann@39028
   727
              else (eqs, NONE)
haftmann@39028
   728
          in (ML_Function (name, (tysm, eqs')), some_value_name) end
haftmann@48072
   729
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as { vs, ... })) =
haftmann@39028
   730
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@39028
   731
      | ml_binding_of_stmt (name, _) =
haftmann@39028
   732
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@39028
   733
    fun modify_fun (name, stmt) =
haftmann@39028
   734
      let
haftmann@39028
   735
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@39028
   736
        val ml_stmt = case binding
haftmann@39028
   737
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@39028
   738
              ML_Exc (name, ((vs, ty),
haftmann@39028
   739
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@39028
   740
          | _ => case some_value_name
haftmann@39028
   741
             of NONE => ML_Funs ([binding], [])
haftmann@39028
   742
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@39028
   743
              | SOME (name, false) => ML_Val binding
haftmann@39028
   744
      in SOME ml_stmt end;
haftmann@39031
   745
    fun modify_funs stmts = single (SOME
haftmann@39031
   746
      (ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst)))
haftmann@39031
   747
    fun modify_datatypes stmts = single (SOME
haftmann@39031
   748
      (ML_Datas (map_filter
haftmann@39031
   749
        (fn (name, Code_Thingol.Datatype (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts)))
haftmann@39031
   750
    fun modify_class stmts = single (SOME
haftmann@39031
   751
      (ML_Class (the_single (map_filter
haftmann@39031
   752
        (fn (name, Code_Thingol.Class (_, stmt)) => SOME (name, stmt) | _ => NONE) stmts))))
haftmann@47576
   753
    fun modify_stmts ([stmt as (_, stmt' as Code_Thingol.Fun _)]) =
haftmann@39059
   754
          if Code_Thingol.is_case stmt' then [] else [modify_fun stmt]
haftmann@39028
   755
      | modify_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@39061
   756
          modify_funs (filter_out (Code_Thingol.is_case o snd) stmts)
haftmann@39028
   757
      | modify_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@39028
   758
          modify_datatypes stmts
haftmann@39028
   759
      | modify_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@39028
   760
          modify_datatypes stmts
haftmann@39028
   761
      | modify_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@39028
   762
          modify_class stmts
haftmann@39028
   763
      | modify_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@39028
   764
          modify_class stmts
haftmann@39028
   765
      | modify_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@39028
   766
          modify_class stmts
haftmann@39028
   767
      | modify_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@39028
   768
          [modify_fun stmt]
haftmann@39028
   769
      | modify_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@39028
   770
          modify_funs stmts
haftmann@39028
   771
      | modify_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@39028
   772
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@39028
   773
  in
haftmann@39028
   774
    Code_Namespace.hierarchical_program labelled_name { module_alias = module_alias, reserved = reserved,
haftmann@39028
   775
      empty_nsp = (reserved, reserved), namify_module = pair, namify_stmt = namify_stmt,
haftmann@39028
   776
      cyclic_modules = false, empty_data = (), memorize_data = K I, modify_stmts = modify_stmts } program
haftmann@39028
   777
  end;
haftmann@39028
   778
haftmann@47576
   779
fun serialize_ml print_ml_module print_ml_stmt with_signatures
haftmann@39142
   780
    { labelled_name, reserved_syms, includes, module_alias,
haftmann@41343
   781
      class_syntax, tyco_syntax, const_syntax } program =
haftmann@28054
   782
  let
haftmann@39147
   783
haftmann@39147
   784
    (* build program *)
haftmann@39028
   785
    val { deresolver, hierarchical_program = ml_program } =
haftmann@39028
   786
      ml_program_of_program labelled_name (Name.make_context reserved_syms) module_alias program;
haftmann@39147
   787
haftmann@39147
   788
    (* print statements *)
haftmann@39147
   789
    fun print_stmt prefix_fragments (_, stmt) = print_ml_stmt
haftmann@47576
   790
      tyco_syntax const_syntax (make_vars reserved_syms)
haftmann@50625
   791
      (Code_Thingol.is_constr program) (deresolver prefix_fragments) stmt
haftmann@39147
   792
      |> apfst SOME;
haftmann@39147
   793
haftmann@39147
   794
    (* print modules *)
haftmann@47576
   795
    fun print_module _ base _ xs =
haftmann@39147
   796
      let
haftmann@39147
   797
        val (raw_decls, body) = split_list xs;
haftmann@39147
   798
        val decls = if with_signatures then SOME (maps these raw_decls) else NONE 
haftmann@39147
   799
      in (NONE, print_ml_module base decls body) end;
haftmann@39147
   800
haftmann@39147
   801
    (* serialization *)
haftmann@39147
   802
    val p = Pretty.chunks2 (map snd includes
haftmann@39147
   803
      @ map snd (Code_Namespace.print_hierarchical {
haftmann@39147
   804
        print_module = print_module, print_stmt = print_stmt,
haftmann@39147
   805
        lift_markup = apsnd } ml_program));
haftmann@39056
   806
    fun write width NONE = writeln o format [] width
haftmann@39056
   807
      | write width (SOME p) = File.write p o format [] width;
haftmann@48568
   808
    fun prepare names width p = ([("", format names width p)], try (deresolver []));
haftmann@28054
   809
  in
haftmann@48568
   810
    Code_Target.serialization write prepare p
haftmann@28054
   811
  end;
haftmann@28054
   812
haftmann@38966
   813
val serializer_sml : Code_Target.serializer =
haftmann@33992
   814
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@47576
   815
  >> (fn with_signatures => serialize_ml print_sml_module print_sml_stmt with_signatures));
haftmann@28054
   816
haftmann@38966
   817
val serializer_ocaml : Code_Target.serializer =
haftmann@33992
   818
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@47576
   819
  >> (fn with_signatures => serialize_ml print_ocaml_module print_ocaml_stmt with_signatures));
haftmann@28054
   820
haftmann@38966
   821
haftmann@38966
   822
(** Isar setup **)
haftmann@38966
   823
haftmann@28054
   824
val setup =
haftmann@37821
   825
  Code_Target.add_target
haftmann@38966
   826
    (target_SML, { serializer = serializer_sml, literals = literals_sml,
wenzelm@41940
   827
      check = { env_var = "ISABELLE_PROCESS",
wenzelm@41940
   828
        make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@50022
   829
        make_command = fn _ =>
haftmann@51091
   830
          "\"$ISABELLE_PROCESS\" -r -q -e 'datatype ref = datatype Unsynchronized.ref; use \"ROOT.ML\" handle _ => exit 1' Pure" } })
haftmann@37821
   831
  #> Code_Target.add_target
haftmann@38966
   832
    (target_OCaml, { serializer = serializer_ocaml, literals = literals_ocaml,
wenzelm@41952
   833
      check = { env_var = "ISABELLE_OCAML",
wenzelm@41940
   834
        make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
wenzelm@41952
   835
        make_command = fn _ => "\"$ISABELLE_OCAML\" -w pu nums.cma ROOT.ocaml" } })
haftmann@38923
   836
  #> Code_Target.add_tyco_syntax target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   837
      brackify_infix (1, R) fxy (
haftmann@33992
   838
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   839
        str "->",
haftmann@33992
   840
        print_typ (INFX (1, R)) ty2
haftmann@37242
   841
      )))
haftmann@38923
   842
  #> Code_Target.add_tyco_syntax target_OCaml "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@28054
   848
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   849
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
   850
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
   851
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   852
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   853
      "and", "as", "assert", "begin", "class",
haftmann@28054
   854
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   855
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   856
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   857
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   858
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   859
      "virtual", "when", "while", "with"
haftmann@28054
   860
    ]
haftmann@34944
   861
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
   862
haftmann@28054
   863
end; (*struct*)