src/Tools/nbe.ML
author haftmann
Fri Oct 19 16:20:27 2007 +0200 (2007-10-19)
changeset 25101 cae0f68b693b
parent 25098 1ec53c9ae71a
child 25167 0fd59d8e2bad
permissions -rw-r--r--
now employing dictionaries
haftmann@24590
     1
(*  Title:      Tools/nbe.ML
haftmann@24155
     2
    ID:         $Id$
haftmann@24155
     3
    Authors:    Klaus Aehlig, LMU Muenchen; Tobias Nipkow, Florian Haftmann, TU Muenchen
haftmann@24155
     4
haftmann@24839
     5
Normalization by evaluation, based on generic code generator.
haftmann@24155
     6
*)
haftmann@24155
     7
haftmann@24155
     8
signature NBE =
haftmann@24155
     9
sig
haftmann@25101
    10
  val norm_conv: cterm -> thm
haftmann@25101
    11
  val norm_term: theory -> term -> term
haftmann@25101
    12
haftmann@24155
    13
  datatype Univ = 
haftmann@24381
    14
      Const of string * Univ list            (*named (uninterpreted) constants*)
haftmann@24155
    15
    | Free of string * Univ list
haftmann@25101
    16
    | DFree of string                        (*free (uninterpreted) dictionary parameters*)
haftmann@24155
    17
    | BVar of int * Univ list
haftmann@24155
    18
    | Abs of (int * (Univ list -> Univ)) * Univ list;
haftmann@25101
    19
  val free: string -> Univ                   (*free (uninterpreted) variables*)
haftmann@24155
    20
  val app: Univ -> Univ -> Univ              (*explicit application*)
haftmann@25101
    21
  val abs: int -> (Univ list -> Univ) -> Univ
haftmann@25101
    22
                                             (*abstractions as closures*)
haftmann@24155
    23
haftmann@24590
    24
  val univs_ref: (unit -> Univ list) ref 
haftmann@24423
    25
  val lookup_fun: string -> Univ
haftmann@24155
    26
haftmann@24155
    27
  val trace: bool ref
haftmann@24155
    28
  val setup: theory -> theory
haftmann@24155
    29
end;
haftmann@24155
    30
haftmann@24155
    31
structure Nbe: NBE =
haftmann@24155
    32
struct
haftmann@24155
    33
haftmann@24155
    34
(* generic non-sense *)
haftmann@24155
    35
haftmann@24155
    36
val trace = ref false;
haftmann@24155
    37
fun tracing f x = if !trace then (Output.tracing (f x); x) else x;
haftmann@24155
    38
haftmann@24155
    39
haftmann@24155
    40
(** the semantical universe **)
haftmann@24155
    41
haftmann@24155
    42
(*
haftmann@24155
    43
   Functions are given by their semantical function value. To avoid
haftmann@24155
    44
   trouble with the ML-type system, these functions have the most
haftmann@24155
    45
   generic type, that is "Univ list -> Univ". The calling convention is
haftmann@24155
    46
   that the arguments come as a list, the last argument first. In
haftmann@24155
    47
   other words, a function call that usually would look like
haftmann@24155
    48
haftmann@24155
    49
   f x_1 x_2 ... x_n   or   f(x_1,x_2, ..., x_n)
haftmann@24155
    50
haftmann@24155
    51
   would be in our convention called as
haftmann@24155
    52
haftmann@24155
    53
              f [x_n,..,x_2,x_1]
haftmann@24155
    54
haftmann@24155
    55
   Moreover, to handle functions that are still waiting for some
haftmann@24155
    56
   arguments we have additionally a list of arguments collected to far
haftmann@24155
    57
   and the number of arguments we're still waiting for.
haftmann@24155
    58
*)
haftmann@24155
    59
haftmann@24155
    60
datatype Univ = 
haftmann@24381
    61
    Const of string * Univ list        (*named (uninterpreted) constants*)
haftmann@24155
    62
  | Free of string * Univ list         (*free variables*)
