src/Tools/code/code_ml.ML
author wenzelm
Mon Mar 23 21:57:52 2009 +0100 (2009-03-23)
changeset 30675 2e796219f441
parent 30672 beaadd5af500
child 30941 705bb15b2365
permissions -rw-r--r--
more systematic type use_context;
haftmann@28054
     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@28054
     9
  val eval_term: string * (unit -> 'a) option ref
haftmann@28724
    10
    -> theory -> term -> string list -> 'a
haftmann@28054
    11
  val setup: theory -> theory
haftmann@28054
    12
end;
haftmann@28054
    13
haftmann@28054
    14
structure Code_ML : CODE_ML =
haftmann@28054
    15
struct
haftmann@28054
    16
haftmann@28054
    17
open Basic_Code_Thingol;
haftmann@28054
    18
open Code_Printer;
haftmann@28054
    19
haftmann@28054
    20
infixr 5 @@;
haftmann@28054
    21
infixr 5 @|;
haftmann@28054
    22
haftmann@28054
    23
val target_SML = "SML";
haftmann@28054
    24
val target_OCaml = "OCaml";
haftmann@28054
    25
haftmann@28054
    26
datatype ml_stmt =
haftmann@29189
    27
    MLExc of string * int
haftmann@29189
    28
  | MLVal of string * ((typscheme * iterm) * (thm * bool))
haftmann@29189
    29
  | MLFuns of (string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)) list * string list
haftmann@28054
    30
  | MLDatas of (string * ((vname * sort) list * (string * itype list) list)) list
haftmann@28054
    31
  | MLClass of string * (vname * ((class * string) list * (string * itype) list))
haftmann@28054
    32
  | MLClassinst of string * ((class * (string * (vname * sort) list))
haftmann@28054
    33
        * ((class * (string * (string * dict list list))) list
haftmann@28350
    34
      * ((string * const) * (thm * bool)) list));
haftmann@28054
    35
haftmann@29189
    36
fun stmt_names_of (MLExc (name, _)) = [name]
haftmann@29189
    37
  | stmt_names_of (MLVal (name, _)) = [name]
haftmann@29189
    38
  | stmt_names_of (MLFuns (fs, _)) = map fst fs
haftmann@28054
    39
  | stmt_names_of (MLDatas ds) = map fst ds
haftmann@29189
    40
  | stmt_names_of (MLClass (name, _)) = [name]
haftmann@29189
    41
  | stmt_names_of (MLClassinst (name, _)) = [name];
haftmann@28054
    42
haftmann@28054
    43
haftmann@28054
    44
(** SML serailizer **)
haftmann@28054
    45
haftmann@28663
    46
fun pr_sml_stmt naming labelled_name syntax_tyco syntax_const reserved_names deresolve is_cons =
haftmann@28054
    47
  let
haftmann@28054
    48
    val pr_label_classrel = translate_string (fn "." => "__" | c => c)
wenzelm@30364
    49
      o Long_Name.qualifier;
wenzelm@30364
    50
    val pr_label_classparam = Long_Name.base_name o Long_Name.qualifier;
haftmann@28054
    51
    fun pr_dicts fxy ds =
haftmann@28054
    52
      let
haftmann@30648
    53
        fun pr_dictvar (v, (_, 1)) = Code_Printer.first_upper v ^ "_"
haftmann@30648
    54
          | pr_dictvar (v, (i, _)) = Code_Printer.first_upper v ^ string_of_int (i+1) ^ "_";
haftmann@28054
    55
        fun pr_proj [] p =
haftmann@28054
    56
              p
