clarified codegen interfaces
authorhaftmann
Tue, 30 Sep 2008 12:49:18 +0200
changeset 28423 9fc3befd8191
parent 28422 bfa368164502
child 28424 fc6ce1c4d5b7
clarified codegen interfaces
src/HOL/Library/Efficient_Nat.thy
src/HOL/Tools/datatype_codegen.ML
src/HOL/Tools/typecopy_package.ML
src/Pure/Isar/code.ML
src/Pure/Isar/code_unit.ML
src/Tools/code/code_funcgr.ML
src/Tools/code/code_thingol.ML
src/Tools/nbe.ML
--- a/src/HOL/Library/Efficient_Nat.thy	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/HOL/Library/Efficient_Nat.thy	Tue Sep 30 12:49:18 2008 +0200
@@ -219,17 +219,20 @@
     then remove_suc_clause thy ths else ths
   end;
 
-fun lift f thy thms1 =
+fun lift f thy eqns1 =
   let
-    val thms2 = Drule.zero_var_indexes_list thms1;
-    val thms3 = try (map (fn thm => thm RS @{thm meta_eq_to_obj_eq})
+    val eqns2 = ((map o apfst) (AxClass.overload thy)
+      o burrow_fst Drule.zero_var_indexes_list) eqns1;
+    val thms3 = try (map fst
+      #> map (fn thm => thm RS @{thm meta_eq_to_obj_eq})
       #> f thy
       #> map (fn thm => thm RS @{thm eq_reflection})
-      #> map (Conv.fconv_rule Drule.beta_eta_conversion)) thms2;
+      #> map (Conv.fconv_rule Drule.beta_eta_conversion)) eqns2;
     val thms4 = Option.map Drule.zero_var_indexes_list thms3;
   in case thms4
    of NONE => NONE
-    | SOME thms4 => if Thm.eq_thms (thms2, thms4) then NONE else SOME thms4
+    | SOME thms4 => if Thm.eq_thms (map fst eqns2, thms4)
+        then NONE else SOME (map (Code_Unit.mk_eqn thy) thms4)
   end
 
 in
--- a/src/HOL/Tools/datatype_codegen.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/HOL/Tools/datatype_codegen.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -449,9 +449,10 @@
     fun tac thms = Class.intro_classes_tac []
       THEN ALLGOALS (ProofContext.fact_tac thms);
     fun get_eq' thy dtco = get_eq thy dtco
-      |> map (Code_Unit.constrain_thm [HOLogic.class_eq])
+      |> map (Code_Unit.constrain_thm thy [HOLogic.class_eq])
       |> map Simpdata.mk_eq
-      |> map (MetaSimplifier.rewrite_rule [Thm.transfer thy @{thm equals_eq}]);
+      |> map (MetaSimplifier.rewrite_rule [Thm.transfer thy @{thm equals_eq}])
+      |> map (AxClass.unoverload thy);
     fun add_eq_thms dtco thy =
       let
         val ty = Type (dtco, map TFree vs');
@@ -460,7 +461,8 @@
         val eq_refl = @{thm HOL.eq_refl}
           |> Thm.instantiate
               ([pairself (Thm.ctyp_of thy) (TVar (("'a", 0), @{sort eq}), Logic.varifyT ty)], [])
-          |> Simpdata.mk_eq;
+          |> Simpdata.mk_eq
+          |> AxClass.unoverload thy;
         fun get_thms () = (eq_refl, false)
           :: rev (map (rpair true) (get_eq' (Theory.deref thy_ref) dtco));
       in
--- a/src/HOL/Tools/typecopy_package.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/HOL/Tools/typecopy_package.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -122,9 +122,10 @@
 
 fun add_typecopy_spec tyco thy =
   let
-    val SOME { constr, proj_def, inject, vs, ... } = get_info thy tyco;
-    val vs' = (map o apsnd) (curry (Sorts.inter_sort (Sign.classes_of thy)) [HOLogic.class_eq]) vs;
-    val ty = Type (tyco, map TFree vs');
+    val SOME { constr, proj_def, inject, vs = raw_vs, ... } = get_info thy tyco;
+    val vs = (map o apsnd)
+      (curry (Sorts.inter_sort (Sign.classes_of thy)) [HOLogic.class_eq]) raw_vs;
+    val ty = Type (tyco, map TFree vs);
     val ty_constr = Logic.unvarifyT (Sign.the_const_type thy constr);
     fun add_def tyco lthy =
       let
@@ -143,12 +144,14 @@
     fun add_eq_thms thy = 
       let
         val eq = inject
-          |> Code_Unit.constrain_thm [HOLogic.class_eq]
+          |> Code_Unit.constrain_thm thy [HOLogic.class_eq]
           |> Simpdata.mk_eq
-          |> MetaSimplifier.rewrite_rule [Thm.transfer thy @{thm equals_eq}];
+          |> MetaSimplifier.rewrite_rule [Thm.transfer thy @{thm equals_eq}]
+          |> AxClass.unoverload thy;
         val eq_refl = @{thm HOL.eq_refl}
           |> Thm.instantiate
-              ([pairself (Thm.ctyp_of thy) (TVar (("'a", 0), @{sort eq}), Logic.varifyT ty)], []);
+              ([pairself (Thm.ctyp_of thy) (TVar (("'a", 0), @{sort eq}), Logic.varifyT ty)], [])
+          |> AxClass.unoverload thy;
       in
         thy
         |> Code.add_eqn eq
@@ -158,7 +161,7 @@
     thy
     |> Code.add_datatype [(constr, ty_constr)]
     |> Code.add_eqn proj_def
-    |> TheoryTarget.instantiation ([tyco], vs', [HOLogic.class_eq])
+    |> TheoryTarget.instantiation ([tyco], vs, [HOLogic.class_eq])
     |> add_def tyco
     |-> (fn thm => Class.prove_instantiation_instance (K (tac [thm]))
     #> LocalTheory.exit_global
--- a/src/Pure/Isar/code.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/Pure/Isar/code.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -22,7 +22,7 @@
   val del_inline: thm -> theory -> theory
   val add_post: thm -> theory -> theory
   val del_post: thm -> theory -> theory
-  val add_functrans: string * (theory -> thm list -> thm list option) -> theory -> theory
+  val add_functrans: string * (theory -> (thm * bool) list -> (thm * bool) list option) -> theory -> theory
   val del_functrans: string -> theory -> theory
   val add_datatype: (string * typ) list -> theory -> theory
   val add_datatype_cmd: string list -> theory -> theory
@@ -40,11 +40,11 @@
   val get_datatype_of_constr: theory -> string -> string option
   val get_case_data: theory -> string -> (int * string list) option
   val is_undefined: theory -> string -> bool
-  val default_typ: theory -> string -> (string * sort) list * typ
+  val default_typscheme: theory -> string -> (string * sort) list * typ
 
-  val preprocess_conv: cterm -> thm
+  val preprocess_conv: theory -> cterm -> thm
   val preprocess_term: theory -> term -> term
-  val postprocess_conv: cterm -> thm
+  val postprocess_conv: theory -> cterm -> thm
   val postprocess_term: theory -> term -> term
 
   val add_attribute: string * (Args.T list -> attribute * Args.T list) -> theory -> theory
@@ -124,14 +124,13 @@
 
 fun certificate thy f r =
   case Susp.peek r
-   of SOME thms => (Susp.value o burrow_fst (f thy)) thms
+   of SOME thms => (Susp.value o f thy) thms
     | NONE => let
         val thy_ref = Theory.check_thy thy;
-      in Susp.delay (fn () => (burrow_fst (f (Theory.deref thy_ref)) o Susp.force) r) end;
+      in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
 
-fun add_drop_redundant (thm, linear) thms =
+fun add_drop_redundant thy (thm, linear) thms =
   let
-    val thy = Thm.theory_of_thm thm;
     val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
     val args = args_of thm;
     val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
@@ -143,9 +142,9 @@
       else false;
   in (thm, linear) :: filter_out drop thms end;
 
-fun add_thm _ thm (false, thms) = (false, Susp.map_force (add_drop_redundant thm) thms)
-  | add_thm true thm (true, thms) = (true, Susp.map_force (fn thms => thms @ [thm]) thms)
-  | add_thm false thm (true, thms) = (false, Susp.value [thm]);
+fun add_thm thy _ thm (false, thms) = (false, Susp.map_force (add_drop_redundant thy thm) thms)
+  | add_thm thy true thm (true, thms) = (true, Susp.map_force (fn thms => thms @ [thm]) thms)
+  | add_thm thy false thm (true, thms) = (false, Susp.value [thm]);
 
 fun add_lthms lthms _ = (false, lthms);
 
@@ -197,7 +196,7 @@
 datatype thmproc = Thmproc of {
   pre: MetaSimplifier.simpset,
   post: MetaSimplifier.simpset,
-  functrans: (string * (serial * (theory -> thm list -> thm list option))) list
+  functrans: (string * (serial * (theory -> (thm * bool) list -> (thm * bool) list option))) list
 };
 
 fun mk_thmproc ((pre, post), functrans) =
@@ -419,25 +418,19 @@
   end;
 
 
-
 (** theorem transformation and certification **)
 
-fun const_of thy = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
-
-fun const_of_eqn thy = AxClass.unoverload_const thy o const_of thy;
-
-fun common_typ_eqns [] = []
-  | common_typ_eqns [thm] = [thm]
-  | common_typ_eqns (thms as thm :: _) = (*FIXME is too general*)
+fun common_typ_eqns thy [] = []
+  | common_typ_eqns thy [thm] = [thm]
+  | common_typ_eqns thy (thms as thm :: _) = (*FIXME is too general*)
       let
-        val thy = Thm.theory_of_thm thm;
         fun incr_thm thm max =
           let
             val thm' = incr_indexes max thm;
             val max' = Thm.maxidx_of thm' + 1;
           in (thm', max') end;
         val (thms', maxidx) = fold_map incr_thm thms 0;
-        val ty1 :: tys = map (snd o const_of thy) thms';
+        val ty1 :: tys = map (snd o Code_Unit.const_typ_eqn) thms';
         fun unify ty env = Sign.typ_unify thy (ty1, ty) env
           handle Type.TUNIFY =>
             error ("Type unificaton failed, while unifying defining equations\n"
@@ -449,90 +442,45 @@
           cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
       in map (Thm.instantiate (instT, [])) thms' end;
 
-fun certify_const thy const thms =
+fun certify_const thy c eqns =
   let
-    fun cert thm = if const = const_of_eqn thy thm
-      then thm else error ("Wrong head of defining equation,\nexpected constant "
-        ^ Code_Unit.string_of_const thy const ^ "\n" ^ Display.string_of_thm thm)
-  in map cert thms end;
+    fun cert (eqn as (thm, _)) = if c = Code_Unit.const_eqn thm
+      then eqn else error ("Wrong head of defining equation,\nexpected constant "
+        ^ Code_Unit.string_of_const thy c ^ "\n" ^ Display.string_of_thm thm)
+  in map cert eqns end;
 
+fun check_linear (eqn as (thm, linear)) =
+  if linear then eqn else Code_Unit.bad_thm
+    ("Duplicate variables on left hand side of defining equation:\n"
+      ^ Display.string_of_thm thm);
+
+fun mk_eqn thy linear =
+  Code_Unit.error_thm ((if linear then check_linear else I) o Code_Unit.mk_eqn thy);
+fun mk_liberal_eqn thy = Code_Unit.warning_thm (check_linear o Code_Unit.mk_eqn thy);
+fun mk_syntactic_eqn thy = Code_Unit.warning_thm (Code_Unit.mk_eqn thy);
+fun mk_default_eqn thy = Code_Unit.try_thm (check_linear o Code_Unit.mk_eqn thy);
 
 
 (** operational sort algebra and class discipline **)
 
 local
 
-fun aggr_neutr f y [] = y
-  | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
-
-fun aggregate f [] = NONE
-  | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
-
-fun inter_sorts algebra =
-  aggregate (map2 (curry (Sorts.inter_sort algebra)));
-
-fun specific_constraints thy (class, tyco) =
+fun arity_constraints thy algebra (class, tyco) =
   let
-    val vs = Name.invents Name.context "" (Sign.arity_number thy tyco);
-    val classparams = (map fst o these o try (#params o AxClass.get_info thy)) class;
-    val eqns = classparams
+    val base_constraints = Sorts.mg_domain algebra tyco [class];
+    val classparam_constraints = Sorts.complete_sort algebra [class]
+      |> maps (map fst o these o try (#params o AxClass.get_info thy))
       |> map_filter (fn c => try (AxClass.param_of_inst thy) (c, tyco))
       |> map (Symtab.lookup ((the_eqns o the_exec) thy))
       |> (map o Option.map) (map fst o Susp.force o snd)
       |> maps these
-      |> map (Thm.transfer thy);
-    fun sorts_of [Type (_, tys)] = map (snd o dest_TVar) tys
-      | sorts_of tys = map (snd o dest_TVar) tys;
-    val sorts = map (sorts_of o Sign.const_typargs thy o const_of thy) eqns;
-  in sorts end;
-
-fun weakest_constraints thy algebra (class, tyco) =
-  let
-    val all_superclasses = Sorts.complete_sort algebra [class];
-  in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) all_superclasses)
-   of SOME sorts => sorts
-    | NONE => Sorts.mg_domain algebra tyco [class]
-  end;
-
-fun strongest_constraints thy algebra (class, tyco) =
-  let
-    val all_subclasses = class :: Graph.all_preds ((#classes o Sorts.rep_algebra) algebra) [class];
-    val inst_subclasses = filter (can (Sorts.mg_domain algebra tyco) o single) all_subclasses;
-  in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) inst_subclasses)
-   of SOME sorts => sorts
-    | NONE => replicate
-        (Sign.arity_number thy tyco) (Sorts.minimize_sort algebra (Sorts.all_classes algebra))
-  end;
-
-fun get_algebra thy (class, tyco) =
-  let
-    val base_algebra = Sign.classes_of thy;
-  in if can (Sorts.mg_domain base_algebra tyco) [class]
-    then base_algebra
-    else let
-      val superclasses = Sorts.super_classes base_algebra class;
-      val sorts = inter_sorts base_algebra
-          (map_filter (fn class => try (Sorts.mg_domain base_algebra tyco) [class]) superclasses)
-        |> the_default (replicate (Sign.arity_number thy tyco) [])
-    in
-      base_algebra
-      |> Sorts.add_arities (Syntax.pp_global thy) (tyco, [(class, sorts)])
-    end
-  end;
-
-fun gen_classparam_typ constr thy class (c, tyco) = 
-  let
-    val algebra = get_algebra thy (class, tyco);
-    val cs = these (try (#params o AxClass.get_info thy) class);
-    val SOME ty = AList.lookup (op =) cs c;
-    val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
-      (constr thy algebra (class, tyco));
-    val ty_inst = Type (tyco, map TFree sort_args);
-  in Logic.varifyT (map_type_tfree (K ty_inst) ty) end;
+      |> map (map (snd o dest_TVar) o Sign.const_typargs thy o Code_Unit.const_typ_eqn);
+    val inter_sorts = map2 (curry (Sorts.inter_sort algebra));
+  in fold inter_sorts classparam_constraints base_constraints end;
 
 fun retrieve_algebra thy operational =
   Sorts.subalgebra (Syntax.pp_global thy) operational
-    (weakest_constraints thy (Sign.classes_of thy))
+    (arity_constraints thy (Sign.classes_of thy))
     (Sign.classes_of thy);
 
 in
@@ -545,76 +493,6 @@
     val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
   in retrieve_algebra thy (member (op =) operational_classes) end;
 
-val classparam_weakest_typ = gen_classparam_typ weakest_constraints;
-val classparam_strongest_typ = gen_classparam_typ strongest_constraints;
-
-fun assert_eqn_linear (eqn as (thm, linear)) =
-  if linear then eqn else Code_Unit.bad_thm
-    ("Duplicate variables on left hand side of defining equation:\n"
-      ^ Display.string_of_thm thm);
-
-fun assert_eqn_typ (thm, linear) =
-  let
-    val thy = Thm.theory_of_thm thm;
-    fun check_typ_classparam tyco (c, thm) =
-          let
-            val SOME class = AxClass.class_of_param thy c;
-            val (_, ty) = const_of thy thm;
-            val ty_decl = classparam_weakest_typ thy class (c, tyco);
-            val ty_strongest = classparam_strongest_typ thy class (c, tyco);
-            fun constrain thm = 
-              let
-                val max = Thm.maxidx_of thm + 1;
-                val ty_decl' = Logic.incr_tvar max ty_decl;
-                val (_, ty') = const_of thy thm;
-                val (env, _) = Sign.typ_unify thy (ty_decl', ty') (Vartab.empty, max);
-                val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
-                  cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
-              in Thm.instantiate (instT, []) thm end;
-          in if Sign.typ_instance thy (ty_strongest, ty)
-            then if Sign.typ_instance thy (ty, ty_decl)
-            then thm
-            else (warning ("Constraining type\n" ^ Code_Unit.string_of_typ thy ty
-              ^ "\nof defining equation\n"
-              ^ Display.string_of_thm thm
-              ^ "\nto permitted most general type\n"
-              ^ Code_Unit.string_of_typ thy ty_decl);
-              constrain thm)
-            else Code_Unit.bad_thm ("Type\n" ^ Code_Unit.string_of_typ thy ty
-              ^ "\nof defining equation\n"
-              ^ Display.string_of_thm thm
-              ^ "\nis incompatible with permitted least general type\n"
-              ^ Code_Unit.string_of_typ thy ty_strongest)
-          end;
-    fun check_typ_fun (c, thm) =
-      let
-        val (_, ty) = const_of thy thm;
-        val ty_decl = Sign.the_const_type thy c;
-      in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
-        then thm
-        else Code_Unit.bad_thm ("Type\n" ^ Code_Unit.string_of_typ thy ty
-           ^ "\nof defining equation\n"
-           ^ Display.string_of_thm thm
-           ^ "\nis incompatible with declared function type\n"
-           ^ Code_Unit.string_of_typ thy ty_decl)
-      end;
-    fun check_typ (c, thm) =
-      case AxClass.inst_of_param thy c
-       of SOME (c, tyco) => check_typ_classparam tyco (c, thm)
-        | NONE => check_typ_fun (c, thm);
-    val c = const_of_eqn thy thm;
-    val thm' = check_typ (c, thm);
-  in (thm', linear) end;
-
-fun mk_eqn linear = Code_Unit.error_thm
-  (assert_eqn_typ o (if linear then assert_eqn_linear else I) o Code_Unit.mk_eqn);
-val mk_liberal_eqn = Code_Unit.warning_thm
-  (assert_eqn_typ o assert_eqn_linear o Code_Unit.mk_eqn);
-val mk_syntactic_eqn = Code_Unit.warning_thm
-  (assert_eqn_typ o Code_Unit.mk_eqn);
-val mk_default_eqn = Code_Unit.try_thm
-  (assert_eqn_typ o assert_eqn_linear o Code_Unit.mk_eqn);
-
 end; (*local*)
 
 
@@ -653,10 +531,10 @@
 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
 
 fun gen_add_eqn linear strict default thm thy =
-  case (if strict then SOME o mk_eqn linear else mk_liberal_eqn) thm
+  case (if strict then SOME o mk_eqn thy linear else mk_liberal_eqn thy) thm
    of SOME (thm, _) =>
         let
-          val c = const_of_eqn thy thm;
+          val c = Code_Unit.const_eqn thm;
           val _ = if strict andalso (is_some o AxClass.class_of_param thy) c
             then error ("Rejected polymorphic equation for overloaded constant:\n"
               ^ Display.string_of_thm thm)
@@ -667,7 +545,7 @@
             else ();
         in
           (map_exec_purge (SOME [c]) o map_eqns) (Symtab.map_default
-            (c, (true, Susp.value [])) (add_thm default (thm, linear))) thy
+            (c, (true, Susp.value [])) (add_thm thy default (thm, linear))) thy
         end
     | NONE => thy;
 
@@ -676,12 +554,9 @@
 val add_default_eqn = gen_add_eqn true false true;
 val add_nonlinear_eqn = gen_add_eqn false true false;
 
-fun del_eqn thm thy = case mk_syntactic_eqn thm
- of SOME (thm, _) => let
-        val c = const_of_eqn thy thm;
-      in map_exec_purge (SOME [c]) (map_eqns
-        (Symtab.map_entry c (del_thm thm))) thy
-      end
+fun del_eqn thm thy = case mk_syntactic_eqn thy thm
+ of SOME (thm, _) => let val c = Code_Unit.const_eqn thm
+      in map_exec_purge (SOME [c]) (map_eqns (Symtab.map_entry c (del_thm thm))) thy end
   | NONE => thy;
 
 fun del_eqns c = map_exec_purge (SOME [c])
@@ -689,9 +564,8 @@
 
 fun add_eqnl (c, lthms) thy =
   let
-    val lthms' = certificate thy (fn thy => certify_const thy c) lthms;
-      (*FIXME must check compatibility with sort algebra;
-        alas, naive checking results in non-termination!*)
+    val lthms' = certificate thy
+      (fn thy => map (Code_Unit.assert_linear) o certify_const thy c) lthms;
   in
     map_exec_purge (SOME [c])
       (map_eqns (Symtab.map_default (c, (true, Susp.value []))
@@ -739,21 +613,12 @@
 val map_pre = map_exec_purge NONE o map_thmproc o apfst o apfst;
 val map_post = map_exec_purge NONE o map_thmproc o apfst o apsnd;
 
-fun add_inline thm thy = (map_pre o MetaSimplifier.add_simp)
-  (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
-    (*fully applied in order to get right context for mk_rew!*)
-
-fun del_inline thm thy = (map_pre o MetaSimplifier.del_simp)
-  (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
-    (*fully applied in order to get right context for mk_rew!*)
+fun gen_add_del_pre_post f thm thy = f thm thy;
 
-fun add_post thm thy = (map_post o MetaSimplifier.add_simp)
-  (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
-    (*fully applied in order to get right context for mk_rew!*)
-
-fun del_post thm thy = (map_post o MetaSimplifier.del_simp)
-  (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
-    (*fully applied in order to get right context for mk_rew!*)
+val add_inline = gen_add_del_pre_post (map_pre o MetaSimplifier.add_simp);
+val del_inline = gen_add_del_pre_post (map_pre o MetaSimplifier.del_simp);
+val add_post = gen_add_del_pre_post (map_post o MetaSimplifier.add_simp);
+val del_post = gen_add_del_pre_post (map_post o MetaSimplifier.del_simp);
   
 fun add_functrans (name, f) =
   (map_exec_purge NONE o map_thmproc o apsnd)
@@ -784,20 +649,14 @@
 
 local
 
-fun apply_functrans thy [] = []
-  | apply_functrans thy (thms as (thm, _) :: _) =
-      let
-        val const = const_of_eqn thy thm;
-        val functrans = (map (fn (_, (_, f)) => f thy) o #functrans
-          o the_thmproc o the_exec) thy;
-        val thms' = perhaps (perhaps_loop (perhaps_apply functrans)) (map fst thms);
-        val thms'' = certify_const thy const thms';
-      in map Code_Unit.add_linear thms'' end;
+fun apply_functrans thy c _ [] = []
+  | apply_functrans thy c [] eqns = eqns
+  | apply_functrans thy c functrans eqns = eqns
+      |> perhaps (perhaps_loop (perhaps_apply functrans))
+      |> map (Code_Unit.assert_linear o apfst (Code_Unit.assert_eqn thy))
+      |> certify_const thy c;
 
-fun rhs_conv conv thm =
-  let
-    val thm' = (conv o Thm.rhs_of) thm;
-  in Thm.transitive thm thm' end
+fun rhs_conv conv thm = Thm.transitive thm ((conv o Thm.rhs_of) thm);
 
 fun term_of_conv thy f =
   Thm.cterm_of thy
@@ -806,24 +665,27 @@
   #> Logic.dest_equals
   #> snd;
 
-in
-
-fun preprocess thy thms =
+fun preprocess thy functrans c eqns =
   let
     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   in
-    thms
-    |> apply_functrans thy
+    eqns
+    |> apply_functrans thy c functrans
     |> (map o apfst) (Code_Unit.rewrite_eqn pre)
-    (*FIXME - must check here: rewrite rule, defining equation, proper constant *)
-    |> (map o apfst) (AxClass.unoverload thy)
-    |> burrow_fst common_typ_eqns
+    |> map (Code_Unit.assert_linear o apfst (Code_Unit.assert_eqn thy))
+    |> burrow_fst (common_typ_eqns thy)
   end;
 
+fun get_eqns thy c =
+  Symtab.lookup ((the_eqns o the_exec) thy) c
+  |> Option.map (Susp.force o snd)
+  |> these
+  |> (map o apfst) (Thm.transfer thy);
 
-fun preprocess_conv ct =
+in
+
+fun preprocess_conv thy ct =
   let
-    val thy = Thm.theory_of_cterm ct;
     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   in
     ct
@@ -831,11 +693,10 @@
     |> rhs_conv (AxClass.unoverload_conv thy)
   end;
 
-fun preprocess_term thy = term_of_conv thy preprocess_conv;
+fun preprocess_term thy = term_of_conv thy (preprocess_conv thy);
 
-fun postprocess_conv ct =
+fun postprocess_conv thy ct =
   let
-    val thy = Thm.theory_of_cterm ct;
     val post = (Simplifier.theory_context thy o #post o the_thmproc o the_exec) thy;
   in
     ct
@@ -843,43 +704,33 @@
     |> rhs_conv (Simplifier.rewrite post)
   end;
 
-fun postprocess_term thy = term_of_conv thy postprocess_conv;
-
-end; (*local*)
-
-fun default_typ_proto thy c = case AxClass.inst_of_param thy c
- of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
-      (c, tyco) |> SOME
-  | NONE => (case AxClass.class_of_param thy c
-     of SOME class => SOME (Term.map_type_tvar
-          (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
-      | NONE => get_constr_typ thy c);
+fun postprocess_term thy = term_of_conv thy (postprocess_conv thy);
 
-local
-
-fun get_eqns thy const =
-  Symtab.lookup ((the_eqns o the_exec) thy) const
-  |> Option.map (Susp.force o snd)
-  |> these
-  |> (map o apfst) (Thm.transfer thy);
-
-in
-
-fun these_eqns thy const =
+fun these_eqns thy c =
   let
+    val functrans = (map (fn (_, (_, f)) => f thy) o #functrans
+      o the_thmproc o the_exec) thy;
     val drop_refl = filter_out
       (is_equal o Term.fast_term_ord o Logic.dest_equals o Thm.plain_prop_of o fst);
   in
-    get_eqns thy const
-    |> preprocess thy
+    get_eqns thy c
+    |> preprocess thy functrans c
     |> drop_refl
   end;
 
-fun default_typ thy c = case default_typ_proto thy c
- of SOME ty => Code_Unit.typscheme thy (c, ty)
-  | NONE => (case get_eqns thy c
-     of (thm, _) :: _ => snd (Code_Unit.head_eqn (AxClass.unoverload thy thm))
-      | [] => Code_Unit.typscheme thy (c, Sign.the_const_type thy c));
+fun default_typscheme thy c = let
+    val typscheme = curry (Code_Unit.typscheme thy) c
+    val the_const_type = snd o dest_Const o TermSubst.zero_var_indexes
+      o curry Const "" o Sign.the_const_type thy;
+  in case AxClass.class_of_param thy c
+   of SOME class => the_const_type c
+        |> Term.map_type_tvar (K (TVar ((Name.aT, 0), [class])))
+        |> typscheme
+    | NONE => (case get_constr_typ thy c
+       of SOME ty => typscheme ty
+        | NONE => (case get_eqns thy c
+           of (thm, _) :: _ => snd (Code_Unit.head_eqn thy (Drule.zero_var_indexes thm))
+            | [] => typscheme (the_const_type c))) end;
 
 end; (*local*)
 
--- a/src/Pure/Isar/code_unit.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/Pure/Isar/code_unit.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -15,8 +15,8 @@
 
   (*typ instantiations*)
   val typscheme: theory -> string * typ -> (string * sort) list * typ
-  val inst_thm: sort Vartab.table -> thm -> thm
-  val constrain_thm: sort -> thm -> thm
+  val inst_thm: theory -> sort Vartab.table -> thm -> thm
+  val constrain_thm: theory -> sort -> thm -> thm
 
   (*constant aliasses*)
   val add_const_alias: thm -> theory -> theory
@@ -36,16 +36,17 @@
     -> string * ((string * sort) list * (string * typ list) list)
 
   (*defining equations*)
-  val assert_rew: thm -> thm
-  val mk_rew: thm -> thm
-  val add_linear: thm -> thm * bool
-  val mk_eqn: thm -> thm * bool
-  val head_eqn: thm -> string * ((string * sort) list * typ)
-  val expand_eta: int -> thm -> thm
+  val assert_eqn: theory -> thm -> thm
+  val mk_eqn: theory -> thm -> thm * bool
+  val assert_linear: thm * bool -> thm * bool
+  val const_eqn: thm -> string
+  val const_typ_eqn: thm -> string * typ
+  val head_eqn: theory -> thm -> string * ((string * sort) list * typ)
+  val expand_eta: theory -> int -> thm -> thm
   val rewrite_eqn: simpset -> thm -> thm
   val rewrite_head: thm list -> thm -> thm
-  val norm_args: thm list -> thm list 
-  val norm_varnames: (string -> string) -> (string -> string) -> thm list -> thm list
+  val norm_args: theory -> thm list -> thm list 
+  val norm_varnames: theory -> (string -> string) -> (string -> string) -> thm list -> thm list
 
   (*case certificates*)
   val case_cert: thm -> string * (int * string list)
@@ -81,9 +82,8 @@
     val vs = map dest (Sign.const_typargs thy (c, ty));
   in (vs, ty) end;
 
-fun inst_thm tvars' thm =
+fun inst_thm thy tvars' thm =
   let
-    val thy = Thm.theory_of_thm thm;
     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
     val inter_sort = Sorts.inter_sort (Sign.classes_of thy);
     fun mk_inst (tvar as (v, sort)) = case Vartab.lookup tvars' v
@@ -93,9 +93,8 @@
     val insts = map_filter mk_inst tvars;
   in Thm.instantiate (insts, []) thm end;
 
-fun constrain_thm sort thm =
+fun constrain_thm thy sort thm =
   let
-    val thy = Thm.theory_of_thm thm;
     val constrain = curry (Sorts.inter_sort (Sign.classes_of thy)) sort
     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
     fun mk_inst (tvar as (v, sort)) = pairself (Thm.ctyp_of thy o TVar o pair v)
@@ -103,9 +102,8 @@
     val insts = map mk_inst tvars;
   in Thm.instantiate (insts, []) thm end;
 
-fun expand_eta k thm =
+fun expand_eta thy k thm =
   let
-    val thy = Thm.theory_of_thm thm;
     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
     val (head, args) = strip_comb lhs;
     val l = if k = ~1
@@ -153,19 +151,19 @@
 val rewrite_eqn = Conv.fconv_rule o eqn_conv o Simplifier.rewrite;
 val rewrite_head = Conv.fconv_rule o head_conv o MetaSimplifier.rewrite false;
 
-fun norm_args thms =
+fun norm_args thy thms =
   let
     val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
     val k = fold (curry Int.max o num_args_of o Thm.prop_of) thms 0;
   in
     thms
-    |> map (expand_eta k)
+    |> map (expand_eta thy k)
     |> map (Conv.fconv_rule Drule.beta_eta_conversion)
   end;
 
-fun canonical_tvars purify_tvar thm =
+fun canonical_tvars thy purify_tvar thm =
   let
-    val ctyp = Thm.ctyp_of (Thm.theory_of_thm thm);
+    val ctyp = Thm.ctyp_of thy;
     fun tvars_subst_for thm = (fold_types o fold_atyps)
       (fn TVar (v_i as (v, _), sort) => let
             val v' = purify_tvar v
@@ -182,9 +180,9 @@
     val (_, inst) = fold mk_inst (tvars_subst_for thm) (maxidx + 1, []);
   in Thm.instantiate (inst, []) thm end;
 
-fun canonical_vars purify_var thm =
+fun canonical_vars thy purify_var thm =
   let
-    val cterm = Thm.cterm_of (Thm.theory_of_thm thm);
+    val cterm = Thm.cterm_of thy;
     fun vars_subst_for thm = fold_aterms
       (fn Var (v_i as (v, _), ty) => let
             val v' = purify_var v
@@ -207,7 +205,7 @@
     val t' = Term.map_abs_vars purify_var t;
   in Thm.rename_boundvars t t' thm end;
 
-fun norm_varnames purify_tvar purify_var thms =
+fun norm_varnames thy purify_tvar purify_var thms =
   let
     fun burrow_thms f [] = []
       | burrow_thms f thms =
@@ -217,8 +215,8 @@
           |> Conjunction.elim_balanced (length thms)
   in
     thms
-    |> burrow_thms (canonical_tvars purify_tvar)
-    |> map (canonical_vars purify_var)
+    |> burrow_thms (canonical_tvars thy purify_tvar)
+    |> map (canonical_vars thy purify_var)
     |> map (canonical_absvars purify_var)
     |> map Drule.zero_var_indexes
   end;
@@ -237,18 +235,16 @@
       Library.merge (op =) (classes1, classes2));
 );
 
-fun add_const_alias thm =
+fun add_const_alias thm thy =
   let
-    val t = Thm.prop_of thm;
-    val thy = Thm.theory_of_thm thm;
-    val lhs_rhs = case try Logic.dest_equals t
+    val lhs_rhs = case try Logic.dest_equals (Thm.prop_of thm)
      of SOME lhs_rhs => lhs_rhs
       | _ => error ("Not an equation: " ^ Display.string_of_thm thm);
     val c_c' = case try (pairself (AxClass.unoverload_const thy o dest_Const)) lhs_rhs
      of SOME c_c' => c_c'
       | _ => error ("Not an equation with two constants: " ^ Display.string_of_thm thm);
     val some_class = the_list (AxClass.class_of_param thy (snd c_c'));
-  in
+  in thy |>
     ConstAlias.map (fn (alias, classes) =>
       ((c_c', thm) :: alias, fold (insert (op =)) some_class classes))
   end;
@@ -319,9 +315,9 @@
   in (tyco, (vs, cs''')) end;
 
 
-(* rewrite theorems *)
+(* defining equations *)
 
-fun assert_rew thm =
+fun assert_eqn thy thm =
   let
     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
       handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm)
@@ -346,34 +342,8 @@
     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
       then ()
       else bad_thm ("Free type variables on right hand side of rewrite theorem\n"
-        ^ Display.string_of_thm thm)
-  in thm end;
-
-fun mk_rew thm =
-  let
-    val thy = Thm.theory_of_thm thm;
-    val ctxt = ProofContext.init thy;
-  in
-    thm
-    |> LocalDefs.meta_rewrite_rule ctxt
-    |> assert_rew
-  end;
-
-
-(* defining equations *)
-
-fun add_linear thm =
-  let
-    val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
-    val linear = not (has_duplicates (op =)
-      ((fold o fold_aterms) (fn Var (v, _) => cons v | _ => I) args []))
-  in (thm, linear) end;
-
-fun assert_eqn thm =
-  let
-    val thy = Thm.theory_of_thm thm;
-    val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
-    val _ = case head of Const _ => () | _ =>
+        ^ Display.string_of_thm thm)    val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
+    val (c, ty) = case head of Const c_ty => c_ty | _ =>
       bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm thm);
     fun check _ (Abs _) = bad_thm
           ("Abstraction on left hand side of equation\n"
@@ -389,25 +359,41 @@
                ^ Display.string_of_thm thm)
           else ();
     val _ = map (check 0) args;
-    val linear = not (has_duplicates (op =)
-      ((fold o fold_aterms) (fn Var (v, _) => cons v | _ => I ) args []))
-  in add_linear thm end;
-
-val mk_eqn = assert_eqn o mk_rew;
+    val ty_decl = Sign.the_const_type thy c;
+    val _ = if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
+      then () else bad_thm ("Type\n" ^ string_of_typ thy ty
+           ^ "\nof defining equation\n"
+           ^ Display.string_of_thm thm
+           ^ "\nis incompatible with declared function type\n"
+           ^ string_of_typ thy ty_decl)
+  in thm end;
 
-fun head_eqn thm =
+fun add_linear thm =
   let
-    val thy = Thm.theory_of_thm thm;
-    val Const (c, ty) = (fst o strip_comb o fst o Logic.dest_equals
-      o Thm.plain_prop_of) thm;
-  in (c, typscheme thy (c, ty)) end;
+    val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
+    val linear = not (has_duplicates (op =)
+      ((fold o fold_aterms) (fn Var (v, _) => cons v | _ => I) args []))
+  in (thm, linear) end;
+
+fun assert_linear (thm, false) = (thm, false)
+  | assert_linear (thm, true) = if snd (add_linear thm) then (thm, true)
+      else bad_thm
+        ("Duplicate variables on left hand side of defining equation:\n"
+          ^ Display.string_of_thm thm);
+
+
+fun mk_eqn thy = add_linear o assert_eqn thy o AxClass.unoverload thy
+  o LocalDefs.meta_rewrite_rule (ProofContext.init thy);
+
+val const_typ_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
+val const_eqn = fst o const_typ_eqn;
+fun head_eqn thy thm = let val (c, ty) = const_typ_eqn thm in (c, typscheme thy (c, ty)) end;
 
 
 (* case cerificates *)
 
 fun case_certificate thm =
   let
-    val thy = Thm.theory_of_thm thm;
     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.prop_of) thm;
     val _ = case head of Free _ => true
--- a/src/Tools/code/code_funcgr.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/Tools/code/code_funcgr.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -95,7 +95,7 @@
             meets_of thy algebra (Sign.const_typargs thy (c, ty)) (map snd vs)
         | NONE => I;
     val tab = fold meets cs Vartab.empty;
-  in map (Code_Unit.inst_thm tab) thms end;
+  in map (Code_Unit.inst_thm thy tab) thms end;
 
 fun resort_eqnss thy algebra funcgr =
   let
@@ -105,14 +105,14 @@
       | resort_rec typ_of (c, thms as (thm, _) :: _) = if is_some (AxClass.inst_of_param thy c)
           then (true, (c, thms))
           else let
-            val (_, (vs, ty)) = Code_Unit.head_eqn thm;
+            val (_, (vs, ty)) = Code_Unit.head_eqn thy thm;
             val thms' as (thm', _) :: _ = burrow_fst (resort_thms thy algebra typ_of) thms
-            val (_, (vs', ty')) = Code_Unit.head_eqn thm'; (*FIXME simplify check*)
+            val (_, (vs', ty')) = Code_Unit.head_eqn thy thm'; (*FIXME simplify check*)
           in (Sign.typ_equiv thy (ty, ty'), (c, thms')) end;
     fun resort_recs eqnss =
       let
         fun typ_of c = case these (AList.lookup (op =) eqnss c)
-         of (thm, _) :: _ => (SOME o snd o Code_Unit.head_eqn) thm
+         of (thm, _) :: _ => (SOME o snd o Code_Unit.head_eqn thy) thm
           | [] => NONE;
         val (unchangeds, eqnss') = split_list (map (resort_rec typ_of) eqnss);
         val unchanged = fold (fn x => fn y => x andalso y) unchangeds true;
@@ -158,8 +158,8 @@
     |> pair (SOME const)
   else let
     val thms = Code.these_eqns thy const
-      |> burrow_fst Code_Unit.norm_args
-      |> burrow_fst (Code_Unit.norm_varnames Code_Name.purify_tvar Code_Name.purify_var);
+      |> burrow_fst (Code_Unit.norm_args thy)
+      |> burrow_fst (Code_Unit.norm_varnames thy Code_Name.purify_tvar Code_Name.purify_var);
     val rhs = consts_of (const, thms);
   in
     auxgr
@@ -181,8 +181,8 @@
     val eqnss = raw_eqnss
       |> resort_eqnss thy algebra funcgr
       |> filter_out (can (Graph.get_node funcgr) o fst);
-    fun typ_eqn c [] = Code.default_typ thy c
-      | typ_eqn c (thms as (thm, _) :: _) = (snd o Code_Unit.head_eqn) thm;
+    fun typ_eqn c [] = Code.default_typscheme thy c
+      | typ_eqn c (thms as (thm, _) :: _) = (snd o Code_Unit.head_eqn thy) thm;
     fun add_eqns (const, thms) =
       Graph.new_node (const, (typ_eqn const thms, thms));
     fun add_deps (eqns as (const, thms)) funcgr =
@@ -226,7 +226,7 @@
     fun consts_of t = fold_aterms (fn Const c_ty => cons c_ty | _ => I)
       t [];
     val algebra = Code.coregular_algebra thy;
-    val thm = Code.preprocess_conv ct;
+    val thm = Code.preprocess_conv thy ct;
     val ct' = Thm.rhs_of thm;
     val t' = Thm.term_of ct';
     val consts = map fst (consts_of t');
@@ -242,7 +242,7 @@
     fun evaluator evaluator' thm1 funcgr t =
       let
         val thm2 = evaluator' funcgr t;
-        val thm3 = Code.postprocess_conv (Thm.rhs_of thm2);
+        val thm3 = Code.postprocess_conv thy (Thm.rhs_of thm2);
       in
         Thm.transitive thm1 (Thm.transitive thm2 thm3) handle THM _ =>
           error ("could not construct evaluation proof:\n"
--- a/src/Tools/code/code_thingol.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/Tools/code/code_thingol.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -485,7 +485,7 @@
         val ty = Logic.unvarifyT raw_ty;
         val thms = if (null o Term.typ_tfrees) ty orelse (null o fst o strip_type) ty
           then raw_thms
-          else (map o apfst) (Code_Unit.expand_eta 1) raw_thms;
+          else (map o apfst) (Code_Unit.expand_eta thy 1) raw_thms;
       in
         trns
         |> fold_map (exprgen_tyvar_sort thy algbr funcgr) vs
--- a/src/Tools/nbe.ML	Tue Sep 30 12:49:17 2008 +0200
+++ b/src/Tools/nbe.ML	Tue Sep 30 12:49:18 2008 +0200
@@ -385,7 +385,7 @@
           let
             val ts' = take_until is_dict ts;
             val c = (the o Code_Name.const_rev thy o the o Inttab.lookup idx_tab) idx;
-            val (_, T) = Code.default_typ thy c;
+            val (_, T) = Code.default_typscheme thy c;
             val T' = map_type_tvar (fn ((v, i), S) => TypeInfer.param (typidx + i) (v, [])) T;
             val typidx' = typidx + maxidx_of_typ T' + 1;
           in of_apps bounds (Term.Const (c, T'), ts') typidx' end