src/Tools/nbe.ML
author haftmann
Fri Jan 18 08:30:12 2008 +0100 (2008-01-18)
changeset 25924 f974a1c64348
parent 25865 a141d6bfd398
child 25935 ce3cd5f0c4ee
permissions -rw-r--r--
improved implementation
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@25924
   126
fun nbe_fun' c = "c_" ^ translate_string (fn "." => "_" | c => c) c;
haftmann@25924
   127
val nbe_fun = nbe_fun'; (*FIXME!*)
haftmann@25101
   128
fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
haftmann@24155
   129
fun nbe_bound v = "v_" ^ v;
haftmann@25924
   130
val nbe_value = "";
haftmann@24155
   131
haftmann@25924
   132
(*note: these three are the "turning spots" where proper argument order is established!*)
haftmann@25924
   133
fun nbe_apps t [] = t
haftmann@25924
   134
  | nbe_apps t ts = name_apps `$$` [t, ml_list (rev ts)];
haftmann@25924
   135
fun nbe_apps_local c ts = nbe_fun c `$` ml_list (rev ts);
haftmann@25924
   136
fun nbe_apps_constr c ts =
haftmann@25924
   137
  name_const `$` ("(" ^ ML_Syntax.print_string c ^ ", " ^ ml_list (rev ts) ^ ")");
haftmann@25924
   138
haftmann@24155
   139
haftmann@24155
   140
fun nbe_abss 0 f = f `$` ml_list []
haftmann@25101
   141
  | nbe_abss n f = name_abs `$$` [string_of_int n, f];
haftmann@24155
   142
haftmann@24155
   143
end;
haftmann@24155
   144
haftmann@24219
   145
open BasicCodeThingol;
haftmann@24155
   146
haftmann@25190
   147
(* sandbox communication *)
haftmann@25190
   148
haftmann@25190
   149
val univs_ref = ref (NONE : (unit -> Univ list -> Univ list) option);
haftmann@25190
   150
wenzelm@25204
   151
val compile =
haftmann@25190
   152
  tracing (fn s => "\n--- code to be evaluated:\n" ^ s)
wenzelm@25204
   153
  #> ML_Context.evaluate
haftmann@25190
   154
      (Output.tracing o enclose "\n---compiler echo:\n" "\n---\n",
haftmann@25190
   155
      Output.tracing o enclose "\n--- compiler echo (with error):\n" "\n---\n")
wenzelm@25204
   156
      (!trace) ("Nbe.univs_ref", univs_ref);
haftmann@25190
   157
haftmann@25865
   158
(* code generation *)
haftmann@24155
   159
haftmann@25924
   160
datatype const_kind = Local of int | Global | Constr;
haftmann@25101
   161
haftmann@25924
   162
fun assemble_constapp kind c dss ts = 
haftmann@25924
   163
      let
haftmann@25924
   164
        val ts' = (maps o map) (assemble_idict kind) dss @ ts;
haftmann@25924
   165
      in case kind c
haftmann@25924
   166
       of Local n => if n <= length ts'
haftmann@25924
   167
            then let val (ts1, ts2) = chop n ts'
haftmann@25924
   168
            in nbe_apps (nbe_apps_local c ts1) ts2
haftmann@25924
   169
            end else nbe_apps (nbe_abss n (nbe_fun c)) ts'
haftmann@25924
   170
        | Global => nbe_apps (nbe_fun c) ts'
haftmann@25924
   171
        | Constr => nbe_apps_constr c ts'
haftmann@25924
   172
      end
haftmann@25924
   173
and assemble_idict kind (DictConst (inst, dss)) =
haftmann@25924
   174
      assemble_constapp kind inst dss []
haftmann@25924
   175
  | assemble_idict kind (DictVar (supers, (v, (n, _)))) =
haftmann@25924
   176
      fold_rev (fn super => assemble_constapp kind super [] o single) supers (nbe_dict v n);
haftmann@25924
   177
haftmann@25924
   178
fun assemble_iterm kind =
haftmann@24155
   179
  let
haftmann@24155
   180
    fun of_iterm t =
haftmann@24155
   181
      let
