src/Tools/Code/code_ml.ML
author haftmann
Fri Dec 04 18:19:32 2009 +0100 (2009-12-04)
changeset 33992 bf22ff4f3d19
parent 33636 a9bb3f063773
child 34028 1e6206763036
permissions -rw-r--r--
signatures for generated code; tuned
haftmann@33636
     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
wenzelm@32740
     9
  val eval: string option -> string * (unit -> 'a) option Unsynchronized.ref
haftmann@30970
    10
    -> ((term -> term) -> 'a -> 'a) -> theory -> term -> string list -> 'a
haftmann@30947
    11
  val target_Eval: string
haftmann@28054
    12
  val setup: theory -> theory
haftmann@28054
    13
end;
haftmann@28054
    14
haftmann@28054
    15
structure Code_ML : CODE_ML =
haftmann@28054
    16
struct
haftmann@28054
    17
haftmann@28054
    18
open Basic_Code_Thingol;
haftmann@28054
    19
open Code_Printer;
haftmann@28054
    20
haftmann@28054
    21
infixr 5 @@;
haftmann@28054
    22
infixr 5 @|;
haftmann@28054
    23
haftmann@33992
    24
haftmann@33992
    25
(** generic **)
haftmann@33992
    26
haftmann@28054
    27
val target_SML = "SML";
haftmann@28054
    28
val target_OCaml = "OCaml";
haftmann@30947
    29
val target_Eval = "Eval";
haftmann@28054
    30
haftmann@33636
    31
datatype ml_binding =
haftmann@33636
    32
    ML_Function of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
haftmann@33636
    33
  | ML_Instance of string * ((class * (string * (vname * sort) list))
haftmann@28054
    34
        * ((class * (string * (string * dict list list))) list
haftmann@28350
    35
      * ((string * const) * (thm * bool)) list));
haftmann@28054
    36
haftmann@33636
    37
datatype ml_stmt =
haftmann@33992
    38
    ML_Exc of string * (typscheme * int)
haftmann@33636
    39
  | ML_Val of ml_binding
haftmann@33636
    40
  | ML_Funs of ml_binding list * string list
haftmann@33636
    41
  | ML_Datas of (string * ((vname * sort) list * (string * itype list) list)) list
haftmann@33636
    42
  | ML_Class of string * (vname * ((class * string) list * (string * itype) list));
haftmann@33636
    43
haftmann@33636
    44
fun stmt_name_of_binding (ML_Function (name, _)) = name
haftmann@33636
    45
  | stmt_name_of_binding (ML_Instance (name, _)) = name;
haftmann@33636
    46
haftmann@33636
    47
fun stmt_names_of (ML_Exc (name, _)) = [name]
haftmann@33636
    48
  | stmt_names_of (ML_Val binding) = [stmt_name_of_binding binding]
haftmann@33636
    49
  | stmt_names_of (ML_Funs (bindings, _)) = map stmt_name_of_binding bindings
haftmann@33636
    50
  | stmt_names_of (ML_Datas ds) = map fst ds
haftmann@33636
    51
  | stmt_names_of (ML_Class (name, _)) = [name];
haftmann@28054
    52
haftmann@33992
    53
fun print_product _ [] = NONE
haftmann@33992
    54
  | print_product print [x] = SOME (print x)
haftmann@33992
    55
  | print_product print xs = (SOME o Pretty.enum " *" "" "") (map print xs);
haftmann@28054
    56
haftmann@33992
    57
fun print_tuple _ _ [] = NONE
haftmann@33992
    58
  | print_tuple print fxy [x] = SOME (print fxy x)
haftmann@33992
    59
  | print_tuple print _ xs = SOME (Pretty.list "(" ")" (map (print NOBR) xs));
haftmann@28054
    60
haftmann@33992
    61
haftmann@33992
    62
(** SML serializer **)
haftmann@33992
    63
haftmann@33992
    64
fun print_sml_stmt labelled_name syntax_tyco syntax_const reserved is_cons deresolve =
haftmann@28054
    65
  let
haftmann@33992
    66
    fun print_tyco_expr fxy (tyco, []) = (str o deresolve) tyco
haftmann@33992
    67
      | print_tyco_expr fxy (tyco, [ty]) =
haftmann@33992
    68
          concat [print_typ BR ty, (str o deresolve) tyco]
haftmann@33992
    69
      | print_tyco_expr fxy (tyco, tys) =
haftmann@33992
    70
          concat [Pretty.list "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@33992
    71
    and print_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@33992
    72
         of NONE => print_tyco_expr fxy (tyco, tys)
haftmann@33992
    73
          | SOME (i, print) => print print_typ fxy tys)
haftmann@33992
    74
      | print_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@33992
    75
    fun print_dicttyp (class, ty) = print_tyco_expr NOBR (class, [ty]);
haftmann@33992
    76
    fun print_typscheme_prefix (vs, p) = Pretty.enum " ->" "" ""
haftmann@33992
    77
      (map_filter (fn (v, sort) =>
haftmann@33992
    78
        (print_product (fn class => print_dicttyp (class, ITyVar v)) sort)) vs @| p);
haftmann@33992
    79
    fun print_typscheme (vs, ty) = print_typscheme_prefix (vs, print_typ NOBR ty);
haftmann@33992
    80
    fun print_dicttypscheme (vs, class_ty) = print_typscheme_prefix (vs, print_dicttyp class_ty);
haftmann@33992
    81
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
    82
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
    83
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
    84
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
    85
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
    86
          let
haftmann@33992
    87
            val v_p = str (if k = 1 then first_upper v ^ "_"
haftmann@33992
    88
              else first_upper v ^ string_of_int (i+1) ^ "_");
haftmann@33992
    89
          in case classrels
haftmann@33992
    90
           of [] => v_p
haftmann@33992
    91
            | [classrel] => brackets [(str o deresolve) classrel, v_p]
haftmann@33992
    92
            | classrels => brackets
haftmann@33992
    93
                [Pretty.enum " o" "(" ")" (map (str o deresolve) classrels), v_p]
haftmann@33992
    94
          end
haftmann@33992
    95
    and print_dicts is_pseudo_fun = print_tuple (print_dict is_pseudo_fun);
haftmann@33992
    96
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
    97
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@33992
    98
    fun print_term is_pseudo_fun thm vars fxy (IConst c) =
haftmann@33992
    99
          print_app is_pseudo_fun thm vars fxy (c, [])
haftmann@33992
   100
      | print_term is_pseudo_fun thm vars fxy (IVar NONE) =
haftmann@31889
   101
          str "_"
haftmann@33992
   102
      | print_term is_pseudo_fun thm vars fxy (IVar (SOME v)) =
haftmann@32924
   103
          str (lookup_var vars v)
haftmann@33992
   104
      | print_term is_pseudo_fun thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   105
          (case Code_Thingol.unfold_const_app t
haftmann@33992
   106
           of SOME c_ts => print_app is_pseudo_fun thm vars fxy c_ts
haftmann@33992
   107
            | NONE => brackify fxy [print_term is_pseudo_fun thm vars NOBR t1,
haftmann@33992
   108
                print_term is_pseudo_fun thm vars BR t2])
haftmann@33992
   109
      | print_term is_pseudo_fun thm vars fxy (t as _ `|=> _) =
haftmann@28054
   110
          let
haftmann@31874
   111
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33992
   112
            fun print_abs (pat, ty) =
haftmann@33992
   113
              print_bind is_pseudo_fun thm NOBR pat
haftmann@28054
   114
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@33992
   115
            val (ps, vars') = fold_map print_abs binds vars;
haftmann@33992
   116
          in brackets (ps @ [print_term is_pseudo_fun thm vars' NOBR t']) end
haftmann@33992
   117
      | print_term is_pseudo_fun thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
   118
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
   119
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@33992
   120
                then print_case is_pseudo_fun thm vars fxy cases
haftmann@33992
   121
                else print_app is_pseudo_fun thm vars fxy c_ts
haftmann@33992
   122
            | NONE => print_case is_pseudo_fun thm vars fxy cases)
haftmann@33992
   123
    and print_app_expr is_pseudo_fun thm vars (app as ((c, ((_, iss), tys)), ts)) =
haftmann@29175
   124
      if is_cons c then
haftmann@33992
   125
        let val k = length tys in
haftmann@33992
   126
          if k < 2 orelse length ts = k
haftmann@33992
   127
          then (str o deresolve) c
haftmann@33992
   128
            :: the_list (print_tuple (print_term is_pseudo_fun thm vars) BR ts)
haftmann@33992
   129
          else [print_term is_pseudo_fun thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   130
        end
haftmann@33636
   131
      else if is_pseudo_fun c
haftmann@29175
   132
        then (str o deresolve) c @@ str "()"
haftmann@33992
   133
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@33992
   134
        @ map (print_term is_pseudo_fun thm vars BR) ts
haftmann@33992
   135
    and print_app is_pseudo_fun thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@33992
   136
      (print_term is_pseudo_fun) syntax_const thm vars
haftmann@33992
   137
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@33992
   138
    and print_case is_pseudo_fun thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   139
          let
haftmann@29952
   140
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   141
            fun print_match ((pat, ty), t) vars =
haftmann@28054
   142
              vars
haftmann@33992
   143
              |> print_bind is_pseudo_fun thm NOBR pat
haftmann@33992
   144
              |>> (fn p => semicolon [str "val", p, str "=",
haftmann@33992
   145
                    print_term is_pseudo_fun thm vars NOBR t])
haftmann@33992
   146
            val (ps, vars') = fold_map print_match binds vars;
haftmann@28054
   147
          in
haftmann@28054
   148
            Pretty.chunks [
haftmann@33992
   149
              Pretty.block [str ("let"), Pretty.fbrk, Pretty.chunks ps],
haftmann@33992
   150
              Pretty.block [str ("in"), Pretty.fbrk, print_term is_pseudo_fun thm vars' NOBR body],
haftmann@28054
   151
              str ("end")
haftmann@28054
   152
            ]
haftmann@28054
   153
          end
haftmann@33992
   154
      | print_case is_pseudo_fun thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   155
          let
haftmann@33992
   156
            fun print_select delim (pat, body) =
haftmann@28054
   157
              let
haftmann@33992
   158
                val (p, vars') = print_bind is_pseudo_fun thm NOBR pat vars;
haftmann@28054
   159
              in
haftmann@33992
   160
                concat [str delim, p, str "=>", print_term is_pseudo_fun thm vars' NOBR body]
haftmann@28054
   161
              end;
haftmann@28054
   162
          in
haftmann@31665
   163
            brackets (
haftmann@28054
   164
              str "case"
haftmann@33992
   165
              :: print_term is_pseudo_fun thm vars NOBR t
haftmann@33992
   166
              :: print_select "of" clause
haftmann@33992
   167
              :: map (print_select "|") clauses
haftmann@28054
   168
            )
haftmann@28054
   169
          end
haftmann@33992
   170
      | print_case is_pseudo_fun thm vars fxy ((_, []), _) =
haftmann@31121
   171
          (concat o map str) ["raise", "Fail", "\"empty case\""];
haftmann@33992
   172
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   173
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   174
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   175
      let
haftmann@33992
   176
        fun print_co (co, []) = str (deresolve co)
haftmann@33992
   177
          | print_co (co, tys) = concat [str (deresolve co), str "of",
haftmann@33992
   178
              Pretty.enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   179
      in
haftmann@33992
   180
        concat (
haftmann@33992
   181
          str definer
haftmann@33992
   182
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   183
          :: str "="
haftmann@33992
   184
          :: separate (str "|") (map print_co cos)
haftmann@33992
   185
        )
haftmann@33992
   186
      end;
haftmann@33992
   187
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   188
          (ML_Function (name, (vs_ty as (vs, ty), eq :: eqs))) =
haftmann@29189
   189
          let
haftmann@33992
   190
            fun print_eqn definer ((ts, t), (thm, _)) =
haftmann@33636
   191
              let
haftmann@33636
   192
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@33636
   193
                val vars = reserved
haftmann@33636
   194
                  |> intro_base_names
haftmann@33636
   195
                       (is_none o syntax_const) deresolve consts
haftmann@33636
   196
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@33636
   197
                       (insert (op =)) ts []);
haftmann@33636
   198
                val prolog = if needs_typ then
haftmann@33992
   199
                  concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@33636
   200
                    else Pretty.strs [definer, deresolve name];
haftmann@33636
   201
              in
haftmann@33636
   202
                concat (
haftmann@33636
   203
                  prolog
haftmann@33636
   204
                  :: (if is_pseudo_fun name then [str "()"]
haftmann@33992
   205
                      else print_dict_args vs
haftmann@33992
   206
                        @ map (print_term is_pseudo_fun thm vars BR) ts)
haftmann@33636
   207
                  @ str "="
haftmann@33992
   208
                  @@ print_term is_pseudo_fun thm vars NOBR t
haftmann@33636
   209
                )
haftmann@33636
   210
              end
haftmann@33992
   211
            val shift = if null eqs then I else
haftmann@33992
   212
              map (Pretty.block o single o Pretty.block o single);
haftmann@33992
   213
          in pair
haftmann@33992
   214
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   215
            ((Pretty.block o Pretty.fbreaks o shift) (
haftmann@33992
   216
              print_eqn definer eq
haftmann@33992
   217
              :: map (print_eqn "|") eqs
haftmann@33992
   218
            ))
haftmann@29189
   219
          end
haftmann@33992
   220
      | print_def is_pseudo_fun _ definer
haftmann@33992
   221
          (ML_Instance (inst, ((class, (tyco, vs)), (superinsts, classparams)))) =
haftmann@29189
   222
          let
haftmann@33992
   223
            fun print_superinst (_, (classrel, dss)) =
haftmann@33636
   224
              concat [
haftmann@33636
   225
                (str o Long_Name.base_name o deresolve) classrel,
haftmann@33636
   226
                str "=",
haftmann@33992
   227
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   228
              ];
haftmann@33992
   229
            fun print_classparam ((classparam, c_inst), (thm, _)) =
haftmann@33636
   230
              concat [
haftmann@33636
   231
                (str o Long_Name.base_name o deresolve) classparam,
haftmann@33636
   232
                str "=",
haftmann@33992
   233
                print_app (K false) thm reserved NOBR (c_inst, [])
haftmann@33636
   234
              ];
haftmann@33992
   235
          in pair
haftmann@33992
   236
            (print_val_decl print_dicttypscheme
haftmann@33992
   237
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   238
            (concat (
haftmann@33636
   239
              str definer
haftmann@33636
   240
              :: (str o deresolve) inst
haftmann@33636
   241
              :: (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   242
                  else print_dict_args vs)
haftmann@33636
   243
              @ str "="
haftmann@33992
   244
              :: Pretty.list "{" "}"
haftmann@33992
   245
                (map print_superinst superinsts @ map print_classparam classparams)
haftmann@33636
   246
              :: str ":"
haftmann@33992
   247
              @@ print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33992
   248
            ))
haftmann@33636
   249
          end;
haftmann@33992
   250
    fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   251
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   252
          ((semicolon o map str) (
haftmann@33636
   253
            (if n = 0 then "val" else "fun")
haftmann@33636
   254
            :: deresolve name
haftmann@33636
   255
            :: replicate n "_"
haftmann@33636
   256
            @ "="
haftmann@33636
   257
            :: "raise"
haftmann@33636
   258
            :: "Fail"
haftmann@33992
   259
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   260
          ))
haftmann@33992
   261
      | print_stmt (ML_Val binding) =
haftmann@33636
   262
          let
haftmann@33992
   263
            val (sig_p, p) = print_def (K false) true "val" binding
haftmann@33992
   264
          in pair
haftmann@33992
   265
            [sig_p]
haftmann@33992
   266
            (semicolon [p])
haftmann@33992
   267
          end
haftmann@33992
   268
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   269
          let
haftmann@33992
   270
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   271
            fun print_pseudo_fun name = concat [
haftmann@29189
   272
                str "val",
haftmann@29189
   273
                (str o deresolve) name,
haftmann@29189
   274
                str "=",
haftmann@29189
   275
                (str o deresolve) name,
haftmann@29189
   276
                str "();"
haftmann@29189
   277
              ];
haftmann@33992
   278
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   279
              (print_def' "fun" binding :: map (print_def' "and") bindings);
haftmann@33992
   280
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   281
          in pair
haftmann@33992
   282
            sig_ps
haftmann@33992
   283
            (Pretty.chunks (ps @ semicolon [p] :: pseudo_ps))
haftmann@33992
   284
          end
haftmann@33992
   285
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   286
          let
haftmann@33992
   287
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   288
          in
haftmann@33992
   289
            pair
haftmann@33992
   290
            [concat [str "type", ty_p]]
haftmann@33992
   291
            (concat [str "datatype", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   292
          end
haftmann@33992
   293
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   294
          let
haftmann@33992
   295
            val sig_ps = print_datatype_decl "datatype" data
haftmann@33992
   296
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   297
            val (ps, p) = split_last sig_ps;
haftmann@33992
   298
          in pair
haftmann@33992
   299
            sig_ps
haftmann@33992
   300
            (Pretty.chunks (ps @| semicolon [p]))
haftmann@33992
   301
          end
haftmann@33992
   302
     | print_stmt (ML_Class (class, (v, (superclasses, classparams)))) =
haftmann@28054
   303
          let
haftmann@33992
   304
            fun print_field s p = concat [str s, str ":", p];
haftmann@33992
   305
            fun print_proj s p = semicolon
haftmann@33992
   306
              (map str ["val", s, "=", "#" ^ s, ":"] @| p);
haftmann@33992
   307
            fun print_superclass_decl (superclass, classrel) =
haftmann@33992
   308
              print_val_decl print_dicttypscheme
haftmann@33992
   309
                (classrel, ([(v, [class])], (superclass, ITyVar v)));
haftmann@33992
   310
            fun print_superclass_field (superclass, classrel) =
haftmann@33992
   311
              print_field (deresolve classrel) (print_dicttyp (superclass, ITyVar v));
haftmann@33992
   312
            fun print_superclass_proj (superclass, classrel) =
haftmann@33992
   313
              print_proj (deresolve classrel)
haftmann@33992
   314
                (print_dicttypscheme ([(v, [class])], (superclass, ITyVar v)));
haftmann@33992
   315
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   316
              print_val_decl print_typscheme
haftmann@33992
   317
                (classparam, ([(v, [class])], ty));
haftmann@33992
   318
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   319
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@33992
   320
            fun print_classparam_proj (classparam, ty) =
haftmann@33992
   321
              print_proj (deresolve classparam)
haftmann@33992
   322
                (print_typscheme ([(v, [class])], ty));
haftmann@33992
   323
          in pair
haftmann@33992
   324
            (concat [str "type", print_dicttyp (class, ITyVar v)]
haftmann@33992
   325
              :: map print_superclass_decl superclasses
haftmann@33992
   326
              @ map print_classparam_decl classparams)
haftmann@33992
   327
            (Pretty.chunks (
haftmann@28054
   328
              concat [
haftmann@28054
   329
                str ("type '" ^ v),
haftmann@28054
   330
                (str o deresolve) class,
haftmann@28054
   331
                str "=",
haftmann@33992
   332
                Pretty.list "{" "};" (
haftmann@33992
   333
                  map print_superclass_field superclasses
haftmann@33992
   334
                  @ map print_classparam_field classparams
haftmann@28054
   335
                )
haftmann@28054
   336
              ]
haftmann@33992
   337
              :: map print_superclass_proj superclasses
haftmann@33992
   338
              @ map print_classparam_proj classparams
haftmann@33992
   339
            ))
haftmann@28054
   340
          end;
haftmann@33992
   341
  in print_stmt end;
haftmann@28054
   342
haftmann@33992
   343
fun print_sml_module name some_decls body = Pretty.chunks2 (
haftmann@33992
   344
    Pretty.chunks (
haftmann@33992
   345
      str ("structure " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@33992
   346
      :: (the_list o Option.map (Pretty.indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   347
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   348
    )
haftmann@33992
   349
    :: body
haftmann@33992
   350
    @| str ("end; (*struct " ^ name ^ "*)")
haftmann@28054
   351
  );
haftmann@28054
   352
haftmann@28064
   353
val literals_sml = Literals {
haftmann@28064
   354
  literal_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@28064
   355
  literal_string = quote o translate_string ML_Syntax.print_char,
haftmann@28064
   356
  literal_numeral = fn unbounded => fn k =>
haftmann@28064
   357
    if unbounded then "(" ^ string_of_int k ^ " : IntInf.int)"
haftmann@28064
   358
    else string_of_int k,
haftmann@33992
   359
  literal_list = Pretty.list "[" "]",
haftmann@28064
   360
  infix_cons = (7, "::")
haftmann@28064
   361
};
haftmann@28064
   362
haftmann@28054
   363
haftmann@28054
   364
(** OCaml serializer **)
haftmann@28054
   365
haftmann@33992
   366
fun print_ocaml_stmt labelled_name syntax_tyco syntax_const 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@33992
   372
          concat [Pretty.list "(" ")" (map (print_typ BR) tys), (str o deresolve) tyco]
haftmann@33992
   373
    and print_typ fxy (tyco `%% tys) = (case syntax_tyco 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@33992
   378
    fun print_typscheme_prefix (vs, p) = Pretty.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@33992
   383
    fun print_dict is_pseudo_fun fxy (DictConst (inst, dss)) =
haftmann@33992
   384
          brackify fxy ((str o deresolve) inst ::
haftmann@33992
   385
            (if is_pseudo_fun inst then [str "()"]
haftmann@33992
   386
            else map_filter (print_dicts is_pseudo_fun BR) dss))
haftmann@33992
   387
      | print_dict is_pseudo_fun fxy (DictVar (classrels, (v, (i, k)))) =
haftmann@33992
   388
          str (if k = 1 then "_" ^ first_upper v
haftmann@33992
   389
            else "_" ^ first_upper v ^ string_of_int (i+1))
haftmann@33992
   390
          |> fold_rev (fn classrel => fn p =>
haftmann@33992
   391
               Pretty.block [p, str ".", (str o deresolve) classrel]) classrels
haftmann@33992
   392
    and print_dicts is_pseudo_fun = print_tuple (print_dict is_pseudo_fun);
haftmann@33992
   393
    val print_dict_args = map_filter (fn (v, sort) => print_dicts (K false) BR
haftmann@33992
   394
      (map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort));
haftmann@33992
   395
    fun print_term is_pseudo_fun thm vars fxy (IConst c) =
haftmann@33992
   396
          print_app is_pseudo_fun thm vars fxy (c, [])
haftmann@33992
   397
      | print_term is_pseudo_fun thm vars fxy (IVar NONE) =
haftmann@31889
   398
          str "_"
haftmann@33992
   399
      | print_term is_pseudo_fun thm vars fxy (IVar (SOME v)) =
haftmann@32924
   400
          str (lookup_var vars v)
haftmann@33992
   401
      | print_term is_pseudo_fun thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   402
          (case Code_Thingol.unfold_const_app t
haftmann@33992
   403
           of SOME c_ts => print_app is_pseudo_fun thm vars fxy c_ts
haftmann@33992
   404
            | NONE => brackify fxy [print_term is_pseudo_fun thm vars NOBR t1,
haftmann@33992
   405
                print_term is_pseudo_fun thm vars BR t2])
haftmann@33992
   406
      | print_term is_pseudo_fun thm vars fxy (t as _ `|=> _) =
haftmann@28054
   407
          let
haftmann@31874
   408
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@33992
   409
            val (ps, vars') = fold_map (print_bind is_pseudo_fun thm BR o fst) binds vars;
haftmann@33992
   410
          in brackets (str "fun" :: ps @ str "->" @@ print_term is_pseudo_fun thm vars' NOBR t') end
haftmann@33992
   411
      | print_term is_pseudo_fun thm vars fxy (ICase (cases as (_, t0))) =
haftmann@33992
   412
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
   413
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@33992
   414
                then print_case is_pseudo_fun thm vars fxy cases
haftmann@33992
   415
                else print_app is_pseudo_fun thm vars fxy c_ts
haftmann@33992
   416
            | NONE => print_case is_pseudo_fun thm vars fxy cases)
haftmann@33992
   417
    and print_app_expr is_pseudo_fun thm vars (app as ((c, ((_, iss), tys)), ts)) =
haftmann@28054
   418
      if is_cons c then
haftmann@33992
   419
        let val k = length tys in
haftmann@33992
   420
          if length ts = k
haftmann@33992
   421
          then (str o deresolve) c
haftmann@33992
   422
            :: the_list (print_tuple (print_term is_pseudo_fun thm vars) BR ts)
haftmann@33992
   423
          else [print_term is_pseudo_fun thm vars BR (Code_Thingol.eta_expand k app)]
haftmann@33992
   424
        end
haftmann@33636
   425
      else if is_pseudo_fun c
haftmann@29175
   426
        then (str o deresolve) c @@ str "()"
haftmann@33992
   427
      else (str o deresolve) c :: map_filter (print_dicts is_pseudo_fun BR) iss
haftmann@33992
   428
        @ map (print_term is_pseudo_fun thm vars BR) ts
haftmann@33992
   429
    and print_app is_pseudo_fun thm vars = gen_print_app (print_app_expr is_pseudo_fun)
haftmann@33992
   430
      (print_term is_pseudo_fun) syntax_const thm vars
haftmann@33992
   431
    and print_bind is_pseudo_fun = gen_print_bind (print_term is_pseudo_fun)
haftmann@33992
   432
    and print_case is_pseudo_fun thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   433
          let
haftmann@29952
   434
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@33992
   435
            fun print_let ((pat, ty), t) vars =
haftmann@28054
   436
              vars
haftmann@33992
   437
              |> print_bind is_pseudo_fun thm NOBR pat
haftmann@28054
   438
              |>> (fn p => concat
haftmann@33992
   439
                  [str "let", p, str "=", print_term is_pseudo_fun thm vars NOBR t, str "in"])
haftmann@33992
   440
            val (ps, vars') = fold_map print_let binds vars;
haftmann@31665
   441
          in
haftmann@31665
   442
            brackify_block fxy (Pretty.chunks ps) []
haftmann@33992
   443
              (print_term is_pseudo_fun thm vars' NOBR body)
haftmann@31665
   444
          end
haftmann@33992
   445
      | print_case is_pseudo_fun thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   446
          let
haftmann@33992
   447
            fun print_select delim (pat, body) =
haftmann@28054
   448
              let
haftmann@33992
   449
                val (p, vars') = print_bind is_pseudo_fun thm NOBR pat vars;
haftmann@33992
   450
              in concat [str delim, p, str "->", print_term is_pseudo_fun thm vars' NOBR body] end;
haftmann@28054
   451
          in
haftmann@31665
   452
            brackets (
haftmann@28054
   453
              str "match"
haftmann@33992
   454
              :: print_term is_pseudo_fun thm vars NOBR t
haftmann@33992
   455
              :: print_select "with" clause
haftmann@33992
   456
              :: map (print_select "|") clauses
haftmann@28054
   457
            )
haftmann@28054
   458
          end
haftmann@33992
   459
      | print_case is_pseudo_fun thm vars fxy ((_, []), _) =
haftmann@31121
   460
          (concat o map str) ["failwith", "\"empty case\""];
haftmann@33992
   461
    fun print_val_decl print_typscheme (name, typscheme) = concat
haftmann@33992
   462
      [str "val", str (deresolve name), str ":", print_typscheme typscheme];
haftmann@33992
   463
    fun print_datatype_decl definer (tyco, (vs, cos)) =
haftmann@33992
   464
      let
haftmann@33992
   465
        fun print_co (co, []) = str (deresolve co)
haftmann@33992
   466
          | print_co (co, tys) = concat [str (deresolve co), str "of",
haftmann@33992
   467
              Pretty.enum " *" "" "" (map (print_typ (INFX (2, X))) tys)];
haftmann@33992
   468
      in
haftmann@33992
   469
        concat (
haftmann@33992
   470
          str definer
haftmann@33992
   471
          :: print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@33992
   472
          :: str "="
haftmann@33992
   473
          :: separate (str "|") (map print_co cos)
haftmann@33992
   474
        )
haftmann@33992
   475
      end;
haftmann@33992
   476
    fun print_def is_pseudo_fun needs_typ definer
haftmann@33992
   477
          (ML_Function (name, (vs_ty as (vs, ty), eqs))) =
haftmann@28054
   478
          let
haftmann@33992
   479
            fun print_eqn ((ts, t), (thm, _)) =
haftmann@28054
   480
              let
haftmann@32913
   481
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   482
                val vars = reserved
haftmann@32924
   483
                  |> intro_base_names
haftmann@32913
   484
                      (is_none o syntax_const) deresolve consts
haftmann@32924
   485
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   486
                      (insert (op =)) ts []);
haftmann@28054
   487
              in concat [
haftmann@29189
   488
                (Pretty.block o Pretty.commas)
haftmann@33992
   489
                  (map (print_term is_pseudo_fun thm vars NOBR) ts),
haftmann@28054
   490
                str "->",
haftmann@33992
   491
                print_term is_pseudo_fun thm vars NOBR t
haftmann@28054
   492
              ] end;
haftmann@33992
   493
            fun print_eqns is_pseudo [((ts, t), (thm, _))] =
haftmann@28054
   494
                  let
haftmann@32913
   495
                    val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   496
                    val vars = reserved
haftmann@32924
   497
                      |> intro_base_names
haftmann@32913
   498
                          (is_none o syntax_const) deresolve consts
haftmann@32924
   499
                      |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@28054
   500
                          (insert (op =)) ts []);
haftmann@28054
   501
                  in
haftmann@28054
   502
                    concat (
haftmann@29189
   503
                      (if is_pseudo then [str "()"]
haftmann@33992
   504
                        else map (print_term is_pseudo_fun thm vars BR) ts)
haftmann@28054
   505
                      @ str "="
haftmann@33992
   506
                      @@ print_term is_pseudo_fun thm vars NOBR t
haftmann@28054
   507
                    )
haftmann@28054
   508
                  end
haftmann@33992
   509
              | print_eqns _ ((eq as (([_], _), _)) :: eqs) =
haftmann@28054
   510
                  Pretty.block (
haftmann@28054
   511
                    str "="
haftmann@28054
   512
                    :: Pretty.brk 1
haftmann@28054
   513
                    :: str "function"
haftmann@28054
   514
                    :: Pretty.brk 1
haftmann@33992
   515
                    :: print_eqn eq
haftmann@28054
   516
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   517
                          o single o print_eqn) eqs
haftmann@28054
   518
                  )
haftmann@33992
   519
              | print_eqns _ (eqs as eq :: eqs') =
haftmann@28054
   520
                  let
haftmann@32913
   521
                    val consts = fold Code_Thingol.add_constnames (map (snd o fst) eqs) [];
haftmann@32924
   522
                    val vars = reserved
haftmann@32924
   523
                      |> intro_base_names
haftmann@32926
   524
                          (is_none o syntax_const) deresolve consts;
haftmann@32924
   525
                    val dummy_parms = (map str o aux_params vars o map (fst o fst)) eqs;
haftmann@28054
   526
                  in
haftmann@28054
   527
                    Pretty.block (
haftmann@28054
   528
                      Pretty.breaks dummy_parms
haftmann@28054
   529
                      @ Pretty.brk 1
haftmann@28054
   530
                      :: str "="
haftmann@28054
   531
                      :: Pretty.brk 1
haftmann@28054
   532
                      :: str "match"
haftmann@28054
   533
                      :: Pretty.brk 1
haftmann@28054
   534
                      :: (Pretty.block o Pretty.commas) dummy_parms
haftmann@28054
   535
                      :: Pretty.brk 1
haftmann@28054
   536
                      :: str "with"
haftmann@28054
   537
                      :: Pretty.brk 1
haftmann@33992
   538
                      :: print_eqn eq
haftmann@28054
   539
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@33992
   540
                           o single o print_eqn) eqs'
haftmann@28054
   541
                    )
haftmann@28054
   542
                  end;
haftmann@33636
   543
            val prolog = if needs_typ then
haftmann@33992
   544
              concat [str definer, (str o deresolve) name, str ":", print_typ NOBR ty]
haftmann@33636
   545
                else Pretty.strs [definer, deresolve name];
haftmann@33992
   546
          in pair
haftmann@33992
   547
            (print_val_decl print_typscheme (name, vs_ty))
haftmann@33992
   548
            (concat (
haftmann@33636
   549
              prolog
haftmann@33992
   550
              :: print_dict_args vs
haftmann@33992
   551
              @| print_eqns (is_pseudo_fun name) eqs
haftmann@33992
   552
            ))
haftmann@33636
   553
          end
haftmann@33992
   554
      | print_def is_pseudo_fun _ definer (ML_Instance (inst, ((class, (tyco, vs)), (superinsts, classparams)))) =
haftmann@33636
   555
          let
haftmann@33992
   556
            fun print_superinst (_, (classrel, dss)) =
haftmann@33636
   557
              concat [
haftmann@33636
   558
                (str o deresolve) classrel,
haftmann@33636
   559
                str "=",
haftmann@33992
   560
                print_dict is_pseudo_fun NOBR (DictConst dss)
haftmann@33636
   561
              ];
haftmann@33992
   562
            fun print_classparam ((classparam, c_inst), (thm, _)) =
haftmann@33636
   563
              concat [
haftmann@33636
   564
                (str o deresolve) classparam,
haftmann@33636
   565
                str "=",
haftmann@33992
   566
                print_app (K false) thm reserved NOBR (c_inst, [])
haftmann@33636
   567
              ];
haftmann@33992
   568
          in pair
haftmann@33992
   569
            (print_val_decl print_dicttypscheme
haftmann@33992
   570
              (inst, (vs, (class, tyco `%% map (ITyVar o fst) vs))))
