src/Tools/code/code_ml.ML
author haftmann
Thu Aug 28 22:09:20 2008 +0200 (2008-08-28)
changeset 28054 2b84d34c5d02
child 28064 d4a6460c53d1
permissions -rw-r--r--
restructured and split code serializer module
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@28054
    30
    MLFuns of (string * (typscheme * ((iterm list * iterm) * thm) 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@28054
    35
      * ((string * const) * thm) 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@28054
    45
fun pr_sml_stmt syntax_tyco syntax_const labelled_name 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@28054
    52
        fun pr_dictvar (v, (_, 1)) = first_upper v ^ "_"
haftmann@28054
    53
          | pr_dictvar (v, (i, _)) = 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@28054
    89
          str (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@28054
   119
    and pr_app thm pat vars = gen_pr_app pr_app' pr_term syntax_const is_cons 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@28054
   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@28054
   202
                          |> intro_vars consts
haftmann@28054
   203
                          |> 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@28054
   253
            val w = 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@28054
   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@28054
   332
haftmann@28054
   333
(** OCaml serializer **)
haftmann@28054
   334
haftmann@28054
   335
fun pr_ocaml_stmt syntax_tyco syntax_const labelled_name reserved_names deresolve is_cons =
haftmann@28054
   336
  let
haftmann@28054
   337
    fun pr_dicts fxy ds =
haftmann@28054
   338
      let
haftmann@28054
   339
        fun pr_dictvar (v, (_, 1)) = "_" ^ first_upper v
haftmann@28054
   340
          | pr_dictvar (v, (i, _)) = "_" ^ first_upper v ^ string_of_int (i+1);
haftmann@28054
   341
        fun pr_proj ps p =
haftmann@28054
   342
          fold_rev (fn p2 => fn p1 => Pretty.block [p1, str ".", str p2]) ps p
haftmann@28054
   343
        fun pr_dict fxy (DictConst (inst, dss)) =
haftmann@28054
   344
              brackify fxy ((str o deresolve) inst :: map (pr_dicts BR) dss)
haftmann@28054
   345
          | pr_dict fxy (DictVar (classrels, v)) =
haftmann@28054
   346
              pr_proj (map deresolve classrels) ((str o pr_dictvar) v)
haftmann@28054
   347
      in case ds
haftmann@28054
   348
       of [] => str "()"
haftmann@28054
   349
        | [d] => pr_dict fxy d
haftmann@28054
   350
        | _ :: _ => (Pretty.list "(" ")" o map (pr_dict NOBR)) ds
haftmann@28054
   351
      end;
haftmann@28054
   352
    fun pr_tyvar_dicts vs =
haftmann@28054
   353
      vs
haftmann@28054
   354
      |> map (fn (v, sort) => map_index (fn (i, _) =>
haftmann@28054
   355
           DictVar ([], (v, (i, length sort)))) sort)
haftmann@28054
   356
      |> map (pr_dicts BR);
haftmann@28054
   357
    fun pr_tycoexpr fxy (tyco, tys) =
haftmann@28054
   358
      let
haftmann@28054
   359
        val tyco' = (str o deresolve) tyco
haftmann@28054
   360
      in case map (pr_typ BR) tys
haftmann@28054
   361
       of [] => tyco'
haftmann@28054
   362
        | [p] => Pretty.block [p, Pretty.brk 1, tyco']
haftmann@28054
   363
        | (ps as _::_) => Pretty.block [Pretty.list "(" ")" ps, Pretty.brk 1, tyco']
haftmann@28054
   364
      end
haftmann@28054
   365
    and pr_typ fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@28054
   366
         of NONE => pr_tycoexpr fxy (tyco, tys)
haftmann@28054
   367
          | SOME (i, pr) => pr pr_typ fxy tys)
haftmann@28054
   368
      | pr_typ fxy (ITyVar v) = str ("'" ^ v);
haftmann@28054
   369
    fun pr_term thm pat vars fxy (IConst c) =
haftmann@28054
   370
          pr_app thm pat vars fxy (c, [])
haftmann@28054
   371
      | pr_term thm pat vars fxy (IVar v) =
haftmann@28054
   372
          str (lookup_var vars v)
haftmann@28054
   373
      | pr_term thm pat vars fxy (t as t1 `$ t2) =
haftmann@28054
   374
          (case Code_Thingol.unfold_const_app t
haftmann@28054
   375
           of SOME c_ts => pr_app thm pat vars fxy c_ts
haftmann@28054
   376
            | NONE =>
haftmann@28054
   377
                brackify fxy [pr_term thm pat vars NOBR t1, pr_term thm pat vars BR t2])
haftmann@28054
   378
      | pr_term thm pat vars fxy (t as _ `|-> _) =
haftmann@28054
   379
          let
haftmann@28054
   380
            val (binds, t') = Code_Thingol.unfold_abs t;
haftmann@28054
   381
            fun pr ((v, pat), ty) = pr_bind thm BR ((SOME v, pat), ty);
haftmann@28054
   382
            val (ps, vars') = fold_map pr binds vars;
haftmann@28054
   383
          in brackets (str "fun" :: ps @ str "->" @@ pr_term thm pat vars' NOBR t') end
haftmann@28054
   384
      | pr_term thm pat vars fxy (ICase (cases as (_, t0))) = (case Code_Thingol.unfold_const_app t0
haftmann@28054
   385
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@28054
   386
                then pr_case thm vars fxy cases
haftmann@28054
   387
                else pr_app thm pat vars fxy c_ts
haftmann@28054
   388
            | NONE => pr_case thm vars fxy cases)
haftmann@28054
   389
    and pr_app' thm pat vars (app as ((c, (iss, tys)), ts)) =
haftmann@28054
   390
      if is_cons c then
haftmann@28054
   391
        if length tys = length ts
haftmann@28054
   392
        then case ts
haftmann@28054
   393
         of [] => [(str o deresolve) c]
haftmann@28054
   394
          | [t] => [(str o deresolve) c, pr_term thm pat vars BR t]
haftmann@28054
   395
          | _ => [(str o deresolve) c, Pretty.enum "," "(" ")"
haftmann@28054
   396
                    (map (pr_term thm pat vars NOBR) ts)]
haftmann@28054
   397
        else [pr_term thm pat vars BR (Code_Thingol.eta_expand (length tys) app)]
haftmann@28054
   398
      else (str o deresolve) c
haftmann@28054
   399
        :: ((map (pr_dicts BR) o filter_out null) iss @ map (pr_term thm pat vars BR) ts)
haftmann@28054
   400
    and pr_app thm pat vars = gen_pr_app pr_app' pr_term syntax_const is_cons thm pat vars
haftmann@28054
   401
    and pr_bind' ((NONE, NONE), _) = str "_"
haftmann@28054
   402
      | pr_bind' ((SOME v, NONE), _) = str v
haftmann@28054
   403
      | pr_bind' ((NONE, SOME p), _) = p
haftmann@28054
   404
      | pr_bind' ((SOME v, SOME p), _) = brackets [p, str "as", str v]
haftmann@28054
   405
    and pr_bind thm = gen_pr_bind pr_bind' pr_term thm
haftmann@28054
   406
    and pr_case thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
   407
          let
haftmann@28054
   408
            val (binds, t') = Code_Thingol.unfold_let (ICase cases);
haftmann@28054
   409
            fun pr ((pat, ty), t) vars =
haftmann@28054
   410
              vars
haftmann@28054
   411
              |> pr_bind thm NOBR ((NONE, SOME pat), ty)
haftmann@28054
   412
              |>> (fn p => concat
haftmann@28054
   413
                  [str "let", p, str "=", pr_term thm false vars NOBR t, str "in"])
haftmann@28054
   414
            val (ps, vars') = fold_map pr binds vars;
haftmann@28054
   415
          in Pretty.chunks (ps @| pr_term thm false vars' NOBR t') end
haftmann@28054
   416
      | pr_case thm vars fxy (((td, ty), b::bs), _) =
haftmann@28054
   417
          let
haftmann@28054
   418
            fun pr delim (pat, t) =
haftmann@28054
   419
              let
haftmann@28054
   420
                val (p, vars') = pr_bind thm NOBR ((NONE, SOME pat), ty) vars;
haftmann@28054
   421
              in concat [str delim, p, str "->", pr_term thm false vars' NOBR t] end;
haftmann@28054
   422
          in
haftmann@28054
   423
            (Pretty.enclose "(" ")" o single o brackify fxy) (
haftmann@28054
   424
              str "match"
haftmann@28054
   425
              :: pr_term thm false vars NOBR td
haftmann@28054
   426
              :: pr "with" b
haftmann@28054
   427
              :: map (pr "|") bs
haftmann@28054
   428
            )
haftmann@28054
   429
          end
haftmann@28054
   430
      | pr_case thm vars fxy ((_, []), _) = str "failwith \"empty case\"";
haftmann@28054
   431
    fun fish_params vars eqs =
haftmann@28054
   432
      let
haftmann@28054
   433
        fun fish_param _ (w as SOME _) = w
haftmann@28054
   434
          | fish_param (IVar v) NONE = SOME v
haftmann@28054
   435
          | fish_param _ NONE = NONE;
haftmann@28054
   436
        fun fillup_param _ (_, SOME v) = v
haftmann@28054
   437
          | fillup_param x (i, NONE) = x ^ string_of_int i;
haftmann@28054
   438
        val fished1 = fold (map2 fish_param) eqs (replicate (length (hd eqs)) NONE);
haftmann@28054
   439
        val x = Name.variant (map_filter I fished1) "x";
haftmann@28054
   440
        val fished2 = map_index (fillup_param x) fished1;
haftmann@28054
   441
        val (fished3, _) = Name.variants fished2 Name.context;
haftmann@28054
   442
        val vars' = intro_vars fished3 vars;
haftmann@28054
   443
      in map (lookup_var vars') fished3 end;
haftmann@28054
   444
    fun pr_stmt (MLFuns (funns as funn :: funns')) =
haftmann@28054
   445
          let
haftmann@28054
   446
            fun pr_eq ((ts, t), thm) =
haftmann@28054
   447
              let
haftmann@28054
   448
                val consts = map_filter
haftmann@28054
   449
                  (fn c => if (is_some o syntax_const) c
haftmann@28054
   450
                    then NONE else (SOME o NameSpace.base o deresolve) c)
haftmann@28054
   451
                    ((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@28054
   452
                val vars = reserved_names
haftmann@28054
   453
                  |> intro_vars consts
haftmann@28054
   454
                  |> intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
haftmann@28054
   455
                      (insert (op =)) ts []);
haftmann@28054
   456
              in concat [
haftmann@28054
   457
                (Pretty.block o Pretty.commas) (map (pr_term thm true vars NOBR) ts),
haftmann@28054
   458
                str "->",
haftmann@28054
   459
                pr_term thm false vars NOBR t
haftmann@28054
   460
              ] end;
haftmann@28054
   461
            fun pr_eqs name ty [] =
haftmann@28054
   462
                  let
haftmann@28054
   463
                    val n = (length o fst o Code_Thingol.unfold_fun) ty;
haftmann@28054
   464
                    val exc_str =
haftmann@28054
   465
                      (ML_Syntax.print_string o NameSpace.base o NameSpace.qualifier) name;
haftmann@28054
   466
                  in
haftmann@28054
   467
                    concat (
haftmann@28054
   468
                      map str (replicate n "_")
haftmann@28054
   469
                      @ str "="
haftmann@28054
   470
                      :: str "failwith"
haftmann@28054
   471
                      @@ str exc_str
haftmann@28054
   472
                    )
haftmann@28054
   473
                  end
haftmann@28054
   474
              | pr_eqs _ _ [((ts, t), thm)] =
haftmann@28054
   475
                  let
haftmann@28054
   476
                    val consts = map_filter
haftmann@28054
   477
                      (fn c => if (is_some o syntax_const) c
haftmann@28054
   478
                        then NONE else (SOME o NameSpace.base o deresolve) c)
haftmann@28054
   479
                        ((fold o Code_Thingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@28054
   480
                    val vars = reserved_names
haftmann@28054
   481
                      |> intro_vars consts
haftmann@28054
   482
                      |> intro_vars ((fold o Code_Thingol.fold_unbound_varnames)
haftmann@28054
   483
                          (insert (op =)) ts []);
haftmann@28054
   484
                  in
haftmann@28054
   485
                    concat (
haftmann@28054
   486
                      map (pr_term thm true vars BR) ts
haftmann@28054
   487
                      @ str "="
haftmann@28054
   488
                      @@ pr_term thm false vars NOBR t
haftmann@28054
   489
                    )
haftmann@28054
   490
                  end
haftmann@28054
   491
              | pr_eqs _ _ (eqs as (eq as (([_], _), _)) :: eqs') =
haftmann@28054
   492
                  Pretty.block (
haftmann@28054
   493
                    str "="
haftmann@28054
   494
                    :: Pretty.brk 1
haftmann@28054
   495
                    :: str "function"
haftmann@28054
   496
                    :: Pretty.brk 1
haftmann@28054
   497
                    :: pr_eq eq
haftmann@28054
   498
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@28054
   499
                          o single o pr_eq) eqs'
haftmann@28054
   500
                  )
haftmann@28054
   501
              | pr_eqs _ _ (eqs as eq :: eqs') =
haftmann@28054
   502
                  let
haftmann@28054
   503
                    val consts = map_filter
haftmann@28054
   504
                      (fn c => if (is_some o syntax_const) c
haftmann@28054
   505
                        then NONE else (SOME o NameSpace.base o deresolve) c)
haftmann@28054
   506
                        ((fold o Code_Thingol.fold_constnames)
haftmann@28054
   507
                          (insert (op =)) (map (snd o fst) eqs) []);
haftmann@28054
   508
                    val vars = reserved_names
haftmann@28054
   509
                      |> intro_vars consts;
haftmann@28054
   510
                    val dummy_parms = (map str o fish_params vars o map (fst o fst)) eqs;
haftmann@28054
   511
                  in
haftmann@28054
   512
                    Pretty.block (
haftmann@28054
   513
                      Pretty.breaks dummy_parms
haftmann@28054
   514
                      @ Pretty.brk 1
haftmann@28054
   515
                      :: str "="
haftmann@28054
   516
                      :: Pretty.brk 1
haftmann@28054
   517
                      :: str "match"
haftmann@28054
   518
                      :: Pretty.brk 1
haftmann@28054
   519
                      :: (Pretty.block o Pretty.commas) dummy_parms
haftmann@28054
   520
                      :: Pretty.brk 1
haftmann@28054
   521
                      :: str "with"
haftmann@28054
   522
                      :: Pretty.brk 1
haftmann@28054
   523
                      :: pr_eq eq
haftmann@28054
   524
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1]
haftmann@28054
   525
                           o single o pr_eq) eqs'
haftmann@28054
   526
                    )
haftmann@28054
   527
                  end;
haftmann@28054
   528
            fun pr_funn definer (name, ((vs, ty), eqs)) =
haftmann@28054
   529
              concat (
haftmann@28054
   530
                str definer
haftmann@28054
   531
                :: (str o deresolve) name
haftmann@28054
   532
                :: pr_tyvar_dicts (filter_out (null o snd) vs)
haftmann@28054
   533
                @| pr_eqs name ty eqs
haftmann@28054
   534
              );
haftmann@28054
   535
            val (ps, p) = split_last
haftmann@28054
   536
              (pr_funn "let rec" funn :: map (pr_funn "and") funns');
haftmann@28054
   537
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";;"])]) end
haftmann@28054
   538
     | pr_stmt (MLDatas (datas as (data :: datas'))) =
haftmann@28054
   539
          let
haftmann@28054
   540
            fun pr_co (co, []) =
haftmann@28054
   541
                  str (deresolve co)
haftmann@28054
   542
              | pr_co (co, tys) =
haftmann@28054
   543
                  concat [
haftmann@28054
   544
                    str (deresolve co),
haftmann@28054
   545
                    str "of",
haftmann@28054
   546
                    Pretty.enum " *" "" "" (map (pr_typ (INFX (2, X))) tys)
haftmann@28054
   547
                  ];
haftmann@28054
   548
            fun pr_data definer (tyco, (vs, [])) =
haftmann@28054
   549
                  concat (
haftmann@28054
   550
                    str definer
haftmann@28054
   551
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   552
                    :: str "="
haftmann@28054
   553
                    @@ str "EMPTY_"
haftmann@28054
   554
                  )
haftmann@28054
   555
              | pr_data definer (tyco, (vs, cos)) =
haftmann@28054
   556
                  concat (
haftmann@28054
   557
                    str definer
haftmann@28054
   558
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@28054
   559
                    :: str "="
haftmann@28054
   560
                    :: separate (str "|") (map pr_co cos)
haftmann@28054
   561
                  );
haftmann@28054
   562
            val (ps, p) = split_last
haftmann@28054
   563
              (pr_data "type" data :: map (pr_data "and") datas');
haftmann@28054
   564
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";;"])]) end
haftmann@28054
   565
     | pr_stmt (MLClass (class, (v, (superclasses, classparams)))) =
haftmann@28054
   566
          let
haftmann@28054
   567
            val w = "_" ^ first_upper v;
haftmann@28054
   568
            fun pr_superclass_field (class, classrel) =
haftmann@28054
   569
              (concat o map str) [
haftmann@28054
   570
                deresolve classrel, ":", "'" ^ v, deresolve class
haftmann@28054
   571
              ];
haftmann@28054
   572
            fun pr_classparam_field (classparam, ty) =
haftmann@28054
   573
              concat [
haftmann@28054
   574
                (str o deresolve) classparam, str ":", pr_typ NOBR ty
haftmann@28054
   575
              ];
haftmann@28054
   576
            fun pr_classparam_proj (classparam, _) =
haftmann@28054
   577
              concat [
haftmann@28054
   578
                str "let",
haftmann@28054
   579
                (str o deresolve) classparam,
haftmann@28054
   580
                str w,
haftmann@28054
   581
                str "=",
haftmann@28054
   582
                str (w ^ "." ^ deresolve classparam ^ ";;")
haftmann@28054
   583
              ];
haftmann@28054
   584
          in Pretty.chunks (
haftmann@28054
   585
            concat [
haftmann@28054
   586
              str ("type '" ^ v),
haftmann@28054
   587
              (str o deresolve) class,
haftmann@28054
   588
              str "=",
haftmann@28054
   589
              enum_default "();;" ";" "{" "};;" (
haftmann@28054
   590
                map pr_superclass_field superclasses
haftmann@28054
   591
                @ map pr_classparam_field classparams
haftmann@28054
   592
              )
haftmann@28054
   593
            ]
haftmann@28054
   594
            :: map pr_classparam_proj classparams
haftmann@28054
   595
          ) end
haftmann@28054
   596
     | pr_stmt (MLClassinst (inst, ((class, (tyco, arity)), (superarities, classparam_insts)))) =
haftmann@28054
   597
          let
haftmann@28054
   598
            fun pr_superclass (_, (classrel, dss)) =
haftmann@28054
   599
              concat [
haftmann@28054
   600
                (str o deresolve) classrel,
haftmann@28054
   601
                str "=",
haftmann@28054
   602
                pr_dicts NOBR [DictConst dss]
haftmann@28054
   603
              ];
haftmann@28054
   604
            fun pr_classparam_inst ((classparam, c_inst), thm) =
haftmann@28054
   605
              concat [
haftmann@28054
   606
                (str o deresolve) classparam,
haftmann@28054
   607
                str "=",
haftmann@28054
   608
                pr_app thm false reserved_names NOBR (c_inst, [])
haftmann@28054
   609
              ];
haftmann@28054
   610
          in
haftmann@28054
   611
            concat (
haftmann@28054
   612
              str "let"
haftmann@28054
   613
              :: (str o deresolve) inst
haftmann@28054
   614
              :: pr_tyvar_dicts arity
haftmann@28054
   615
              @ str "="
haftmann@28054
   616
              @@ (Pretty.enclose "(" ");;" o Pretty.breaks) [
haftmann@28054
   617
                enum_default "()" ";" "{" "}" (map pr_superclass superarities
haftmann@28054
   618
                  @ map pr_classparam_inst classparam_insts),
haftmann@28054
   619
                str ":",
haftmann@28054
   620
                pr_tycoexpr NOBR (class, [tyco `%% map (ITyVar o fst) arity])
haftmann@28054
   621
              ]
haftmann@28054
   622
            )
haftmann@28054
   623
          end;
haftmann@28054
   624
  in pr_stmt end;
haftmann@28054
   625
haftmann@28054
   626
fun pr_ocaml_module name content =
haftmann@28054
   627
  Pretty.chunks (
haftmann@28054
   628
    str ("module " ^ name ^ " = ")
haftmann@28054
   629
    :: str "struct"
haftmann@28054
   630
    :: str ""
haftmann@28054
   631
    :: content
haftmann@28054
   632
    @ str ""
haftmann@28054
   633
    @@ str ("end;; (*struct " ^ name ^ "*)")
haftmann@28054
   634
  );
haftmann@28054
   635
haftmann@28054
   636
haftmann@28054
   637
(** SML/OCaml generic part **)
haftmann@28054
   638
haftmann@28054
   639
local
haftmann@28054
   640
haftmann@28054
   641
datatype ml_node =
haftmann@28054
   642
    Dummy of string
haftmann@28054
   643
  | Stmt of string * ml_stmt
haftmann@28054
   644
  | Module of string * ((Name.context * Name.context) * ml_node Graph.T);
haftmann@28054
   645
haftmann@28054
   646
in
haftmann@28054
   647
haftmann@28054
   648
fun ml_node_of_program labelled_name module_name reserved_names raw_module_alias program =
haftmann@28054
   649
  let
haftmann@28054
   650
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@28054
   651
    val reserved_names = Name.make_context reserved_names;
haftmann@28054
   652
    val empty_module = ((reserved_names, reserved_names), Graph.empty);
haftmann@28054
   653
    fun map_node [] f = f
haftmann@28054
   654
      | map_node (m::ms) f =
haftmann@28054
   655
          Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   656
          #> Graph.map_node m (fn (Module (module_name, (nsp, nodes))) =>
haftmann@28054
   657
               Module (module_name, (nsp, map_node ms f nodes)));
haftmann@28054
   658
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@28054
   659
          let
haftmann@28054
   660
            val (x, nsp') = f nsp
haftmann@28054
   661
          in (x, (nsp', nodes)) end
haftmann@28054
   662
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@28054
   663
          let
haftmann@28054
   664
            val (x, nodes') =
haftmann@28054
   665
              nodes
haftmann@28054
   666
              |> Graph.default_node (m, Module (m, empty_module))
haftmann@28054
   667
              |> Graph.map_node_yield m (fn Module (d_module_name, nsp_nodes) => 
haftmann@28054
   668
                  let
haftmann@28054
   669
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@28054
   670
                  in (x, Module (d_module_name, nsp_nodes')) end)
haftmann@28054
   671
          in (x, (nsp, nodes')) end;
haftmann@28054
   672
    fun map_nsp_fun_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   673
      let
haftmann@28054
   674
        val (x, nsp_fun') = f nsp_fun
haftmann@28054
   675
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@28054
   676
    fun map_nsp_typ_yield f (nsp_fun, nsp_typ) =
haftmann@28054
   677
      let
haftmann@28054
   678
        val (x, nsp_typ') = f nsp_typ
haftmann@28054
   679
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@28054
   680
    val mk_name_module = mk_name_module reserved_names NONE module_alias program;
haftmann@28054
   681
    fun mk_name_stmt upper name nsp =
haftmann@28054
   682
      let
haftmann@28054
   683
        val (_, base) = dest_name name;
haftmann@28054
   684
        val base' = if upper then first_upper base else base;
haftmann@28054
   685
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@28054
   686
      in (base'', nsp') end;
haftmann@28054
   687
    fun add_funs stmts =
haftmann@28054
   688
      fold_map
haftmann@28054
   689
        (fn (name, Code_Thingol.Fun stmt) =>
haftmann@28054
   690
              map_nsp_fun_yield (mk_name_stmt false name) #>>
haftmann@28054
   691
                rpair (name, stmt)
haftmann@28054
   692
          | (name, _) =>
haftmann@28054
   693
              error ("Function block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   694
        ) stmts
haftmann@28054
   695
      #>> (split_list #> apsnd MLFuns);
haftmann@28054
   696
    fun add_datatypes stmts =
haftmann@28054
   697
      fold_map
haftmann@28054
   698
        (fn (name, Code_Thingol.Datatype stmt) =>
haftmann@28054
   699
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, stmt))
haftmann@28054
   700
          | (name, Code_Thingol.Datatypecons _) =>
haftmann@28054
   701
              map_nsp_fun_yield (mk_name_stmt true name) #>> rpair NONE
haftmann@28054
   702
          | (name, _) =>
haftmann@28054
   703
              error ("Datatype block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   704
        ) stmts
haftmann@28054
   705
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   706
        #> (fn [] => error ("Datatype block without data statement: "
haftmann@28054
   707
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@28054
   708
             | stmts => MLDatas stmts)));
haftmann@28054
   709
    fun add_class stmts =
haftmann@28054
   710
      fold_map
haftmann@28054
   711
        (fn (name, Code_Thingol.Class info) =>
haftmann@28054
   712
              map_nsp_typ_yield (mk_name_stmt false name) #>> rpair (SOME (name, info))
haftmann@28054
   713
          | (name, Code_Thingol.Classrel _) =>
haftmann@28054
   714
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   715
          | (name, Code_Thingol.Classparam _) =>
haftmann@28054
   716
              map_nsp_fun_yield (mk_name_stmt false name) #>> rpair NONE
haftmann@28054
   717
          | (name, _) =>
haftmann@28054
   718
              error ("Class block containing illegal statement: " ^ labelled_name name)
haftmann@28054
   719
        ) stmts
haftmann@28054
   720
      #>> (split_list #> apsnd (map_filter I
haftmann@28054
   721
        #> (fn [] => error ("Class block without class statement: "
haftmann@28054
   722
                  ^ (commas o map (labelled_name o fst)) stmts)
haftmann@28054
   723
             | [stmt] => MLClass stmt)));
haftmann@28054
   724
    fun add_inst [(name, Code_Thingol.Classinst stmt)] =
haftmann@28054
   725
      map_nsp_fun_yield (mk_name_stmt false name)
haftmann@28054
   726
      #>> (fn base => ([base], MLClassinst (name, stmt)));
haftmann@28054
   727
    fun add_stmts ((stmts as (_, Code_Thingol.Fun _)::_)) =
haftmann@28054
   728
          add_funs stmts
haftmann@28054
   729
      | add_stmts ((stmts as (_, Code_Thingol.Datatypecons _)::_)) =
haftmann@28054
   730
          add_datatypes stmts
haftmann@28054
   731
      | add_stmts ((stmts as (_, Code_Thingol.Datatype _)::_)) =
haftmann@28054
   732
          add_datatypes stmts
haftmann@28054
   733
      | add_stmts ((stmts as (_, Code_Thingol.Class _)::_)) =
haftmann@28054
   734
          add_class stmts
haftmann@28054
   735
      | add_stmts ((stmts as (_, Code_Thingol.Classrel _)::_)) =
haftmann@28054
   736
          add_class stmts
haftmann@28054
   737
      | add_stmts ((stmts as (_, Code_Thingol.Classparam _)::_)) =
haftmann@28054
   738
          add_class stmts
haftmann@28054
   739
      | add_stmts ((stmts as [(_, Code_Thingol.Classinst _)])) =
haftmann@28054
   740
          add_inst stmts
haftmann@28054
   741
      | add_stmts stmts = error ("Illegal mutual dependencies: " ^
haftmann@28054
   742
          (commas o map (labelled_name o fst)) stmts);
haftmann@28054
   743
    fun add_stmts' stmts nsp_nodes =
haftmann@28054
   744
      let
haftmann@28054
   745
        val names as (name :: names') = map fst stmts;
haftmann@28054
   746
        val deps =
haftmann@28054
   747
          []
haftmann@28054
   748
          |> fold (fold (insert (op =)) o Graph.imm_succs program) names
haftmann@28054
   749
          |> subtract (op =) names;
haftmann@28054
   750
        val (module_names, _) = (split_list o map dest_name) names;
haftmann@28054
   751
        val module_name = (the_single o distinct (op =) o map mk_name_module) module_names
haftmann@28054
   752
          handle Empty =>
haftmann@28054
   753
            error ("Different namespace prefixes for mutual dependencies:\n"
haftmann@28054
   754
              ^ commas (map labelled_name names)
haftmann@28054
   755
              ^ "\n"
haftmann@28054
   756
              ^ commas module_names);
haftmann@28054
   757
        val module_name_path = NameSpace.explode module_name;
haftmann@28054
   758
        fun add_dep name name' =
haftmann@28054
   759
          let
haftmann@28054
   760
            val module_name' = (mk_name_module o fst o dest_name) name';
haftmann@28054
   761
          in if module_name = module_name' then
haftmann@28054
   762
            map_node module_name_path (Graph.add_edge (name, name'))
haftmann@28054
   763
          else let
haftmann@28054
   764
            val (common, (diff1::_, diff2::_)) = chop_prefix (op =)
haftmann@28054
   765
              (module_name_path, NameSpace.explode module_name');
haftmann@28054
   766
          in
haftmann@28054
   767
            map_node common
haftmann@28054
   768
              (fn node => Graph.add_edge_acyclic (diff1, diff2) node
haftmann@28054
   769
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@28054
   770
                  ^ quote name ^ " -> " ^ quote name'
haftmann@28054
   771
                  ^ " would result in module dependency cycle"))
haftmann@28054
   772
          end end;
haftmann@28054
   773
      in
haftmann@28054
   774
        nsp_nodes
haftmann@28054
   775
        |> map_nsp_yield module_name_path (add_stmts stmts)
haftmann@28054
   776
        |-> (fn (base' :: bases', stmt') =>
haftmann@28054
   777
           apsnd (map_node module_name_path (Graph.new_node (name, (Stmt (base', stmt')))
haftmann@28054
   778
              #> fold2 (fn name' => fn base' =>
haftmann@28054
   779
                   Graph.new_node (name', (Dummy base'))) names' bases')))
haftmann@28054
   780
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@28054
   781
        |> apsnd (fold_product (curry (map_node module_name_path o Graph.add_edge)) names names)
haftmann@28054
   782
      end;
haftmann@28054
   783
    val (_, nodes) = empty_module
haftmann@28054
   784
      |> fold add_stmts' (map (AList.make (Graph.get_node program))
haftmann@28054
   785
          (rev (Graph.strong_conn program)));
haftmann@28054
   786
    fun deresolver prefix name = 
haftmann@28054
   787
      let
haftmann@28054
   788
        val module_name = (fst o dest_name) name;
haftmann@28054
   789
        val module_name' = (NameSpace.explode o mk_name_module) module_name;
haftmann@28054
   790
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, module_name');
haftmann@28054
   791
        val stmt_name =
haftmann@28054
   792
          nodes
haftmann@28054
   793
          |> fold (fn name => fn node => case Graph.get_node node name
haftmann@28054
   794
              of Module (_, (_, node)) => node) module_name'
haftmann@28054
   795
          |> (fn node => case Graph.get_node node name of Stmt (stmt_name, _) => stmt_name
haftmann@28054
   796
               | Dummy stmt_name => stmt_name);
haftmann@28054
   797
      in
haftmann@28054
   798
        NameSpace.implode (remainder @ [stmt_name])
haftmann@28054
   799
      end handle Graph.UNDEF _ =>
haftmann@28054
   800
        error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   801
  in (deresolver, nodes) end;
haftmann@28054
   802
haftmann@28054
   803
fun serialize_ml target compile pr_module pr_stmt raw_module_name labelled_name reserved_names includes raw_module_alias
haftmann@28054
   804
  _ syntax_tyco syntax_const program cs destination =
haftmann@28054
   805
  let
haftmann@28054
   806
    val is_cons = Code_Thingol.is_cons program;
haftmann@28054
   807
    val stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@28054
   808
    val module_name = if null stmt_names then raw_module_name else SOME "Code";
haftmann@28054
   809
    val (deresolver, nodes) = ml_node_of_program labelled_name module_name
haftmann@28054
   810
      reserved_names raw_module_alias program;
haftmann@28054
   811
    val reserved_names = make_vars reserved_names;
haftmann@28054
   812
    fun pr_node prefix (Dummy _) =
haftmann@28054
   813
          NONE
haftmann@28054
   814
      | pr_node prefix (Stmt (_, stmt)) = if null stmt_names orelse
haftmann@28054
   815
          (not o null o filter (member (op =) stmt_names) o stmt_names_of) stmt then SOME
haftmann@28054
   816
            (pr_stmt syntax_tyco syntax_const labelled_name reserved_names
haftmann@28054
   817
              (deresolver prefix) is_cons stmt)
haftmann@28054
   818
          else NONE
haftmann@28054
   819
      | pr_node prefix (Module (module_name, (_, nodes))) =
haftmann@28054
   820
          separate (str "")
haftmann@28054
   821
            ((map_filter (pr_node (prefix @ [module_name]) o Graph.get_node nodes)
haftmann@28054
   822
              o rev o flat o Graph.strong_conn) nodes)
haftmann@28054
   823
          |> (if null stmt_names then pr_module module_name else Pretty.chunks)
haftmann@28054
   824
          |> SOME;
haftmann@28054
   825
    val cs' = map_filter (try (deresolver (if is_some module_name then the_list module_name else [])))
haftmann@28054
   826
      cs;
haftmann@28054
   827
    val p = Pretty.chunks (separate (str "") (map snd includes @ (map_filter
haftmann@28054
   828
      (pr_node [] o Graph.get_node nodes) o rev o flat o Graph.strong_conn) nodes));
haftmann@28054
   829
  in
haftmann@28054
   830
    Code_Target.mk_serialization target
haftmann@28054
   831
      (case compile of SOME compile => SOME (compile o Code_Target.code_of_pretty) | NONE => NONE)
haftmann@28054
   832
      (fn NONE => Code_Target.code_writeln | SOME file => File.write file o Code_Target.code_of_pretty)
haftmann@28054
   833
      (rpair cs' o Code_Target.code_of_pretty) p destination
haftmann@28054
   834
  end;
haftmann@28054
   835
haftmann@28054
   836
end; (*local*)
haftmann@28054
   837
haftmann@28054
   838
haftmann@28054
   839
(** ML (system language) code for evaluation and instrumentalization **)
haftmann@28054
   840
haftmann@28054
   841
fun ml_code_of thy = Code_Target.serialize_custom thy
haftmann@28054
   842
  (target_SML, (fn _ => fn [] => serialize_ml target_SML (SOME (K ())) (K Pretty.chunks) pr_sml_stmt (SOME "")));
haftmann@28054
   843
haftmann@28054
   844
haftmann@28054
   845
(* evaluation *)
haftmann@28054
   846
haftmann@28054
   847
fun eval eval'' term_of reff thy ct args =
haftmann@28054
   848
  let
haftmann@28054
   849
    val _ = if null (term_frees (term_of ct)) then () else error ("Term "
haftmann@28054
   850
      ^ quote (Syntax.string_of_term_global thy (term_of ct))
haftmann@28054
   851
      ^ " to be evaluated contains free variables");
haftmann@28054
   852
    fun eval' program ((vs, ty), t) deps =
haftmann@28054
   853
      let
haftmann@28054
   854
        val _ = if Code_Thingol.contains_dictvar t then
haftmann@28054
   855
          error "Term to be evaluated constains free dictionaries" else ();
haftmann@28054
   856
        val program' = program
haftmann@28054
   857
          |> Graph.new_node (Code_Name.value_name, Code_Thingol.Fun (([], ty), [(([], t), Drule.dummy_thm)]))
haftmann@28054
   858
          |> fold (curry Graph.add_edge Code_Name.value_name) deps;
haftmann@28054
   859
        val (value_code, [value_name']) = ml_code_of thy program' [Code_Name.value_name];
haftmann@28054
   860
        val sml_code = "let\n" ^ value_code ^ "\nin " ^ value_name'
haftmann@28054
   861
          ^ space_implode " " (map (enclose "(" ")") args) ^ " end";
haftmann@28054
   862
      in ML_Context.evaluate Output.ml_output false reff sml_code end;
haftmann@28054
   863
  in eval'' thy (fn t => (t, eval')) ct end;
haftmann@28054
   864
haftmann@28054
   865
fun eval_conv reff = eval Code_Thingol.eval_conv Thm.term_of reff;
haftmann@28054
   866
fun eval_term reff = eval Code_Thingol.eval_term I reff;
haftmann@28054
   867
haftmann@28054
   868
haftmann@28054
   869
(* instrumentalization by antiquotation *)
haftmann@28054
   870
haftmann@28054
   871
local
haftmann@28054
   872
haftmann@28054
   873
structure CodeAntiqData = ProofDataFun
haftmann@28054
   874
(
haftmann@28054
   875
  type T = string list * (bool * (string * (string * (string * string) list) Susp.T));
haftmann@28054
   876
  fun init _ = ([], (true, ("", Susp.value ("", []))));
haftmann@28054
   877
);
haftmann@28054
   878
haftmann@28054
   879
val is_first_occ = fst o snd o CodeAntiqData.get;
haftmann@28054
   880
haftmann@28054
   881
fun delayed_code thy consts () =
haftmann@28054
   882
  let
haftmann@28054
   883
    val (consts', program) = Code_Thingol.consts_program thy consts;
haftmann@28054
   884
    val (ml_code, consts'') = ml_code_of thy program consts';
haftmann@28054
   885
    val _ = if length consts <> length consts'' then
haftmann@28054
   886
      error ("One of the constants " ^ commas (map (quote o Code_Unit.string_of_const thy) consts)
haftmann@28054
   887
        ^ "\nhas a user-defined serialization") else ();
haftmann@28054
   888
  in (ml_code, consts ~~ consts'') end;
haftmann@28054
   889
haftmann@28054
   890
fun register_const const ctxt =
haftmann@28054
   891
  let
haftmann@28054
   892
    val (consts, (_, (struct_name, _))) = CodeAntiqData.get ctxt;
haftmann@28054
   893
    val consts' = insert (op =) const consts;
haftmann@28054
   894
    val (struct_name', ctxt') = if struct_name = ""
haftmann@28054
   895
      then ML_Antiquote.variant "Code" ctxt
haftmann@28054
   896
      else (struct_name, ctxt);
haftmann@28054
   897
    val acc_code = Susp.delay (delayed_code (ProofContext.theory_of ctxt) consts');
haftmann@28054
   898
  in CodeAntiqData.put (consts', (false, (struct_name', acc_code))) ctxt' end;
haftmann@28054
   899
haftmann@28054
   900
fun print_code struct_name is_first const ctxt =
haftmann@28054
   901
  let
haftmann@28054
   902
    val (consts, (_, (struct_code_name, acc_code))) = CodeAntiqData.get ctxt;
haftmann@28054
   903
    val (raw_ml_code, consts_map) = Susp.force acc_code;
haftmann@28054
   904
    val const'' = NameSpace.append (NameSpace.append struct_name struct_code_name)
haftmann@28054
   905
      ((the o AList.lookup (op =) consts_map) const);
haftmann@28054
   906
    val ml_code = if is_first then "\nstructure " ^ struct_code_name
haftmann@28054
   907
        ^ " =\nstruct\n\n" ^ raw_ml_code ^ "\nend;\n\n"
haftmann@28054
   908
      else "";
haftmann@28054
   909
  in (ml_code, const'') end;
haftmann@28054
   910
haftmann@28054
   911
in
haftmann@28054
   912
haftmann@28054
   913
fun ml_code_antiq raw_const {struct_name, background} =
haftmann@28054
   914
  let
haftmann@28054
   915
    val const = Code_Unit.check_const (ProofContext.theory_of background) raw_const;
haftmann@28054
   916
    val is_first = is_first_occ background;
haftmann@28054
   917
    val background' = register_const const background;
haftmann@28054
   918
  in (print_code struct_name is_first const, background') end;
haftmann@28054
   919
haftmann@28054
   920
end; (*local*)
haftmann@28054
   921
haftmann@28054
   922
haftmann@28054
   923
(** Isar setup **)
haftmann@28054
   924
haftmann@28054
   925
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@28054
   926
haftmann@28054
   927
fun isar_seri_sml module_name =
haftmann@28054
   928
  Code_Target.parse_args (Scan.succeed ())
haftmann@28054
   929
  #> (fn () => serialize_ml target_SML (SOME (use_text (1, "generated code") Output.ml_output false))
haftmann@28054
   930
      pr_sml_module pr_sml_stmt module_name);
haftmann@28054
   931
haftmann@28054
   932
fun isar_seri_ocaml module_name =
haftmann@28054
   933
  Code_Target.parse_args (Scan.succeed ())
haftmann@28054
   934
  #> (fn () => serialize_ml target_OCaml NONE
haftmann@28054
   935
      pr_ocaml_module pr_ocaml_stmt module_name);
haftmann@28054
   936
haftmann@28054
   937
val setup =
haftmann@28054
   938
  Code_Target.add_target (target_SML, isar_seri_sml)
haftmann@28054
   939
  #> Code_Target.add_target (target_OCaml, isar_seri_ocaml)
haftmann@28054
   940
  #> Code_Target.add_syntax_tyco target_SML "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
   941
      brackify_infix (1, R) fxy [
haftmann@28054
   942
        pr_typ (INFX (1, X)) ty1,
haftmann@28054
   943
        str "->",
haftmann@28054
   944
        pr_typ (INFX (1, R)) ty2
haftmann@28054
   945
      ]))
haftmann@28054
   946
  #> Code_Target.add_syntax_tyco target_OCaml "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
   947
      brackify_infix (1, R) fxy [
haftmann@28054
   948
        pr_typ (INFX (1, X)) ty1,
haftmann@28054
   949
        str "->",
haftmann@28054
   950
        pr_typ (INFX (1, R)) ty2
haftmann@28054
   951
      ]))
haftmann@28054
   952
  #> fold (Code_Target.add_reserved target_SML) ML_Syntax.reserved_names
haftmann@28054
   953
  #> fold (Code_Target.add_reserved target_SML)
haftmann@28054
   954
      ["o" (*dictionary projections use it already*), "Fail", "div", "mod" (*standard infixes*)]
haftmann@28054
   955
  #> fold (Code_Target.add_reserved target_OCaml) [
haftmann@28054
   956
      "and", "as", "assert", "begin", "class",
haftmann@28054
   957
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@28054
   958
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@28054
   959
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@28054
   960
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@28054
   961
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@28054
   962
      "virtual", "when", "while", "with"
haftmann@28054
   963
    ]
haftmann@28054
   964
  #> fold (Code_Target.add_reserved target_OCaml) ["failwith", "mod"];
haftmann@28054
   965
haftmann@28054
   966
end; (*struct*)