haftmann@24219
   182
        val (t', ts) = CodeThingol.unfold_app t
haftmann@25924
   183
      in of_iapp t' (fold_rev (cons o of_iterm) ts []) end
haftmann@25924
   184
    and of_iapp (IConst (c, (dss, _))) ts = assemble_constapp kind c dss ts
haftmann@24347
   185
      | of_iapp (IVar v) ts = nbe_apps (nbe_bound v) ts
haftmann@24347
   186
      | of_iapp ((v, _) `|-> t) ts =
haftmann@24155
   187
          nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound v]) (of_iterm t))) ts
haftmann@24347
   188
      | of_iapp (ICase (((t, _), cs), t0)) ts =
haftmann@24155
   189
          nbe_apps (ml_cases (of_iterm t) (map (pairself of_iterm) cs
haftmann@24155
   190
            @ [("_", of_iterm t0)])) ts
haftmann@24155
   191
  in of_iterm end;
haftmann@24155
   192
haftmann@25924
   193
fun assemble_eqns kind (c, (vs, eqns)) =
haftmann@24155
   194
  let
haftmann@25924
   195
    val dict_args = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs;
haftmann@25924
   196
    val assemble_arg = assemble_iterm (K Constr);
haftmann@25924
   197
    val assemble_rhs = assemble_iterm kind;
haftmann@24155
   198
    fun assemble_eqn (args, rhs) =
haftmann@25924
   199
      ([ml_list (rev (dict_args @ map assemble_arg args))], assemble_rhs rhs);
haftmann@25924
   200
    val default_args = dict_args @ map nbe_bound (Name.invent_list [] "a" ((length o fst o hd) eqns));
haftmann@25924
   201
    val default_eqn = ([ml_list (rev default_args)], nbe_apps_constr c default_args);
haftmann@25924
   202
  in (nbe_fun' c, map assemble_eqn eqns @ [default_eqn]) end;
haftmann@24155
   203
haftmann@25190
   204
fun assemble_eqnss gr deps [] = ([], ("", []))
haftmann@25190
   205
  | assemble_eqnss gr deps eqnss =
haftmann@24155
   206
      let
haftmann@24155
   207
        val cs = map fst eqnss;
haftmann@25101
   208
        val num_args = cs ~~ map (fn (_, (vs, (args, rhs) :: _)) =>
haftmann@25101
   209
          length (maps snd vs) + length args) eqnss;
haftmann@25924
   210
        fun kind c = case AList.lookup (op =) num_args c
haftmann@25924
   211
         of SOME n => Local n
haftmann@25924
   212
          | NONE => if (is_some o Option.join o try (Graph.get_node gr)) c
haftmann@25924
   213
              then Global else Constr;
haftmann@25190
   214
        val deps' = filter (is_some o Option.join o try (Graph.get_node gr)) deps;
haftmann@25924
   215
        val bind_deps = ml_list (map nbe_fun' deps');
haftmann@25924
   216
        val bind_locals = ml_fundefs (map (assemble_eqns kind) eqnss);
haftmann@25190
   217
        val result = ml_list (map (fn (c, n) => nbe_abss n (nbe_fun c)) num_args);
haftmann@25190
   218
        val arg_deps = map (the o Graph.get_node gr) deps';
haftmann@25190
   219
      in (cs, (ml_abs bind_deps (ml_Let [bind_locals] result), arg_deps)) end;
haftmann@25190
   220
haftmann@25190
   221
fun compile_eqnss gr deps eqnss = case assemble_eqnss gr deps eqnss
haftmann@25190
   222
 of ([], _) => []
haftmann@25190
   223
  | (cs, (s, deps)) => cs ~~ compile s deps;
haftmann@24155
   224
haftmann@25101
   225
fun eqns_of_stmt (_, CodeThingol.Fun (_, [])) =
haftmann@25101
   226
      []
haftmann@25101
   227
  | eqns_of_stmt (const, CodeThingol.Fun ((vs, _), eqns)) =
haftmann@25101
   228
      [(const, (vs, map fst eqns))]
haftmann@25101
   229
  | eqns_of_stmt (_, CodeThingol.Datatypecons _) =
haftmann@25101
   230
      []
haftmann@25101
   231
  | eqns_of_stmt (_, CodeThingol.Datatype _) =
haftmann@25101
   232
      []
haftmann@25101
   233
  | eqns_of_stmt (class, CodeThingol.Class (v, (superclasses, classops))) =
haftmann@25101
   234
      let
haftmann@25101
   235
        val names = map snd superclasses @ map fst classops;
haftmann@25101
   236
        val params = Name.invent_list [] "d" (length names);
haftmann@25101
   237
        fun mk (k, name) =
haftmann@25101
   238
          (name, ([(v, [])],
haftmann@25101
   239
            [([IConst (class, ([], [])) `$$ map IVar params], IVar (nth params k))]));