haftmann@33992
   571
            (concat (
haftmann@33636
   572
              str definer
haftmann@33636
   573
              :: (str o deresolve) inst
haftmann@33992
   574
              :: print_dict_args vs
haftmann@33636
   575
              @ str "="
haftmann@33636
   576
              @@ brackets [
haftmann@33992
   577
                enum_default "()" ";" "{" "}" (map print_superinst superinsts
haftmann@33992
   578
                  @ map print_classparam classparams),
haftmann@33636
   579
                str ":",
haftmann@33992
   580
                print_tyco_expr NOBR (class, [tyco `%% map (ITyVar o fst) vs])
haftmann@33636
   581
              ]
haftmann@33992
   582
            ))
haftmann@33636
   583
          end;
haftmann@33992
   584
     fun print_stmt (ML_Exc (name, (vs_ty, n))) = pair
haftmann@33992
   585
          [print_val_decl print_typscheme (name, vs_ty)]
haftmann@33992
   586
          ((doublesemicolon o map str) (
haftmann@33636
   587
            "let"
haftmann@33636
   588
            :: deresolve name
haftmann@33636
   589
            :: replicate n "_"
haftmann@33636
   590
            @ "="
haftmann@33636
   591
            :: "failwith"
haftmann@33992
   592
            @@ (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name
haftmann@33992
   593
          ))
haftmann@33992
   594
      | print_stmt (ML_Val binding) =
haftmann@33636
   595
          let
haftmann@33992
   596
            val (sig_p, p) = print_def (K false) true "let" binding
haftmann@33992
   597
          in pair
haftmann@33992
   598
            [sig_p]
haftmann@33992
   599
            (doublesemicolon [p])
haftmann@33992
   600
          end
haftmann@33992
   601
      | print_stmt (ML_Funs (binding :: bindings, pseudo_funs)) =
haftmann@33992
   602
          let
haftmann@33992
   603
            val print_def' = print_def (member (op =) pseudo_funs) false;
haftmann@33992
   604
            fun print_pseudo_fun name = concat [
haftmann@29189
   605
                str "let",
haftmann@29189
   606
                (str o deresolve) name,
haftmann@29189
   607
                str "=",
haftmann@29189
   608
                (str o deresolve) name,
haftmann@29189
   609
                str "();;"
haftmann@29189
   610
              ];
haftmann@33992
   611
            val (sig_ps, (ps, p)) = (apsnd split_last o split_list)
haftmann@33992
   612
              (print_def' "let rec" binding :: map (print_def' "and") bindings);
haftmann@33992
   613
            val pseudo_ps = map print_pseudo_fun pseudo_funs;
haftmann@33992
   614
          in pair
haftmann@33992
   615
            sig_ps
haftmann@33992
   616
            (Pretty.chunks (ps @ doublesemicolon [p] :: pseudo_ps))
haftmann@33992
   617
          end
haftmann@33992
   618
     | print_stmt (ML_Datas [(tyco, (vs, []))]) =
haftmann@33992
   619
          let
haftmann@33992
   620
            val ty_p = print_tyco_expr NOBR (tyco, map (ITyVar o fst) vs);
haftmann@33992
   621
          in
haftmann@33992
   622
            pair
haftmann@33992
   623
            [concat [str "type", ty_p]]
haftmann@33992
   624
            (concat [str "type", ty_p, str "=", str "EMPTY__"])
haftmann@33992
   625
          end
haftmann@33992
   626
     | print_stmt (ML_Datas (data :: datas)) = 
haftmann@28054
   627
          let
haftmann@33992
   628
            val sig_ps = print_datatype_decl "type" data
haftmann@33992
   629
              :: map (print_datatype_decl "and") datas;
haftmann@33992
   630
            val (ps, p) = split_last sig_ps;
haftmann@33992
   631
          in pair
haftmann@33992
   632
            sig_ps
haftmann@33992
   633
            (Pretty.chunks (ps @| doublesemicolon [p]))
haftmann@33992
   634
          end
haftmann@33992
   635
     | print_stmt (ML_Class (class, (v, (superclasses, classparams)))) =
haftmann@28054
   636
          let
haftmann@33992
   637
            fun print_field s p = concat [str s, str ":", p];
haftmann@33992
   638
            fun print_superclass_field (superclass, classrel) =
haftmann@33992
   639
              print_field (deresolve classrel) (print_dicttyp (superclass, ITyVar v));
haftmann@33992
   640
            fun print_classparam_decl (classparam, ty) =
haftmann@33992
   641
              print_val_decl print_typscheme
haftmann@33992
   642
                (classparam, ([(v, [class])], ty));
haftmann@33992
   643
            fun print_classparam_field (classparam, ty) =
haftmann@33992
   644
              print_field (deresolve classparam) (print_typ NOBR ty);
haftmann@32924
   645
            val w = "_" ^ first_upper v;
haftmann@33992
   646
            fun print_classparam_proj (classparam, _) =
haftmann@33992
   647
              (concat o map str) ["let", deresolve classparam, w, "=",
haftmann@33992
   648
                w ^ "." ^ deresolve classparam ^ ";;"];
haftmann@33992
   649
            val type_decl_p = concat [
haftmann@33992
   650
                str ("type '" ^ v),
haftmann@33992
   651
                (str o deresolve) class,
haftmann@28054
   652
                str "=",
haftmann@33992
   653
                enum_default "unit" ";" "{" "}" (
haftmann@33992
   654
                  map print_superclass_field superclasses
haftmann@33992
   655
                  @ map print_classparam_field classparams
haftmann@33992
   656
                )
haftmann@28054
   657
              ];
haftmann@33992
   658
          in pair
haftmann@33992
   659
            (type_decl_p :: map print_classparam_decl classparams)
haftmann@33992
   660
            (Pretty.chunks (
haftmann@33992
   661
              doublesemicolon [type_decl_p]
haftmann@33992
   662
              :: map print_classparam_proj classparams
haftmann@33992
   663
            ))
haftmann@33992
   664
          end;
haftmann@33992
   665
  in print_stmt end;
haftmann@28054
   666
haftmann@33992
   667
fun print_ocaml_module name some_decls body = Pretty.chunks2 (
haftmann@33992
   668
    Pretty.chunks (
haftmann@33992
   669
      str ("module " ^ name ^ (if is_some some_decls then " : sig" else " ="))
haftmann@33992
   670
      :: (the_list o Option.map (Pretty.indent 2 o Pretty.chunks)) some_decls
haftmann@33992
   671
      @| (if is_some some_decls then str "end = struct" else str "struct")
haftmann@33992
   672
    )
haftmann@33992
   673
    :: body
haftmann@33992
   674
    @| str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   675
  );
haftmann@28054
   676
haftmann@28064
   677
val literals_ocaml = let
haftmann@28064
   678
  fun chr i =
haftmann@28064
   679
    let
haftmann@28064
   680
      val xs = string_of_int i;
haftmann@28064
   681
      val ys = replicate_string (3 - length (explode xs)) "0";
haftmann@28064
   682
    in "\\" ^ ys ^ xs end;
haftmann@28064
   683
  fun char_ocaml c =
haftmann@28064
   684
    let
haftmann@28064
   685
      val i = ord c;
haftmann@28064
   686
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   687
        then chr i else c
haftmann@28064
   688
    in s end;
haftmann@31377
   689
  fun bignum_ocaml k = if k <= 1073741823
haftmann@31377
   690
    then "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@31377
   691
    else "(Big_int.big_int_of_string " ^ quote (string_of_int k) ^ ")"
haftmann@28064
   692
in Literals {
haftmann@28064
   693
  literal_char = enclose "'" "'" o char_ocaml,
haftmann@28064
   694
  literal_string = quote o translate_string char_ocaml,
haftmann@28064
   695
  literal_numeral = fn unbounded => fn k => if k >= 0 then
haftmann@31377
   696
      if unbounded then bignum_ocaml k
haftmann@28064
   697
      else string_of_int k
haftmann@28064
   698
    else
haftmann@31377
   699
      if unbounded then "(Big_int.minus_big_int " ^ bignum_ocaml (~ k) ^ ")"
haftmann@28064
   700
      else (enclose "(" ")" o prefix "-" o string_of_int o op ~) k,
haftmann@28064
   701
  literal_list = Pretty.enum ";" "[" "]",
haftmann@28064
   702
  infix_cons = (6, "::")
haftmann@28064
   703
} end;
haftmann@28064
   704
haftmann@28064
   705
haftmann@28054
   706
haftmann@28054
   707
(** SML/OCaml generic part **)
haftmann@28054
   708
haftmann@28054
   709
local
haftmann@28054
   710
haftmann@28054
   711
datatype ml_node =
haftmann@28054
   712
    Dummy of string
haftmann@28054
   713
  | Stmt of string * ml_stmt
haftmann@28054
   714
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   715
haftmann@28054
   716
in
haftmann@28054
   717
haftmann@32924
   718
fun ml_node_of_program labelled_name module_name reserved raw_module_alias program =
haftmann@28054
   719
  let
haftmann@28054
   720
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@32924
   721
    val reserved = Name.make_context reserved;
haftmann@32924
   722
    val empty_module = ((reserved, reserved), Graph.empty);
haftmann@28054
   723
    fun map_node [] f = f
haftmann@28054
   724
      | map_node (m::ms) f =
haftmann@28054
   725
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   726
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   727
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   728
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   729
          let
haftmann@28054
   730
            val (x, nsp') = f nsp
haftmann@28054
   731
          in (x, (nsp', nodes)) end
haftmann@28054
   732
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   733
          let
haftmann@28054
   734
            val (x, nodes') =
haftmann@28054
   735
              nodes
haftmann@28054
   736
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   737
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   738
                  let
haftmann@28054
   739
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   740
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   741
          in (x, (nsp, nodes')) end;
haftmann@28054
   742
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   743
      let
haftmann@28054
   744
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   745
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   746
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   747
      let
haftmann@28054
   748
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   749
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@32924
   750
    val mk_name_module = mk_name_module reserved NONE module_alias program;
haftmann@28054
   751
    fun mk_name_stmt upper name nsp =
haftmann@28054
   752
      let
haftmann@32924
   753
        val (_, base) = dest_name name;
haftmann@32924
   754
        val base' = if upper then first_upper base else base;
haftmann@28054
   755
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   756
      in (base'', nsp') end;
haftmann@33636
   757
    fun ml_binding_of_stmt (name, Code_Thingol.Fun (_, (tysm as (vs, ty), raw_eqs))) =
haftmann@33636
   758
          let
haftmann@33636
   759
            val eqs = filter (snd o snd) raw_eqs;
haftmann@33636
   760
            val (eqs', is_value) = if null (filter_out (null o snd) vs) then case eqs
haftmann@33636
   761
               of [(([], t), thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@33636
   762
                  then ([(([IVar (SOME "x")], t `$ IVar (SOME "x")), thm)], NONE)
haftmann@33636
   763
                  else (eqs, SOME (name, member (op =) (Code_Thingol.add_constnames t []) name))
haftmann@33636
   764
                | _ => (eqs, NONE)
haftmann@33636
   765
              else (eqs, NONE)
haftmann@33636
   766
          in (ML_Function (name, (tysm, eqs')), is_value) end
haftmann@33992
   767
      | ml_binding_of_stmt (name, Code_Thingol.Classinst (stmt as ((_, (_, vs)), _))) =
haftmann@33992
   768
          (ML_Instance (name, stmt), if forall (null o snd) vs then SOME (name, false) else NONE)
haftmann@33636
   769
      | ml_binding_of_stmt (name, _) =
haftmann@33636
   770
          error ("Binding block containing illegal statement: " ^ labelled_name name)
haftmann@33636
   771
    fun add_fun (name, stmt) =
haftmann@29189
   772
      let
haftmann@33636
   773
        val (binding, some_value_name) = ml_binding_of_stmt (name, stmt);
haftmann@33636
   774
        val ml_stmt = case binding
haftmann@33636
   775
         of ML_Function (name, ((vs, ty), [])) =>
haftmann@33992
   776
              ML_Exc (name, ((vs, ty),
haftmann@33992
   777
                (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty))
haftmann@33636
   778
          | _ => case some_value_name
haftmann@33636
   779
             of NONE => ML_Funs ([binding], [])
haftmann@33636
   780
              | SOME (name, true) => ML_Funs ([binding], [name])
haftmann@33636
   781
              | SOME (name, false) => ML_Val binding
haftmann@33636
   782
      in
haftmann@33636
   783
        map_nsp_fun_yield (mk_name_stmt false name)
haftmann@33636
   784
        #>> (fn name' => ([name'], ml_stmt))
haftmann@33636
   785
      end;
haftmann@33636
   786
    fun add_funs stmts =
haftmann@33636
   787
      let
haftmann@33636
   788
        val ml_stmt = ML_Funs (map_split ml_binding_of_stmt stmts |> (apsnd o map_filter o Option.map) fst);
haftmann@33636
   789
      in
haftmann@33636
   790
        fold_map (fn (name, _) => map_nsp_fun_yield (mk_name_stmt false name)) stmts
haftmann@33636
   791
        #>> rpair ml_stmt
haftmann@33636
   792
      end;
haftmann@28054
   793
    fun add_datatypes stmts =
haftmann@28054
   794
      fold_map
haftmann@28663
   795
        (fn (name, Code_Thingol.Datatype (_, stmt)) =>
haftmann@28054
   796
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   797
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   798
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   799
          | (name, _) =>
haftmann@28054
   800
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   801
        ) stmts
haftmann@28054
   802
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   803
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@28054
   804
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@33636
   805
             | stmts => ML_Datas stmts)));
haftmann@28054
   806
    fun add_class stmts =
haftmann@28054
   807
      fold_map
haftmann@28663
   808
        (fn (name, Code_Thingol.Class (_, stmt)) =>
haftmann@28663
   809
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   810
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   811
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   812
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   813
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   814
          | (name, _) =>
haftmann@28054
   815
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   816
        ) stmts
haftmann@28054
   817
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   818
        #> (fn [] => error ("Class block without class statement: "
haftmann@28054
   819
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@33636
   820
             | [stmt] => ML_Class stmt)));