haftmann@28054
    57
          | pr_proj [p'] p =
haftmann@28054
    58
              brackets [p', p]
haftmann@28054
    59
          | pr_proj (ps as _ :: _) p =
haftmann@28054
    60
              brackets [Pretty.enum " o" "(" ")" ps, p];
haftmann@28054
    61
        fun pr_dict fxy (DictConst (inst, dss)) =
haftmann@28054
    62
              brackify fxy ((str o deresolve) inst :: map (pr_dicts BR) dss)
haftmann@28054
    63
          | pr_dict fxy (DictVar (classrels, v)) =
haftmann@28054
    64
              pr_proj (map (str o deresolve) classrels) ((str o pr_dictvar) v)
haftmann@28054
    65
      in case ds
haftmann@28054
    66
       of [] => str "()"
haftmann@28054
    67
        | [d] => pr_dict fxy d
haftmann@28054
    68
        | _ :: _ => (Pretty.list "(" ")" o map (pr_dict NOBR)) ds
haftmann@28054
    69
      end;
haftmann@28054
    70
    fun pr_tyvar_dicts vs =
haftmann@28054
    71
      vs
haftmann@28054
    72
      |> map (fn (v, sort) => map_index (fn (i, _) =>
haftmann@28054
    73
           DictVar ([], (v, (i, length sort)))) sort)
haftmann@28054
    74
      |> map (pr_dicts BR);
haftmann@28054
    75
    fun pr_tycoexpr fxy (tyco, tys) =
haftmann@28054
    76
      let
haftmann@28054
    77
        val tyco' = (str o deresolve) tyco
haftmann@28054
    78
      in case map (pr_typ BR) tys
haftmann@28054
    79
       of [] => tyco'
haftmann@28054
    80
        | [p] => Pretty.block [p, Pretty.brk 1, tyco']
haftmann@28054
    81
        | (ps as _::_) => Pretty.block [Pretty.list "(" ")" ps, Pretty.brk 1, tyco']
haftmann@28054
    82
      end
haftmann@28054
    83
    and pr_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@28054
    84
         of NONE => pr_tycoexpr fxy (tyco, tys)
haftmann@28054
    85
          | SOME (i, pr) => pr pr_typ fxy tys)
haftmann@28054
    86
      | pr_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@29175
    87
    fun pr_term is_closure thm vars fxy (IConst c) =
haftmann@29175
    88
          pr_app is_closure thm vars fxy (c, [])
haftmann@29175
    89
      | pr_term is_closure thm vars fxy (IVar v) =
haftmann@30648
    90
          str (Code_Printer.lookup_var vars v)
haftmann@29175
    91
      | pr_term is_closure thm vars fxy (t as t1 `$ t2) =
haftmann@28054
    92
          (case Code_Thingol.unfold_const_app t
haftmann@29175
    93
           of SOME c_ts => pr_app is_closure thm vars fxy c_ts
haftmann@29175
    94
            | NONE => brackify fxy
haftmann@29175
    95
               [pr_term is_closure thm vars NOBR t1, pr_term is_closure thm vars BR t2])
haftmann@29175
    96
      | pr_term is_closure thm vars fxy (t as _ `|-> _) =
haftmann@28054
    97
          let
haftmann@28054
    98
            val (binds, t') = Code_Thingol.unfold_abs t;
haftmann@28054
    99
            fun pr ((v, pat), ty) =
haftmann@29175
   100
              pr_bind is_closure thm NOBR ((SOME v, pat), ty)
haftmann@28054
   101
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@28054
   102
            val (ps, vars') = fold_map pr binds vars;
haftmann@29175
   103
          in brackets (ps @ [pr_term is_closure thm vars' NOBR t']) end
haftmann@29175
   104
      | pr_term is_closure thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
   105
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
   106
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@29175
   107
                then pr_case is_closure thm vars fxy cases
haftmann@29175
   108
                else pr_app is_closure thm vars fxy c_ts
haftmann@29175
   109
            | NONE => pr_case is_closure thm vars fxy cases)
haftmann@29175
   110
    and pr_app' is_closure thm vars (app as ((c, (iss, tys)), ts)) =
haftmann@29175
   111
      if is_cons c then
haftmann@29175
   112
        let
haftmann@29175
   113
          val k = length tys
haftmann@29175
   114
        in if k < 2 then 
haftmann@29175
   115
          (str o deresolve) c :: map (pr_term is_closure thm vars BR) ts
haftmann@29175
   116
        else if k = length ts then
haftmann@29175
   117
          [(str o deresolve) c, Pretty.enum "," "(" ")" (map (pr_term is_closure thm vars NOBR) ts)]
haftmann@29175
   118
        else [pr_term is_closure thm vars BR (Code_Thingol.eta_expand k app)] end
haftmann@29175
   119
      else if is_closure c
haftmann@29175
   120
        then (str o deresolve) c @@ str "()"
haftmann@29175
   121
      else
haftmann@28054
   122
        (str o deresolve) c
haftmann@29175
   123
          :: (map (pr_dicts BR) o filter_out null) iss @ map (pr_term is_closure thm vars BR) ts
haftmann@29175
   124
    and pr_app is_closure thm vars = gen_pr_app (pr_app' is_closure) (pr_term is_closure)
haftmann@29175
   125
      syntax_const naming thm vars
haftmann@28054
   126
    and pr_bind' ((NONE, NONE), _) = str "_"
haftmann@28054
   127
      | pr_bind' ((SOME v, NONE), _) = str v
haftmann@28054
   128
      | pr_bind' ((NONE, SOME p), _) = p
haftmann@28054
   129
      | pr_bind' ((SOME v, SOME p), _) = concat [str v, str "as", p]
haftmann@29175
   130
    and pr_bind is_closure = gen_pr_bind pr_bind' (pr_term is_closure)
haftmann@29175
   131
    and pr_case is_closure thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   132
          let
haftmann@29952
   133
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@28054
   134
            fun pr ((pat, ty), t) vars =
haftmann@28054
   135
              vars
haftmann@29175
   136
              |> pr_bind is_closure thm NOBR ((NONE, SOME pat), ty)
haftmann@29175
   137
              |>> (fn p => semicolon [str "val", p, str "=", pr_term is_closure thm vars NOBR t])
haftmann@28054
   138
            val (ps, vars') = fold_map pr binds vars;
haftmann@28054
   139
          in
haftmann@28054
   140
            Pretty.chunks [
haftmann@28054
   141
              [str ("let"), Pretty.fbrk, Pretty.chunks ps] |> Pretty.block,
haftmann@29952
   142
              [str ("in"), Pretty.fbrk, pr_term is_closure thm vars' NOBR body] |> Pretty.block,
haftmann@28054
   143
              str ("end")
haftmann@28054
   144
            ]
haftmann@28054
   145
          end
haftmann@29952
   146
      | pr_case is_closure thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   147
          let
haftmann@29952
   148
            fun pr delim (pat, body) =
haftmann@28054
   149
              let
haftmann@29175
   150
                val (p, vars') = pr_bind is_closure thm NOBR ((NONE, SOME pat), ty) vars;
haftmann@28054
   151
              in
haftmann@29952
   152
                concat [str delim, p, str "=>", pr_term is_closure thm vars' NOBR body]
haftmann@28054
   153
              end;
haftmann@28054
   154
          in
haftmann@28054
   155
            (Pretty.enclose "(" ")" o single o brackify fxy) (
haftmann@28054
   156
              str "case"
haftmann@29952
   157
              :: pr_term is_closure thm vars NOBR t
haftmann@29952
   158
              :: pr "of" clause
haftmann@29952
   159
              :: map (pr "|") clauses
haftmann@28054
   160
            )
haftmann@28054
   161
          end
haftmann@29175
   162
      | pr_case is_closure thm vars fxy ((_, []), _) = str "raise Fail \"empty case\"";
haftmann@29189
   163
    fun pr_stmt (MLExc (name, n)) =
haftmann@29189
   164
          let
haftmann@29189
   165
            val exc_str =
wenzelm@30364
   166
              (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name;
haftmann@29189
   167
          in
haftmann@29189
   168
            concat (
haftmann@29189
   169
              str (if n = 0 then "val" else "fun")
haftmann@29189
   170
              :: (str o deresolve) name
haftmann@29189
   171
              :: map str (replicate n "_")
haftmann@29189
   172
              @ str "="
haftmann@29189
   173
              :: str "raise"
haftmann@29189
   174
              :: str "(Fail"
haftmann@29189
   175
              @@ str (exc_str ^ ")")
haftmann@29189
   176
            )
haftmann@29189
   177
          end
haftmann@29189
   178
      | pr_stmt (MLVal (name, (((vs, ty), t), (thm, _)))) =
haftmann@28054
   179
          let
haftmann@29189
   180
            val consts = map_filter
haftmann@29189
   181
              (fn c => if (is_some o syntax_const) c
wenzelm@30364
   182
                then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@29189
   183
                (Code_Thingol.fold_constnames (insert (op =)) t []);
haftmann@29189
   184
            val vars = reserved_names
haftmann@30648
   185
              |> Code_Printer.intro_vars consts;
haftmann@29189
   186
          in
haftmann@29189
   187
            concat [
haftmann@29189
   188
              str "val",
haftmann@29189
   189
              (str o deresolve) name,
haftmann@29189
   190
              str ":",
haftmann@29189
   191
              pr_typ NOBR ty,
haftmann@29189
   192
              str "=",
haftmann@29189
   193
              pr_term (K false) thm vars NOBR t
haftmann@29189
   194
            ]
haftmann@29189
   195
          end
haftmann@29189
   196
      | pr_stmt (MLFuns (funn :: funns, pseudo_funs)) =
haftmann@29189
   197
          let
haftmann@29189
   198
            fun pr_funn definer (name, ((vs, ty), eqs as eq :: eqs')) =
haftmann@28054
   199
              let
haftmann@29189
   200
                val vs_dict = filter_out (null o snd) vs;
haftmann@29189
   201
                val shift = if null eqs' then I else
haftmann@29189
   202
                  map (Pretty.block o single o Pretty.block o single);
haftmann@29189
   203
                fun pr_eq definer ((ts, t), (thm, _)) =
haftmann@28054
   204
                  let
haftmann@29189
   205
                    val consts = map_filter
haftmann@29189
   206
                      (fn c => if (is_some o syntax_const) c
wenzelm@30364
   207
                        then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@29189
   208
                        ((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@29189
   209
                    val vars = reserved_names
haftmann@30648
   210
                      |> Code_Printer.intro_vars consts
haftmann@30648
   211
                      |> Code_Printer.intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
haftmann@29189
   212
                           (insert (op =)) ts []);
haftmann@28054
   213
                  in
haftmann@28054
   214
                    concat (
haftmann@28054
   215
                      str definer
haftmann@28054
   216
                      :: (str o deresolve) name
haftmann@29189
   217
                      :: (if member (op =) pseudo_funs name then [str "()"]
haftmann@29189
   218
                          else pr_tyvar_dicts vs_dict
haftmann@29189
   219
                            @ map (pr_term (member (op =) pseudo_funs) thm vars BR) ts)
haftmann@28054
   220
                      @ str "="
haftmann@29189
   221
                      @@ pr_term (member (op =) pseudo_funs) thm vars NOBR t
haftmann@28054
   222
                    )
haftmann@28054
   223
                  end
haftmann@29189
   224
              in
haftmann@29189
   225
                (Pretty.block o Pretty.fbreaks o shift) (
haftmann@29189
   226
                  pr_eq definer eq
haftmann@29189
   227
                  :: map (pr_eq "|") eqs'
haftmann@29189
   228
                )
haftmann@29189
   229
              end;
haftmann@29189
   230
            fun pr_pseudo_fun name = concat [
haftmann@29189
   231
                str "val",
haftmann@29189
   232
                (str o deresolve) name,
haftmann@29189
   233
                str "=",
haftmann@29189
   234
                (str o deresolve) name,
haftmann@29189
   235
                str "();"
haftmann@29189
   236
              ];
haftmann@29189
   237
            val (ps, p) = split_last (pr_funn "fun" funn :: map (pr_funn "and") funns);
haftmann@29189
   238
            val pseudo_ps = map pr_pseudo_fun pseudo_funs;
haftmann@29189
   239
          in Pretty.chunks (ps @ Pretty.block ([p, str ";"]) :: pseudo_ps) end
haftmann@28054
   240
     | pr_stmt (MLDatas (datas as (data :: datas'))) =
haftmann@28054
   241
          let
haftmann@28054
   242
            fun pr_co (co, []) =
haftmann@28054
   243
                  str (deresolve co)
haftmann@28054
   244
              | pr_co (co, tys) =
haftmann@28054
   245
                  concat [
haftmann@28054
   246
                    str (deresolve co),
haftmann@28054
   247
                    str "of",
haftmann@28054
   248
                    Pretty.enum " *" "" "" (map (pr_typ (INFX (2, X))) tys)
haftmann@28054
   249
                  ];
haftmann@28054
   250
            fun pr_data definer (tyco, (vs, [])) =
haftmann@28054
   251
                  concat (
haftmann@28054
   252
                    str definer
haftmann@28054
   253
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   254
                    :: str "="
haftmann@28054
   255
                    @@ str "EMPTY__" 
haftmann@28054
   256
                  )
haftmann@28054
   257
              | pr_data definer (tyco, (vs, cos)) =
haftmann@28054
   258
                  concat (
haftmann@28054
   259
                    str definer
haftmann@28054
   260
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   261
                    :: str "="
haftmann@28054
   262
                    :: separate (str "|") (map pr_co cos)
haftmann@28054
   263
                  );
haftmann@28054
   264
            val (ps, p) = split_last
haftmann@28054
   265
              (pr_data "datatype" data :: map (pr_data "and") datas');
haftmann@29189
   266
          in Pretty.chunks (ps @| Pretty.block ([p, str ";"])) end
haftmann@28054
   267
     | pr_stmt (MLClass (class, (v, (superclasses, classparams)))) =
haftmann@28054
   268
          let
haftmann@30648
   269
            val w = Code_Printer.first_upper v ^ "_";
haftmann@28054
   270
            fun pr_superclass_field (class, classrel) =
haftmann@28054
   271
              (concat o map str) [
haftmann@28054
   272
                pr_label_classrel classrel, ":", "'" ^ v, deresolve class
haftmann@28054
   273
              ];
haftmann@28054
   274
            fun pr_classparam_field (classparam, ty) =
haftmann@28054
   275
              concat [
haftmann@28054
   276
                (str o pr_label_classparam) classparam, str ":", pr_typ NOBR ty
haftmann@28054
   277
              ];
haftmann@28054
   278
            fun pr_classparam_proj (classparam, _) =
haftmann@28054
   279
              semicolon [
haftmann@28054
   280
                str "fun",
haftmann@28054
   281
                (str o deresolve) classparam,
haftmann@28054
   282
                Pretty.enclose "(" ")" [str (w ^ ":'" ^ v ^ " " ^ deresolve class)],
haftmann@28054
   283
                str "=",
haftmann@28054
   284
                str ("#" ^ pr_label_classparam classparam),
haftmann@28054
   285
                str w
haftmann@28054
   286
              ];
haftmann@28054
   287
            fun pr_superclass_proj (_, classrel) =
haftmann@28054
   288
              semicolon [
haftmann@28054
   289
                str "fun",
haftmann@28054
   290
                (str o deresolve) classrel,
haftmann@28054
   291
                Pretty.enclose "(" ")" [str (w ^ ":'" ^ v ^ " " ^ deresolve class)],
haftmann@28054
   292
                str "=",
haftmann@28054
   293
                str ("#" ^ pr_label_classrel classrel),
haftmann@28054
   294
                str w
haftmann@28054
   295
              ];
haftmann@28054
   296
          in
haftmann@28054
   297
            Pretty.chunks (
haftmann@28054
   298
              concat [
haftmann@28054
   299
                str ("type '" ^ v),
haftmann@28054
   300
                (str o deresolve) class,
haftmann@28054
   301
                str "=",
haftmann@28054
   302
                Pretty.enum "," "{" "};" (
haftmann@28054
   303
                  map pr_superclass_field superclasses @ map pr_classparam_field classparams
haftmann@28054
   304
                )
haftmann@28054
   305
              ]
haftmann@28054
   306
              :: map pr_superclass_proj superclasses
haftmann@28054
   307
              @ map pr_classparam_proj classparams
haftmann@28054
   308
            )
haftmann@28054
   309
          end
haftmann@28054
   310
     | pr_stmt (MLClassinst (inst, ((class, (tyco, arity)), (superarities, classparam_insts)))) =
haftmann@28054
   311
          let
haftmann@28054
   312
            fun pr_superclass (_, (classrel, dss)) =
haftmann@28054
   313
              concat [
haftmann@28054
   314
                (str o pr_label_classrel) classrel,
haftmann@28054
   315
                str "=",
haftmann@28054
   316
                pr_dicts NOBR [DictConst dss]
haftmann@28054
   317
              ];
haftmann@28350
   318
            fun pr_classparam ((classparam, c_inst), (thm, _)) =
haftmann@28054
   319
              concat [
haftmann@28054
   320
                (str o pr_label_classparam) classparam,
haftmann@28054
   321
                str "=",
haftmann@29175
   322
                pr_app (K false) thm reserved_names NOBR (c_inst, [])
haftmann@28054
   323
              ];
haftmann@28054
   324
          in
haftmann@28054
   325
            semicolon ([
haftmann@28054
   326
              str (if null arity then "val" else "fun"),
haftmann@28054
   327
              (str o deresolve) inst ] @
haftmann@28054
   328
              pr_tyvar_dicts arity @ [
haftmann@28054
   329
              str "=",
haftmann@28054
   330
              Pretty.enum "," "{" "}"
haftmann@28054
   331
                (map pr_superclass superarities @ map pr_classparam classparam_insts),
haftmann@28054
   332
              str ":",
haftmann@28054
   333
              pr_tycoexpr NOBR (class, [tyco `%% map (ITyVar o fst) arity])
haftmann@28054
   334
            ])
haftmann@28054
   335
          end;
haftmann@28054
   336
  in pr_stmt end;
haftmann@28054
   337
haftmann@28054
   338
fun pr_sml_module name content =
haftmann@28054
   339
  Pretty.chunks (
haftmann@28054
   340
    str ("structure " ^ name ^ " = ")
haftmann@28054
   341
    :: str "struct"
haftmann@28054
   342
    :: str ""
haftmann@28054
   343
    :: content
haftmann@28054
   344
    @ str ""
haftmann@28054
   345
    @@ str ("end; (*struct " ^ name ^ "*)")
haftmann@28054
   346
  );
haftmann@28054
   347
haftmann@28064
   348
val literals_sml = Literals {
haftmann@28064
   349
  literal_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@28064
   350
  literal_string = quote o translate_string ML_Syntax.print_char,
haftmann@28064
   351
  literal_numeral = fn unbounded => fn k =>
haftmann@28064
   352
    if unbounded then "(" ^ string_of_int k ^ " : IntInf.int)"
haftmann@28064
   353
    else string_of_int k,
haftmann@28064
   354
  literal_list = Pretty.enum "," "[" "]",
haftmann@28064
   355
  infix_cons = (7, "::")
haftmann@28064
   356
};
haftmann@28064
   357
haftmann@28054
   358
haftmann@28054
   359
(** OCaml serializer **)
haftmann@28054
   360
haftmann@28663
   361
fun pr_ocaml_stmt naming labelled_name syntax_tyco syntax_const reserved_names deresolve is_cons =
haftmann@28054
   362
  let
haftmann@28054
   363
    fun pr_dicts fxy ds =
haftmann@28054
   364
      let
haftmann@30648
   365
        fun pr_dictvar (v, (_, 1)) = "_" ^ Code_Printer.first_upper v
haftmann@30648
   366
          | pr_dictvar (v, (i, _)) = "_" ^ Code_Printer.first_upper v ^ string_of_int (i+1);
haftmann@28054
   367
        fun pr_proj ps p =
haftmann@28054
   368
          fold_rev (fn p2 => fn p1 => Pretty.block [p1, str ".", str p2]) ps p
haftmann@28054
   369
        fun pr_dict fxy (DictConst (inst, dss)) =
haftmann@28054
   370
              brackify fxy ((str o deresolve) inst :: map (pr_dicts BR) dss)
haftmann@28054
   371
          | pr_dict fxy (DictVar (classrels, v)) =
haftmann@28054
   372
              pr_proj (map deresolve classrels) ((str o pr_dictvar) v)
haftmann@28054
   373
      in case ds
haftmann@28054
   374
       of [] => str "()"
haftmann@28054
   375
        | [d] => pr_dict fxy d
haftmann@28054
   376
        | _ :: _ => (Pretty.list "(" ")" o map (pr_dict NOBR)) ds
haftmann@28054
   377
      end;
haftmann@28054
   378
    fun pr_tyvar_dicts vs =
haftmann@28054
   379
      vs
haftmann@28054
   380
      |> map (fn (v, sort) => map_index (fn (i, _) =>
haftmann@28054
   381
           DictVar ([], (v, (i, length sort)))) sort)
haftmann@28054
   382
      |> map (pr_dicts BR);
haftmann@28054
   383
    fun pr_tycoexpr fxy (tyco, tys) =
haftmann@28054
   384
      let
haftmann@28054
   385
        val tyco' = (str o deresolve) tyco
haftmann@28054
   386
      in case map (pr_typ BR) tys
haftmann@28054
   387
       of [] => tyco'
haftmann@28054
   388
        | [p] => Pretty.block [p, Pretty.brk 1, tyco']
haftmann@28054
   389
        | (ps as _::_) => Pretty.block [Pretty.list "(" ")" ps, Pretty.brk 1, tyco']
haftmann@28054
   390
      end
haftmann@28054
   391
    and pr_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@28054
   392
         of NONE => pr_tycoexpr fxy (tyco, tys)
haftmann@28054
   393
          | SOME (i, pr) => pr pr_typ fxy tys)
haftmann@28054
   394
      | pr_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@29175
   395
    fun pr_term is_closure thm vars fxy (IConst c) =
haftmann@29175
   396
          pr_app is_closure thm vars fxy (c, [])
haftmann@29175
   397
      | pr_term is_closure thm vars fxy (IVar v) =
haftmann@30648
   398
          str (Code_Printer.lookup_var vars v)
haftmann@29175
   399
      | pr_term is_closure thm vars fxy (t as t1 `$ t2) =
haftmann@28054
   400
          (case Code_Thingol.unfold_const_app t
haftmann@29175
   401
           of SOME c_ts => pr_app is_closure thm vars fxy c_ts
haftmann@28054
   402
            | NONE =>
haftmann@29175
   403
                brackify fxy [pr_term is_closure thm vars NOBR t1, pr_term is_closure thm vars BR t2])
haftmann@29175
   404
      | pr_term is_closure thm vars fxy (t as _ `|-> _) =
haftmann@28054
   405
          let
haftmann@28054
   406
            val (binds, t') = Code_Thingol.unfold_abs t;
haftmann@29175
   407
            fun pr ((v, pat), ty) = pr_bind is_closure thm BR ((SOME v, pat), ty);
haftmann@28054
   408
            val (ps, vars') = fold_map pr binds vars;
haftmann@29175
   409
          in brackets (str "fun" :: ps @ str "->" @@ pr_term is_closure thm vars' NOBR t') end
haftmann@29175
   410
      | pr_term is_closure thm vars fxy (ICase (cases as (_, t0))) = (case Code_Thingol.unfold_const_app t0
haftmann@28054
   411
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@29175
   412
                then pr_case is_closure thm vars fxy cases
haftmann@29175
   413
                else pr_app is_closure thm vars fxy c_ts
haftmann@29175
   414
            | NONE => pr_case is_closure thm vars fxy cases)
haftmann@29175
   415
    and pr_app' is_closure thm vars (app as ((c, (iss, tys)), ts)) =
haftmann@28054
   416
      if is_cons c then
haftmann@28054
   417
        if length tys = length ts
haftmann@28054
   418
        then case ts
haftmann@28054
   419
         of [] => [(str o deresolve) c]
haftmann@29175
   420
          | [t] => [(str o deresolve) c, pr_term is_closure thm vars BR t]
haftmann@28054
   421
          | _ => [(str o deresolve) c, Pretty.enum "," "(" ")"
haftmann@29175
   422
                    (map (pr_term is_closure thm vars NOBR) ts)]
haftmann@29175
   423
        else [pr_term is_closure thm vars BR (Code_Thingol.eta_expand (length tys) app)]
haftmann@29175
   424
      else if is_closure c
haftmann@29175
   425
        then (str o deresolve) c @@ str "()"
haftmann@28054
   426
      else (str o deresolve) c
haftmann@29175
   427
        :: ((map (pr_dicts BR) o filter_out null) iss @ map (pr_term is_closure thm vars BR) ts)
haftmann@29175
   428
    and pr_app is_closure = gen_pr_app (pr_app' is_closure) (pr_term is_closure)
haftmann@29175
   429
      syntax_const naming
haftmann@28054
   430
    and pr_bind' ((NONE, NONE), _) = str "_"
haftmann@28054
   431
      | pr_bind' ((SOME v, NONE), _) = str v
haftmann@28054
   432
      | pr_bind' ((NONE, SOME p), _) = p
haftmann@28054
   433
      | pr_bind' ((SOME v, SOME p), _) = brackets [p, str "as", str v]
haftmann@29175
   434
    and pr_bind is_closure = gen_pr_bind pr_bind' (pr_term is_closure)
haftmann@29175
   435
    and pr_case is_closure thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   436
          let
haftmann@29952
   437
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@28054
   438
            fun pr ((pat, ty), t) vars =
haftmann@28054
   439
              vars
haftmann@29175
   440
              |> pr_bind is_closure thm NOBR ((NONE, SOME pat), ty)
haftmann@28054
   441
              |>> (fn p => concat
haftmann@29175
   442
                  [str "let", p, str "=", pr_term is_closure thm vars NOBR t, str "in"])
haftmann@28054
   443
            val (ps, vars') = fold_map pr binds vars;
haftmann@29952
   444
          in Pretty.chunks (ps @| pr_term is_closure thm vars' NOBR body) end
haftmann@29952
   445
      | pr_case is_closure thm vars fxy (((t, ty), clause :: clauses), _) =
haftmann@28054
   446
          let
haftmann@29952
   447
            fun pr delim (pat, body) =
haftmann@28054
   448
              let
haftmann@29175
   449
                val (p, vars') = pr_bind is_closure thm NOBR ((NONE, SOME pat), ty) vars;
haftmann@29952
   450
              in concat [str delim, p, str "->", pr_term is_closure thm vars' NOBR body] end;
haftmann@28054
   451
          in
haftmann@28054
   452
            (Pretty.enclose "(" ")" o single o brackify fxy) (
haftmann@28054
   453
              str "match"
haftmann@29952
   454
              :: pr_term is_closure thm vars NOBR t
haftmann@29952
   455
              :: pr "with" clause
haftmann@29952
   456
              :: map (pr "|") clauses
haftmann@28054
   457
            )
haftmann@28054
   458
          end
haftmann@29175
   459
      | pr_case is_closure thm vars fxy ((_, []), _) = str "failwith \"empty case\"";
haftmann@28054
   460
    fun fish_params vars eqs =
haftmann@28054
   461
      let
haftmann@28054
   462
        fun fish_param _ (w as SOME _) = w
haftmann@28054
   463
          | fish_param (IVar v) NONE = SOME v
haftmann@28054
   464
          | fish_param _ NONE = NONE;
haftmann@28054
   465
        fun fillup_param _ (_, SOME v) = v
haftmann@28054
   466
          | fillup_param x (i, NONE) = x ^ string_of_int i;
haftmann@28054
   467
        val fished1 = fold (map2 fish_param) eqs (replicate (length (hd eqs)) NONE);
haftmann@28054
   468
        val x = Name.variant (map_filter I fished1) "x";
haftmann@28054
   469
        val fished2 = map_index (fillup_param x) fished1;
haftmann@28054
   470
        val (fished3, _) = Name.variants fished2 Name.context;
haftmann@30648
   471
        val vars' = Code_Printer.intro_vars fished3 vars;
haftmann@30648
   472
      in map (Code_Printer.lookup_var vars') fished3 end;
haftmann@29189
   473
    fun pr_stmt (MLExc (name, n)) =
haftmann@29189
   474
          let
haftmann@29189
   475
            val exc_str =
wenzelm@30364
   476
              (ML_Syntax.print_string o Long_Name.base_name o Long_Name.qualifier) name;
haftmann@29189
   477
          in
haftmann@29189
   478
            concat (
haftmann@29189
   479
              str "let"
haftmann@29189
   480
              :: (str o deresolve) name
haftmann@29189
   481
              :: map str (replicate n "_")
haftmann@29189
   482
              @ str "="
haftmann@29189
   483
              :: str "failwith"
haftmann@29189
   484
              @@ str exc_str
haftmann@29189
   485
            )
haftmann@29189
   486
          end
haftmann@29189
   487
      | pr_stmt (MLVal (name, (((vs, ty), t), (thm, _)))) =
haftmann@29189
   488
          let
haftmann@29189
   489
            val consts = map_filter
haftmann@29189
   490
              (fn c => if (is_some o syntax_const) c
wenzelm@30364
   491
                then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@29189
   492
                (Code_Thingol.fold_constnames (insert (op =)) t []);
haftmann@29189
   493
            val vars = reserved_names
haftmann@30648
   494
              |> Code_Printer.intro_vars consts;
haftmann@29189
   495
          in
haftmann@29189
   496
            concat [
haftmann@29189
   497
              str "let",
haftmann@29189
   498
              (str o deresolve) name,
haftmann@29189
   499
              str ":",
haftmann@29189
   500
              pr_typ NOBR ty,
haftmann@29189
   501
              str "=",
haftmann@29189
   502
              pr_term (K false) thm vars NOBR t
haftmann@29189
   503
            ]
haftmann@29189
   504
          end
haftmann@29189
   505
      | pr_stmt (MLFuns (funn :: funns, pseudo_funs)) =
haftmann@28054
   506
          let
haftmann@28350
   507
            fun pr_eq ((ts, t), (thm, _)) =
haftmann@28054
   508
              let
haftmann@28054
   509
                val consts = map_filter
haftmann@28054
   510
                  (fn c => if (is_some o syntax_const) c
wenzelm@30364
   511
                    then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@28054
   512
                    ((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@28054
   513
                val vars = reserved_names
haftmann@30648
   514
                  |> Code_Printer.intro_vars consts
haftmann@30648
   515
                  |> Code_Printer.intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
haftmann@28054
   516
                      (insert (op =)) ts []);
haftmann@28054
   517
              in concat [
haftmann@29189
   518
                (Pretty.block o Pretty.commas)
haftmann@29189
   519
                  (map (pr_term (member (op =) pseudo_funs) thm vars NOBR) ts),
haftmann@28054
   520
                str "->",
haftmann@29189
   521
                pr_term (member (op =) pseudo_funs) thm vars NOBR t
haftmann@28054
   522
              ] end;
haftmann@29189
   523
            fun pr_eqs is_pseudo [((ts, t), (thm, _))] =
haftmann@28054
   524
                  let
haftmann@28054
   525
                    val consts = map_filter
haftmann@28054
   526
                      (fn c => if (is_some o syntax_const) c
wenzelm@30364
   527
                        then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@28054
   528
                        ((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@28054
   529
                    val vars = reserved_names
haftmann@30648
   530
                      |> Code_Printer.intro_vars consts
haftmann@30648
   531
                      |> Code_Printer.intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
haftmann@28054
   532
                          (insert (op =)) ts []);
haftmann@28054
   533
                  in
haftmann@28054
   534
                    concat (
haftmann@29189
   535
                      (if is_pseudo then [str "()"]
haftmann@29189
   536
                        else map (pr_term (member (op =) pseudo_funs) thm vars BR) ts)
haftmann@28054
   537
                      @ str "="
haftmann@29189
   538
                      @@ pr_term (member (op =) pseudo_funs) thm vars NOBR t
haftmann@28054
   539
                    )
haftmann@28054
   540
                  end
haftmann@29189
   541
              | pr_eqs _ (eqs as (eq as (([_], _), _)) :: eqs') =
haftmann@28054
   542
                  Pretty.block (
haftmann@28054
   543
                    str "="
haftmann@28054
   544
                    :: Pretty.brk 1
haftmann@28054
   545
                    :: str "function"
haftmann@28054
   546
                    :: Pretty.brk 1
haftmann@28054
   547
                    :: pr_eq eq
haftmann@28054
   548
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@28054
   549
                          o single o pr_eq) eqs'
haftmann@28054
   550
                  )
haftmann@29189
   551
              | pr_eqs _ (eqs as eq :: eqs') =
haftmann@28054
   552
                  let
haftmann@28054
   553
                    val consts = map_filter
haftmann@28054
   554
                      (fn c => if (is_some o syntax_const) c
wenzelm@30364
   555
                        then NONE else (SOME o Long_Name.base_name o deresolve) c)
haftmann@28054
   556
                        ((fold o Code_Thingol.fold_constnames)
haftmann@28054
   557
                          (insert (op =)) (map (snd o fst) eqs) []);
haftmann@28054
   558
                    val vars = reserved_names
haftmann@30648
   559
                      |> Code_Printer.intro_vars consts;
haftmann@28054
   560
                    val dummy_parms = (map str o fish_params vars o map (fst o fst)) eqs;
haftmann@28054
   561
                  in
haftmann@28054
   562
                    Pretty.block (
haftmann@28054
   563
                      Pretty.breaks dummy_parms
haftmann@28054
   564
                      @ Pretty.brk 1
haftmann@28054
   565
                      :: str "="
haftmann@28054
   566
                      :: Pretty.brk 1
haftmann@28054
   567
                      :: str "match"
haftmann@28054
   568
                      :: Pretty.brk 1
haftmann@28054
   569
                      :: (Pretty.block o Pretty.commas) dummy_parms
haftmann@28054
   570
                      :: Pretty.brk 1
haftmann@28054
   571
                      :: str "with"
haftmann@28054
   572
                      :: Pretty.brk 1
haftmann@28054
   573
                      :: pr_eq eq
haftmann@28054
   574
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@28054
   575
                           o single o pr_eq) eqs'
haftmann@28054
   576
                    )
haftmann@28054
   577
                  end;
haftmann@29189
   578
            fun pr_funn definer (name, ((vs, ty), eqs)) =
haftmann@28054
   579
              concat (
haftmann@28054
   580
                str definer
haftmann@28054
   581
                :: (str o deresolve) name
haftmann@28054
   582
                :: pr_tyvar_dicts (filter_out (null o snd) vs)
haftmann@29189
   583
                @| pr_eqs (member (op =) pseudo_funs name) eqs
haftmann@28054
   584
              );
haftmann@29189
   585
            fun pr_pseudo_fun name = concat [
haftmann@29189
   586
                str "let",
haftmann@29189
   587
                (str o deresolve) name,
haftmann@29189
   588
                str "=",
haftmann@29189
   589
                (str o deresolve) name,
haftmann@29189
   590
                str "();;"
haftmann@29189
   591
              ];
haftmann@29189
   592
            val (ps, p) = split_last (pr_funn "fun" funn :: map (pr_funn "and") funns);
haftmann@28054
   593
            val (ps, p) = split_last
haftmann@29189
   594
              (pr_funn "let rec" funn :: map (pr_funn "and") funns);
haftmann@29189
   595
            val pseudo_ps = map pr_pseudo_fun pseudo_funs;
haftmann@29189
   596
          in Pretty.chunks (ps @ Pretty.block ([p, str ";;"]) :: pseudo_ps) end
haftmann@28054
   597
     | pr_stmt (MLDatas (datas as (data :: datas'))) =
haftmann@28054
   598
          let
haftmann@28054
   599
            fun pr_co (co, []) =
haftmann@28054
   600
                  str (deresolve co)
haftmann@28054
   601
              | pr_co (co, tys) =
haftmann@28054
   602
                  concat [
haftmann@28054
   603
                    str (deresolve co),
haftmann@28054
   604
                    str "of",
haftmann@28054
   605
                    Pretty.enum " *" "" "" (map (pr_typ (INFX (2, X))) tys)
haftmann@28054
   606
                  ];
haftmann@28054
   607
            fun pr_data definer (tyco, (vs, [])) =
haftmann@28054
   608
                  concat (
haftmann@28054
   609
                    str definer
haftmann@28054
   610
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   611
                    :: str "="
haftmann@28054
   612
                    @@ str "EMPTY_"
haftmann@28054
   613
                  )
haftmann@28054
   614
              | pr_data definer (tyco, (vs, cos)) =
haftmann@28054
   615
                  concat (
haftmann@28054
   616
                    str definer
haftmann@28054
   617
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   618
                    :: str "="
haftmann@28054
   619
                    :: separate (str "|") (map pr_co cos)
haftmann@28054
   620
                  );
haftmann@28054
   621
            val (ps, p) = split_last
haftmann@28054
   622
              (pr_data "type" data :: map (pr_data "and") datas');
haftmann@29189
   623
          in Pretty.chunks (ps @| Pretty.block ([p, str ";;"])) end
haftmann@28054
   624
     | pr_stmt (MLClass (class, (v, (superclasses, classparams)))) =
haftmann@28054
   625
          let
haftmann@30648
   626
            val w = "_" ^ Code_Printer.first_upper v;
haftmann@28054
   627
            fun pr_superclass_field (class, classrel) =
haftmann@28054
   628
              (concat o map str) [
haftmann@28054
   629
                deresolve classrel, ":", "'" ^ v, deresolve class
haftmann@28054
   630
              ];
haftmann@28054
   631
            fun pr_classparam_field (classparam, ty) =
haftmann@28054
   632
              concat [
haftmann@28054
   633
                (str o deresolve) classparam, str ":", pr_typ NOBR ty
haftmann@28054
   634
              ];
haftmann@28054
   635
            fun pr_classparam_proj (classparam, _) =
haftmann@28054
   636
              concat [
haftmann@28054
   637
                str "let",
haftmann@28054
   638
                (str o deresolve) classparam,
haftmann@28054
   639
                str w,
haftmann@28054
   640
                str "=",
haftmann@28054
   641
                str (w ^ "." ^ deresolve classparam ^ ";;")
haftmann@28054
   642
              ];
haftmann@28054
   643
          in Pretty.chunks (
haftmann@28054
   644
            concat [
haftmann@28054
   645
              str ("type '" ^ v),
haftmann@28054
   646
              (str o deresolve) class,
haftmann@28054
   647
              str "=",
haftmann@28054
   648
              enum_default "();;" ";" "{" "};;" (
haftmann@28054
   649
                map pr_superclass_field superclasses
haftmann@28054
   650
                @ map pr_classparam_field classparams
haftmann@28054
   651
              )
haftmann@28054
   652
            ]
haftmann@28054
   653
            :: map pr_classparam_proj classparams
haftmann@28054
   654
          ) end
haftmann@28054
   655
     | pr_stmt (MLClassinst (inst, ((class, (tyco, arity)), (superarities, classparam_insts)))) =
haftmann@28054
   656
          let
haftmann@28054
   657
            fun pr_superclass (_, (classrel, dss)) =
haftmann@28054
   658
              concat [
haftmann@28054
   659
                (str o deresolve) classrel,
haftmann@28054
   660
                str "=",
haftmann@28054
   661
                pr_dicts NOBR [DictConst dss]
haftmann@28054
   662
              ];
haftmann@28350
   663
            fun pr_classparam_inst ((classparam, c_inst), (thm, _)) =
haftmann@28054
   664
              concat [
haftmann@28054
   665
                (str o deresolve) classparam,
haftmann@28054
   666
                str "=",
haftmann@29175
   667
                pr_app (K false) thm reserved_names NOBR (c_inst, [])
haftmann@28054
   668
              ];
haftmann@28054
   669
          in
haftmann@28054
   670
            concat (
haftmann@28054
   671
              str "let"
haftmann@28054
   672
              :: (str o deresolve) inst
haftmann@28054
   673
              :: pr_tyvar_dicts arity
haftmann@28054
   674
              @ str "="
haftmann@28054
   675
              @@ (Pretty.enclose "(" ");;" o Pretty.breaks) [
haftmann@28054
   676
                enum_default "()" ";" "{" "}" (map pr_superclass superarities
haftmann@28054
   677
                  @ map pr_classparam_inst classparam_insts),
haftmann@28054
   678
                str ":",
haftmann@28054
   679
                pr_tycoexpr NOBR (class, [tyco `%% map (ITyVar o fst) arity])
haftmann@28054
   680
              ]
haftmann@28054
   681
            )
haftmann@28054
   682
          end;
haftmann@28054
   683
  in pr_stmt end;
haftmann@28054
   684
haftmann@28054
   685
fun pr_ocaml_module name content =
haftmann@28054
   686
  Pretty.chunks (
haftmann@28054
   687
    str ("module " ^ name ^ " = ")
haftmann@28054
   688
    :: str "struct"
haftmann@28054
   689
    :: str ""
haftmann@28054
   690
    :: content
haftmann@28054
   691
    @ str ""
haftmann@28054
   692
    @@ str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   693
  );
haftmann@28054
   694
haftmann@28064
   695
val literals_ocaml = let
haftmann@28064
   696
  fun chr i =
haftmann@28064
   697
    let
haftmann@28064
   698
      val xs = string_of_int i;
haftmann@28064
   699
      val ys = replicate_string (3 - length (explode xs)) "0";
haftmann@28064
   700
    in "\\" ^ ys ^ xs end;
haftmann@28064
   701
  fun char_ocaml c =
haftmann@28064
   702
    let
haftmann@28064
   703
      val i = ord c;
haftmann@28064
   704
      val s = if i < 32 orelse i = 34 orelse i = 39 orelse i = 92 orelse i > 126
haftmann@28064
   705
        then chr i else c
haftmann@28064
   706
    in s end;
haftmann@28064
   707
in Literals {
haftmann@28064
   708
  literal_char = enclose "'" "'" o char_ocaml,
haftmann@28064
   709
  literal_string = quote o translate_string char_ocaml,
haftmann@28064
   710
  literal_numeral = fn unbounded => fn k => if k >= 0 then
haftmann@28064
   711
      if unbounded then
haftmann@28064
   712
        "(Big_int.big_int_of_int " ^ string_of_int k ^ ")"
haftmann@28064
   713
      else string_of_int k
haftmann@28064
   714
    else
haftmann@28064
   715
      if unbounded then
haftmann@28064
   716
        "(Big_int.big_int_of_int " ^ (enclose "(" ")" o prefix "-"
haftmann@28064
   717
          o string_of_int o op ~) k ^ ")"
haftmann@28064
   718
      else (enclose "(" ")" o prefix "-" o string_of_int o op ~) k,
haftmann@28064
   719
  literal_list = Pretty.enum ";" "[" "]",
haftmann@28064
   720
  infix_cons = (6, "::")
haftmann@28064
   721
} end;
haftmann@28064
   722
haftmann@28064
   723
haftmann@28054
   724
haftmann@28054
   725
(** SML/OCaml generic part **)
haftmann@28054
   726
haftmann@28054
   727
local
haftmann@28054
   728
haftmann@28054
   729
datatype ml_node =
haftmann@28054
   730
    Dummy of string
haftmann@28054
   731
  | Stmt of string * ml_stmt
haftmann@28054
   732
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   733
haftmann@28054
   734
in
haftmann@28054
   735
haftmann@28054
   736
fun ml_node_of_program labelled_name module_name reserved_names raw_module_alias program =
haftmann@28054
   737
  let
haftmann@28054
   738
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@28054
   739
    val reserved_names = Name.make_context reserved_names;
haftmann@28054
   740
    val empty_module = ((reserved_names, reserved_names), Graph.empty);
haftmann@28054
   741
    fun map_node [] f = f
haftmann@28054
   742
      | map_node (m::ms) f =
haftmann@28054
   743
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   744
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   745
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   746
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   747
          let
haftmann@28054
   748
            val (x, nsp') = f nsp
haftmann@28054
   749
          in (x, (nsp', nodes)) end
haftmann@28054
   750
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   751
          let
haftmann@28054
   752
            val (x, nodes') =
haftmann@28054
   753
              nodes
haftmann@28054
   754
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   755
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   756
                  let
haftmann@28054
   757
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   758
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   759
          in (x, (nsp, nodes')) end;
haftmann@28054
   760
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   761
      let
haftmann@28054
   762
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   763
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   764
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   765
      let
haftmann@28054
   766
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   767
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@30648
   768
    val mk_name_module = Code_Printer.mk_name_module reserved_names NONE module_alias program;
haftmann@28054
   769
    fun mk_name_stmt upper name nsp =
haftmann@28054
   770
      let
haftmann@30648
   771
        val (_, base) = Code_Printer.dest_name name;
haftmann@30648
   772
        val base' = if upper then Code_Printer.first_upper base else base;
haftmann@28054
   773
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   774
      in (base'', nsp') end;
haftmann@29189
   775
    fun rearrange_fun name (tysm as (vs, ty), raw_eqs) =
haftmann@29189
   776
      let
haftmann@29189
   777
        val eqs = filter (snd o snd) raw_eqs;
haftmann@29189
   778
        val (eqs', is_value) = if null (filter_out (null o snd) vs) then case eqs
haftmann@29189
   779
         of [(([], t), thm)] => if (not o null o fst o Code_Thingol.unfold_fun) ty
haftmann@29189
   780
            then ([(([IVar "x"], t `$ IVar "x"), thm)], false)
haftmann@29189
   781
            else (eqs, not (Code_Thingol.fold_constnames
haftmann@29189
   782
              (fn name' => fn b => b orelse name = name') t false))
haftmann@29189
   783
          | _ => (eqs, false)
haftmann@29189
   784
          else (eqs, false)
haftmann@29189
   785
      in ((name, (tysm, eqs')), is_value) end;
haftmann@29189
   786
    fun check_kind [((name, (tysm, [(([], t), thm)])), true)] = MLVal (name, ((tysm, t), thm))
haftmann@29189
   787
      | check_kind [((name, ((vs, ty), [])), _)] =
haftmann@29189
   788
          MLExc (name, (length o filter_out (null o snd)) vs + (length o fst o Code_Thingol.unfold_fun) ty)
haftmann@29189
   789
      | check_kind funns =
haftmann@29189
   790
          MLFuns (map fst funns, map_filter
haftmann@29189
   791
            (fn ((name, ((vs, _), [(([], _), _)])), _) =>
haftmann@29189
   792
                  if null (filter_out (null o snd) vs) then SOME name else NONE
haftmann@29189
   793
              | _ => NONE) funns);
haftmann@29189
   794
    fun add_funs stmts = fold_map
haftmann@28663
   795
        (fn (name, Code_Thingol.Fun (_, stmt)) =>
haftmann@29189
   796
              map_nsp_fun_yield (mk_name_stmt false name)
haftmann@29189
   797
              #>> rpair (rearrange_fun name stmt)
haftmann@28054
   798
          | (name, _) =>
haftmann@28054
   799
              error ("Function block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   800
        ) stmts
haftmann@29189
   801
      #>> (split_list #> apsnd check_kind);
haftmann@28054
   802
    fun add_datatypes stmts =
haftmann@28054
   803
      fold_map
haftmann@28663
   804
        (fn (name, Code_Thingol.Datatype (_, stmt)) =>
haftmann@28054
   805
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   806
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   807
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   808
          | (name, _) =>
haftmann@28054
   809
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   810
        ) stmts
haftmann@28054
   811
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   812
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@28054
   813
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@28054
   814
             | stmts => MLDatas stmts)));
haftmann@28054
   815
    fun add_class stmts =
haftmann@28054
   816
      fold_map
haftmann@28663
   817
        (fn (name, Code_Thingol.Class (_, stmt)) =>
haftmann@28663
   818
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   819
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   820
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   821
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   822
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   823
          | (name, _) =>
haftmann@28054
   824
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   825
        ) stmts
haftmann@28054
   826
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   827
        #> (fn [] => error ("Class block without class statement: "
haftmann@28054
   828
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@28054
   829
             | [stmt] => MLClass stmt)));
haftmann@28054
   830
    fun add_inst [(name, Code_Thingol.Classinst stmt)] =
haftmann@28054
   831
      map_nsp_fun_yield (mk_name_stmt false name)
haftmann@28054
   832
      #>> (fn base => ([base], MLClassinst (name, stmt)));
haftmann@28054
   833
    fun add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   834
          add_funs stmts
haftmann@28054
   835
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   836
          add_datatypes stmts
haftmann@28054
   837
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   838
          add_datatypes stmts
haftmann@28054
   839
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   840
          add_class stmts
haftmann@28054
   841
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   842
          add_class stmts
haftmann@28054
   843
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   844
          add_class stmts
haftmann@28054
   845
      | add_stmts ((stmts as [(_, Code_Thingol.Classinst _)])) =
haftmann@28054
   846
          add_inst stmts
haftmann@28054
   847
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@28054
   848
          (commas o map (labelled_name o fst)) stmts);
haftmann@28054
   849
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   850
      let
haftmann@28054
   851
        val names as (name :: names') = map fst stmts;
haftmann@28054
   852
        val deps =
haftmann@28054
   853
          []
haftmann@28054
   854
          |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@28054
   855
          |> subtract (op =) names;
haftmann@30648
   856
        val (module_names, _) = (split_list o map Code_Printer.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@28054
   860
              ^ commas (map labelled_name names)
haftmann@28054
   861
              ^ "\n"
haftmann@28054
   862
              ^ 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@30648
   866
            val module_name' = (mk_name_module o fst o Code_Printer.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@28054
   889
    val (_, nodes) = empty_module
haftmann@28054
   890
      |> fold add_stmts' (map (AList.make (Graph.get_node program))
haftmann@28054
   891
          (rev (Graph.strong_conn program)));
haftmann@28054
   892
    fun deresolver prefix name = 
haftmann@28054
   893
      let
haftmann@30648
   894
        val module_name = (fst o Code_Printer.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@28054
   909
fun serialize_ml target compile pr_module pr_stmt raw_module_name labelled_name reserved_names includes raw_module_alias
haftmann@28663
   910
  _ syntax_tyco syntax_const naming program cs destination =
haftmann@28054
   911
  let
haftmann@28054
   912
    val is_cons = Code_Thingol.is_cons program;
haftmann@28054
   913
    val stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@28054
   914
    val module_name = if null stmt_names then raw_module_name else SOME "Code";
haftmann@28054
   915
    val (deresolver, nodes) = ml_node_of_program labelled_name module_name
haftmann@28054
   916
      reserved_names raw_module_alias program;
haftmann@30648
   917
    val reserved_names = Code_Printer.make_vars reserved_names;
haftmann@28054
   918
    fun pr_node prefix (Dummy _) =
haftmann@28054
   919
          NONE
haftmann@28054
   920
      | pr_node prefix (Stmt (_, stmt)) = if null stmt_names orelse
haftmann@28054
   921
          (not o null o filter (member (op =) stmt_names) o stmt_names_of) stmt then SOME
haftmann@28663
   922
            (pr_stmt naming labelled_name syntax_tyco syntax_const reserved_names
haftmann@28054
   923
              (deresolver prefix) is_cons stmt)
haftmann@28054
   924
          else NONE
haftmann@28054
   925
      | pr_node prefix (Module (module_name, (_, nodes))) =
haftmann@28054
   926
          separate (str "")
haftmann@28054
   927
            ((map_filter (pr_node (prefix @ [module_name]) o Graph.get_node nodes)
haftmann@28054
   928
              o rev o flat o Graph.strong_conn) nodes)
haftmann@28054
   929
          |> (if null stmt_names then pr_module module_name else Pretty.chunks)
haftmann@28054
   930
          |> SOME;
haftmann@28663
   931
    val cs' = (map o try)
haftmann@28663
   932
      (deresolver (if is_some module_name then the_list module_name else [])) cs;
haftmann@28054
   933
    val p = Pretty.chunks (separate (str "") (map snd includes @ (map_filter
haftmann@28054
   934
      (pr_node [] o Graph.get_node nodes) o rev o flat o Graph.strong_conn) nodes));
haftmann@28054
   935
  in
haftmann@28054
   936
    Code_Target.mk_serialization target
haftmann@28054
   937
      (case compile of SOME compile => SOME (compile o Code_Target.code_of_pretty) | NONE => NONE)
haftmann@28054
   938
      (fn NONE => Code_Target.code_writeln | SOME file => File.write file o Code_Target.code_of_pretty)
haftmann@28054
   939
      (rpair cs' o Code_Target.code_of_pretty) p destination
haftmann@28054
   940
  end;
haftmann@28054
   941
haftmann@28054
   942
end; (*local*)
haftmann@28054
   943
haftmann@28054
   944
haftmann@28054
   945
(** ML (system language) code for evaluation and instrumentalization **)
haftmann@28054
   946
haftmann@28663
   947
fun ml_code_of thy = Code_Target.serialize_custom thy (target_SML,
haftmann@28663
   948
    (fn _ => fn [] => serialize_ml target_SML (SOME (K ())) (K Pretty.chunks) pr_sml_stmt (SOME ""),
haftmann@28064
   949
  literals_sml));
haftmann@28054
   950
haftmann@28054
   951
haftmann@28054
   952
(* evaluation *)
haftmann@28054
   953
haftmann@28054
   954
fun eval eval'' term_of reff thy ct args =
haftmann@28054
   955
  let
wenzelm@28275
   956
    val ctxt = ProofContext.init thy;
wenzelm@29264
   957
    val _ = if null (Term.add_frees (term_of ct) []) then () else error ("Term "
haftmann@28054
   958
      ^ quote (Syntax.string_of_term_global thy (term_of ct))
haftmann@28054
   959
      ^ " to be evaluated contains free variables");
haftmann@28663
   960
    fun eval' naming program ((vs, ty), t) deps =
haftmann@28054
   961
      let
haftmann@28054
   962
        val _ = if Code_Thingol.contains_dictvar t then
haftmann@28724
   963
          error "Term to be evaluated contains free dictionaries" else ();
haftmann@28663
   964
        val value_name = "Value.VALUE.value"
haftmann@28054
   965
        val program' = program
haftmann@28663
   966
          |> Graph.new_node (value_name,
haftmann@28663
   967
              Code_Thingol.Fun (Term.dummy_patternN, (([], ty), [(([], t), (Drule.dummy_thm, true))])))
haftmann@28663
   968
          |> fold (curry Graph.add_edge value_name) deps;
haftmann@28663
   969
        val (value_code, [SOME value_name']) = ml_code_of thy naming program' [value_name];
haftmann@28054
   970
        val sml_code = "let\n" ^ value_code ^ "\nin " ^ value_name'
haftmann@28054
   971
          ^ space_implode " " (map (enclose "(" ")") args) ^ " end";
wenzelm@30672
   972
      in ML_Context.evaluate ctxt false reff sml_code end;
haftmann@28724
   973
  in eval'' thy (rpair eval') ct end;
haftmann@28054
   974
haftmann@28054
   975
fun eval_term reff = eval Code_Thingol.eval_term I reff;
haftmann@28054
   976
haftmann@28054
   977
haftmann@28054
   978
(* instrumentalization by antiquotation *)
haftmann@28054
   979
haftmann@28054
   980
local
haftmann@28054
   981
haftmann@28054
   982
structure CodeAntiqData = ProofDataFun
haftmann@28054
   983
(
wenzelm@28971
   984
  type T = string list * (bool * (string * (string * (string * string) list) lazy));
wenzelm@28673
   985
  fun init _ = ([], (true, ("", Lazy.value ("", []))));
haftmann@28054
   986
);
haftmann@28054
   987
haftmann@28054
   988
val is_first_occ = fst o snd o CodeAntiqData.get;
haftmann@28054
   989
haftmann@28054
   990
fun delayed_code thy consts () =
haftmann@28054
   991
  let
haftmann@28663
   992
    val (consts', (naming, program)) = Code_Thingol.consts_program thy consts;
haftmann@28663
   993
    val (ml_code, consts'') = ml_code_of thy naming program consts';
haftmann@28663
   994
    val const_tab = map2 (fn const => fn NONE =>
haftmann@28663
   995
      error ("Constant " ^ (quote o Code_Unit.string_of_const thy) const
haftmann@28663
   996
        ^ "\nhas a user-defined serialization")
haftmann@28663
   997
      | SOME const' => (const, const')) consts consts''
haftmann@28663
   998
  in (ml_code, const_tab) end;
haftmann@28054
   999
haftmann@28054
  1000
fun register_const const ctxt =
haftmann@28054
  1001
  let
haftmann@28054
  1002
    val (consts, (_, (struct_name, _))) = CodeAntiqData.get ctxt;
haftmann@28054
  1003
    val consts' = insert (op =) const consts;
haftmann@28054
  1004
    val (struct_name', ctxt') = if struct_name = ""
haftmann@28054
  1005
      then ML_Antiquote.variant "Code" ctxt
haftmann@28054
  1006
      else (struct_name, ctxt);
wenzelm@28673
  1007
    val acc_code = Lazy.lazy (delayed_code (ProofContext.theory_of ctxt) consts');
haftmann@28054
  1008
  in CodeAntiqData.put (consts', (false, (struct_name', acc_code))) ctxt' end;
haftmann@28054
  1009
haftmann@28054
  1010
fun print_code struct_name is_first const ctxt =
haftmann@28054
  1011
  let
haftmann@28054
  1012
    val (consts, (_, (struct_code_name, acc_code))) = CodeAntiqData.get ctxt;
wenzelm@28673
  1013
    val (raw_ml_code, consts_map) = Lazy.force acc_code;
wenzelm@30364
  1014
    val const'' = Long_Name.append (Long_Name.append struct_name struct_code_name)
haftmann@28054
  1015
      ((the o AList.lookup (op =) consts_map) const);
haftmann@28054
  1016
    val ml_code = if is_first then "\nstructure " ^ struct_code_name
haftmann@28054
  1017
        ^ " =\nstruct\n\n" ^ raw_ml_code ^ "\nend;\n\n"
haftmann@28054
  1018
      else "";
haftmann@28054
  1019
  in (ml_code, const'') end;
haftmann@28054
  1020
haftmann@28054
  1021
in
haftmann@28054
  1022
haftmann@28054
  1023
fun ml_code_antiq raw_const {struct_name, background} =
haftmann@28054
  1024
  let
haftmann@28054
  1025
    val const = Code_Unit.check_const (ProofContext.theory_of background) raw_const;
haftmann@28054
  1026
    val is_first = is_first_occ background;
haftmann@28054
  1027
    val background' = register_const const background;
haftmann@28054
  1028
  in (print_code struct_name is_first const, background') end;
haftmann@28054
  1029
haftmann@28054
  1030
end; (*local*)
haftmann@28054
  1031
haftmann@28054
  1032
haftmann@28054
  1033
(** Isar setup **)
haftmann@28054
  1034
haftmann@28054
  1035
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@28054
  1036
haftmann@28054
  1037
fun isar_seri_sml module_name =
haftmann@28054
  1038
  Code_Target.parse_args (Scan.succeed ())
wenzelm@28275
  1039
  #> (fn () => serialize_ml target_SML
wenzelm@30675
  1040
      (SOME (use_text ML_Context.local_context (1, "generated code") false))
haftmann@28054
  1041
      pr_sml_module pr_sml_stmt module_name);
haftmann@28054
  1042
haftmann@28054
  1043
fun isar_seri_ocaml module_name =
haftmann@28054
  1044
  Code_Target.parse_args (Scan.succeed ())
haftmann@28054
  1045
  #> (fn () => serialize_ml target_OCaml NONE
haftmann@28054
  1046
      pr_ocaml_module pr_ocaml_stmt module_name);
haftmann@28054
  1047
haftmann@28054
  1048
val setup =
haftmann@28064
  1049
  Code_Target.add_target (target_SML, (isar_seri_sml, literals_sml))
haftmann@28064
  1050
  #> Code_Target.add_target (target_OCaml, (isar_seri_ocaml, literals_ocaml))
haftmann@28054
  1051
  #> Code_Target.add_syntax_tyco target_SML "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
  1052
      brackify_infix (1, R) fxy [
haftmann@28054
  1053
        pr_typ (INFX (1, X)) ty1,
haftmann@28054
  1054
        str "->",
haftmann@28054
  1055
        pr_typ (INFX (1, R)) ty2
haftmann@28054
  1056
      ]))
haftmann@28054
  1057
  #> Code_Target.add_syntax_tyco target_OCaml "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
  1058
      brackify_infix (1, R) fxy [
haftmann@28054
  1059
        pr_typ (INFX (1, X)) ty1,
haftmann@28054
  1060
        str "->",
haftmann@28054
  1061
        pr_typ (INFX (1, R)) ty2
haftmann@28054
  1062
      ]))
haftmann@28054
  1063
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
  1064
  #> fold (Code_Target.add_reserved target_SML)
haftmann@28054
  1065
      ["o" (*dictionary projections use it already*), "Fail", "div", "mod" (*standard infixes*)]
haftmann@28054
  1066
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
  1067
      "and", "as", "assert", "begin", "class",
haftmann@28054
  1068
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
  1069
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
  1070
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
  1071
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
  1072
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
  1073
      "virtual", "when", "while", "with"
haftmann@28054
  1074
    ]
haftmann@28054
  1075
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod"];
haftmann@28054
  1076
haftmann@28054
  1077
end; (*struct*)