haftmann@25101
    63
  | DFree of string                    (*free (uninterpreted) dictionary parameters*)
haftmann@24155
    64
  | BVar of int * Univ list            (*bound named variables*)
haftmann@24155
    65
  | Abs of (int * (Univ list -> Univ)) * Univ list
haftmann@24381
    66
                                      (*abstractions as closures*);
haftmann@24155
    67
haftmann@24155
    68
(* constructor functions *)
haftmann@24155
    69
haftmann@25101
    70
fun free v = Free (v, []);
haftmann@25101
    71
fun abs n f = Abs ((n, f), []);
haftmann@24155
    72
fun app (Abs ((1, f), xs)) x = f (x :: xs)
haftmann@24155
    73
  | app (Abs ((n, f), xs)) x = Abs ((n - 1, f), x :: xs)
haftmann@24155
    74
  | app (Const (name, args)) x = Const (name, x :: args)
haftmann@24155
    75
  | app (Free (name, args)) x = Free (name, x :: args)
haftmann@24155
    76
  | app (BVar (name, args)) x = BVar (name, x :: args);
haftmann@24155
    77
haftmann@25101
    78
(* universe graph *)
haftmann@24155
    79
haftmann@25101
    80
type univ_gr = Univ option Graph.T;
haftmann@25101
    81
val compiled : univ_gr -> string -> bool = can o Graph.get_node;
haftmann@24839
    82
haftmann@24155
    83
(* sandbox communication *)
haftmann@24155
    84
haftmann@24590
    85
val univs_ref = ref (fn () => [] : Univ list);
haftmann@24155
    86
haftmann@24155
    87
local
haftmann@24155
    88
haftmann@25101
    89
val gr_ref = ref NONE : univ_gr option ref;
haftmann@24155
    90
haftmann@25101
    91
fun compile gr raw_s = NAMED_CRITICAL "nbe" (fn () =>
haftmann@25080
    92
  let
haftmann@25080
    93
    val _ = univs_ref := (fn () => []);
haftmann@25080
    94
    val s = "Nbe.univs_ref := " ^ raw_s;
haftmann@25080
    95
    val _ = tracing (fn () => "\n--- generated code:\n" ^ s) ();
haftmann@25101
    96
    val _ = gr_ref := SOME gr;
haftmann@25080
    97
    val _ = use_text "" (Output.tracing o enclose "\n---compiler echo:\n" "\n---\n",
haftmann@25080
    98
      Output.tracing o enclose "\n--- compiler echo (with error):\n" "\n---\n")
haftmann@25080
    99
      (!trace) s;
haftmann@25080
   100
    val _ = gr_ref := NONE;
wenzelm@25098
   101
  in !univs_ref end);
haftmann@25101
   102
haftmann@24155
   103
in
haftmann@24155
   104
haftmann@25101
   105
fun lookup_fun s = NAMED_CRITICAL "nbe" (fn () => case ! gr_ref
haftmann@24155
   106
 of NONE => error "compile_univs"
haftmann@25101
   107
  | SOME gr => the (Graph.get_node gr s));
haftmann@24155
   108
haftmann@25101
   109
fun compile_univs gr ([], _) = []
haftmann@25101
   110
  | compile_univs gr (cs, raw_s) = cs ~~ compile gr raw_s ();
haftmann@24155
   111
haftmann@24155
   112
end; (*local*)
haftmann@24155
   113
haftmann@24155
   114
haftmann@24155
   115
(** assembling and compiling ML code from terms **)
haftmann@24155
   116
haftmann@24155
   117
(* abstract ML syntax *)
haftmann@24155
   118
haftmann@24155
   119
infix 9 `$` `$$`;
haftmann@24155
   120
fun e1 `$` e2 = "(" ^ e1 ^ " " ^ e2 ^ ")";
haftmann@25101
   121
fun e `$$` [] = e
haftmann@25101
   122
  | e `$$` es = "(" ^ e ^ " " ^ space_implode " " es ^ ")";
