src/Tools/nbe.ML
author haftmann
Mon Jan 21 08:43:35 2008 +0100 (2008-01-21)
changeset 25935 ce3cd5f0c4ee
parent 25924 f974a1c64348
child 25944 f0301d6c7b79
permissions -rw-r--r--
tuned
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@25924
    15
    | Free of string * Univ list             (*free (uninterpreted) variables*)
haftmann@25924
    16
    | DFree of string * int                  (*free (uninterpreted) dictionary parameters*)
haftmann@24155
    17
    | BVar of int * Univ list
haftmann@24155
    18
    | Abs of (int * (Univ list -> Univ)) * Univ list;
haftmann@25924
    19
  val apps: Univ -> Univ list -> Univ        (*explicit applications*)
haftmann@25101
    20
  val abs: int -> (Univ list -> Univ) -> Univ
haftmann@25924
    21
                                            (*abstractions as closures*)
haftmann@24155
    22
wenzelm@25204
    23
  val univs_ref: (unit -> Univ list -> Univ list) option ref
haftmann@25924
    24
  val norm_invoke: theory -> CodeThingol.code -> term
haftmann@25924
    25
    -> CodeThingol.typscheme * CodeThingol.iterm -> string list -> thm
haftmann@24155
    26
  val trace: bool ref
