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