src/Tools/nbe.ML
author haftmann
Thu May 26 15:27:50 2016 +0200 (2016-05-26)
changeset 63157 65a81a4ef7f8
parent 63156 3cb84e4469a7
child 63158 534f16b0ca39
permissions -rw-r--r--
clarified naming conventions and code for code evaluation sandwiches
     1 (*  Title:      Tools/nbe.ML
     2     Authors:    Klaus Aehlig, LMU Muenchen; Tobias Nipkow, Florian Haftmann, TU Muenchen
     3 
     4 Normalization by evaluation, based on generic code generator.
     5 *)
     6 
     7 signature NBE =
     8 sig
     9   val dynamic_conv: Proof.context -> conv
    10   val dynamic_value: Proof.context -> term -> term
    11   val static_conv: { ctxt: Proof.context, consts: string list } -> Proof.context -> conv
    12   val static_value: { ctxt: Proof.context, consts: string list } -> Proof.context -> term -> term
    13 
    14   datatype Univ =
    15       Const of int * Univ list               (*named (uninterpreted) constants*)
    16     | DFree of string * int                  (*free (uninterpreted) dictionary parameters*)
    17     | BVar of int * Univ list
    18     | Abs of (int * (Univ list -> Univ)) * Univ list
    19   val apps: Univ -> Univ list -> Univ        (*explicit applications*)
    20   val abss: int -> (Univ list -> Univ) -> Univ
    21                                              (*abstractions as closures*)
    22   val same: Univ * Univ -> bool
    23 
    24   val put_result: (unit -> Univ list -> Univ list) -> Proof.context -> Proof.context
    25   val trace: bool Config.T
    26 
    27   val add_const_alias: thm -> theory -> theory
    28 end;
    29 
    30 structure Nbe: NBE =
    31 struct
    32 
    33 (* generic non-sense *)
    34 
    35 val trace = Attrib.setup_config_bool @{binding "nbe_trace"} (K false);
    36 fun traced ctxt f x = if Config.get ctxt trace then (tracing (f x); x) else x;
    37 
    38 
    39 (** certificates and oracle for "trivial type classes" **)
    40 
    41 structure Triv_Class_Data = Theory_Data
    42 (
    43   type T = (class * thm) list;
    44   val empty = [];
    45   val extend = I;
    46   fun merge data : T = AList.merge (op =) (K true) data;
    47 );
    48 
    49 fun add_const_alias thm thy =
    50   let
    51     val (ofclass, eqn) = case try Logic.dest_equals (Thm.prop_of thm)
    52      of SOME ofclass_eq => ofclass_eq
    53       | _ => error ("Bad certificate: " ^ Thm.string_of_thm_global thy thm);
    54     val (T, class) = case try Logic.dest_of_class ofclass
    55      of SOME T_class => T_class
    56       | _ => error ("Bad certificate: " ^ Thm.string_of_thm_global thy thm);
    57     val tvar = case try Term.dest_TVar T
    58      of SOME (tvar as (_, sort)) => if null (filter (can (Axclass.get_info thy)) sort)
    59           then tvar
    60           else error ("Bad sort: " ^ Thm.string_of_thm_global thy thm)
    61       | _ => error ("Bad type: " ^ Thm.string_of_thm_global thy thm);
    62     val _ = if Term.add_tvars eqn [] = [tvar] then ()
    63       else error ("Inconsistent type: " ^ Thm.string_of_thm_global thy thm);
    64     val lhs_rhs = case try Logic.dest_equals eqn
    65      of SOME lhs_rhs => lhs_rhs
    66       | _ => error ("Not an equation: " ^ Syntax.string_of_term_global thy eqn);
    67     val c_c' = case try (apply2 (Axclass.unoverload_const thy o dest_Const)) lhs_rhs
    68      of SOME c_c' => c_c'
    69       | _ => error ("Not an equation with two constants: "
    70           ^ Syntax.string_of_term_global thy eqn);
    71     val _ = if the_list (Axclass.class_of_param thy (snd c_c')) = [class] then ()
    72       else error ("Inconsistent class: " ^ Thm.string_of_thm_global thy thm);
    73   in Triv_Class_Data.map (AList.update (op =) (class, Thm.trim_context thm)) thy end;
    74 
    75 local
    76 
    77 val get_triv_classes = map fst o Triv_Class_Data.get;
    78 
    79 val (_, triv_of_class) = Context.>>> (Context.map_theory_result
    80   (Thm.add_oracle (@{binding triv_of_class}, fn (thy, T, class) =>
    81     Thm.global_cterm_of thy (Logic.mk_of_class (T, class)))));
    82 
    83 in
    84 
    85 fun lift_triv_classes_conv ctxt conv ct =
    86   let
    87     val thy = Proof_Context.theory_of ctxt;
    88     val algebra = Sign.classes_of thy;
    89     val triv_classes = get_triv_classes thy;
    90     fun additional_classes sort = filter_out (fn class => Sorts.sort_le algebra (sort, [class])) triv_classes;
    91     fun mk_entry (v, sort) =
    92       let
    93         val T = TFree (v, sort);
    94         val cT = Thm.ctyp_of ctxt T;
    95         val triv_sort = additional_classes sort;
    96       in
    97         (v, (Sorts.inter_sort algebra (sort, triv_sort),
    98           (cT, AList.make (fn class => Thm.of_class (cT, class)) sort
    99             @ AList.make (fn class => triv_of_class (thy, T, class)) triv_sort)))
   100       end;
   101     val vs_tab = map mk_entry (Term.add_tfrees (Thm.term_of ct) []);
   102     fun instantiate thm =
   103       let
   104         val tvars =
   105           Term.add_tvars (#1 (Logic.dest_equals (Logic.strip_imp_concl (Thm.prop_of thm)))) [];
   106         val instT = map2 (fn v => fn (_, (_, (cT, _))) => (v, cT)) tvars vs_tab;
   107       in Thm.instantiate (instT, []) thm end;
   108     fun of_class (TFree (v, _), class) =
   109           the (AList.lookup (op =) ((snd o snd o the o AList.lookup (op =) vs_tab) v) class)
   110       | of_class (T, _) = error ("Bad type " ^ Syntax.string_of_typ ctxt T);
   111     fun strip_of_class thm =
   112       let
   113         val prems_of_class = Thm.prop_of thm
   114           |> Logic.strip_imp_prems
   115           |> map (Logic.dest_of_class #> of_class);
   116       in fold Thm.elim_implies prems_of_class thm end;
   117   in
   118     ct
   119     |> Thm.term_of
   120     |> (map_types o map_type_tfree)
   121         (fn (v, _) => TFree (v, (fst o the o AList.lookup (op =) vs_tab) v))
   122     |> Thm.cterm_of ctxt
   123     |> conv
   124     |> Thm.strip_shyps
   125     |> Thm.varifyT_global
   126     |> Thm.unconstrainT
   127     |> instantiate
   128     |> strip_of_class
   129   end;
   130 
   131 fun lift_triv_classes_rew ctxt rew t =
   132   let
   133     val thy = Proof_Context.theory_of ctxt;
   134     val algebra = Sign.classes_of thy;
   135     val triv_classes = get_triv_classes thy;
   136     val vs = Term.add_tfrees t [];
   137   in
   138     t
   139     |> (map_types o map_type_tfree)
   140         (fn (v, sort) => TFree (v, Sorts.inter_sort algebra (sort, triv_classes)))
   141     |> rew
   142     |> (map_types o map_type_tfree)
   143         (fn (v, sort) => TFree (v, the_default sort (AList.lookup (op =) vs v)))
   144   end;
   145 
   146 end;
   147 
   148 
   149 (** the semantic universe **)
   150 
   151 (*
   152    Functions are given by their semantical function value. To avoid
   153    trouble with the ML-type system, these functions have the most
   154    generic type, that is "Univ list -> Univ". The calling convention is
   155    that the arguments come as a list, the last argument first. In
   156    other words, a function call that usually would look like
   157 
   158    f x_1 x_2 ... x_n   or   f(x_1,x_2, ..., x_n)
   159 
   160    would be in our convention called as
   161 
   162               f [x_n,..,x_2,x_1]
   163 
   164    Moreover, to handle functions that are still waiting for some
   165    arguments we have additionally a list of arguments collected to far
   166    and the number of arguments we're still waiting for.
   167 *)
   168 
   169 datatype Univ =
   170     Const of int * Univ list           (*named (uninterpreted) constants*)
   171   | DFree of string * int              (*free (uninterpreted) dictionary parameters*)
   172   | BVar of int * Univ list            (*bound variables, named*)
   173   | Abs of (int * (Univ list -> Univ)) * Univ list
   174                                        (*abstractions as closures*);
   175 
   176 
   177 (* constructor functions *)
   178 
   179 fun abss n f = Abs ((n, f), []);
   180 fun apps (Abs ((n, f), xs)) ys = let val k = n - length ys in
   181       case int_ord (k, 0)
   182        of EQUAL => f (ys @ xs)
   183         | LESS => let val (zs, ws) = chop (~ k) ys in apps (f (ws @ xs)) zs end
   184         | GREATER => Abs ((k, f), ys @ xs) (*note: reverse convention also for apps!*)
   185       end
   186   | apps (Const (name, xs)) ys = Const (name, ys @ xs)
   187   | apps (BVar (n, xs)) ys = BVar (n, ys @ xs);
   188 
   189 fun same (Const (k, xs), Const (l, ys)) = k = l andalso eq_list same (xs, ys)
   190   | same (DFree (s, k), DFree (t, l)) = s = t andalso k = l
   191   | same (BVar (k, xs), BVar (l, ys)) = k = l andalso eq_list same (xs, ys)
   192   | same _ = false;
   193 
   194 
   195 (** assembling and compiling ML code from terms **)
   196 
   197 (* abstract ML syntax *)
   198 
   199 infix 9 `$` `$$`;
   200 fun e1 `$` e2 = "(" ^ e1 ^ " " ^ e2 ^ ")";
   201 fun e `$$` [] = e
   202   | e `$$` es = "(" ^ e ^ " " ^ space_implode " " es ^ ")";
   203 fun ml_abs v e = "(fn " ^ v ^ " => " ^ e ^ ")";
   204 
   205 fun ml_cases t cs =
   206   "(case " ^ t ^ " of " ^ space_implode " | " (map (fn (p, t) => p ^ " => " ^ t) cs) ^ ")";
   207 fun ml_Let d e = "let\n" ^ d ^ " in " ^ e ^ " end";
   208 fun ml_as v t = "(" ^ v ^ " as " ^ t ^ ")";
   209 
   210 fun ml_and [] = "true"
   211   | ml_and [x] = x
   212   | ml_and xs = "(" ^ space_implode " andalso " xs ^ ")";
   213 fun ml_if b x y = "(if " ^ b ^ " then " ^ x ^ " else " ^ y ^ ")";
   214 
   215 fun ml_list es = "[" ^ commas es ^ "]";
   216 
   217 fun ml_fundefs ([(name, [([], e)])]) =
   218       "val " ^ name ^ " = " ^ e ^ "\n"
   219   | ml_fundefs (eqs :: eqss) =
   220       let
   221         fun fundef (name, eqs) =
   222           let
   223             fun eqn (es, e) = name ^ " " ^ space_implode " " es ^ " = " ^ e
   224           in space_implode "\n  | " (map eqn eqs) end;
   225       in
   226         (prefix "fun " o fundef) eqs :: map (prefix "and " o fundef) eqss
   227         |> cat_lines
   228         |> suffix "\n"
   229       end;
   230 
   231 
   232 (* nbe specific syntax and sandbox communication *)
   233 
   234 structure Univs = Proof_Data
   235 (
   236   type T = unit -> Univ list -> Univ list;
   237   val empty: T = fn () => raise Fail "Univs";
   238   fun init _ = empty;
   239 );
   240 val get_result = Univs.get;
   241 val put_result = Univs.put;
   242 
   243 local
   244   val prefix = "Nbe.";
   245   val name_put = prefix ^ "put_result";
   246   val name_const = prefix ^ "Const";
   247   val name_abss = prefix ^ "abss";
   248   val name_apps = prefix ^ "apps";
   249   val name_same = prefix ^ "same";
   250 in
   251 
   252 val univs_cookie = (get_result, put_result, name_put);
   253 
   254 fun nbe_fun idx_of 0 (Code_Symbol.Constant "") = "nbe_value"
   255   | nbe_fun idx_of i sym = "c_" ^ string_of_int (idx_of sym)
   256       ^ "_" ^ Code_Symbol.default_base sym ^ "_" ^ string_of_int i;
   257 fun nbe_dict v n = "d_" ^ v ^ "_" ^ string_of_int n;
   258 fun nbe_bound v = "v_" ^ v;
   259 fun nbe_bound_optional NONE = "_"
   260   | nbe_bound_optional (SOME v) = nbe_bound v;
   261 fun nbe_default v = "w_" ^ v;
   262 
   263 (*note: these three are the "turning spots" where proper argument order is established!*)
   264 fun nbe_apps t [] = t
   265   | nbe_apps t ts = name_apps `$$` [t, ml_list (rev ts)];
   266 fun nbe_apps_local idx_of i c ts = nbe_fun idx_of i c `$` ml_list (rev ts);
   267 fun nbe_apps_constr ctxt idx_of c ts =
   268   let
   269     val c' = if Config.get ctxt trace
   270       then string_of_int (idx_of c) ^ " (*" ^ Code_Symbol.default_base c ^ "*)"
   271       else string_of_int (idx_of c);
   272   in name_const `$` ("(" ^ c' ^ ", " ^ ml_list (rev ts) ^ ")") end;
   273 
   274 fun nbe_abss 0 f = f `$` ml_list []
   275   | nbe_abss n f = name_abss `$$` [string_of_int n, f];
   276 
   277 fun nbe_same (v1, v2) = "(" ^ name_same ^ " (" ^ nbe_bound v1 ^ ", " ^ nbe_bound v2 ^ "))";
   278 
   279 end;
   280 
   281 open Basic_Code_Symbol;
   282 open Basic_Code_Thingol;
   283 
   284 
   285 (* code generation *)
   286 
   287 fun assemble_eqnss ctxt idx_of deps eqnss =
   288   let
   289     fun prep_eqns (c, (vs, eqns)) =
   290       let
   291         val dicts = maps (fn (v, sort) => map_index (nbe_dict v o fst) sort) vs;
   292         val num_args = length dicts + ((length o fst o hd) eqns);
   293       in (c, (num_args, (dicts, eqns))) end;
   294     val eqnss' = map prep_eqns eqnss;
   295 
   296     fun assemble_constapp sym dss ts = 
   297       let
   298         val ts' = (maps o map) assemble_dict dss @ ts;
   299       in case AList.lookup (op =) eqnss' sym
   300        of SOME (num_args, _) => if num_args <= length ts'
   301             then let val (ts1, ts2) = chop num_args ts'
   302             in nbe_apps (nbe_apps_local idx_of 0 sym ts1) ts2
   303             end else nbe_apps (nbe_abss num_args (nbe_fun idx_of 0 sym)) ts'
   304         | NONE => if member (op =) deps sym
   305             then nbe_apps (nbe_fun idx_of 0 sym) ts'
   306             else nbe_apps_constr ctxt idx_of sym ts'
   307       end
   308     and assemble_classrels classrels =
   309       fold_rev (fn classrel => assemble_constapp (Class_Relation classrel) [] o single) classrels
   310     and assemble_dict (Dict (classrels, x)) =
   311           assemble_classrels classrels (assemble_plain_dict x)
   312     and assemble_plain_dict (Dict_Const (inst, dss)) =
   313           assemble_constapp (Class_Instance inst) dss []
   314       | assemble_plain_dict (Dict_Var { var, index, ... }) =
   315           nbe_dict var index
   316 
   317     fun assemble_iterm constapp =
   318       let
   319         fun of_iterm match_cont t =
   320           let
   321             val (t', ts) = Code_Thingol.unfold_app t
   322           in of_iapp match_cont t' (fold_rev (cons o of_iterm NONE) ts []) end
   323         and of_iapp match_cont (IConst { sym, dicts = dss, ... }) ts = constapp sym dss ts
   324           | of_iapp match_cont (IVar v) ts = nbe_apps (nbe_bound_optional v) ts
   325           | of_iapp match_cont ((v, _) `|=> t) ts =
   326               nbe_apps (nbe_abss 1 (ml_abs (ml_list [nbe_bound_optional v]) (of_iterm NONE t))) ts
   327           | of_iapp match_cont (ICase { term = t, clauses = clauses, primitive = t0, ... }) ts =
   328               nbe_apps (ml_cases (of_iterm NONE t)
   329                 (map (fn (p, t) => (of_iterm NONE p, of_iterm match_cont t)) clauses
   330                   @ [("_", case match_cont of SOME s => s | NONE => of_iterm NONE t0)])) ts
   331       in of_iterm end;
   332 
   333     fun subst_nonlin_vars args =
   334       let
   335         val vs = (fold o Code_Thingol.fold_varnames)
   336           (fn v => AList.map_default (op =) (v, 0) (Integer.add 1)) args [];
   337         val names = Name.make_context (map fst vs);
   338         fun declare v k ctxt =
   339           let val vs = Name.invent ctxt v k
   340           in (vs, fold Name.declare vs ctxt) end;
   341         val (vs_renames, _) = fold_map (fn (v, k) => if k > 1
   342           then declare v (k - 1) #>> (fn vs => (v, vs))
   343           else pair (v, [])) vs names;
   344         val samepairs = maps (fn (v, vs) => map (pair v) vs) vs_renames;
   345         fun subst_vars (t as IConst _) samepairs = (t, samepairs)
   346           | subst_vars (t as IVar NONE) samepairs = (t, samepairs)
   347           | subst_vars (t as IVar (SOME v)) samepairs = (case AList.lookup (op =) samepairs v
   348              of SOME v' => (IVar (SOME v'), AList.delete (op =) v samepairs)
   349               | NONE => (t, samepairs))
   350           | subst_vars (t1 `$ t2) samepairs = samepairs
   351               |> subst_vars t1
   352               ||>> subst_vars t2
   353               |>> (op `$)
   354           | subst_vars (ICase { primitive = t, ... }) samepairs = subst_vars t samepairs;
   355         val (args', _) = fold_map subst_vars args samepairs;
   356       in (samepairs, args') end;
   357 
   358     fun assemble_eqn sym dicts default_args (i, (args, rhs)) =
   359       let
   360         val match_cont = if Code_Symbol.is_value sym then NONE
   361           else SOME (nbe_apps_local idx_of (i + 1) sym (dicts @ default_args));
   362         val assemble_arg = assemble_iterm
   363           (fn sym' => fn dss => fn ts => nbe_apps_constr ctxt idx_of sym' ((maps o map) (K "_")
   364             dss @ ts)) NONE;
   365         val assemble_rhs = assemble_iterm assemble_constapp match_cont;
   366         val (samepairs, args') = subst_nonlin_vars args;
   367         val s_args = map assemble_arg args';
   368         val s_rhs = if null samepairs then assemble_rhs rhs
   369           else ml_if (ml_and (map nbe_same samepairs))
   370             (assemble_rhs rhs) (the match_cont);
   371         val eqns = case match_cont
   372          of NONE => [([ml_list (rev (dicts @ s_args))], s_rhs)]
   373           | SOME default_rhs =>
   374               [([ml_list (rev (dicts @ map2 ml_as default_args s_args))], s_rhs),
   375                 ([ml_list (rev (dicts @ default_args))], default_rhs)]
   376       in (nbe_fun idx_of i sym, eqns) end;
   377 
   378     fun assemble_eqns (sym, (num_args, (dicts, eqns))) =
   379       let
   380         val default_args = map nbe_default
   381           (Name.invent Name.context "a" (num_args - length dicts));
   382         val eqns' = map_index (assemble_eqn sym dicts default_args) eqns
   383           @ (if Code_Symbol.is_value sym then [] else [(nbe_fun idx_of (length eqns) sym,
   384             [([ml_list (rev (dicts @ default_args))],
   385               nbe_apps_constr ctxt idx_of sym (dicts @ default_args))])]);
   386       in (eqns', nbe_abss num_args (nbe_fun idx_of 0 sym)) end;
   387 
   388     val (fun_vars, fun_vals) = map_split assemble_eqns eqnss';
   389     val deps_vars = ml_list (map (nbe_fun idx_of 0) deps);
   390   in ml_abs deps_vars (ml_Let (ml_fundefs (flat fun_vars)) (ml_list fun_vals)) end;
   391 
   392 
   393 (* compile equations *)
   394 
   395 fun compile_eqnss ctxt nbe_program raw_deps [] = []
   396   | compile_eqnss ctxt nbe_program raw_deps eqnss =
   397       let
   398         val (deps, deps_vals) = split_list (map_filter
   399           (fn dep => Option.map (fn univ => (dep, univ)) (fst ((Code_Symbol.Graph.get_node nbe_program dep)))) raw_deps);
   400         val idx_of = raw_deps
   401           |> map (fn dep => (dep, snd (Code_Symbol.Graph.get_node nbe_program dep)))
   402           |> AList.lookup (op =)
   403           |> (fn f => the o f);
   404         val s = assemble_eqnss ctxt idx_of deps eqnss;
   405         val cs = map fst eqnss;
   406       in
   407         s
   408         |> traced ctxt (fn s => "\n--- code to be evaluated:\n" ^ s)
   409         |> pair ""
   410         |> Code_Runtime.value ctxt univs_cookie
   411         |> (fn f => f deps_vals)
   412         |> (fn univs => cs ~~ univs)
   413       end;
   414 
   415 
   416 (* extract equations from statements *)
   417 
   418 fun dummy_const sym dss =
   419   IConst { sym = sym, typargs = [], dicts = dss,
   420     dom = [], annotation = NONE };
   421 
   422 fun eqns_of_stmt (_, Code_Thingol.NoStmt) =
   423       []
   424   | eqns_of_stmt (_, Code_Thingol.Fun ((_, []), _)) =
   425       []
   426   | eqns_of_stmt (sym_const, Code_Thingol.Fun (((vs, _), eqns), _)) =
   427       [(sym_const, (vs, map fst eqns))]
   428   | eqns_of_stmt (_, Code_Thingol.Datatypecons _) =
   429       []
   430   | eqns_of_stmt (_, Code_Thingol.Datatype _) =
   431       []
   432   | eqns_of_stmt (sym_class, Code_Thingol.Class (v, (classrels, classparams))) =
   433       let
   434         val syms = map Class_Relation classrels @ map (Constant o fst) classparams;
   435         val params = Name.invent Name.context "d" (length syms);
   436         fun mk (k, sym) =
   437           (sym, ([(v, [])],
   438             [([dummy_const sym_class [] `$$ map (IVar o SOME) params],
   439               IVar (SOME (nth params k)))]));
   440       in map_index mk syms end
   441   | eqns_of_stmt (_, Code_Thingol.Classrel _) =
   442       []
   443   | eqns_of_stmt (_, Code_Thingol.Classparam _) =
   444       []
   445   | eqns_of_stmt (sym_inst, Code_Thingol.Classinst { class, tyco, vs, superinsts, inst_params, ... }) =
   446       [(sym_inst, (vs, [([], dummy_const (Type_Class class) [] `$$
   447         map (fn (class, dss) => dummy_const (Class_Instance (tyco, class)) dss) superinsts
   448         @ map (IConst o fst o snd o fst) inst_params)]))];
   449 
   450 
   451 (* compile whole programs *)
   452 
   453 fun ensure_const_idx name (nbe_program, (maxidx, idx_tab)) =
   454   if can (Code_Symbol.Graph.get_node nbe_program) name
   455   then (nbe_program, (maxidx, idx_tab))
   456   else (Code_Symbol.Graph.new_node (name, (NONE, maxidx)) nbe_program,
   457     (maxidx + 1, Inttab.update_new (maxidx, name) idx_tab));
   458 
   459 fun compile_stmts ctxt stmts_deps =
   460   let
   461     val names = map (fst o fst) stmts_deps;
   462     val names_deps = map (fn ((name, _), deps) => (name, deps)) stmts_deps;
   463     val eqnss = maps (eqns_of_stmt o fst) stmts_deps;
   464     val refl_deps = names_deps
   465       |> maps snd
   466       |> distinct (op =)
   467       |> fold (insert (op =)) names;
   468     fun compile nbe_program = eqnss
   469       |> compile_eqnss ctxt nbe_program refl_deps
   470       |> rpair nbe_program;
   471   in
   472     fold ensure_const_idx refl_deps
   473     #> apfst (fold (fn (name, deps) => fold (curry Code_Symbol.Graph.add_edge name) deps) names_deps
   474       #> compile
   475       #-> fold (fn (name, univ) => (Code_Symbol.Graph.map_node name o apfst) (K (SOME univ))))
   476   end;
   477 
   478 fun compile_program ctxt program =
   479   let
   480     fun add_stmts names (nbe_program, (maxidx, idx_tab)) = if exists ((can o Code_Symbol.Graph.get_node) nbe_program) names
   481       then (nbe_program, (maxidx, idx_tab))
   482       else (nbe_program, (maxidx, idx_tab))
   483         |> compile_stmts ctxt (map (fn name => ((name, Code_Symbol.Graph.get_node program name),
   484           Code_Symbol.Graph.immediate_succs program name)) names);
   485   in
   486     fold_rev add_stmts (Code_Symbol.Graph.strong_conn program)
   487   end;
   488 
   489 
   490 (** normalization **)
   491 
   492 (* term normalization by compilation *)
   493 
   494 fun compile_term ctxt nbe_program deps (vs : (string * sort) list, t) =
   495   let 
   496     val dict_frees = maps (fn (v, sort) => map_index (curry DFree v o fst) sort) vs;
   497   in
   498     (Code_Symbol.value, (vs, [([], t)]))
   499     |> singleton (compile_eqnss ctxt nbe_program deps)
   500     |> snd
   501     |> (fn t => apps t (rev dict_frees))
   502   end;
   503 
   504 
   505 (* reconstruction *)
   506 
   507 fun term_of_univ ctxt (idx_tab : Code_Symbol.T Inttab.table) t =
   508   let
   509     fun take_until f [] = []
   510       | take_until f (x :: xs) = if f x then [] else x :: take_until f xs;
   511     fun is_dict (Const (idx, _)) =
   512           (case Inttab.lookup idx_tab idx of
   513             SOME (Constant _) => false
   514           | _ => true)
   515       | is_dict (DFree _) = true
   516       | is_dict _ = false;
   517     fun const_of_idx idx =
   518       case Inttab.lookup idx_tab idx of SOME (Constant const) => const;
   519     fun of_apps bounds (t, ts) =
   520       fold_map (of_univ bounds) ts
   521       #>> (fn ts' => list_comb (t, rev ts'))
   522     and of_univ bounds (Const (idx, ts)) typidx =
   523           let
   524             val ts' = take_until is_dict ts;
   525             val const = const_of_idx idx;
   526             val T = map_type_tvar (fn ((v, i), _) =>
   527               Type_Infer.param typidx (v ^ string_of_int i, []))
   528                 (Sign.the_const_type (Proof_Context.theory_of ctxt) const);
   529             val typidx' = typidx + 1;
   530           in of_apps bounds (Term.Const (const, T), ts') typidx' end
   531       | of_univ bounds (BVar (n, ts)) typidx =
   532           of_apps bounds (Bound (bounds - n - 1), ts) typidx
   533       | of_univ bounds (t as Abs _) typidx =
   534           typidx
   535           |> of_univ (bounds + 1) (apps t [BVar (bounds, [])])
   536           |-> (fn t' => pair (Term.Abs ("u", dummyT, t')))
   537   in of_univ 0 t 0 |> fst end;
   538 
   539 
   540 (* normalize with type reconstruction *)
   541 
   542 fun normalize (nbe_program, idx_tab) raw_ctxt t_original ((vs, ty) : typscheme, t) deps =
   543   let
   544     val ctxt = Syntax.init_pretty_global (Proof_Context.theory_of raw_ctxt);
   545     val string_of_term = Syntax.string_of_term (Config.put show_types true ctxt);
   546     fun type_infer t' =
   547       Syntax.check_term
   548         (ctxt
   549           |> Config.put Type_Infer.object_logic false
   550           |> Config.put Type_Infer_Context.const_sorts false)
   551         (Type.constraint (fastype_of t_original) t');
   552     fun check_tvars t' =
   553       if null (Term.add_tvars t' []) then t'
   554       else error ("Illegal schematic type variables in normalized term: " ^ string_of_term t');
   555   in
   556     compile_term ctxt nbe_program deps (vs, t)
   557     |> term_of_univ ctxt idx_tab
   558     |> traced ctxt (fn t => "Normalized:\n" ^ string_of_term t)
   559     |> type_infer
   560     |> traced ctxt (fn t => "Types inferred:\n" ^ string_of_term t)
   561     |> check_tvars
   562     |> traced ctxt (fn _ => "---\n")
   563   end;
   564 
   565 
   566 (* function store *)
   567 
   568 structure Nbe_Functions = Code_Data
   569 (
   570   type T = (Univ option * int) Code_Symbol.Graph.T * (int * Code_Symbol.T Inttab.table);
   571   val empty = (Code_Symbol.Graph.empty, (0, Inttab.empty));
   572 );
   573 
   574 fun compile ignore_cache ctxt program =
   575   let
   576     val (nbe_program, (_, idx_tab)) =
   577       Nbe_Functions.change (if ignore_cache then NONE else SOME (Proof_Context.theory_of ctxt))
   578         (compile_program ctxt program);
   579   in (nbe_program, idx_tab) end;
   580 
   581 
   582 (* evaluation oracle *)
   583 
   584 fun mk_equals ctxt lhs raw_rhs =
   585   let
   586     val ty = Thm.typ_of_cterm lhs;
   587     val eq = Thm.cterm_of ctxt (Term.Const (@{const_name Pure.eq}, ty --> ty --> propT));
   588     val rhs = Thm.cterm_of ctxt raw_rhs;
   589   in Thm.mk_binop eq lhs rhs end;
   590 
   591 val (_, raw_oracle) = Context.>>> (Context.map_theory_result
   592   (Thm.add_oracle (@{binding normalization_by_evaluation},
   593     fn (nbe_program_idx_tab, ctxt, vs_ty_t, deps, ct) =>
   594       mk_equals ctxt ct (normalize nbe_program_idx_tab ctxt (Thm.term_of ct) vs_ty_t deps))));
   595 
   596 fun oracle nbe_program_idx_tab ctxt vs_ty_t deps ct =
   597   raw_oracle (nbe_program_idx_tab, ctxt, vs_ty_t, deps, ct);
   598 
   599 fun dynamic_conv ctxt = lift_triv_classes_conv ctxt
   600   (Code_Thingol.dynamic_conv ctxt (fn program =>
   601     oracle (compile false ctxt program) ctxt));
   602 
   603 fun dynamic_value ctxt = lift_triv_classes_rew ctxt
   604   (Code_Thingol.dynamic_value ctxt I (fn program =>
   605     normalize (compile false ctxt program) ctxt));
   606 
   607 fun static_conv (ctxt_consts as { ctxt, ... }) =
   608   let
   609     val conv = Code_Thingol.static_conv_thingol ctxt_consts
   610       (fn { program, ... } => oracle (compile true ctxt program));
   611   in fn ctxt' => lift_triv_classes_conv ctxt' (conv ctxt') end;
   612 
   613 fun static_value { ctxt, consts } =
   614   let
   615     val comp = Code_Thingol.static_value { ctxt = ctxt, lift_postproc = I, consts = consts }
   616       (fn { program, ... } => normalize (compile false ctxt program));
   617   in fn ctxt' => lift_triv_classes_rew ctxt' (comp ctxt') end;
   618 
   619 end;