haftmann@24590
   123
fun ml_abs v e = "(fn " ^ v ^ " => " ^ e ^ ")";
haftmann@24155
   124
haftmann@24155
   125
fun ml_Val v s = "val " ^ v ^ " = " ^ s;
haftmann@24155
   126
fun ml_cases t cs =
haftmann@24155
   127
  "(case " ^ t ^ " of " ^ space_implode " | " (map (fn (p, t) => p ^ " => " ^ t) cs) ^ ")";
haftmann@24155
   128
fun ml_Let ds e = "let\n" ^ space_implode "\n" ds ^ " in " ^ e ^ " end";
haftmann@24155
   129
haftmann@24155
   130
fun ml_list es = "[" ^ commas es ^ "]";
haftmann@24155
   131
haftmann@24590
   132
val ml_delay = ml_abs "()"
haftmann@24590
   133
haftmann@24155
   134
fun ml_fundefs ([(name, [([], e)])]) =
haftmann@24155
   135
      "val " ^ name ^ " = " ^ e ^ "\n"
haftmann@24155
   136
  | ml_fundefs (eqs :: eqss) =
haftmann@24155
   137
      let
haftmann@24155
   138
        fun fundef (name, eqs) =
haftmann@24155
   139
          let
haftmann@24155
   140
            fun eqn (es, e) = name ^ " " ^ space_implode " " es ^ " = " ^ e
haftmann@24155
   141
          in space_implode "\n  | " (map eqn eqs) end;
haftmann@24155
   142
      in
haftmann@24155
   143
        (prefix "fun " o fundef) eqs :: map (prefix "and " o fundef) eqss
haftmann@24155
   144
        |> space_implode "\n"
haftmann@24155
   145
        |> suffix "\n"
haftmann@24155
   146
      end;
haftmann@24155
   147
haftmann@24155
   148
(* nbe specific syntax *)
haftmann@24155
   149
haftmann@24155
   150
local
haftmann@24155
   151
  val prefix =          "Nbe.";
haftmann@24155
   152
  val name_const =      prefix ^ "Const";
haftmann@24155
   153
  val name_free =       prefix ^ "free";
haftmann@25101
   154
  val name_dfree =      prefix ^ "DFree";
haftmann@24155
   155
  val name_abs =        prefix ^ "abs";
haftmann@24155
   156
  val name_app =        prefix ^ "app";
haftmann@24155
   157
  val name_lookup_fun = prefix ^ "lookup_fun";
haftmann@24155
   158
in
haftmann@24155
   159
haftmann@25101
   160
fun nbe_const c ts =
haftmann@25101
   161
  name_const `$` ("(" ^ ML_Syntax.print_string c ^ ", " ^ ml_list ts ^ ")");
haftmann@24155
   162
fun nbe_fun c = "c_" ^ translate_string (fn "." => "_" | c => c) c;
haftmann@25101
   163
fun nbe_free v = name_free `$` ML_Syntax.print_string v;
haftmann@25101
   164
fun nbe_dfree v = name_dfree `$` ML_Syntax.print_string v;
haftmann@25101
   165
fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
haftmann@24155
   166
fun nbe_bound v = "v_" ^ v;
haftmann@24155
   167
haftmann@24155
   168
fun nbe_apps e es =
haftmann@24155
   169
  Library.foldr (fn (s, e) => name_app `$$` [e, s]) (es, e);
haftmann@24155
   170
haftmann@24155
   171
fun nbe_abss 0 f = f `$` ml_list []
haftmann@25101
   172
  | nbe_abss n f = name_abs `$$` [string_of_int n, f];
haftmann@24155
   173
haftmann@24155
   174
fun nbe_lookup c = ml_Val (nbe_fun c) (name_lookup_fun `$` ML_Syntax.print_string c);
haftmann@24155
   175
haftmann@24155
   176
val nbe_value = "value";
haftmann@24155
   177
