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