haftmann@25101
   240
      in map_index mk names end
haftmann@25101
   241
  | eqns_of_stmt (_, CodeThingol.Classrel _) =
haftmann@25101
   242
      []
haftmann@25101
   243
  | eqns_of_stmt (_, CodeThingol.Classparam _) =
haftmann@25101
   244
      []
haftmann@25101
   245
  | eqns_of_stmt (inst, CodeThingol.Classinst ((class, (_, arities)), (superinsts, instops))) =
haftmann@25101
   246
      [(inst, (arities, [([], IConst (class, ([], [])) `$$
haftmann@25101
   247
        map (fn (_, (_, (inst, dicts))) => IConst (inst, (dicts, []))) superinsts
haftmann@25101
   248
        @ map (IConst o snd o fst) instops)]))];
haftmann@24155
   249
haftmann@25101
   250
fun compile_stmts stmts_deps =
haftmann@25101
   251
  let
haftmann@25101
   252
    val names = map (fst o fst) stmts_deps;
haftmann@25101
   253
    val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
haftmann@25101
   254
    val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
haftmann@25190
   255
    val compiled_deps = names_deps
haftmann@25190
   256
      |> maps snd
haftmann@25190
   257
      |> distinct (op =)
haftmann@25190
   258
      |> subtract (op =) names;
haftmann@25190
   259
    fun compile gr = eqnss
haftmann@25190
   260
      |> compile_eqnss gr compiled_deps
haftmann@25190
   261
      |> rpair gr;
haftmann@25101
   262
  in
haftmann@25101
   263
    fold (fn name => Graph.new_node (name, NONE)) names
haftmann@25101
   264
    #> fold (fn (name, deps) => fold (curry Graph.add_edge name) deps) names_deps
haftmann@25101
   265
    #> compile
haftmann@25101
   266
    #-> fold (fn (name, univ) => Graph.map_node name (K (SOME univ)))
haftmann@25101
   267
  end;
haftmann@24155
   268
haftmann@25101
   269
fun ensure_stmts code =
haftmann@25101
   270
  let
haftmann@25101
   271
    fun add_stmts names gr = if exists (compiled gr) names then gr else gr
haftmann@25101
   272
      |> compile_stmts (map (fn name => ((name, Graph.get_node code name),
haftmann@25101
   273
          Graph.imm_succs code name)) names);
haftmann@25101
   274
  in fold_rev add_stmts (Graph.strong_conn code) end;
haftmann@24155
   275
haftmann@25924
   276
fun eval_term gr deps ((vs, ty), t) =
haftmann@25924
   277
  let 
haftmann@25924
   278
    val frees = CodeThingol.fold_unbound_varnames (insert (op =)) t []
haftmann@25924
   279
    val frees' = map (fn v => Free (v, [])) frees;
haftmann@25924
   280
    val dict_frees = maps (fn (v, sort) => map_index (curry DFree v o fst) sort) vs;
haftmann@25924
   281
  in
haftmann@25924
   282
    (nbe_value, (vs, [(map IVar frees, t)]))
haftmann@25924
   283
    |> singleton (compile_eqnss gr deps)
haftmann@25924
   284
    |> snd
haftmann@25924
   285
    |> (fn t => apps t (rev (dict_frees @ frees')))
haftmann@25924
   286
  end;
haftmann@24155
   287
haftmann@24155
   288
haftmann@25101
   289
(** evaluation **)
haftmann@24155
   290
haftmann@24839
   291
(* reification *)
haftmann@24155
   292
haftmann@24155
   293
fun term_of_univ thy t =
haftmann@24155
   294
  let
haftmann@25101
   295
    fun take_until f [] = []
haftmann@25101
   296
      | take_until f (x::xs) = if f x then [] else x :: take_until f xs;
haftmann@25101
   297
    fun is_dict (Const (c, _)) =
haftmann@25101
   298
          (is_some o CodeName.class_rev thy) c
haftmann@25101
   299
          orelse (is_some o CodeName.classrel_rev thy) c
haftmann@25101
   300
          orelse (is_some o CodeName.instance_rev thy) c
haftmann@25101
   301
      | is_dict (DFree _) = true
haftmann@25101
   302
      | is_dict _ = false;
haftmann@24155
   303
    fun of_apps bounds (t, ts) =
haftmann@24155
   304
      fold_map (of_univ bounds) ts
haftmann@24155
   305
      #>> (fn ts' => list_comb (t, rev ts'))
haftmann@24155
   306
    and of_univ bounds (Const (name, ts)) typidx =
haftmann@24155
   307
          let
haftmann@25101
   308
            val ts' = take_until is_dict ts;
haftmann@24423
   309
            val SOME c = CodeName.const_rev thy name;
haftmann@24423
   310
            val T = Code.default_typ thy c;
haftmann@24155
   311
            val T' = map_type_tvar (fn ((v, i), S) => TypeInfer.param (typidx + i) (v, S)) T;
haftmann@24155
   312
            val typidx' = typidx + maxidx_of_typ T' + 1;
haftmann@25101
   313
          in of_apps bounds (Term.Const (c, T'), ts') typidx' end
haftmann@24155
   314
      | of_univ bounds (Free (name, ts)) typidx =
haftmann@24155
   315
          of_apps bounds (Term.Free (name, dummyT), ts) typidx
haftmann@24155
   316
      | of_univ bounds (BVar (name, ts)) typidx =
haftmann@24155
   317
          of_apps bounds (Bound (bounds - name - 1), ts) typidx
haftmann@24155
   318
      | of_univ bounds (t as Abs _) typidx =
haftmann@24155
   319
          typidx
haftmann@25924
   320
          |> of_univ (bounds + 1) (apps t [BVar (bounds, [])])
haftmann@24155
   321
          |-> (fn t' => pair (Term.Abs ("u", dummyT, t')))
haftmann@24155
   322
  in of_univ 0 t 0 |> fst end;
haftmann@24155
   323
haftmann@25101
   324
(* function store *)
haftmann@25101
   325
haftmann@25101
   326
structure Nbe_Functions = CodeDataFun
haftmann@25101
   327
(
haftmann@25101
   328
  type T = univ_gr;
haftmann@25101
   329
  val empty = Graph.empty;
haftmann@25101
   330
  fun merge _ = Graph.merge (K true);
haftmann@25101
   331
  fun purge _ NONE _ = Graph.empty
haftmann@25101
   332
    | purge NONE _ _ = Graph.empty
haftmann@25101
   333
    | purge (SOME thy) (SOME cs) gr =
haftmann@25101
   334
        let
haftmann@25101
   335
          val cs_exisiting =
haftmann@25101
   336
            map_filter (CodeName.const_rev thy) (Graph.keys gr);
haftmann@25101
   337
          val dels = (Graph.all_preds gr
haftmann@25101
   338
              o map (CodeName.const thy)
haftmann@25101
   339
              o filter (member (op =) cs_exisiting)
haftmann@25101
   340
            ) cs;
haftmann@25101
   341
        in Graph.del_nodes dels gr end;
haftmann@25101
   342
);
haftmann@25101
   343
haftmann@25101
   344
(* compilation, evaluation and reification *)
haftmann@25101
   345
haftmann@25101
   346
fun compile_eval thy code vs_ty_t deps =
haftmann@25190
   347
  vs_ty_t
haftmann@25190
   348
  |> eval_term (Nbe_Functions.change thy (ensure_stmts code)) deps
haftmann@25101
   349
  |> term_of_univ thy;
haftmann@25101
   350
haftmann@24155
   351
(* evaluation with type reconstruction *)
haftmann@24155
   352
haftmann@24381
   353
fun eval thy code t vs_ty_t deps =
haftmann@24155
   354
  let
haftmann@24347
   355
    val ty = type_of t;
haftmann@24155
   356
    fun subst_Frees [] = I
haftmann@24155
   357
      | subst_Frees inst =
haftmann@24155
   358
          Term.map_aterms (fn (t as Term.Free (s, _)) => the_default t (AList.lookup (op =) inst s)
haftmann@24155
   359
                            | t => t);
haftmann@24155
   360
    val anno_vars =
haftmann@24155
   361
      subst_Frees (map (fn (s, T) => (s, Term.Free (s, T))) (Term.add_frees t []))
haftmann@24155
   362
      #> subst_Vars (map (fn (ixn, T) => (ixn, Var (ixn, T))) (Term.add_vars t []))
haftmann@24347
   363
    fun constrain t =
wenzelm@24680
   364
      singleton (Syntax.check_terms (ProofContext.init thy)) (TypeInfer.constrain ty t);
haftmann@24155
   365
    fun check_tvars t = if null (Term.term_tvars t) then t else
haftmann@24155
   366
      error ("Illegal schematic type variables in normalized term: "
haftmann@24155
   367
        ^ setmp show_types true (Sign.string_of_term thy) t);
haftmann@25167
   368
    val string_of_term = setmp show_types true (Sign.string_of_term thy);
haftmann@24155
   369
  in
haftmann@25101
   370
    compile_eval thy code vs_ty_t deps
haftmann@25167
   371
    |> tracing (fn t => "Normalized:\n" ^ string_of_term t)
haftmann@24155
   372
    |> anno_vars
haftmann@25167
   373
    |> tracing (fn t => "Vars typed:\n" ^ string_of_term t)
haftmann@24155
   374
    |> constrain
haftmann@25167
   375
    |> tracing (fn t => "Types inferred:\n" ^ string_of_term t)
haftmann@25101
   376
    |> tracing (fn t => "---\n")
haftmann@24155
   377
    |> check_tvars
haftmann@24155
   378
  end;
haftmann@24155
   379
haftmann@24155
   380
(* evaluation oracle *)
haftmann@24155
   381
haftmann@24839
   382
exception Norm of CodeThingol.code * term
haftmann@24381
   383
  * (CodeThingol.typscheme * CodeThingol.iterm) * string list;
haftmann@24155
   384
haftmann@24839
   385
fun norm_oracle (thy, Norm (code, t, vs_ty_t, deps)) =
haftmann@24381
   386
  Logic.mk_equals (t, eval thy code t vs_ty_t deps);
haftmann@24155
   387
haftmann@24839
   388
fun norm_invoke thy code t vs_ty_t deps =
haftmann@24839
   389
  Thm.invoke_oracle_i thy "HOL.norm" (thy, Norm (code, t, vs_ty_t, deps));
haftmann@24283
   390
  (*FIXME get rid of hardwired theory name*)
haftmann@24155
   391
haftmann@24839
   392
fun norm_conv ct =
haftmann@24155
   393
  let
haftmann@24155
   394
    val thy = Thm.theory_of_cterm ct;
haftmann@24381
   395
    fun conv code vs_ty_t deps ct =
haftmann@24155
   396
      let
haftmann@24155
   397
        val t = Thm.term_of ct;
haftmann@24839
   398
      in norm_invoke thy code t vs_ty_t deps end;
haftmann@24219
   399
  in CodePackage.eval_conv thy conv ct end;
haftmann@24155
   400
haftmann@24839
   401
fun norm_term thy =
haftmann@24839
   402
  let
haftmann@24839
   403
    fun invoke code vs_ty_t deps t =
haftmann@24839
   404
      eval thy code t vs_ty_t deps;
haftmann@24839
   405
  in CodePackage.eval_term thy invoke #> Code.postprocess_term thy end;
haftmann@24839
   406
haftmann@24155
   407
(* evaluation command *)
haftmann@24155
   408
haftmann@24155
   409
fun norm_print_term ctxt modes t =
haftmann@24155
   410
  let
haftmann@24155
   411
    val thy = ProofContext.theory_of ctxt;
haftmann@24839
   412
    val t' = norm_term thy t;
haftmann@24839
   413
    val ty' = Term.type_of t';
wenzelm@24634
   414
    val p = PrintMode.with_modes modes (fn () =>
wenzelm@24920
   415
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt t'), Pretty.fbrk,
wenzelm@24920
   416
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt ty')]) ();
haftmann@24155
   417
  in Pretty.writeln p end;
haftmann@24155
   418
haftmann@24155
   419
haftmann@24155
   420
(** Isar setup **)
haftmann@24155
   421
wenzelm@24508
   422
fun norm_print_term_cmd (modes, s) state =
haftmann@24155
   423
  let val ctxt = Toplevel.context_of state
wenzelm@24508
   424
  in norm_print_term ctxt modes (Syntax.read_term ctxt s) end;
haftmann@24155
   425
haftmann@24839
   426
val setup = Theory.add_oracle ("norm", norm_oracle)
haftmann@24155
   427
haftmann@24155
   428
local structure P = OuterParse and K = OuterKeyword in
haftmann@24155
   429
haftmann@24155
   430
val opt_modes = Scan.optional (P.$$$ "(" |-- P.!!! (Scan.repeat1 P.xname --| P.$$$ ")")) [];
haftmann@24155
   431
wenzelm@24867
   432
val _ =
haftmann@24155
   433
  OuterSyntax.improper_command "normal_form" "normalize term by evaluation" K.diag
haftmann@24155
   434
    (opt_modes -- P.typ >> (Toplevel.keep o norm_print_term_cmd));
haftmann@24155
   435
haftmann@24155
   436
end;
haftmann@24155
   437
haftmann@24155
   438
end;