haftmann@33636
   821
    fun add_stmts ([stmt as (name, Code_Thingol.Fun _)]) =
haftmann@33636
   822
          add_fun stmt
haftmann@33636
   823
      | add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   824
          add_funs stmts
haftmann@28054
   825
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   826
          add_datatypes stmts
haftmann@28054
   827
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   828
          add_datatypes stmts
haftmann@28054
   829
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   830
          add_class stmts
haftmann@28054
   831
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   832
          add_class stmts
haftmann@28054
   833
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   834
          add_class stmts
haftmann@33636
   835
      | add_stmts ([stmt as (_, Code_Thingol.Classinst _)]) =
haftmann@33636
   836
          add_fun stmt
haftmann@33636
   837
      | add_stmts ((stmts as (_, Code_Thingol.Classinst _)::_)) =
haftmann@33636
   838
          add_funs stmts
haftmann@28054
   839
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@28054
   840
          (commas o map (labelled_name o fst)) stmts);
haftmann@28054
   841
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   842
      let
haftmann@28054
   843
        val names as (name :: names') = map fst stmts;
haftmann@28054
   844
        val deps =
haftmann@28054
   845
          []
haftmann@28054
   846
          |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@28054
   847
          |> subtract (op =) names;
haftmann@32924
   848
        val (module_names, _) = (split_list o map dest_name) names;
haftmann@28054
   849
        val module_name = (the_single o distinct (op =) o map mk_name_module) module_names
haftmann@28054
   850
          handle Empty =>
haftmann@28054
   851
            error ("Different namespace prefixes for mutual dependencies:\n"
haftmann@28054
   852
              ^ commas (map labelled_name names)
haftmann@28054
   853
              ^ "\n"
haftmann@28054
   854
              ^ commas module_names);
wenzelm@30364
   855
        val module_name_path = Long_Name.explode module_name;
haftmann@28054
   856
        fun add_dep name name' =
haftmann@28054
   857
          let
haftmann@32924
   858
            val module_name' = (mk_name_module o fst o dest_name) name';
haftmann@28054
   859
          in if module_name = module_name' then
haftmann@28054
   860
            map_node module_name_path (Graph.add_edge (name, name'))
haftmann@28054
   861
          else let
haftmann@28705
   862
            val (common, (diff1 :: _, diff2 :: _)) = chop_prefix (op =)
wenzelm@30364
   863
              (module_name_path, Long_Name.explode module_name');
haftmann@28054
   864
          in
haftmann@28054
   865
            map_node common
haftmann@28054
   866
              (fn node => Graph.add_edge_acyclic (diff1, diff2) node
haftmann@28054
   867
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@28054
   868
                  ^ quote name ^ " -> " ^ quote name'
haftmann@28054
   869
                  ^ " would result in module dependency cycle"))
haftmann@28054
   870
          end end;
haftmann@28054
   871
      in
haftmann@28054
   872
        nsp_nodes
haftmann@28054
   873
        |> map_nsp_yield module_name_path (add_stmts stmts)
haftmann@28054
   874
        |-> (fn (base' :: bases', stmt') =>
haftmann@28054
   875
           apsnd (map_node module_name_path (Graph.new_node (name, (Stmt (base', stmt')))
haftmann@28054
   876
              #> fold2 (fn name' => fn base' =>
haftmann@28054
   877
                   Graph.new_node (name', (Dummy base'))) names' bases')))
haftmann@28054
   878
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@28054
   879
        |> apsnd (fold_product (curry (map_node module_name_path o Graph.add_edge)) names names)
haftmann@28054
   880
      end;
haftmann@28054
   881
    val (_, nodes) = empty_module
haftmann@28054
   882
      |> fold add_stmts' (map (AList.make (Graph.get_node program))
haftmann@28054
   883
          (rev (Graph.strong_conn program)));
haftmann@28054
   884
    fun deresolver prefix name = 
haftmann@28054
   885
      let
haftmann@32924
   886
        val module_name = (fst o dest_name) name;
wenzelm@30364
   887
        val module_name' = (Long_Name.explode o mk_name_module) module_name;
haftmann@28054
   888
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, module_name');
haftmann@28054
   889
        val stmt_name =
haftmann@28054
   890
          nodes
haftmann@28054
   891
          |> fold (fn name => fn node => case Graph.get_node node name
haftmann@28054
   892
              of Module (_, (_, node)) => node) module_name'
haftmann@28054
   893
          |> (fn node => case Graph.get_node node name of Stmt (stmt_name, _) => stmt_name
haftmann@28054
   894
               | Dummy stmt_name => stmt_name);
haftmann@28054
   895
      in
wenzelm@30364
   896
        Long_Name.implode (remainder @ [stmt_name])
haftmann@28054
   897
      end handle Graph.UNDEF _ =>
haftmann@28054
   898
        error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   899
  in (deresolver, nodes) end;
haftmann@28054
   900
haftmann@33992
   901
fun serialize_ml target compile print_module print_stmt raw_module_name with_signatures labelled_name
haftmann@33992
   902
  reserved includes raw_module_alias _ syntax_tyco syntax_const program stmt_names destination =
haftmann@28054
   903
  let
haftmann@28054
   904
    val is_cons = Code_Thingol.is_cons program;
haftmann@33992
   905
    val presentation_stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@33992
   906
    val is_presentation = not (null presentation_stmt_names);
haftmann@33992
   907
    val module_name = if is_presentation then SOME "Code" else raw_module_name;
haftmann@28054
   908
    val (deresolver, nodes) = ml_node_of_program labelled_name module_name
haftmann@32924
   909
      reserved raw_module_alias program;
haftmann@32924
   910
    val reserved = make_vars reserved;
haftmann@33992
   911
    fun print_node prefix (Dummy _) =
haftmann@28054
   912
          NONE
haftmann@33992
   913
      | print_node prefix (Stmt (_, stmt)) = if is_presentation andalso
haftmann@33992
   914
          (null o filter (member (op =) presentation_stmt_names) o stmt_names_of) stmt
haftmann@30962
   915
          then NONE
haftmann@33992
   916
          else SOME (print_stmt labelled_name syntax_tyco syntax_const reserved is_cons (deresolver prefix) stmt)
haftmann@33992
   917
      | print_node prefix (Module (module_name, (_, nodes))) =
haftmann@33992
   918
          let
haftmann@33992
   919
            val (decls, body) = print_nodes (prefix @ [module_name]) nodes;
haftmann@33992
   920
            val p = if is_presentation then Pretty.chunks2 body
haftmann@33992
   921
              else print_module module_name (if with_signatures then SOME decls else NONE) body;
haftmann@33992
   922
          in SOME ([], p) end
haftmann@33992
   923
    and print_nodes prefix nodes = (map_filter (print_node prefix o Graph.get_node nodes)
haftmann@33992
   924
        o rev o flat o Graph.strong_conn) nodes
haftmann@33992
   925
      |> split_list
haftmann@33992
   926
      |> (fn (decls, body) => (flat decls, body))
haftmann@30962
   927
    val stmt_names' = (map o try)
haftmann@30962
   928
      (deresolver (if is_some module_name then the_list module_name else [])) stmt_names;
haftmann@33992
   929
    val p = Pretty.chunks2 (map snd includes @ snd (print_nodes [] nodes));
haftmann@28054
   930
  in
haftmann@28054
   931
    Code_Target.mk_serialization target
haftmann@28054
   932
      (case compile of SOME compile => SOME (compile o Code_Target.code_of_pretty) | NONE => NONE)
haftmann@28054
   933
      (fn NONE => Code_Target.code_writeln | SOME file => File.write file o Code_Target.code_of_pretty)
haftmann@30962
   934
      (rpair stmt_names' o Code_Target.code_of_pretty) p destination
haftmann@28054
   935
  end;
haftmann@28054
   936
haftmann@28054
   937
end; (*local*)
haftmann@28054
   938
haftmann@28054
   939
haftmann@28054
   940
(** ML (system language) code for evaluation and instrumentalization **)
haftmann@28054
   941
haftmann@33992
   942
val eval_struct_name = "Code"
haftmann@33992
   943
haftmann@33992
   944
fun eval_code_of some_target with_struct thy =
haftmann@33992
   945
  let
haftmann@33992
   946
    val target = the_default target_Eval some_target;
haftmann@33992
   947
    val serialize = if with_struct then fn _ => fn [] =>
haftmann@33992
   948
        serialize_ml target_SML (SOME (K ())) print_sml_module print_sml_stmt (SOME eval_struct_name) true
haftmann@33992
   949
      else fn _ => fn [] => 
haftmann@33992
   950
        serialize_ml target_SML (SOME (K ())) ((K o K) Pretty.chunks2) print_sml_stmt (SOME eval_struct_name) true;
haftmann@33992
   951
  in Code_Target.serialize_custom thy (target, (serialize, literals_sml)) end;
haftmann@28054
   952
haftmann@28054
   953
haftmann@28054
   954
(* evaluation *)
haftmann@28054
   955
haftmann@30970
   956
fun eval some_target reff postproc thy t args =
haftmann@28054
   957
  let
wenzelm@28275
   958
    val ctxt = ProofContext.init thy;
haftmann@31063
   959
    fun evaluator naming program ((_, (_, ty)), t) deps =
haftmann@28054
   960
      let
haftmann@28054
   961
        val _ = if Code_Thingol.contains_dictvar t then
haftmann@28724
   962
          error "Term to be evaluated contains free dictionaries" else ();
haftmann@28663
   963
        val value_name = "Value.VALUE.value"
haftmann@28054
   964
        val program' = program
haftmann@28663
   965
          |> Graph.new_node (value_name,
haftmann@28663
   966
              Code_Thingol.Fun (Term.dummy_patternN, (([], ty), [(([], t), (Drule.dummy_thm, true))])))
haftmann@28663
   967
          |> fold (curry Graph.add_edge value_name) deps;
haftmann@33992
   968
        val (value_code, [SOME value_name']) = eval_code_of some_target false thy naming program' [value_name];
haftmann@28054
   969
        val sml_code = "let\n" ^ value_code ^ "\nin " ^ value_name'
haftmann@28054
   970
          ^ space_implode " " (map (enclose "(" ")") args) ^ " end";
wenzelm@30672
   971
      in ML_Context.evaluate ctxt false reff sml_code end;
haftmann@32123
   972
  in Code_Thingol.eval thy postproc evaluator t end;
haftmann@28054
   973
haftmann@28054
   974
haftmann@28054
   975
(* instrumentalization by antiquotation *)
haftmann@28054
   976
haftmann@28054
   977
local
haftmann@28054
   978
wenzelm@33519
   979
structure CodeAntiqData = Proof_Data
haftmann@28054
   980
(
haftmann@30962
   981
  type T = (string list * string list) * (bool * (string
haftmann@30962
   982
    * (string * ((string * string) list * (string * string) list)) lazy));
haftmann@30962
   983
  fun init _ = (([], []), (true, ("", Lazy.value ("", ([], [])))));
haftmann@28054
   984
);
haftmann@28054
   985
haftmann@28054
   986
val is_first_occ = fst o snd o CodeAntiqData.get;
haftmann@28054
   987
haftmann@30962
   988
fun delayed_code thy tycos consts () =
haftmann@28054
   989
  let
haftmann@28663
   990
    val (consts', (naming, program)) = Code_Thingol.consts_program thy consts;
haftmann@30962
   991
    val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
haftmann@33992
   992
    val (ml_code, target_names) = eval_code_of NONE true thy naming program (consts' @ tycos');
haftmann@30962
   993
    val (consts'', tycos'') = chop (length consts') target_names;
haftmann@30962
   994
    val consts_map = map2 (fn const => fn NONE =>
haftmann@31156
   995
        error ("Constant " ^ (quote o Code.string_of_const thy) const
haftmann@30962
   996
          ^ "\nhas a user-defined serialization")
haftmann@30962
   997
      | SOME const'' => (const, const'')) consts consts''
haftmann@30962
   998
    val tycos_map = map2 (fn tyco => fn NONE =>
haftmann@30962
   999
        error ("Type " ^ (quote o Sign.extern_type thy) tyco
haftmann@30962
  1000
          ^ "\nhas a user-defined serialization")
haftmann@30962
  1001
      | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
haftmann@30962
  1002
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
  1003
haftmann@30962
  1004
fun register_code new_tycos new_consts ctxt =
haftmann@28054
  1005
  let
haftmann@30962
  1006
    val ((tycos, consts), (_, (struct_name, _))) = CodeAntiqData.get ctxt;
haftmann@30962
  1007
    val tycos' = fold (insert (op =)) new_tycos tycos;
haftmann@30962
  1008
    val consts' = fold (insert (op =)) new_consts consts;
haftmann@28054
  1009
    val (struct_name', ctxt') = if struct_name = ""
haftmann@33992
  1010
      then ML_Antiquote.variant eval_struct_name ctxt
haftmann@28054
  1011
      else (struct_name, ctxt);
haftmann@30962
  1012
    val acc_code = Lazy.lazy (delayed_code (ProofContext.theory_of ctxt) tycos' consts');
haftmann@30962
  1013
  in CodeAntiqData.put ((tycos', consts'), (false, (struct_name', acc_code))) ctxt' end;
haftmann@30962
  1014
haftmann@30962
  1015
fun register_const const = register_code [] [const];
haftmann@28054
  1016
haftmann@30962
  1017
fun register_datatype tyco constrs = register_code [tyco] constrs;
haftmann@30962
  1018
haftmann@30962
  1019
fun print_const const all_struct_name tycos_map consts_map =
haftmann@30962
  1020
  (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
haftmann@30962
  1021
haftmann@30962
  1022
fun print_datatype tyco constrs all_struct_name tycos_map consts_map =
haftmann@28054
  1023
  let
haftmann@30962
  1024
    val upperize = implode o nth_map 0 Symbol.to_ascii_upper o explode;
haftmann@30962
  1025
    fun check_base name name'' =
haftmann@30962
  1026
      if upperize (Long_Name.base_name name) = upperize name''
haftmann@30962
  1027
      then () else error ("Name as printed " ^ quote name''
haftmann@30962
  1028
        ^ "\ndiffers from logical base name " ^ quote (Long_Name.base_name name) ^ "; sorry.");
haftmann@30962
  1029
    val tyco'' = (the o AList.lookup (op =) tycos_map) tyco;
haftmann@30962
  1030
    val constrs'' = map (the o AList.lookup (op =) consts_map) constrs;
haftmann@30962
  1031
    val _ = check_base tyco tyco'';
haftmann@30962
  1032
    val _ = map2 check_base constrs constrs'';
haftmann@30962
  1033
  in "datatype " ^ tyco'' ^ " = datatype " ^ Long_Name.append all_struct_name tyco'' end;
haftmann@30962
  1034
haftmann@30962
  1035
fun print_code struct_name is_first print_it ctxt =
haftmann@30962
  1036
  let
haftmann@30962
  1037
    val (_, (_, (struct_code_name, acc_code))) = CodeAntiqData.get ctxt;
haftmann@33992
  1038
    val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
haftmann@33992
  1039
    val ml_code = if is_first then ml_code
haftmann@28054
  1040
      else "";
haftmann@30962
  1041
    val all_struct_name = Long_Name.append struct_name struct_code_name;
haftmann@30962
  1042
  in (ml_code, print_it all_struct_name tycos_map consts_map) end;
haftmann@28054
  1043
haftmann@28054
  1044
in
haftmann@28054
  1045
haftmann@28054
  1046
fun ml_code_antiq raw_const {struct_name, background} =
haftmann@28054
  1047
  let
haftmann@31156
  1048
    val const = Code.check_const (ProofContext.theory_of background) raw_const;
haftmann@28054
  1049
    val is_first = is_first_occ background;
haftmann@28054
  1050
    val background' = register_const const background;
haftmann@30962
  1051
  in (print_code struct_name is_first (print_const const), background') end;
haftmann@30962
  1052
haftmann@30962
  1053
fun ml_code_datatype_antiq (raw_tyco, raw_constrs) {struct_name, background} =
haftmann@30962
  1054
  let
haftmann@30962
  1055
    val thy = ProofContext.theory_of background;
haftmann@30962
  1056
    val tyco = Sign.intern_type thy raw_tyco;
haftmann@31156
  1057
    val constrs = map (Code.check_const thy) raw_constrs;
haftmann@30962
  1058
    val constrs' = (map fst o snd o Code.get_datatype thy) tyco;
haftmann@33038
  1059
    val _ = if eq_set (op =) (constrs, constrs') then ()
haftmann@30962
  1060
      else error ("Type " ^ quote tyco ^ ": given constructors diverge from real constructors")
haftmann@30962
  1061
    val is_first = is_first_occ background;
haftmann@30962
  1062
    val background' = register_datatype tyco constrs background;
haftmann@30962
  1063
  in (print_code struct_name is_first (print_datatype tyco constrs), background') end;
haftmann@28054
  1064
haftmann@28054
  1065
end; (*local*)
haftmann@28054
  1066
haftmann@28054
  1067
haftmann@28054
  1068
(** Isar setup **)
haftmann@28054
  1069
haftmann@28054
  1070
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@30962
  1071
val _ = ML_Context.add_antiq "code_datatype" (fn _ =>
haftmann@30962
  1072
  (Args.tyname --| Scan.lift (Args.$$$ "=")
haftmann@30962
  1073
    -- (Args.term ::: Scan.repeat (Scan.lift (Args.$$$ "|") |-- Args.term)))
haftmann@30962
  1074
      >> ml_code_datatype_antiq);
haftmann@28054
  1075
haftmann@28054
  1076
fun isar_seri_sml module_name =
haftmann@33992
  1077
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33992
  1078
  >> (fn with_signatures => serialize_ml target_SML
wenzelm@31327
  1079
      (SOME (use_text ML_Env.local_context (1, "generated code") false))
haftmann@33992
  1080
      print_sml_module print_sml_stmt module_name with_signatures));
haftmann@28054
  1081
haftmann@28054
  1082
fun isar_seri_ocaml module_name =
haftmann@33992
  1083
  Code_Target.parse_args (Scan.optional (Args.$$$ "no_signatures" >> K false) true
haftmann@33992
  1084
  >> (fn with_signatures => serialize_ml target_OCaml NONE
haftmann@33992
  1085
      print_ocaml_module print_ocaml_stmt module_name with_signatures));
haftmann@28054
  1086
haftmann@28054
  1087
val setup =
haftmann@28064
  1088
  Code_Target.add_target (target_SML, (isar_seri_sml, literals_sml))
haftmann@28064
  1089
  #> Code_Target.add_target (target_OCaml, (isar_seri_ocaml, literals_ocaml))
haftmann@30947
  1090
  #> Code_Target.extend_target (target_Eval, (target_SML, K I))
haftmann@33992
  1091
  #> Code_Target.add_syntax_tyco target_SML "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
  1092
      brackify_infix (1, R) fxy [
haftmann@33992
  1093
        print_typ (INFX (1, X)) ty1,
haftmann@28054
  1094
        str "->",
haftmann@33992
  1095
        print_typ (INFX (1, R)) ty2
haftmann@28054
  1096
      ]))
haftmann@33992
  1097
  #> Code_Target.add_syntax_tyco target_OCaml "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
  1098
      brackify_infix (1, R) fxy [
haftmann@33992
  1099
        print_typ (INFX (1, X)) ty1,
haftmann@28054
  1100
        str "->",
haftmann@33992
  1101
        print_typ (INFX (1, R)) ty2
haftmann@28054
  1102
      ]))
haftmann@28054
  1103
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
  1104
  #> fold (Code_Target.add_reserved target_SML)
haftmann@28054
  1105
      ["o" (*dictionary projections use it already*), "Fail", "div", "mod" (*standard infixes*)]
haftmann@28054
  1106
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
  1107
      "and", "as", "assert", "begin", "class",
haftmann@28054
  1108
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
  1109
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
  1110
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
  1111
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
  1112
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
  1113
      "virtual", "when", "while", "with"
haftmann@28054
  1114
    ]
haftmann@28054
  1115
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod"];
haftmann@28054
  1116
haftmann@28054
  1117
end; (*struct*)