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