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