haftmann@25924
    27
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
wenzelm@25204
    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@25924
    63
  | DFree of string * int              (*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 abs n f = Abs ((n, f), []);
haftmann@25924
    71
fun apps (Abs ((n, f), xs)) ys = let val k = n - length ys in
haftmann@25924
    72
      if k = 0 then f (ys @ xs)
haftmann@25924
    73
      else if k < 0 then
haftmann@25924
    74
        let val (zs, ws) = chop (~ k) ys
haftmann@25924
    75
        in apps (f (ws @ xs)) zs end
haftmann@25924
    76
      else Abs ((k, f), ys @ xs) end (*note: reverse convention also for apps!*)
haftmann@25924
    77
  | apps (Const (name, xs)) ys = Const (name, ys @ xs)
haftmann@25924
    78
  | apps (Free (name, xs)) ys = Free (name, ys @ xs)
haftmann@25924
    79
  | apps (BVar (name, xs)) ys = BVar (name, ys @ xs);
haftmann@24155
    80
haftmann@25101
    81
(* universe graph *)
haftmann@24155
    82
haftmann@25101
    83
type univ_gr = Univ option Graph.T;
haftmann@25101
    84
val compiled : univ_gr -> string -> bool = can o Graph.get_node;
haftmann@24839
    85
haftmann@24155
    86
haftmann@24155
    87
(** assembling and compiling ML code from terms **)
haftmann@24155
    88
haftmann@24155
    89
(* abstract ML syntax *)
haftmann@24155
    90
haftmann@24155
    91
infix 9 `$` `$$`;
haftmann@24155
    92
fun e1 `$` e2 = "(" ^ e1 ^ " " ^ e2 ^ ")";
haftmann@25101
    93
fun e `$$` [] = e
haftmann@25101
    94
  | e `$$` es = "(" ^ e ^ " " ^ space_implode " " es ^ ")";
haftmann@24590
    95
fun ml_abs v e = "(fn " ^ v ^ " => " ^ e ^ ")";
haftmann@24155
    96
haftmann@24155
    97
fun ml_cases t cs =
haftmann@24155
    98
  "(case " ^ t ^ " of " ^ space_implode " | " (map (fn (p, t) => p ^ " => " ^ t) cs) ^ ")";
haftmann@24155
    99
fun ml_Let ds e = "let\n" ^ space_implode "\n" ds ^ " in " ^ e ^ " end";
haftmann@24155
   100
haftmann@24155
   101
fun ml_list es = "[" ^ commas es ^ "]";
haftmann@24155
   102
haftmann@24155
   103
fun ml_fundefs ([(name, [([], e)])]) =
haftmann@24155
   104
      "val " ^ name ^ " = " ^ e ^ "\n"
haftmann@24155
   105
  | ml_fundefs (eqs :: eqss) =
haftmann@24155
   106
      let
haftmann@24155
   107
        fun fundef (name, eqs) =
haftmann@24155
   108
          let
haftmann@24155
   109
            fun eqn (es, e) = name ^ " " ^ space_implode " " es ^ " = " ^ e
haftmann@24155
   110
          in space_implode "\n  | " (map eqn eqs) end;
haftmann@24155
   111
      in
haftmann@24155
   112
        (prefix "fun " o fundef) eqs :: map (prefix "and " o fundef) eqss
haftmann@24155
   113
        |> space_implode "\n"
haftmann@24155
   114
        |> suffix "\n"
haftmann@24155
   115
      end;
haftmann@24155
   116
haftmann@24155
   117
(* nbe specific syntax *)
haftmann@24155
   118
haftmann@24155
   119
local
haftmann@24155
   120
  val prefix =          "Nbe.";
haftmann@24155
   121
  val name_const =      prefix ^ "Const";
haftmann@24155
   122
  val name_abs =        prefix ^ "abs";
haftmann@25924
   123
  val name_apps =       prefix ^ "apps";
haftmann@24155
   124
in
haftmann@24155
   125
haftmann@25935
   126
fun nbe_fun "" = "nbe_value"
haftmann@25935
   127
  | nbe_fun c = "c_" ^ translate_string (fn "." => "_" | c => c) c;
haftmann@25101
   128
fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
haftmann@24155
   129
fun nbe_bound v = "v_" ^ v;
haftmann@24155
   130
haftmann@25924
   131
(*note: these three are the "turning spots" where proper argument order is established!*)
haftmann@25924
   132
fun nbe_apps t [] = t
haftmann@25924
   133
  | nbe_apps t ts = name_apps `$$` [t, ml_list (rev ts)];
haftmann@25924
   134
fun nbe_apps_local c ts = nbe_fun c `$` ml_list (rev ts);
haftmann@25924
   135
fun nbe_apps_constr c ts =
haftmann@25924
   136
  name_const `$` ("(" ^ ML_Syntax.print_string c ^ ", " ^ ml_list (rev ts) ^ ")");
haftmann@25924
   137
haftmann@24155
   138
fun nbe_abss 0 f = f `$` ml_list []
haftmann@25101
   139
  | nbe_abss n f = name_abs `$$` [string_of_int n, f];
haftmann@24155
   140
haftmann@24155
   141
end;
haftmann@24155
   142
haftmann@24219
   143
open BasicCodeThingol;
haftmann@24155
   144
haftmann@25190
   145
(* sandbox communication *)
haftmann@25190
   146
haftmann@25190
   147
val univs_ref = ref (NONE : (unit -> Univ list -> Univ list) option);
haftmann@25190
   148
wenzelm@25204
   149
val compile =
haftmann@25190
   150
  tracing (fn s => "\n--- code to be evaluated:\n" ^ s)
wenzelm@25204
   151
  #> ML_Context.evaluate
haftmann@25190
   152
      (Output.tracing o enclose "\n---compiler echo:\n" "\n---\n",
haftmann@25190
   153
      Output.tracing o enclose "\n--- compiler echo (with error):\n" "\n---\n")
wenzelm@25204
   154
      (!trace) ("Nbe.univs_ref", univs_ref);
haftmann@25190
   155
haftmann@25865
   156
(* code generation *)
haftmann@24155
   157
haftmann@25924
   158
datatype const_kind = Local of int | Global | Constr;
haftmann@25101
   159
haftmann@25924
   160
fun assemble_constapp kind c dss ts = 
haftmann@25924
   161
      let
haftmann@25924
   162
        val ts' = (maps o map) (assemble_idict kind) dss @ ts;
haftmann@25924
   163
      in case kind c
haftmann@25924
   164
       of Local n => if n <= length ts'
haftmann@25924
   165
            then let val (ts1, ts2) = chop n ts'
haftmann@25924
   166
            in nbe_apps (nbe_apps_local c ts1) ts2
haftmann@25924
   167
            end else nbe_apps (nbe_abss n (nbe_fun c)) ts'
haftmann@25924
   168
        | Global => nbe_apps (nbe_fun c) ts'
haftmann@25924
   169
        | Constr => nbe_apps_constr c ts'
haftmann@25924
   170
      end
haftmann@25924
   171
and assemble_idict kind (DictConst (inst, dss)) =
haftmann@25924
   172
      assemble_constapp kind inst dss []
haftmann@25924
   173
  | assemble_idict kind (DictVar (supers, (v, (n, _)))) =
haftmann@25924
   174
      fold_rev (fn super => assemble_constapp kind super [] o single) supers (nbe_dict v n);
haftmann@25924
   175
haftmann@25924
   176
fun assemble_iterm kind =
haftmann@24155
   177
  let
haftmann@24155
   178
    fun of_iterm t =
haftmann@24155
   179
      let
haftmann@24219
   180
        val (t', ts) = CodeThingol.unfold_app t
haftmann@25924
   181
      in of_iapp t' (fold_rev (cons o of_iterm) ts []) end
haftmann@25924
   182
    and of_iapp (IConst (c, (dss, _))) ts = assemble_constapp kind c dss ts
haftmann@24347
   183
      | of_iapp (IVar v) ts = nbe_apps (nbe_bound v) ts
haftmann@24347
   184
      | of_iapp ((v, _) `|-> t) ts =
haftmann@24155
   185
          nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound v]) (of_iterm t))) ts
haftmann@24347
   186
      | of_iapp (ICase (((t, _), cs), t0)) ts =
haftmann@24155
   187
          nbe_apps (ml_cases (of_iterm t) (map (pairself of_iterm) cs
haftmann@24155
   188
            @ [("_", of_iterm t0)])) ts
haftmann@24155
   189
  in of_iterm end;
haftmann@24155
   190
haftmann@25924
   191
fun assemble_eqns kind (c, (vs, eqns)) =
haftmann@24155
   192
  let
haftmann@25924
   193
    val dict_args = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs;
haftmann@25924
   194
    val assemble_arg = assemble_iterm (K Constr);
haftmann@25924
   195
    val assemble_rhs = assemble_iterm kind;
haftmann@24155
   196
    fun assemble_eqn (args, rhs) =
haftmann@25924
   197
      ([ml_list (rev (dict_args @ map assemble_arg args))], assemble_rhs rhs);
haftmann@25924
   198
    val default_args = dict_args @ map nbe_bound (Name.invent_list [] "a" ((length o fst o hd) eqns));
haftmann@25924
   199
    val default_eqn = ([ml_list (rev default_args)], nbe_apps_constr c default_args);
haftmann@25935
   200
  in (nbe_fun c, map assemble_eqn eqns @ [default_eqn]) end;
haftmann@24155
   201
haftmann@25190
   202
fun assemble_eqnss gr deps [] = ([], ("", []))
haftmann@25190
   203
  | assemble_eqnss gr deps eqnss =
haftmann@24155
   204
      let
haftmann@24155
   205
        val cs = map fst eqnss;
haftmann@25101
   206
        val num_args = cs ~~ map (fn (_, (vs, (args, rhs) :: _)) =>
haftmann@25101
   207
          length (maps snd vs) + length args) eqnss;
haftmann@25924
   208
        fun kind c = case AList.lookup (op =) num_args c
haftmann@25924
   209
         of SOME n => Local n
haftmann@25924
   210
          | NONE => if (is_some o Option.join o try (Graph.get_node gr)) c
haftmann@25924
   211
              then Global else Constr;
haftmann@25190
   212
        val deps' = filter (is_some o Option.join o try (Graph.get_node gr)) deps;
haftmann@25935
   213
        val bind_deps = ml_list (map nbe_fun deps');
haftmann@25924
   214
        val bind_locals = ml_fundefs (map (assemble_eqns kind) eqnss);
haftmann@25190
   215
        val result = ml_list (map (fn (c, n) => nbe_abss n (nbe_fun c)) num_args);
haftmann@25190
   216
        val arg_deps = map (the o Graph.get_node gr) deps';
haftmann@25190
   217
      in (cs, (ml_abs bind_deps (ml_Let [bind_locals] result), arg_deps)) end;
haftmann@25190
   218
haftmann@25190
   219
fun compile_eqnss gr deps eqnss = case assemble_eqnss gr deps eqnss
haftmann@25190
   220
 of ([], _) => []
haftmann@25190
   221
  | (cs, (s, deps)) => cs ~~ compile s deps;
haftmann@24155
   222
haftmann@25101
   223
fun eqns_of_stmt (_, CodeThingol.Fun (_, [])) =
haftmann@25101
   224
      []
haftmann@25101
   225
  | eqns_of_stmt (const, CodeThingol.Fun ((vs, _), eqns)) =
haftmann@25101
   226
      [(const, (vs, map fst eqns))]
haftmann@25101
   227
  | eqns_of_stmt (_, CodeThingol.Datatypecons _) =
haftmann@25101
   228
      []
haftmann@25101
   229
  | eqns_of_stmt (_, CodeThingol.Datatype _) =
haftmann@25101
   230
      []
haftmann@25101
   231
  | eqns_of_stmt (class, CodeThingol.Class (v, (superclasses, classops))) =
haftmann@25101
   232
      let
haftmann@25101
   233
        val names = map snd superclasses @ map fst classops;
haftmann@25101
   234
        val params = Name.invent_list [] "d" (length names);
haftmann@25101
   235
        fun mk (k, name) =
haftmann@25101
   236
          (name, ([(v, [])],
haftmann@25101
   237
            [([IConst (class, ([], [])) `$$ map IVar params], IVar (nth params k))]));
