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