src/Tools/Code/code_ml.ML
author haftmann
Mon Aug 30 16:31:38 2010 +0200 (2010-08-30)
changeset 38915 026526cba0e6
parent 38913 d1d4d808be26
child 38916 c0b857a04758
permissions -rw-r--r--
tuned
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@34032
    11
  val evaluation_code_of: theory -> string -> string
haftmann@34028
    12
    -> Code_Thingol.naming -> Code_Thingol.program -> string list -> string * string option list
haftmann@36515
    13
  val print_tuple: (Code_Printer.fixity -> 'a -> Pretty.T)
haftmann@36515
    14
    -> Code_Printer.fixity -> 'a list -> Pretty.T option
haftmann@28054
    15
  val setup: theory -> theory
haftmann@28054
    16
end;
haftmann@28054
    17
haftmann@28054
    18
structure Code_ML : CODE_ML =
haftmann@28054
    19
struct
haftmann@28054
    20
haftmann@28054
    21
open Basic_Code_Thingol;
haftmann@28054
    22
open Code_Printer;
haftmann@28054
    23
haftmann@28054
    24
infixr 5 @@;
haftmann@28054
    25
infixr 5 @|;
haftmann@28054
    26
haftmann@33992
    27
haftmann@33992
    28
(** generic **)
haftmann@33992
    29
haftmann@28054
    30
val target_SML = "SML";
haftmann@28054
    31
val target_OCaml = "OCaml";
haftmann@28054
    32
haftmann@33636
    33
datatype ml_binding =
haftmann@35228
    34
    ML_Function of string * (typscheme * ((iterm list * iterm) * (thm option * bool)) list)
haftmann@33636
    35
  | ML_Instance of string * ((class * (string * (vname * sort) list))
haftmann@37445
    36
        * ((class * (string * (string * dict list list))) list
haftmann@37449
    37
      * (((string * const) * (thm * bool)) list * ((string * const) * (thm * bool)) list)));
haftmann@28054
    38
haftmann@33636
    39
datatype ml_stmt =
haftmann@33992
    40
    ML_Exc of string * (typscheme * int)
haftmann@33636
    41
  | ML_Val of ml_binding
haftmann@33636
    42
  | ML_Funs of ml_binding list * string list
haftmann@37449
    43
  | ML_Datas of (string * ((vname * sort) list * ((string * vname list) * itype list) list)) list
haftmann@37447
    44
  | ML_Class of string * (vname * ((class * string) list * (string * itype) list));
haftmann@33636
    45
haftmann@33636
    46
fun stmt_name_of_binding (ML_Function (name, _)) = name
haftmann@33636
    47
  | stmt_name_of_binding (ML_Instance (name, _)) = name;
haftmann@33636
    48
haftmann@33636
    49
fun stmt_names_of (ML_Exc (name, _)) = [name]
haftmann@33636
    50
  | stmt_names_of (ML_Val binding) = [stmt_name_of_binding binding]
haftmann@33636
    51
  | stmt_names_of (ML_Funs (bindings, _)) = map stmt_name_of_binding bindings
haftmann@33636
    52
  | stmt_names_of (ML_Datas ds) = map fst ds
haftmann@33636
    53
  | stmt_names_of (ML_Class (name, _)) = [name];
haftmann@28054
    54
haftmann@33992
    55
fun print_product _ [] = NONE
haftmann@33992
    56
  | print_product print [x] = SOME (print x)
haftmann@34178
    57
  | print_product print xs = (SOME o enum " *" "" "") (map print xs);
haftmann@28054
    58
haftmann@33992
    59
fun print_tuple _ _ [] = NONE
haftmann@33992
    60
  | print_tuple print fxy [x] = SOME (print fxy x)
haftmann@34178
    61
  | print_tuple print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
haftmann@28054
    62
haftmann@33992
    63
haftmann@33992
    64
(** SML serializer **)
haftmann@33992
    65
haftmann@33992
    66
fun print_sml_stmt labelled_name syntax_tyco syntax_const reserved is_cons deresolve =
haftmann@28054
    67
  let
haftmann@33992
    68
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33992
    69
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33992
    70
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33992
    71
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
    72
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@33992
    73
    and print_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@33992
    74
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33992
    75
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33992
    76
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33992
    77
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
    78
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
    79
      (map_filter (fn (v, sort) =>
haftmann@33992
    80
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
    81
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
    82
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33992
    83
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
    84
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
    85
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
    86
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
    87
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
    88
          let
haftmann@33992
    89
            val v_p = str (if k = 1 then first_upper v ^ "_"
haftmann@33992
    90
              else first_upper v ^ string_of_int (i+1) ^ "_");
haftmann@33992
    91
          in case classrels
haftmann@33992
    92
           of [] => v_p
haftmann@33992
    93
            | [classrel] => brackets [(str o deresolve) classrel, v_p]
haftmann@33992
    94
            | classrels => brackets
haftmann@34178
    95
                [enum " o" "(" ")" (map (str o deresolve) classrels), v_p]
haftmann@33992
    96
          end
haftmann@33992
    97
    and print_dicts is_pseudo_fun = print_tuple (print_dict is_pseudo_fun);
haftmann@33992
    98
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
    99
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@35228
   100
    fun print_term is_pseudo_fun some_thm vars fxy (IConst c) =
haftmann@35228
   101
          print_app is_pseudo_fun some_thm vars fxy (c, [])
haftmann@35228
   102
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   103
          str "_"
haftmann@35228
   104
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   105
          str (lookup_var vars v)
haftmann@35228
   106
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   107
          (case Code_Thingol.unfold_const_app t
haftmann@35228
   108
           of SOME c_ts => print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   109
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   110
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   111
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   112
          let
haftmann@31874
   113
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33992
   114
            fun print_abs (pat, ty) =
haftmann@35228
   115
              print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   116
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@33992
   117
            val (ps, vars') = fold_map print_abs binds vars;
haftmann@35228
   118
          in brackets (ps @ [print_term is_pseudo_fun some_thm vars' NOBR t']) end
haftmann@35228
   119
      | print_term is_pseudo_fun some_thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
   120
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
   121
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@35228
   122
                then print_case is_pseudo_fun some_thm vars fxy cases
haftmann@35228
   123
                else print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   124
            | NONE => print_case is_pseudo_fun some_thm vars fxy cases)
haftmann@37449
   125
    and print_app_expr is_pseudo_fun some_thm vars (app as ((c, ((_, iss), function_typs)), ts)) =
haftmann@29175
   126
      if is_cons c then
haftmann@37449
   127
        let val k = length function_typs in
haftmann@33992
   128
          if k < 2 orelse length ts = k
haftmann@33992
   129
          then (str o deresolve) c
haftmann@35228
   130
            :: the_list (print_tuple (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   131
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   132
        end
haftmann@33636
   133
      else if is_pseudo_fun c
haftmann@29175
   134
        then (str o deresolve) c @@ str "()"
haftmann@33992
   135
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@35228
   136
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   137
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@35228
   138
      (print_term is_pseudo_fun) syntax_const some_thm vars
haftmann@33992
   139
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@35228
   140
    and print_case is_pseudo_fun some_thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   141
          let
haftmann@29952
   142
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   143
            fun print_match ((pat, ty), t) vars =
haftmann@28054
   144
              vars
haftmann@35228
   145
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@33992
   146
              |>> (fn p => semicolon [str "val", p, str "=",
haftmann@35228
   147
                    print_term is_pseudo_fun some_thm vars NOBR t])
haftmann@33992
   148
            val (ps, vars') = fold_map print_match binds vars;
haftmann@28054
   149
          in
haftmann@28054
   150
            Pretty.chunks [
haftmann@34178
   151
              Pretty.block [str "let", Pretty.fbrk, Pretty.chunks ps],
haftmann@35228
   152
              Pretty.block [str "in", Pretty.fbrk, print_term is_pseudo_fun some_thm vars' NOBR body],
haftmann@34178
   153
              str "end"
haftmann@28054
   154
            ]
haftmann@28054
   155
          end
haftmann@35228
   156
      | print_case is_pseudo_fun some_thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   157
          let
haftmann@33992
   158
            fun print_select delim (pat, body) =
haftmann@28054
   159
              let
haftmann@35228
   160
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@28054
   161
              in
haftmann@35228
   162
                concat [str delim, p, str "=>", print_term is_pseudo_fun some_thm vars' NOBR body]
haftmann@28054
   163
              end;
haftmann@28054
   164
          in
haftmann@31665
   165
            brackets (
haftmann@28054
   166
              str "case"
haftmann@35228
   167
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   168
              :: print_select "of" clause
haftmann@33992
   169
              :: map (print_select "|") clauses
haftmann@28054
   170
            )
haftmann@28054
   171
          end
haftmann@35228
   172
      | print_case is_pseudo_fun some_thm vars fxy ((_, []), _) =
haftmann@31121
   173
          (concat o map str) ["raise", "Fail", "\"empty case\""];
haftmann@33992
   174
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   175
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   176
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   177
      let
haftmann@37449
   178
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37449
   179
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   180
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   181
      in
haftmann@33992
   182
        concat (
haftmann@33992
   183
          str definer
haftmann@33992
   184
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   185
          :: str "="
haftmann@33992
   186
          :: separate (str "|") (map print_co cos)
haftmann@33992
   187
        )
haftmann@33992
   188
      end;
haftmann@33992
   189
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   190
          (ML_Function (name, (vs_ty as (vs, ty), eq :: eqs))) =
haftmann@29189
   191
          let
haftmann@35228
   192
            fun print_eqn definer ((ts, t), (some_thm, _)) =
haftmann@33636
   193
              let
haftmann@33636
   194
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@33636
   195
                val vars = reserved
haftmann@33636
   196
                  |> intro_base_names
haftmann@33636
   197
                       (is_none o syntax_const) deresolve consts
haftmann@33636
   198
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@33636
   199
                       (insert (op =)) ts []);
haftmann@33636
   200
                val prolog = if needs_typ then
haftmann@33992
   201
                  concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@34178
   202
                    else (concat o map str) [definer, deresolve name];
haftmann@33636
   203
              in
haftmann@33636
   204
                concat (
haftmann@33636
   205
                  prolog
haftmann@33636
   206
                  :: (if is_pseudo_fun name then [str "()"]
haftmann@33992
   207
                      else print_dict_args vs
haftmann@35228
   208
                        @ map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@33636
   209
                  @ str "="
haftmann@35228
   210
                  @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33636
   211
                )
haftmann@33636
   212
              end
haftmann@33992
   213
            val shift = if null eqs then I else
haftmann@33992
   214
              map (Pretty.block o single o Pretty.block o single);
haftmann@33992
   215
          in pair
haftmann@33992
   216
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   217
            ((Pretty.block o Pretty.fbreaks o shift) (
haftmann@33992
   218
              print_eqn definer eq
haftmann@33992
   219
              :: map (print_eqn "|") eqs
haftmann@33992
   220
            ))
haftmann@29189
   221
          end
haftmann@33992
   222
      | print_def is_pseudo_fun _ definer
haftmann@37449
   223
          (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@29189
   224
          let
haftmann@37384
   225
            fun print_super_instance (_, (classrel, dss)) =
haftmann@33636
   226
              concat [
haftmann@33636
   227
                (str o Long_Name.base_name o deresolve) classrel,
haftmann@33636
   228
                str "=",
haftmann@33992
   229
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   230
              ];
haftmann@37384
   231
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   232
              concat [
haftmann@33636
   233
                (str o Long_Name.base_name o deresolve) classparam,
haftmann@33636
   234
                str "=",
haftmann@37384
   235
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   236
              ];
haftmann@33992
   237
          in pair
haftmann@33992
   238
            (print_val_decl print_dicttypscheme
haftmann@33992
   239
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   240
            (concat (
haftmann@33636
   241
              str definer
haftmann@33636
   242
              :: (str o deresolve) inst
haftmann@33636
   243
              :: (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   244
                  else print_dict_args vs)
haftmann@33636
   245
              @ str "="
haftmann@34178
   246
              :: enum "," "{" "}"
haftmann@37384
   247
                (map print_super_instance super_instances
haftmann@37384
   248
                  @ map print_classparam_instance classparam_instances)
haftmann@33636
   249
              :: str ":"
haftmann@33992
   250
              @@ print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33992
   251
            ))
haftmann@33636
   252
          end;
haftmann@33992
   253
    fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   254
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   255
          ((semicolon o map str) (
haftmann@33636
   256
            (if n = 0 then "val" else "fun")
haftmann@33636
   257
            :: deresolve name
haftmann@33636
   258
            :: replicate n "_"
haftmann@33636
   259
            @ "="
haftmann@33636
   260
            :: "raise"
haftmann@33636
   261
            :: "Fail"
haftmann@33992
   262
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   263
          ))
haftmann@33992
   264
      | print_stmt (ML_Val binding) =
haftmann@33636
   265
          let
haftmann@33992
   266
            val (sig_p, p) = print_def (K false) true "val" binding
haftmann@33992
   267
          in pair
haftmann@33992
   268
            [sig_p]
haftmann@33992
   269
            (semicolon [p])
haftmann@33992
   270
          end
haftmann@33992
   271
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   272
          let
haftmann@33992
   273
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   274
            fun print_pseudo_fun name = concat [
haftmann@29189
   275
                str "val",
haftmann@29189
   276
                (str o deresolve) name,
haftmann@29189
   277
                str "=",
haftmann@29189
   278
                (str o deresolve) name,
haftmann@29189
   279
                str "();"
haftmann@29189
   280
              ];
haftmann@33992
   281
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   282
              (print_def' "fun" binding :: map (print_def' "and") bindings);
haftmann@33992
   283
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   284
          in pair
haftmann@33992
   285
            sig_ps
haftmann@33992
   286
            (Pretty.chunks (ps @ semicolon [p] :: pseudo_ps))
haftmann@33992
   287
          end
haftmann@33992
   288
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   289
          let
haftmann@33992
   290
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   291
          in
haftmann@33992
   292
            pair
haftmann@33992
   293
            [concat [str "type", ty_p]]
haftmann@33992
   294
            (concat [str "datatype", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   295
          end
haftmann@33992
   296
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   297
          let
haftmann@33992
   298
            val sig_ps = print_datatype_decl "datatype" data
haftmann@33992
   299
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   300
            val (ps, p) = split_last sig_ps;
haftmann@33992
   301
          in pair
haftmann@33992
   302
            sig_ps
haftmann@33992
   303
            (Pretty.chunks (ps @| semicolon [p]))
haftmann@33992
   304
          end
haftmann@37447
   305
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@28054
   306
          let
haftmann@33992
   307
            fun print_field s p = concat [str s, str ":", p];
haftmann@33992
   308
            fun print_proj s p = semicolon
haftmann@33992
   309
              (map str ["val", s, "=", "#" ^ s, ":"] @| p);
haftmann@37384
   310
            fun print_super_class_decl (super_class, classrel) =
haftmann@33992
   311
              print_val_decl print_dicttypscheme
haftmann@37384
   312
                (classrel, ([(v, [class])], (super_class, ITyVar v)));
haftmann@37384
   313
            fun print_super_class_field (super_class, classrel) =
haftmann@37384
   314
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@37384
   315
            fun print_super_class_proj (super_class, classrel) =
haftmann@33992
   316
              print_proj (deresolve classrel)
haftmann@37384
   317
                (print_dicttypscheme ([(v, [class])], (super_class, ITyVar v)));
haftmann@33992
   318
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   319
              print_val_decl print_typscheme
haftmann@33992
   320
                (classparam, ([(v, [class])], ty));
haftmann@33992
   321
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   322
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@33992
   323
            fun print_classparam_proj (classparam, ty) =
haftmann@33992
   324
              print_proj (deresolve classparam)
haftmann@33992
   325
                (print_typscheme ([(v, [class])], ty));
haftmann@33992
   326
          in pair
haftmann@33992
   327
            (concat [str "type", print_dicttyp (class, ITyVar v)]
haftmann@37384
   328
              :: map print_super_class_decl super_classes
haftmann@33992
   329
              @ map print_classparam_decl classparams)
haftmann@33992
   330
            (Pretty.chunks (
haftmann@28054
   331
              concat [
haftmann@28054
   332
                str ("type '" ^ v),
haftmann@28054
   333
                (str o deresolve) class,
haftmann@28054
   334
                str "=",
haftmann@34178
   335
                enum "," "{" "};" (
haftmann@37384
   336
                  map print_super_class_field super_classes
haftmann@33992
   337
                  @ map print_classparam_field classparams
haftmann@28054
   338
                )
haftmann@28054
   339
              ]
haftmann@37384
   340
              :: map print_super_class_proj super_classes
haftmann@33992
   341
              @ map print_classparam_proj classparams
haftmann@33992
   342
            ))
haftmann@28054
   343
          end;
haftmann@33992
   344
  in print_stmt end;
haftmann@28054
   345
haftmann@34032
   346
fun print_sml_module name some_decls body = if name = ""
haftmann@34032
   347
  then Pretty.chunks2 body
haftmann@34032
   348
  else Pretty.chunks2 (
haftmann@33992
   349
    Pretty.chunks (
haftmann@33992
   350
      str ("structure " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   351
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   352
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   353
    )
haftmann@33992
   354
    :: body
haftmann@33992
   355
    @| str ("end; (*struct " ^ name ^ "*)")
haftmann@28054
   356
  );
haftmann@28054
   357
haftmann@28064
   358
val literals_sml = Literals {
haftmann@28064
   359
  literal_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@28064
   360
  literal_string = quote o translate_string ML_Syntax.print_char,
haftmann@34944
   361
  literal_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34944
   362
  literal_positive_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@37958
   363
  literal_alternative_numeral = fn k => "(" ^ string_of_int k ^ " : IntInf.int)",
haftmann@34944
   364
  literal_naive_numeral = string_of_int,
haftmann@34178
   365
  literal_list = enum "," "[" "]",
haftmann@28064
   366
  infix_cons = (7, "::")
haftmann@28064
   367
};
haftmann@28064
   368
haftmann@28054
   369
haftmann@28054
   370
(** OCaml serializer **)
haftmann@28054
   371
haftmann@33992
   372
fun print_ocaml_stmt labelled_name syntax_tyco syntax_const reserved is_cons deresolve =
haftmann@28054
   373
  let
haftmann@33992
   374
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33992
   375
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33992
   376
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33992
   377
      | print_tyco_expr fxy (tyco, tys) =
haftmann@34178
   378
          concat [enum "," "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@33992
   379
    and print_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@33992
   380
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33992
   381
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33992
   382
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33992
   383
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@34178
   384
    fun print_typscheme_prefix (vs, p) = enum " ->" "" ""
haftmann@33992
   385
      (map_filter (fn (v, sort) =>
haftmann@33992
   386
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
   387
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
   388
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33992
   389
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
   390
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
   391
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   392
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
   393
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
   394
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   395
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@33992
   396
          |> fold_rev (fn classrel => fn p =>
haftmann@33992
   397
               Pretty.block [p, str ".", (str o deresolve) classrel]) classrels
haftmann@33992
   398
    and print_dicts is_pseudo_fun = print_tuple (print_dict is_pseudo_fun);
haftmann@33992
   399
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
   400
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@35228
   401
    fun print_term is_pseudo_fun some_thm vars fxy (IConst c) =
haftmann@35228
   402
          print_app is_pseudo_fun some_thm vars fxy (c, [])
haftmann@35228
   403
      | print_term is_pseudo_fun some_thm vars fxy (IVar NONE) =
haftmann@31889
   404
          str "_"
haftmann@35228
   405
      | print_term is_pseudo_fun some_thm vars fxy (IVar (SOME v)) =
haftmann@32924
   406
          str (lookup_var vars v)
haftmann@35228
   407
      | print_term is_pseudo_fun some_thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   408
          (case Code_Thingol.unfold_const_app t
haftmann@35228
   409
           of SOME c_ts => print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   410
            | NONE => brackify fxy [print_term is_pseudo_fun some_thm vars NOBR t1,
haftmann@35228
   411
                print_term is_pseudo_fun some_thm vars BR t2])
haftmann@35228
   412
      | print_term is_pseudo_fun some_thm vars fxy (t as _ `|=> _) =
haftmann@28054
   413
          let
haftmann@31874
   414
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@35228
   415
            val (ps, vars') = fold_map (print_bind is_pseudo_fun some_thm BR o fst) binds vars;
haftmann@35228
   416
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun some_thm vars' NOBR t') end
haftmann@35228
   417
      | print_term is_pseudo_fun some_thm vars fxy (ICase (cases as (_, t0))) =
haftmann@33992
   418
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
   419
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@35228
   420
                then print_case is_pseudo_fun some_thm vars fxy cases
haftmann@35228
   421
                else print_app is_pseudo_fun some_thm vars fxy c_ts
haftmann@35228
   422
            | NONE => print_case is_pseudo_fun some_thm vars fxy cases)
haftmann@35228
   423
    and print_app_expr is_pseudo_fun some_thm vars (app as ((c, ((_, iss), tys)), ts)) =
haftmann@28054
   424
      if is_cons c then
haftmann@33992
   425
        let val k = length tys in
haftmann@33992
   426
          if length ts = k
haftmann@33992
   427
          then (str o deresolve) c
haftmann@35228
   428
            :: the_list (print_tuple (print_term is_pseudo_fun some_thm vars) BR ts)
haftmann@35228
   429
          else [print_term is_pseudo_fun some_thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   430
        end
haftmann@33636
   431
      else if is_pseudo_fun c
haftmann@29175
   432
        then (str o deresolve) c @@ str "()"
haftmann@33992
   433
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@35228
   434
        @ map (print_term is_pseudo_fun some_thm vars BR) ts
haftmann@35228
   435
    and print_app is_pseudo_fun some_thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@35228
   436
      (print_term is_pseudo_fun) syntax_const some_thm vars
haftmann@33992
   437
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@35228
   438
    and print_case is_pseudo_fun some_thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   439
          let
haftmann@29952
   440
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   441
            fun print_let ((pat, ty), t) vars =
haftmann@28054
   442
              vars
haftmann@35228
   443
              |> print_bind is_pseudo_fun some_thm NOBR pat
haftmann@28054
   444
              |>> (fn p => concat
haftmann@35228
   445
                  [str "let", p, str "=", print_term is_pseudo_fun some_thm vars NOBR t, str "in"])
haftmann@33992
   446
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   447
          in
haftmann@31665
   448
            brackify_block fxy (Pretty.chunks ps) []
haftmann@35228
   449
              (print_term is_pseudo_fun some_thm vars' NOBR body)
haftmann@31665
   450
          end
haftmann@35228
   451
      | print_case is_pseudo_fun some_thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   452
          let
haftmann@33992
   453
            fun print_select delim (pat, body) =
haftmann@28054
   454
              let
haftmann@35228
   455
                val (p, vars') = print_bind is_pseudo_fun some_thm NOBR pat vars;
haftmann@35228
   456
              in concat [str delim, p, str "->", print_term is_pseudo_fun some_thm vars' NOBR body] end;
haftmann@28054
   457
          in
haftmann@31665
   458
            brackets (
haftmann@28054
   459
              str "match"
haftmann@35228
   460
              :: print_term is_pseudo_fun some_thm vars NOBR t
haftmann@33992
   461
              :: print_select "with" clause
haftmann@33992
   462
              :: map (print_select "|") clauses
haftmann@28054
   463
            )
haftmann@28054
   464
          end
haftmann@35228
   465
      | print_case is_pseudo_fun some_thm vars fxy ((_, []), _) =
haftmann@31121
   466
          (concat o map str) ["failwith", "\"empty case\""];
haftmann@33992
   467
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   468
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   469
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   470
      let
haftmann@37449
   471
        fun print_co ((co, _), []) = str (deresolve co)
haftmann@37449
   472
          | print_co ((co, _), tys) = concat [str (deresolve co), str "of",
haftmann@34178
   473
              enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   474
      in
haftmann@33992
   475
        concat (
haftmann@33992
   476
          str definer
haftmann@33992
   477
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   478
          :: str "="
haftmann@33992
   479
          :: separate (str "|") (map print_co cos)
haftmann@33992
   480
        )
haftmann@33992
   481
      end;
haftmann@33992
   482
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   483
          (ML_Function (name, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   484
          let
haftmann@35228
   485
            fun print_eqn ((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_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   490
                      (insert (op =)) ts []);
haftmann@28054
   491
              in concat [
haftmann@38778
   492
                (Pretty.block o commas)
haftmann@35228
   493
                  (map (print_term is_pseudo_fun some_thm vars NOBR) ts),
haftmann@28054
   494
                str "->",
haftmann@35228
   495
                print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   496
              ] end;
haftmann@35228
   497
            fun print_eqns is_pseudo [((ts, t), (some_thm, _))] =
haftmann@28054
   498
                  let
haftmann@32913
   499
                    val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   500
                    val vars = reserved
haftmann@32924
   501
                      |> intro_base_names
haftmann@32913
   502
                          (is_none o syntax_const) deresolve consts
haftmann@32924
   503
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   504
                          (insert (op =)) ts []);
haftmann@28054
   505
                  in
haftmann@28054
   506
                    concat (
haftmann@29189
   507
                      (if is_pseudo then [str "()"]
haftmann@35228
   508
                        else map (print_term is_pseudo_fun some_thm vars BR) ts)
haftmann@28054
   509
                      @ str "="
haftmann@35228
   510
                      @@ print_term is_pseudo_fun some_thm vars NOBR t
haftmann@28054
   511
                    )
haftmann@28054
   512
                  end
haftmann@33992
   513
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   514
                  Pretty.block (
haftmann@28054
   515
                    str "="
haftmann@28054
   516
                    :: Pretty.brk 1
haftmann@28054
   517
                    :: str "function"
haftmann@28054
   518
                    :: Pretty.brk 1
haftmann@33992
   519
                    :: print_eqn eq
haftmann@28054
   520
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   521
                          o single o print_eqn) eqs
haftmann@28054
   522
                  )
haftmann@33992
   523
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   524
                  let
haftmann@32913
   525
                    val consts = fold Code_Thingol.add_constnames (map (snd o fst) eqs) [];
haftmann@32924
   526
                    val vars = reserved
haftmann@32924
   527
                      |> intro_base_names
haftmann@32926
   528
                          (is_none o syntax_const) deresolve consts;
haftmann@32924
   529
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   530
                  in
haftmann@28054
   531
                    Pretty.block (
haftmann@28054
   532
                      Pretty.breaks dummy_parms
haftmann@28054
   533
                      @ Pretty.brk 1
haftmann@28054
   534
                      :: str "="
haftmann@28054
   535
                      :: Pretty.brk 1
haftmann@28054
   536
                      :: str "match"
haftmann@28054
   537
                      :: Pretty.brk 1
haftmann@38778
   538
                      :: (Pretty.block o commas) dummy_parms
haftmann@28054
   539
                      :: Pretty.brk 1
haftmann@28054
   540
                      :: str "with"
haftmann@28054
   541
                      :: Pretty.brk 1
haftmann@33992
   542
                      :: print_eqn eq
haftmann@28054
   543
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   544
                           o single o print_eqn) eqs'
haftmann@28054
   545
                    )
haftmann@28054
   546
                  end;
haftmann@33636
   547
            val prolog = if needs_typ then
haftmann@33992
   548
              concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@34178
   549
                else (concat o map str) [definer, deresolve name];
haftmann@33992
   550
          in pair
haftmann@33992
   551
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   552
            (concat (
haftmann@33636
   553
              prolog
haftmann@33992
   554
              :: print_dict_args vs
haftmann@33992
   555
              @| print_eqns (is_pseudo_fun name) eqs
haftmann@33992
   556
            ))
haftmann@33636
   557
          end
haftmann@37384
   558
      | print_def is_pseudo_fun _ definer
haftmann@37449
   559
            (ML_Instance (inst, ((class, (tyco, vs)), (super_instances, (classparam_instances, _))))) =
haftmann@33636
   560
          let
haftmann@37384
   561
            fun print_super_instance (_, (classrel, dss)) =
haftmann@33636
   562
              concat [
haftmann@33636
   563
                (str o deresolve) classrel,
haftmann@33636
   564
                str "=",
haftmann@33992
   565
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   566
              ];
haftmann@37384
   567
            fun print_classparam_instance ((classparam, const), (thm, _)) =
haftmann@33636
   568
              concat [
haftmann@33636
   569
                (str o deresolve) classparam,
haftmann@33636
   570
                str "=",
haftmann@37384
   571
                print_app (K false) (SOME thm) reserved NOBR (const, [])
haftmann@33636
   572
              ];
haftmann@33992
   573
          in pair
haftmann@33992
   574
            (print_val_decl print_dicttypscheme
haftmann@33992
   575
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   576
            (concat (
haftmann@33636
   577
              str definer
haftmann@33636
   578
              :: (str o deresolve) inst
haftmann@33992
   579
              :: print_dict_args vs
haftmann@33636
   580
              @ str "="
haftmann@33636
   581
              @@ brackets [
haftmann@37384
   582
                enum_default "()" ";" "{" "}" (map print_super_instance super_instances
haftmann@37384
   583
                  @ map print_classparam_instance classparam_instances),
haftmann@33636
   584
                str ":",
haftmann@33992
   585
                print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33636
   586
              ]
haftmann@33992
   587
            ))
haftmann@33636
   588
          end;
haftmann@33992
   589
     fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   590
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   591
          ((doublesemicolon o map str) (
haftmann@33636
   592
            "let"
haftmann@33636
   593
            :: deresolve name
haftmann@33636
   594
            :: replicate n "_"
haftmann@33636
   595
            @ "="
haftmann@33636
   596
            :: "failwith"
haftmann@33992
   597
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   598
          ))
haftmann@33992
   599
      | print_stmt (ML_Val binding) =
haftmann@33636
   600
          let
haftmann@33992
   601
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   602
          in pair
haftmann@33992
   603
            [sig_p]
haftmann@33992
   604
            (doublesemicolon [p])
haftmann@33992
   605
          end
haftmann@33992
   606
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   607
          let
haftmann@33992
   608
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   609
            fun print_pseudo_fun name = concat [
haftmann@29189
   610
                str "let",
haftmann@29189
   611
                (str o deresolve) name,
haftmann@29189
   612
                str "=",
haftmann@29189
   613
                (str o deresolve) name,
haftmann@29189
   614
                str "();;"
haftmann@29189
   615
              ];
haftmann@33992
   616
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   617
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   618
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   619
          in pair
haftmann@33992
   620
            sig_ps
haftmann@33992
   621
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   622
          end
haftmann@33992
   623
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   624
          let
haftmann@33992
   625
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   626
          in
haftmann@33992
   627
            pair
haftmann@33992
   628
            [concat [str "type", ty_p]]
haftmann@33992
   629
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   630
          end
haftmann@33992
   631
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   632
          let
haftmann@33992
   633
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   634
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   635
            val (ps, p) = split_last sig_ps;
haftmann@33992
   636
          in pair
haftmann@33992
   637
            sig_ps
haftmann@33992
   638
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   639
          end
haftmann@37447
   640
     | print_stmt (ML_Class (class, (v, (super_classes, classparams)))) =
haftmann@28054
   641
          let
haftmann@33992
   642
            fun print_field s p = concat [str s, str ":", p];
haftmann@37384
   643
            fun print_super_class_field (super_class, classrel) =
haftmann@37384
   644
              print_field (deresolve classrel) (print_dicttyp (super_class, ITyVar v));
haftmann@33992
   645
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   646
              print_val_decl print_typscheme
haftmann@33992
   647
                (classparam, ([(v, [class])], ty));
haftmann@33992
   648
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   649
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@32924
   650
            val w = "_" ^ first_upper v;
haftmann@33992
   651
            fun print_classparam_proj (classparam, _) =
haftmann@33992
   652
              (concat o map str) ["let", deresolve classparam, w, "=",
haftmann@33992
   653
                w ^ "." ^ deresolve classparam ^ ";;"];
haftmann@33992
   654
            val type_decl_p = concat [
haftmann@33992
   655
                str ("type '" ^ v),
haftmann@33992
   656
                (str o deresolve) class,
haftmann@28054
   657
                str "=",
haftmann@33992
   658
                enum_default "unit" ";" "{" "}" (
haftmann@37384
   659
                  map print_super_class_field super_classes
haftmann@33992
   660
                  @ map print_classparam_field classparams
haftmann@33992
   661
                )
haftmann@28054
   662
              ];
haftmann@33992
   663
          in pair
haftmann@33992
   664
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   665
            (Pretty.chunks (
haftmann@33992
   666
              doublesemicolon [type_decl_p]
haftmann@33992
   667
              :: map print_classparam_proj classparams
haftmann@33992
   668
            ))
haftmann@33992
   669
          end;
haftmann@33992
   670
  in print_stmt end;
haftmann@28054
   671
haftmann@34032
   672
fun print_ocaml_module name some_decls body = if name = ""
haftmann@34032
   673
  then Pretty.chunks2 body
haftmann@34032
   674
  else Pretty.chunks2 (
haftmann@33992
   675
    Pretty.chunks (
haftmann@33992
   676
      str ("module " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@34178
   677
      :: (the_list o Option.map (indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   678
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   679
    )
haftmann@33992
   680
    :: body
haftmann@33992
   681
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   682
  );
haftmann@28054
   683
haftmann@28064
   684
val literals_ocaml = let
haftmann@28064
   685
  fun chr i =
haftmann@28064
   686
    let
haftmann@28064
   687
      val xs = string_of_int i;
haftmann@28064
   688
      val ys = replicate_string (3 - length (explode xs)) "0";
haftmann@28064
   689
    in "\\" ^ ys ^ xs end;
haftmann@28064
   690
  fun char_ocaml c =
haftmann@28064
   691
    let
haftmann@28064
   692
      val i = ord c;
haftmann@28064
   693
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   694
        then chr i else c
haftmann@28064
   695
    in s end;
haftmann@34944
   696
  fun numeral_ocaml k = if k < 0
haftmann@34944
   697
    then "(Big_int.minus_big_int " ^ numeral_ocaml (~ k) ^ ")"
haftmann@34944
   698
    else if k <= 1073741823
haftmann@34944
   699
      then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@34944
   700
      else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   701
in Literals {
haftmann@34178
   702
  literal_char = Library.enclose "'" "'" o char_ocaml,
haftmann@28064
   703
  literal_string = quote o translate_string char_ocaml,
haftmann@34944
   704
  literal_numeral = numeral_ocaml,
haftmann@34944
   705
  literal_positive_numeral = numeral_ocaml,
haftmann@37958
   706
  literal_alternative_numeral = numeral_ocaml,
haftmann@34944
   707
  literal_naive_numeral = numeral_ocaml,
haftmann@34178
   708
  literal_list = enum ";" "[" "]",
haftmann@28064
   709
  infix_cons = (6, "::")
haftmann@28064
   710
} end;
haftmann@28064
   711
haftmann@28064
   712
haftmann@28054
   713
haftmann@28054
   714
(** SML/OCaml generic part **)
haftmann@28054
   715
haftmann@28054
   716
local
haftmann@28054
   717
haftmann@28054
   718
datatype ml_node =
haftmann@28054
   719
    Dummy of string
haftmann@28054
   720
  | Stmt of string * ml_stmt
haftmann@28054
   721
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   722
haftmann@28054
   723
in
haftmann@28054
   724
haftmann@38779
   725
fun ml_node_of_program labelled_name module_name reserved module_alias program =
haftmann@28054
   726
  let
haftmann@32924
   727
    val reserved = Name.make_context reserved;
haftmann@32924
   728
    val empty_module = ((reserved, reserved), Graph.empty);
haftmann@28054
   729
    fun map_node [] f = f
haftmann@28054
   730
      | map_node (m::ms) f =
haftmann@28054
   731
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   732
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   733
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   734
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   735
          let
haftmann@28054
   736
            val (x, nsp') = f nsp
haftmann@28054
   737
          in (x, (nsp', nodes)) end
haftmann@28054
   738
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   739
          let
haftmann@28054
   740
            val (x, nodes') =
haftmann@28054
   741
              nodes
haftmann@28054
   742
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   743
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   744
                  let
haftmann@28054
   745
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   746
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   747
          in (x, (nsp, nodes')) end;
haftmann@28054
   748
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   749
      let
haftmann@28054
   750
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   751
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   752
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   753
      let
haftmann@28054
   754
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   755
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@32924
   756
    val mk_name_module = mk_name_module reserved NONE module_alias program;
haftmann@28054
   757
    fun mk_name_stmt upper name nsp =
haftmann@28054
   758
      let
haftmann@32924
   759
        val (_, base) = dest_name name;
haftmann@32924
   760
        val base' = if upper then first_upper base else base;
haftmann@28054
   761
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   762
      in (base'', nsp') end;
haftmann@37439
   763
    fun deps_of names =
haftmann@37439
   764
      []
haftmann@37439
   765
      |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@37439
   766
      |> subtract (op =) names
haftmann@37439
   767
      |> filter_out (Code_Thingol.is_case o Graph.get_node program);
haftmann@37437
   768
    fun ml_binding_of_stmt (name, Code_Thingol.Fun (_, ((tysm as (vs, ty), raw_eqs), _))) =
haftmann@33636
   769
          let
haftmann@33636
   770
            val eqs = filter (snd o snd) raw_eqs;
haftmann@33636
   771
            val (eqs', is_value) = if null (filter_out (null o snd) vs) then case eqs
haftmann@35228
   772
               of [(([], t), some_thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@35228
   773
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), some_thm)], NONE)
haftmann@33636
   774
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@33636
   775
                | _ => (eqs, NONE)
haftmann@33636
   776
              else (eqs, NONE)
haftmann@33636
   777
          in (ML_Function (name, (tysm, eqs')), is_value) end
haftmann@33992
   778
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as ((_, (_, vs)), _))) =
haftmann@33992
   779
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@33636
   780
      | ml_binding_of_stmt (name, _) =
haftmann@33636
   781
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@33636
   782
    fun add_fun (name, stmt) =
haftmann@29189
   783
      let
haftmann@33636
   784
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@33636
   785
        val ml_stmt = case binding
haftmann@33636
   786
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@33992
   787
              ML_Exc (name, ((vs, ty),
haftmann@33992
   788
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@33636
   789
          | _ => case some_value_name
haftmann@33636
   790
             of NONE => ML_Funs ([binding], [])
haftmann@33636
   791
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@33636
   792
              | SOME (name, false) => ML_Val binding
haftmann@33636
   793
      in
haftmann@33636
   794
        map_nsp_fun_yield (mk_name_stmt false name)
haftmann@33636
   795
        #>> (fn name' => ([name'], ml_stmt))
haftmann@33636
   796
      end;
haftmann@33636
   797
    fun add_funs stmts =
haftmann@33636
   798
      let
haftmann@33636
   799
        val ml_stmt = ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst);
haftmann@33636
   800
      in
haftmann@33636
   801
        fold_map (fn (name, _) => map_nsp_fun_yield (mk_name_stmt false name)) stmts
haftmann@33636
   802
        #>> rpair ml_stmt
haftmann@33636
   803
      end;
haftmann@28054
   804
    fun add_datatypes stmts =
haftmann@28054
   805
      fold_map
haftmann@28663
   806
        (fn (name, Code_Thingol.Datatype (_, stmt)) =>
haftmann@28054
   807
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   808
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   809
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   810
          | (name, _) =>
haftmann@28054
   811
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   812
        ) stmts
haftmann@28054
   813
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   814
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@38778
   815
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   816
             | stmts => ML_Datas stmts)));
haftmann@28054
   817
    fun add_class stmts =
haftmann@28054
   818
      fold_map
haftmann@28663
   819
        (fn (name, Code_Thingol.Class (_, stmt)) =>
haftmann@28663
   820
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   821
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   822
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   823
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   824
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   825
          | (name, _) =>
haftmann@28054
   826
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   827
        ) stmts
haftmann@28054
   828
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   829
        #> (fn [] => error ("Class block without class statement: "
haftmann@38778
   830
                  ^ (Library.commas o map (labelled_name o fst)) stmts)
haftmann@33636
   831
             | [stmt] => ML_Class stmt)));
haftmann@33636
   832
    fun add_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@33636
   833
          add_fun stmt
haftmann@33636
   834
      | add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   835
          add_funs stmts
haftmann@28054
   836
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   837
          add_datatypes stmts
haftmann@28054
   838
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   839
          add_datatypes stmts
haftmann@28054
   840
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   841
          add_class stmts
haftmann@28054
   842
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   843
          add_class stmts
haftmann@28054
   844
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   845
          add_class stmts
haftmann@33636
   846
      | add_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@33636
   847
          add_fun stmt
haftmann@33636
   848
      | add_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@33636
   849
          add_funs stmts
haftmann@28054
   850
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@38778
   851
          (Library.commas o map (labelled_name o fst)) stmts);
haftmann@28054
   852
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   853
      let
haftmann@28054
   854
        val names as (name :: names') = map fst stmts;
haftmann@37439
   855
        val deps = deps_of names;
haftmann@32924
   856
        val (module_names, _) = (split_list o map dest_name) names;
haftmann@28054
   857
        val module_name = (the_single o distinct (op =) o map mk_name_module) module_names
haftmann@28054
   858
          handle Empty =>
haftmann@28054
   859
            error ("Different namespace prefixes for mutual dependencies:\n"
haftmann@38778
   860
              ^ Library.commas (map labelled_name names)
haftmann@28054
   861
              ^ "\n"
haftmann@38778
   862
              ^ Library.commas module_names);
wenzelm@30364
   863
        val module_name_path = Long_Name.explode module_name;
haftmann@28054
   864
        fun add_dep name name' =
haftmann@28054
   865
          let
haftmann@32924
   866
            val module_name' = (mk_name_module o fst o dest_name) name';
haftmann@28054
   867
          in if module_name = module_name' then
haftmann@28054
   868
            map_node module_name_path (Graph.add_edge (name, name'))
haftmann@28054
   869
          else let
haftmann@28705
   870
            val (common, (diff1 :: _, diff2 :: _)) = chop_prefix (op =)
wenzelm@30364
   871
              (module_name_path, Long_Name.explode module_name');
haftmann@28054
   872
          in
haftmann@28054
   873
            map_node common
haftmann@28054
   874
              (fn node => Graph.add_edge_acyclic (diff1, diff2) node
haftmann@28054
   875
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@28054
   876
                  ^ quote name ^ " -> " ^ quote name'
haftmann@28054
   877
                  ^ " would result in module dependency cycle"))
haftmann@28054
   878
          end end;
haftmann@28054
   879
      in
haftmann@28054
   880
        nsp_nodes
haftmann@28054
   881
        |> map_nsp_yield module_name_path (add_stmts stmts)
haftmann@28054
   882
        |-> (fn (base' :: bases', stmt') =>
haftmann@28054
   883
           apsnd (map_node module_name_path (Graph.new_node (name, (Stmt (base', stmt')))
haftmann@28054
   884
              #> fold2 (fn name' => fn base' =>
haftmann@28054
   885
                   Graph.new_node (name', (Dummy base'))) names' bases')))
haftmann@28054
   886
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@28054
   887
        |> apsnd (fold_product (curry (map_node module_name_path o Graph.add_edge)) names names)
haftmann@28054
   888
      end;
haftmann@37439
   889
    val stmts = map (AList.make (Graph.get_node program)) (rev (Graph.strong_conn program))
haftmann@37439
   890
      |> filter_out (fn [(_, stmt)] => Code_Thingol.is_case stmt | _ => false);
haftmann@37439
   891
    val (_, nodes) = fold add_stmts' stmts empty_module;
haftmann@28054
   892
    fun deresolver prefix name = 
haftmann@28054
   893
      let
haftmann@32924
   894
        val module_name = (fst o dest_name) name;
wenzelm@30364
   895
        val module_name' = (Long_Name.explode o mk_name_module) module_name;
haftmann@28054
   896
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, module_name');
haftmann@28054
   897
        val stmt_name =
haftmann@28054
   898
          nodes
haftmann@28054
   899
          |> fold (fn name => fn node => case Graph.get_node node name
haftmann@28054
   900
              of Module (_, (_, node)) => node) module_name'
haftmann@28054
   901
          |> (fn node => case Graph.get_node node name of Stmt (stmt_name, _) => stmt_name
haftmann@28054
   902
               | Dummy stmt_name => stmt_name);
haftmann@28054
   903
      in
wenzelm@30364
   904
        Long_Name.implode (remainder @ [stmt_name])
haftmann@28054
   905
      end handle Graph.UNDEF _ =>
haftmann@28054
   906
        error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   907
  in (deresolver, nodes) end;
haftmann@28054
   908
haftmann@38779
   909
fun serialize_ml target print_module print_stmt module_name with_signatures labelled_name
haftmann@38912
   910
  reserved includes module_alias _ syntax_tyco syntax_const program
haftmann@38913
   911
  (stmt_names, presentation_stmt_names) =
haftmann@28054
   912
  let
haftmann@28054
   913
    val is_cons = Code_Thingol.is_cons program;
haftmann@33992
   914
    val is_presentation = not (null presentation_stmt_names);
haftmann@28054
   915
    val (deresolver, nodes) = ml_node_of_program labelled_name module_name
haftmann@38779
   916
      reserved module_alias program;
haftmann@32924
   917
    val reserved = make_vars reserved;
haftmann@33992
   918
    fun print_node prefix (Dummy _) =
haftmann@28054
   919
          NONE
haftmann@33992
   920
      | print_node prefix (Stmt (_, stmt)) = if is_presentation andalso
haftmann@33992
   921
          (null o filter (member (op =) presentation_stmt_names) o stmt_names_of) stmt
haftmann@30962
   922
          then NONE
haftmann@33992
   923
          else SOME (print_stmt labelled_name syntax_tyco syntax_const reserved is_cons (deresolver prefix) stmt)
haftmann@33992
   924
      | print_node prefix (Module (module_name, (_, nodes))) =
haftmann@33992
   925
          let
haftmann@33992
   926
            val (decls, body) = print_nodes (prefix @ [module_name]) nodes;
haftmann@33992
   927
            val p = if is_presentation then Pretty.chunks2 body
haftmann@33992
   928
              else print_module module_name (if with_signatures then SOME decls else NONE) body;
haftmann@33992
   929
          in SOME ([], p) end
haftmann@33992
   930
    and print_nodes prefix nodes = (map_filter (print_node prefix o Graph.get_node nodes)
haftmann@33992
   931
        o rev o flat o Graph.strong_conn) nodes
haftmann@33992
   932
      |> split_list
haftmann@33992
   933
      |> (fn (decls, body) => (flat decls, body))
haftmann@30962
   934
    val stmt_names' = (map o try)
haftmann@30962
   935
      (deresolver (if is_some module_name then the_list module_name else [])) stmt_names;
haftmann@33992
   936
    val p = Pretty.chunks2 (map snd includes @ snd (print_nodes [] nodes));
haftmann@38915
   937
    fun write width NONE = writeln_pretty width
haftmann@38915
   938
      | write width (SOME p) = File.write p o string_of_pretty width;
haftmann@28054
   939
  in
haftmann@38915
   940
    Code_Target.mk_serialization write (fn width => (rpair stmt_names' o string_of_pretty width)) p
haftmann@28054
   941
  end;
haftmann@28054
   942
haftmann@28054
   943
end; (*local*)
haftmann@28054
   944
haftmann@28054
   945
haftmann@34028
   946
(** for instrumentalization **)
haftmann@28054
   947
haftmann@34032
   948
fun evaluation_code_of thy target struct_name =
haftmann@38784
   949
  Code_Target.serialize_custom thy (target, fn module_name => fn [] =>
haftmann@38784
   950
    serialize_ml target print_sml_module print_sml_stmt module_name true) (SOME struct_name);
haftmann@28054
   951
haftmann@28054
   952
haftmann@28054
   953
(** Isar setup **)
haftmann@28054
   954
haftmann@37821
   955
fun isar_serializer_sml module_name =
haftmann@33992
   956
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33992
   957
  >> (fn with_signatures => serialize_ml target_SML
haftmann@33992
   958
      print_sml_module print_sml_stmt module_name with_signatures));
haftmann@28054
   959
haftmann@37821
   960
fun isar_serializer_ocaml module_name =
haftmann@33992
   961
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@37748
   962
  >> (fn with_signatures => serialize_ml target_OCaml
haftmann@33992
   963
      print_ocaml_module print_ocaml_stmt module_name with_signatures));
haftmann@28054
   964
haftmann@28054
   965
val setup =
haftmann@37821
   966
  Code_Target.add_target
haftmann@37822
   967
    (target_SML, { serializer = isar_serializer_sml, literals = literals_sml,
haftmann@37822
   968
      check = { env_var = "ISABELLE_PROCESS", make_destination = fn p => Path.append p (Path.explode "ROOT.ML"),
haftmann@38863
   969
        make_command = fn isabelle => fn _ => isabelle ^ " -r -q -u Pure" } })
haftmann@37821
   970
  #> Code_Target.add_target
haftmann@37822
   971
    (target_OCaml, { serializer = isar_serializer_ocaml, literals = literals_ocaml,
haftmann@37822
   972
      check = { env_var = "EXEC_OCAML", make_destination = fn p => Path.append p (Path.explode "ROOT.ocaml"),
haftmann@38863
   973
        make_command = fn ocaml => fn _ => ocaml ^ " -w pu nums.cma ROOT.ocaml" } })
haftmann@33992
   974
  #> Code_Target.add_syntax_tyco target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   975
      brackify_infix (1, R) fxy (
haftmann@33992
   976
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   977
        str "->",
haftmann@33992
   978
        print_typ (INFX (1, R)) ty2
haftmann@37242
   979
      )))
haftmann@33992
   980
  #> Code_Target.add_syntax_tyco target_OCaml "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37242
   981
      brackify_infix (1, R) fxy (
haftmann@33992
   982
        print_typ (INFX (1, X)) ty1,
haftmann@28054
   983
        str "->",
haftmann@33992
   984
        print_typ (INFX (1, R)) ty2
haftmann@37242
   985
      )))
haftmann@28054
   986
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   987
  #> fold (Code_Target.add_reserved target_SML)
haftmann@38070
   988
      ["ref" (*rebinding is illegal*), "o" (*dictionary projections use it already*),
haftmann@38070
   989
        "Fail", "div", "mod" (*standard infixes*), "IntInf"]
haftmann@28054
   990
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   991
      "and", "as", "assert", "begin", "class",
haftmann@28054
   992
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   993
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   994
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   995
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   996
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   997
      "virtual", "when", "while", "with"
haftmann@28054
   998
    ]
haftmann@34944
   999
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod", "Big_int"];
haftmann@28054
  1000
haftmann@28054
  1001
end; (*struct*)