haftmann@24155
   178
end;
haftmann@24155
   179
haftmann@24219
   180
open BasicCodeThingol;
haftmann@24155
   181
haftmann@24155
   182
(* greetings to Tarski *)
haftmann@24155
   183
haftmann@25101
   184
fun assemble_idict (DictConst (inst, dss)) =
haftmann@25101
   185
      nbe_apps (nbe_fun inst) ((maps o map) assemble_idict dss)
haftmann@25101
   186
  | assemble_idict (DictVar (supers, (v, (n, _)))) =
haftmann@25101
   187
      fold (fn super => nbe_apps (nbe_fun super) o single) supers (nbe_dict v n);
haftmann@25101
   188
haftmann@25101
   189
fun assemble_iterm is_fun num_args =
haftmann@24155
   190
  let
haftmann@24155
   191
    fun of_iterm t =
haftmann@24155
   192
      let
haftmann@24219
   193
        val (t', ts) = CodeThingol.unfold_app t
haftmann@24347
   194
      in of_iapp t' (fold (cons o of_iterm) ts []) end
haftmann@24347
   195
    and of_iconst c ts = case num_args c
haftmann@24347
   196
     of SOME n => if n <= length ts
haftmann@24347
   197
          then let val (args2, args1) = chop (length ts - n) ts
haftmann@24347
   198
          in nbe_apps (nbe_fun c `$` ml_list args1) args2
haftmann@24347
   199
          end else nbe_const c ts
haftmann@24347
   200
      | NONE => if is_fun c then nbe_apps (nbe_fun c) ts
haftmann@24347
   201
          else nbe_const c ts
haftmann@25101
   202
    and of_iapp (IConst (c, (dss, _))) ts = of_iconst c
haftmann@25101
   203
          (ts @ rev ((maps o map) assemble_idict dss))
haftmann@24347
   204
      | of_iapp (IVar v) ts = nbe_apps (nbe_bound v) ts
haftmann@24347
   205
      | of_iapp ((v, _) `|-> t) ts =
haftmann@24155
   206
          nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound v]) (of_iterm t))) ts
haftmann@24347
   207
      | of_iapp (ICase (((t, _), cs), t0)) ts =
haftmann@24155
   208
          nbe_apps (ml_cases (of_iterm t) (map (pairself of_iterm) cs
haftmann@24155
   209
            @ [("_", of_iterm t0)])) ts
haftmann@24155
   210
  in of_iterm end;
haftmann@24155
   211
haftmann@25101
   212
fun assemble_fun gr num_args (c, (vs, eqns)) =
haftmann@24155
   213
  let
haftmann@25101
   214
    val assemble_arg = assemble_iterm (K false) (K NONE);
haftmann@25101
   215
    val assemble_rhs = assemble_iterm (is_some o Graph.get_node gr) num_args;
haftmann@25101
   216
    val dict_params = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs
haftmann@25101
   217
      |> rev;
haftmann@24155
   218
    fun assemble_eqn (args, rhs) =
haftmann@25101
   219
      ([ml_list (map assemble_arg (rev args) @ dict_params)], assemble_rhs rhs);
haftmann@25101
   220
    val default_params = map nbe_bound (Name.invent_list [] "a" ((the o num_args) c));
haftmann@24155
   221
    val default_eqn = ([ml_list default_params], nbe_const c default_params);
haftmann@24155
   222
  in map assemble_eqn eqns @ [default_eqn] end;
haftmann@24155
   223
haftmann@25101
   224
fun assemble_eqnss gr ([], deps) = ([], "")
haftmann@25101
   225
  | assemble_eqnss gr (eqnss, deps) =
haftmann@24155
   226
      let
haftmann@24155
   227
        val cs = map fst eqnss;
haftmann@25101
   228
        val num_args = cs ~~ map (fn (_, (vs, (args, rhs) :: _)) =>
haftmann@25101
   229
          length (maps snd vs) + length args) eqnss;
haftmann@25101
   230
        val bind_deps = map nbe_lookup (filter (is_some o Graph.get_node gr) deps);
haftmann@24155
   231
        val bind_locals = ml_fundefs (map nbe_fun cs ~~ map
haftmann@25101
   232
          (assemble_fun gr (AList.lookup (op =) num_args)) eqnss);
haftmann@24590
   233
        val result = ml_list (map (fn (c, n) => nbe_abss n (nbe_fun c)) num_args)
haftmann@24590
   234
          |> ml_delay;
haftmann@25101
   235
      in (cs, ml_Let (bind_deps @ [bind_locals]) result) end;
haftmann@24155
   236
haftmann@25101
   237
fun eqns_of_stmt (_, CodeThingol.Fun (_, [])) =
haftmann@25101
   238
      []
haftmann@25101
   239
  | eqns_of_stmt (const, CodeThingol.Fun ((vs, _), eqns)) =
haftmann@25101
   240
      [(const, (vs, map fst eqns))]
haftmann@25101
   241
  | eqns_of_stmt (_, CodeThingol.Datatypecons _) =
haftmann@25101
   242
      []
haftmann@25101
   243
  | eqns_of_stmt (_, CodeThingol.Datatype _) =
haftmann@25101
   244
      []
haftmann@25101
   245
  | eqns_of_stmt (class, CodeThingol.Class (v, (superclasses, classops))) =
haftmann@25101
   246
      let
haftmann@25101
   247
        val names = map snd superclasses @ map fst classops;
haftmann@25101
   248
        val params = Name.invent_list [] "d" (length names);
haftmann@25101
   249
        fun mk (k, name) =
haftmann@25101
   250
          (name, ([(v, [])],
haftmann@25101
   251
            [([IConst (class, ([], [])) `$$ map IVar params], IVar (nth params k))]));