haftmann@25101
   238
      in map_index mk names end
haftmann@25101
   239
  | eqns_of_stmt (_, CodeThingol.Classrel _) =
haftmann@25101
   240
      []
haftmann@25101
   241
  | eqns_of_stmt (_, CodeThingol.Classparam _) =
haftmann@25101
   242
      []
haftmann@25101
   243
  | eqns_of_stmt (inst, CodeThingol.Classinst ((class, (_, arities)), (superinsts, instops))) =
haftmann@25101
   244
      [(inst, (arities, [([], IConst (class, ([], [])) `$$
haftmann@25101
   245
        map (fn (_, (_, (inst, dicts))) => IConst (inst, (dicts, []))) superinsts
haftmann@25101
   246
        @ map (IConst o snd o fst) instops)]))];
haftmann@24155
   247
haftmann@25101
   248
fun compile_stmts stmts_deps =
haftmann@25101
   249
  let
haftmann@25101
   250
    val names = map (fst o fst) stmts_deps;
haftmann@25101
   251
    val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
haftmann@25101
   252
    val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
haftmann@25190
   253
    val compiled_deps = names_deps
haftmann@25190
   254
      |> maps snd
haftmann@25190
   255
      |> distinct (op =)
haftmann@25190
   256
      |> subtract (op =) names;
haftmann@25190
   257
    fun compile gr = eqnss
haftmann@25190
   258
      |> compile_eqnss gr compiled_deps
haftmann@25190
   259
      |> rpair gr;
haftmann@25101
   260
  in
haftmann@25101
   261
    fold (fn name => Graph.new_node (name, NONE)) names
haftmann@25101
   262
    #> fold (fn (name, deps) => fold (curry Graph.add_edge name) deps) names_deps
haftmann@25101
   263
    #> compile
haftmann@25101
   264
    #-> fold (fn (name, univ) => Graph.map_node name (K (SOME univ)))
haftmann@25101
   265
  end;
haftmann@24155
   266
haftmann@25101
   267
fun ensure_stmts code =
haftmann@25101
   268
  let
haftmann@25101
   269
    fun add_stmts names gr = if exists (compiled gr) names then gr else gr
haftmann@25101
   270
      |> compile_stmts (map (fn name => ((name, Graph.get_node code name),
haftmann@25101
   271
          Graph.imm_succs code name)) names);
haftmann@25101
   272
  in fold_rev add_stmts (Graph.strong_conn code) end;
haftmann@24155
   273
haftmann@25924
   274
fun eval_term gr deps ((vs, ty), t) =
haftmann@25924
   275
  let 
haftmann@25924
   276
    val frees = CodeThingol.fold_unbound_varnames (insert (op =)) t []
haftmann@25924
   277
    val frees' = map (fn v => Free (v, [])) frees;
haftmann@25924
   278
    val dict_frees = maps (fn (v, sort) => map_index (curry DFree v o fst) sort) vs;
haftmann@25924
   279
  in
haftmann@25935
   280
    ("", (vs, [(map IVar frees, t)]))
haftmann@25924
   281
    |> singleton (compile_eqnss gr deps)
haftmann@25924
   282
    |> snd
haftmann@25924
   283
    |> (fn t => apps t (rev (dict_frees @ frees')))
haftmann@25924
   284
  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@25924
   318
          |> of_univ (bounds + 1) (apps 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;