haftmann@25101
   252
      in map_index mk names end
haftmann@25101
   253
  | eqns_of_stmt (_, CodeThingol.Classrel _) =
haftmann@25101
   254
      []
haftmann@25101
   255
  | eqns_of_stmt (_, CodeThingol.Classparam _) =
haftmann@25101
   256
      []
haftmann@25101
   257
  | eqns_of_stmt (inst, CodeThingol.Classinst ((class, (_, arities)), (superinsts, instops))) =
haftmann@25101
   258
      [(inst, (arities, [([], IConst (class, ([], [])) `$$
haftmann@25101
   259
        map (fn (_, (_, (inst, dicts))) => IConst (inst, (dicts, []))) superinsts
haftmann@25101
   260
        @ map (IConst o snd o fst) instops)]))];
haftmann@24155
   261
haftmann@25101
   262
fun compile_stmts stmts_deps =
haftmann@25101
   263
  let
haftmann@25101
   264
    val names = map (fst o fst) stmts_deps;
haftmann@25101
   265
    val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
haftmann@25101
   266
    val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
haftmann@25101
   267
    val compiled_deps = names_deps |> maps snd |> distinct (op =) |> subtract (op =) names;
haftmann@25101
   268
    fun compile gr = (eqnss, compiled_deps) |> assemble_eqnss gr |> compile_univs gr |> rpair gr;
haftmann@25101
   269
  in
haftmann@25101
   270
    fold (fn name => Graph.new_node (name, NONE)) names
haftmann@25101
   271
    #> fold (fn (name, deps) => fold (curry Graph.add_edge name) deps) names_deps
haftmann@25101
   272
    #> compile
haftmann@25101
   273
    #-> fold (fn (name, univ) => Graph.map_node name (K (SOME univ)))
haftmann@25101
   274
  end;
haftmann@24155
   275
haftmann@25101
   276
fun ensure_stmts code =
haftmann@25101
   277
  let
haftmann@25101
   278
    fun add_stmts names gr = if exists (compiled gr) names then gr else gr
haftmann@25101
   279
      |> compile_stmts (map (fn name => ((name, Graph.get_node code name),
haftmann@25101
   280
          Graph.imm_succs code name)) names);
haftmann@25101
   281
  in fold_rev add_stmts (Graph.strong_conn code) end;
haftmann@24155
   282
haftmann@25101
   283
fun assemble_eval gr (((vs, ty), t), deps) =
haftmann@25101
   284
  let
haftmann@25101
   285
    val frees = CodeThingol.fold_unbound_varnames (insert (op =)) t [];
haftmann@25101
   286
    val bind_deps = map nbe_lookup (filter (is_some o Graph.get_node gr) deps);
haftmann@25101
   287
    val dict_params = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs
haftmann@25101
   288
      |> rev;
haftmann@25101
   289
    val bind_value = ml_fundefs [(nbe_value,
haftmann@25101
   290
      [([ml_list (map nbe_bound frees @ dict_params)],
haftmann@25101
   291
        assemble_iterm (is_some o Graph.get_node gr) (K NONE) t)])];
haftmann@25101
   292
    val result = ml_list [nbe_value `$` ml_list
haftmann@25101
   293
      (map nbe_free frees @ map nbe_dfree dict_params)]
haftmann@25101
   294
      |> ml_delay;
haftmann@25101
   295
  in ([nbe_value], ml_Let (bind_deps @ [bind_value]) result) end;
haftmann@25101
   296
haftmann@25101
   297
fun eval_term gr =
haftmann@25101
   298
  assemble_eval gr
haftmann@25101
   299
  #> compile_univs gr
haftmann@24155
   300
  #> the_single
haftmann@24155
   301
  #> snd;
haftmann@24155
   302
haftmann@24155
   303
haftmann@25101
   304
(** evaluation **)
haftmann@24155
   305
haftmann@24839
   306
(* reification *)
haftmann@24155
   307
haftmann@24155
   308
fun term_of_univ thy t =
haftmann@24155
   309
  let
haftmann@25101
   310
    fun take_until f [] = []
haftmann@25101
   311
      | take_until f (x::xs) = if f x then [] else x :: take_until f xs;
haftmann@25101
   312
    fun is_dict (Const (c, _)) =
haftmann@25101
   313
          (is_some o CodeName.class_rev thy) c
haftmann@25101
   314
          orelse (is_some o CodeName.classrel_rev thy) c
haftmann@25101
   315
          orelse (is_some o CodeName.instance_rev thy) c
haftmann@25101
   316
      | is_dict (DFree _) = true
haftmann@25101
   317
      | is_dict _ = false;
haftmann@24155
   318
    fun of_apps bounds (t, ts) =
haftmann@24155
   319
      fold_map (of_univ bounds) ts
haftmann@24155
   320
      #>> (fn ts' => list_comb (t, rev ts'))
haftmann@24155
   321
    and of_univ bounds (Const (name, ts)) typidx =
haftmann@24155
   322
          let
haftmann@25101
   323
            val ts' = take_until is_dict ts;
haftmann@24423
   324
            val SOME c = CodeName.const_rev thy name;
haftmann@24423
   325
            val T = Code.default_typ thy c;
haftmann@24155
   326
            val T' = map_type_tvar (fn ((v, i), S) => TypeInfer.param (typidx + i) (v, S)) T;
haftmann@24155
   327
            val typidx' = typidx + maxidx_of_typ T' + 1;
haftmann@25101
   328
          in of_apps bounds (Term.Const (c, T'), ts') typidx' end
haftmann@24155
   329
      | of_univ bounds (Free (name, ts)) typidx =
haftmann@24155
   330
          of_apps bounds (Term.Free (name, dummyT), ts) typidx
haftmann@24155
   331
      | of_univ bounds (BVar (name, ts)) typidx =
haftmann@24155
   332
          of_apps bounds (Bound (bounds - name - 1), ts) typidx
haftmann@24155
   333
      | of_univ bounds (t as Abs _) typidx =
haftmann@24155
   334
          typidx
haftmann@24155
   335
          |> of_univ (bounds + 1) (app t (BVar (bounds, [])))
haftmann@24155
   336
          |-> (fn t' => pair (Term.Abs ("u", dummyT, t')))
haftmann@24155
   337
  in of_univ 0 t 0 |> fst end;
haftmann@24155
   338
haftmann@25101
   339
(* function store *)
haftmann@25101
   340
haftmann@25101
   341
structure Nbe_Functions = CodeDataFun
haftmann@25101
   342
(
haftmann@25101
   343
  type T = univ_gr;
haftmann@25101
   344
  val empty = Graph.empty;
haftmann@25101
   345
  fun merge _ = Graph.merge (K true);
haftmann@25101
   346
  fun purge _ NONE _ = Graph.empty
haftmann@25101
   347
    | purge NONE _ _ = Graph.empty
haftmann@25101
   348
    | purge (SOME thy) (SOME cs) gr =
haftmann@25101
   349
        let
haftmann@25101
   350
          val cs_exisiting =
haftmann@25101
   351
            map_filter (CodeName.const_rev thy) (Graph.keys gr);
haftmann@25101
   352
          val dels = (Graph.all_preds gr
haftmann@25101
   353
              o map (CodeName.const thy)
haftmann@25101
   354
              o filter (member (op =) cs_exisiting)
haftmann@25101
   355
            ) cs;
haftmann@25101
   356
        in Graph.del_nodes dels gr end;
haftmann@25101
   357
);
haftmann@25101
   358
haftmann@25101
   359
(* compilation, evaluation and reification *)
haftmann@25101
   360
haftmann@25101
   361
fun compile_eval thy code vs_ty_t deps =
haftmann@25101
   362
  (vs_ty_t, deps)
haftmann@25101
   363
  |> eval_term (Nbe_Functions.change thy (ensure_stmts code))
haftmann@25101
   364
  |> term_of_univ thy;
haftmann@25101
   365
haftmann@24155
   366
(* evaluation with type reconstruction *)
haftmann@24155
   367
haftmann@24381
   368
fun eval thy code t vs_ty_t deps =
haftmann@24155
   369
  let
haftmann@24347
   370
    val ty = type_of t;
haftmann@24155
   371
    fun subst_Frees [] = I
haftmann@24155
   372
      | subst_Frees inst =
haftmann@24155
   373
          Term.map_aterms (fn (t as Term.Free (s, _)) => the_default t (AList.lookup (op =) inst s)
haftmann@24155
   374
                            | t => t);
haftmann@24155
   375
    val anno_vars =
haftmann@24155
   376
      subst_Frees (map (fn (s, T) => (s, Term.Free (s, T))) (Term.add_frees t []))
haftmann@24155
   377
      #> subst_Vars (map (fn (ixn, T) => (ixn, Var (ixn, T))) (Term.add_vars t []))
haftmann@24347
   378
    fun constrain t =
wenzelm@24680
   379
      singleton (Syntax.check_terms (ProofContext.init thy)) (TypeInfer.constrain ty t);
haftmann@24155
   380
    fun check_tvars t = if null (Term.term_tvars t) then t else
haftmann@24155
   381
      error ("Illegal schematic type variables in normalized term: "
haftmann@24155
   382
        ^ setmp show_types true (Sign.string_of_term thy) t);
haftmann@24155
   383
  in
haftmann@25101
   384
    compile_eval thy code vs_ty_t deps
haftmann@24155
   385
    |> tracing (fn t => "Normalized:\n" ^ setmp show_types true Display.raw_string_of_term t)
haftmann@24155
   386
    |> anno_vars
haftmann@24155
   387
    |> tracing (fn t => "Vars typed:\n" ^ setmp show_types true Display.raw_string_of_term t)
haftmann@24155
   388
    |> constrain
haftmann@24155
   389
    |> tracing (fn t => "Types inferred:\n" ^ setmp show_types true Display.raw_string_of_term t)
haftmann@25101
   390
    |> tracing (fn t => "---\n")
haftmann@24155
   391
    |> check_tvars
haftmann@24155
   392
  end;
haftmann@24155
   393
haftmann@24155
   394
(* evaluation oracle *)
haftmann@24155
   395
haftmann@24839
   396
exception Norm of CodeThingol.code * term
haftmann@24381
   397
  * (CodeThingol.typscheme * CodeThingol.iterm) * string list;
haftmann@24155
   398
haftmann@24839
   399
fun norm_oracle (thy, Norm (code, t, vs_ty_t, deps)) =
haftmann@24381
   400
  Logic.mk_equals (t, eval thy code t vs_ty_t deps);
haftmann@24155
   401
haftmann@24839
   402
fun norm_invoke thy code t vs_ty_t deps =
haftmann@24839
   403
  Thm.invoke_oracle_i thy "HOL.norm" (thy, Norm (code, t, vs_ty_t, deps));
haftmann@24283
   404
  (*FIXME get rid of hardwired theory name*)
haftmann@24155
   405
haftmann@24839
   406
fun norm_conv ct =
haftmann@24155
   407
  let
haftmann@24155
   408
    val thy = Thm.theory_of_cterm ct;
haftmann@24381
   409
    fun conv code vs_ty_t deps ct =
haftmann@24155
   410
      let
haftmann@24155
   411
        val t = Thm.term_of ct;
haftmann@24839
   412
      in norm_invoke thy code t vs_ty_t deps end;
haftmann@24219
   413
  in CodePackage.eval_conv thy conv ct end;
haftmann@24155
   414
haftmann@24839
   415
fun norm_term thy =
haftmann@24839
   416
  let
haftmann@24839
   417
    fun invoke code vs_ty_t deps t =
haftmann@24839
   418
      eval thy code t vs_ty_t deps;
haftmann@24839
   419
  in CodePackage.eval_term thy invoke #> Code.postprocess_term thy end;
haftmann@24839
   420
haftmann@24155
   421
(* evaluation command *)
haftmann@24155
   422
haftmann@24155
   423
fun norm_print_term ctxt modes t =
haftmann@24155
   424
  let
haftmann@24155
   425
    val thy = ProofContext.theory_of ctxt;
haftmann@24839
   426
    val t' = norm_term thy t;
haftmann@24839
   427
    val ty' = Term.type_of t';
wenzelm@24634
   428
    val p = PrintMode.with_modes modes (fn () =>
wenzelm@24920
   429
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt t'), Pretty.fbrk,
wenzelm@24920
   430
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt ty')]) ();
haftmann@24155
   431
  in Pretty.writeln p end;
haftmann@24155
   432
haftmann@24155
   433
haftmann@24155
   434
(** Isar setup **)
haftmann@24155
   435
wenzelm@24508
   436
fun norm_print_term_cmd (modes, s) state =
haftmann@24155
   437
  let val ctxt = Toplevel.context_of state
wenzelm@24508
   438
  in norm_print_term ctxt modes (Syntax.read_term ctxt s) end;
haftmann@24155
   439
haftmann@24839
   440
val setup = Theory.add_oracle ("norm", norm_oracle)
haftmann@24155
   441
haftmann@24155
   442
local structure P = OuterParse and K = OuterKeyword in
haftmann@24155
   443
haftmann@24155
   444
val opt_modes = Scan.optional (P.$$$ "(" |-- P.!!! (Scan.repeat1 P.xname --| P.$$$ ")")) [];
haftmann@24155
   445
wenzelm@24867
   446
val _ =
haftmann@24155
   447
  OuterSyntax.improper_command "normal_form" "normalize term by evaluation" K.diag
haftmann@24155
   448
    (opt_modes -- P.typ >> (Toplevel.keep o norm_print_term_cmd));
haftmann@24155
   449
haftmann@24155
   450
end;
haftmann@24155
   451
haftmann@24155
   452
end;