src/Pure/Isar/code.ML
author haftmann
Fri Sep 05 06:50:22 2008 +0200 (2008-09-05)
changeset 28143 e5c6c4aac52c
parent 28054 2b84d34c5d02
child 28350 715163ec93c0
permissions -rw-r--r--
different bookkeeping for code equations
     1 (*  Title:      Pure/Isar/code.ML
     2     ID:         $Id$
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Abstract executable content of theory.  Management of data dependent on
     6 executable content.  Cache assumes non-concurrent processing of a single theory.
     7 *)
     8 
     9 signature CODE =
    10 sig
    11   val add_func: thm -> theory -> theory
    12   val add_liberal_func: thm -> theory -> theory
    13   val add_default_func: thm -> theory -> theory
    14   val add_default_func_attr: Attrib.src
    15   val del_func: thm -> theory -> theory
    16   val del_funcs: string -> theory -> theory
    17   val add_funcl: string * thm list Susp.T -> theory -> theory
    18   val map_pre: (MetaSimplifier.simpset -> MetaSimplifier.simpset) -> theory -> theory
    19   val map_post: (MetaSimplifier.simpset -> MetaSimplifier.simpset) -> theory -> theory
    20   val add_inline: thm -> theory -> theory
    21   val del_inline: thm -> theory -> theory
    22   val add_post: thm -> theory -> theory
    23   val del_post: thm -> theory -> theory
    24   val add_functrans: string * (theory -> thm list -> thm list option) -> theory -> theory
    25   val del_functrans: string -> theory -> theory
    26   val add_datatype: (string * typ) list -> theory -> theory
    27   val add_datatype_cmd: string list -> theory -> theory
    28   val type_interpretation:
    29     (string * ((string * sort) list * (string * typ list) list)
    30       -> theory -> theory) -> theory -> theory
    31   val add_case: thm -> theory -> theory
    32   val add_undefined: string -> theory -> theory
    33   val purge_data: theory -> theory
    34 
    35   val coregular_algebra: theory -> Sorts.algebra
    36   val operational_algebra: theory -> (sort -> sort) * Sorts.algebra
    37   val these_funcs: theory -> string -> thm list
    38   val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
    39   val get_datatype_of_constr: theory -> string -> string option
    40   val get_case_data: theory -> string -> (int * string list) option
    41   val is_undefined: theory -> string -> bool
    42   val default_typ: theory -> string -> (string * sort) list * typ
    43 
    44   val preprocess_conv: cterm -> thm
    45   val preprocess_term: theory -> term -> term
    46   val postprocess_conv: cterm -> thm
    47   val postprocess_term: theory -> term -> term
    48 
    49   val add_attribute: string * (Args.T list -> attribute * Args.T list) -> theory -> theory
    50 
    51   val print_codesetup: theory -> unit
    52 end;
    53 
    54 signature CODE_DATA_ARGS =
    55 sig
    56   type T
    57   val empty: T
    58   val purge: theory -> string list -> T -> T
    59 end;
    60 
    61 signature CODE_DATA =
    62 sig
    63   type T
    64   val get: theory -> T
    65   val change: theory -> (T -> T) -> T
    66   val change_yield: theory -> (T -> 'a * T) -> 'a * T
    67 end;
    68 
    69 signature PRIVATE_CODE =
    70 sig
    71   include CODE
    72   val declare_data: Object.T -> (theory -> string list -> Object.T -> Object.T)
    73     -> serial
    74   val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    75     -> theory -> 'a
    76   val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    77     -> theory -> ('a -> 'a) -> 'a
    78   val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    79     -> theory -> ('a -> 'b * 'a) -> 'b * 'a
    80 end;
    81 
    82 structure Code : PRIVATE_CODE =
    83 struct
    84 
    85 (** code attributes **)
    86 
    87 structure CodeAttr = TheoryDataFun (
    88   type T = (string * (Args.T list -> attribute * Args.T list)) list;
    89   val empty = [];
    90   val copy = I;
    91   val extend = I;
    92   fun merge _ = AList.merge (op = : string * string -> bool) (K true);
    93 );
    94 
    95 fun add_attribute (attr as (name, _)) =
    96   let
    97     fun add_parser ("", parser) attrs = attrs @ [("", parser)]
    98       | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
    99     fun error "" = error ("Code attribute already declared")
   100       | error name = error ("Code attribute " ^ name ^ " already declared")
   101   in CodeAttr.map (fn attrs => if AList.defined (op =) attrs name
   102     then error name else add_parser attr attrs)
   103   end;
   104 
   105 val _ =
   106   let
   107     val code_attr = Attrib.syntax (Scan.peek (fn context =>
   108       List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))));
   109   in
   110     Context.>> (Context.map_theory
   111       (Attrib.add_attributes
   112         [("code", code_attr, "declare theorems for code generation")]))
   113   end;
   114 
   115 
   116 (** logical and syntactical specification of executable code **)
   117 
   118 (* defining equations with default flag and lazy theorems *)
   119 
   120 fun pretty_lthms ctxt r = case Susp.peek r
   121  of SOME thms => map (ProofContext.pretty_thm ctxt) thms
   122   | NONE => [Pretty.str "[...]"];
   123 
   124 fun certificate thy f r =
   125   case Susp.peek r
   126    of SOME thms => (Susp.value o f thy) thms
   127     | NONE => let
   128         val thy_ref = Theory.check_thy thy;
   129       in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
   130 
   131 fun add_drop_redundant verbose thm thms =
   132   let
   133     fun warn thm' = (if verbose
   134       then warning ("Code generator: dropping redundant defining equation\n" ^ Display.string_of_thm thm')
   135       else (); true);
   136     val thy = Thm.theory_of_thm thm;
   137     val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   138     val args = args_of thm;
   139     fun matches [] _ = true
   140       | matches (Var _ :: xs) [] = matches xs []
   141       | matches (_ :: _) [] = false
   142       | matches (x :: xs) (y :: ys) = Pattern.matches thy (x, y) andalso matches xs ys;
   143     fun drop thm' = matches args (args_of thm') andalso warn thm';
   144   in thm :: filter_out drop thms end;
   145 
   146 fun add_thm _ thm (false, thms) = (false, Susp.value (add_drop_redundant true thm (Susp.force thms)))
   147   | add_thm true thm (true, thms) = (true, Susp.value (Susp.force thms @ [thm]))
   148   | add_thm false thm (true, thms) = (false, Susp.value [thm]);
   149 
   150 fun add_lthms lthms _ = (false, lthms);
   151 
   152 fun del_thm thm = apsnd (Susp.value o remove Thm.eq_thm_prop thm o Susp.force);
   153 
   154 fun merge_defthms ((true, _), defthms2) = defthms2
   155   | merge_defthms (defthms1 as (false, _), (true, _)) = defthms1
   156   | merge_defthms ((false, _), defthms2 as (false, _)) = defthms2;
   157 
   158 
   159 (* syntactic datatypes *)
   160 
   161 val eq_string = op = : string * string -> bool;
   162 
   163 fun eq_dtyp ((vs1, cs1), (vs2, cs2)) = 
   164   gen_eq_set (eq_pair eq_string (gen_eq_set eq_string)) (vs1, vs2)
   165     andalso gen_eq_set (eq_fst eq_string) (cs1, cs2);
   166 
   167 fun merge_dtyps (tabs as (tab1, tab2)) =
   168   let
   169     fun join _ (cos as (_, cos2)) = if eq_dtyp cos then raise Symtab.SAME else cos2;
   170   in Symtab.join join tabs end;
   171 
   172 
   173 (* specification data *)
   174 
   175 datatype spec = Spec of {
   176   funcs: (bool * thm list Susp.T) Symtab.table,
   177   dtyps: ((string * sort) list * (string * typ list) list) Symtab.table,
   178   cases: (int * string list) Symtab.table * unit Symtab.table
   179 };
   180 
   181 fun mk_spec (funcs, (dtyps, cases)) =
   182   Spec { funcs = funcs, dtyps = dtyps, cases = cases };
   183 fun map_spec f (Spec { funcs = funcs, dtyps = dtyps, cases = cases }) =
   184   mk_spec (f (funcs, (dtyps, cases)));
   185 fun merge_spec (Spec { funcs = funcs1, dtyps = dtyps1, cases = (cases1, undefs1) },
   186   Spec { funcs = funcs2, dtyps = dtyps2, cases = (cases2, undefs2) }) =
   187   let
   188     val funcs = Symtab.join (K merge_defthms) (funcs1, funcs2);
   189     val dtyps = merge_dtyps (dtyps1, dtyps2);
   190     val cases = (Symtab.merge (K true) (cases1, cases2),
   191       Symtab.merge (K true) (undefs1, undefs2));
   192   in mk_spec (funcs, (dtyps, cases)) end;
   193 
   194 
   195 (* pre- and postprocessor *)
   196 
   197 datatype thmproc = Thmproc of {
   198   pre: MetaSimplifier.simpset,
   199   post: MetaSimplifier.simpset,
   200   functrans: (string * (serial * (theory -> thm list -> thm list option))) list
   201 };
   202 
   203 fun mk_thmproc ((pre, post), functrans) =
   204   Thmproc { pre = pre, post = post, functrans = functrans };
   205 fun map_thmproc f (Thmproc { pre, post, functrans }) =
   206   mk_thmproc (f ((pre, post), functrans));
   207 fun merge_thmproc (Thmproc { pre = pre1, post = post1, functrans = functrans1 },
   208   Thmproc { pre = pre2, post = post2, functrans = functrans2 }) =
   209     let
   210       val pre = MetaSimplifier.merge_ss (pre1, pre2);
   211       val post = MetaSimplifier.merge_ss (post1, post2);
   212       val functrans = AList.merge (op =) (eq_fst (op =)) (functrans1, functrans2);
   213     in mk_thmproc ((pre, post), functrans) end;
   214 
   215 datatype exec = Exec of {
   216   thmproc: thmproc,
   217   spec: spec
   218 };
   219 
   220 
   221 (* code setup data *)
   222 
   223 fun mk_exec (thmproc, spec) =
   224   Exec { thmproc = thmproc, spec = spec };
   225 fun map_exec f (Exec { thmproc = thmproc, spec = spec }) =
   226   mk_exec (f (thmproc, spec));
   227 fun merge_exec (Exec { thmproc = thmproc1, spec = spec1 },
   228   Exec { thmproc = thmproc2, spec = spec2 }) =
   229   let
   230     val thmproc = merge_thmproc (thmproc1, thmproc2);
   231     val spec = merge_spec (spec1, spec2);
   232   in mk_exec (thmproc, spec) end;
   233 val empty_exec = mk_exec (mk_thmproc ((MetaSimplifier.empty_ss, MetaSimplifier.empty_ss), []),
   234   mk_spec (Symtab.empty, (Symtab.empty, (Symtab.empty, Symtab.empty))));
   235 
   236 fun the_thmproc (Exec { thmproc = Thmproc x, ...}) = x;
   237 fun the_spec (Exec { spec = Spec x, ...}) = x;
   238 val the_funcs = #funcs o the_spec;
   239 val the_dtyps = #dtyps o the_spec;
   240 val the_cases = #cases o the_spec;
   241 val map_thmproc = map_exec o apfst o map_thmproc;
   242 val map_funcs = map_exec o apsnd o map_spec o apfst;
   243 val map_dtyps = map_exec o apsnd o map_spec o apsnd o apfst;
   244 val map_cases = map_exec o apsnd o map_spec o apsnd o apsnd;
   245 
   246 
   247 (* data slots dependent on executable content *)
   248 
   249 (*private copy avoids potential conflict of table exceptions*)
   250 structure Datatab = TableFun(type key = int val ord = int_ord);
   251 
   252 local
   253 
   254 type kind = {
   255   empty: Object.T,
   256   purge: theory -> string list -> Object.T -> Object.T
   257 };
   258 
   259 val kinds = ref (Datatab.empty: kind Datatab.table);
   260 val kind_keys = ref ([]: serial list);
   261 
   262 fun invoke f k = case Datatab.lookup (! kinds) k
   263  of SOME kind => f kind
   264   | NONE => sys_error "Invalid code data identifier";
   265 
   266 in
   267 
   268 fun declare_data empty purge =
   269   let
   270     val k = serial ();
   271     val kind = {empty = empty, purge = purge};
   272     val _ = change kinds (Datatab.update (k, kind));
   273     val _ = change kind_keys (cons k);
   274   in k end;
   275 
   276 fun invoke_init k = invoke (fn kind => #empty kind) k;
   277 
   278 fun invoke_purge_all thy cs =
   279   fold (fn k => Datatab.map_entry k
   280     (invoke (fn kind => #purge kind thy cs) k)) (! kind_keys);
   281 
   282 end; (*local*)
   283 
   284 
   285 (** theory store **)
   286 
   287 local
   288 
   289 type data = Object.T Datatab.table;
   290 val empty_data = Datatab.empty : data;
   291 
   292 structure CodeData = TheoryDataFun
   293 (
   294   type T = exec * data ref;
   295   val empty = (empty_exec, ref empty_data);
   296   fun copy (exec, data) = (exec, ref (! data));
   297   val extend = copy;
   298   fun merge pp ((exec1, data1), (exec2, data2)) =
   299     (merge_exec (exec1, exec2), ref empty_data);
   300 );
   301 
   302 val _ = Context.>> (Context.map_theory CodeData.init);
   303 
   304 fun thy_data f thy = f ((snd o CodeData.get) thy);
   305 
   306 fun get_ensure_init kind data_ref =
   307   case Datatab.lookup (! data_ref) kind
   308    of SOME x => x
   309     | NONE => let val y = invoke_init kind
   310         in (change data_ref (Datatab.update (kind, y)); y) end;
   311 
   312 in
   313 
   314 (* access to executable content *)
   315 
   316 val the_exec = fst o CodeData.get;
   317 
   318 fun complete_class_params thy cs =
   319   fold (fn c => case AxClass.inst_of_param thy c
   320    of NONE => insert (op =) c
   321     | SOME (c', _) => insert (op =) c' #> insert (op =) c) cs [];
   322 
   323 fun map_exec_purge touched f thy =
   324   CodeData.map (fn (exec, data) => (f exec, ref (case touched
   325    of SOME cs => invoke_purge_all thy (complete_class_params thy cs) (! data)
   326     | NONE => empty_data))) thy;
   327 
   328 val purge_data = (CodeData.map o apsnd) (K (ref empty_data));
   329 
   330 
   331 (* access to data dependent on abstract executable content *)
   332 
   333 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
   334 
   335 fun change_data (kind, mk, dest) =
   336   let
   337     fun chnge data_ref f =
   338       let
   339         val data = get_ensure_init kind data_ref;
   340         val data' = f (dest data);
   341       in (change data_ref (Datatab.update (kind, mk data')); data') end;
   342   in thy_data chnge end;
   343 
   344 fun change_yield_data (kind, mk, dest) =
   345   let
   346     fun chnge data_ref f =
   347       let
   348         val data = get_ensure_init kind data_ref;
   349         val (x, data') = f (dest data);
   350       in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
   351   in thy_data chnge end;
   352 
   353 end; (*local*)
   354 
   355 
   356 (* print executable content *)
   357 
   358 fun print_codesetup thy =
   359   let
   360     val ctxt = ProofContext.init thy;
   361     val exec = the_exec thy;
   362     fun pretty_func (s, (_, lthms)) =
   363       (Pretty.block o Pretty.fbreaks) (
   364         Pretty.str s :: pretty_lthms ctxt lthms
   365       );
   366     fun pretty_dtyp (s, []) =
   367           Pretty.str s
   368       | pretty_dtyp (s, cos) =
   369           (Pretty.block o Pretty.breaks) (
   370             Pretty.str s
   371             :: Pretty.str "="
   372             :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str c
   373                  | (c, tys) =>
   374                      (Pretty.block o Pretty.breaks)
   375                         (Pretty.str (Code_Unit.string_of_const thy c)
   376                           :: Pretty.str "of"
   377                           :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
   378           );
   379     val pre = (#pre o the_thmproc) exec;
   380     val post = (#post o the_thmproc) exec;
   381     val functrans = (map fst o #functrans o the_thmproc) exec;
   382     val funcs = the_funcs exec
   383       |> Symtab.dest
   384       |> (map o apfst) (Code_Unit.string_of_const thy)
   385       |> sort (string_ord o pairself fst);
   386     val dtyps = the_dtyps exec
   387       |> Symtab.dest
   388       |> map (fn (dtco, (vs, cos)) =>
   389           (Syntax.string_of_typ_global thy (Type (dtco, map TFree vs)), cos))
   390       |> sort (string_ord o pairself fst)
   391   in
   392     (Pretty.writeln o Pretty.chunks) [
   393       Pretty.block (
   394         Pretty.str "defining equations:"
   395         :: Pretty.fbrk
   396         :: (Pretty.fbreaks o map pretty_func) funcs
   397       ),
   398       Pretty.block [
   399         Pretty.str "preprocessing simpset:",
   400         Pretty.fbrk,
   401         MetaSimplifier.pretty_ss pre
   402       ],
   403       Pretty.block [
   404         Pretty.str "postprocessing simpset:",
   405         Pretty.fbrk,
   406         MetaSimplifier.pretty_ss post
   407       ],
   408       Pretty.block (
   409         Pretty.str "function transformers:"
   410         :: Pretty.fbrk
   411         :: (Pretty.fbreaks o map Pretty.str) functrans
   412       ),
   413       Pretty.block (
   414         Pretty.str "datatypes:"
   415         :: Pretty.fbrk
   416         :: (Pretty.fbreaks o map pretty_dtyp) dtyps
   417       )
   418     ]
   419   end;
   420 
   421 
   422 
   423 (** theorem transformation and certification **)
   424 
   425 fun const_of thy = dest_Const o fst o strip_comb o fst o Logic.dest_equals
   426   o ObjectLogic.drop_judgment thy o Thm.plain_prop_of;
   427 
   428 fun const_of_func thy = AxClass.unoverload_const thy o const_of thy;
   429 
   430 fun common_typ_funcs [] = []
   431   | common_typ_funcs [thm] = [thm]
   432   | common_typ_funcs (thms as thm :: _) = (*FIXME is too general*)
   433       let
   434         val thy = Thm.theory_of_thm thm;
   435         fun incr_thm thm max =
   436           let
   437             val thm' = incr_indexes max thm;
   438             val max' = Thm.maxidx_of thm' + 1;
   439           in (thm', max') end;
   440         val (thms', maxidx) = fold_map incr_thm thms 0;
   441         val ty1 :: tys = map (snd o const_of thy) thms';
   442         fun unify ty env = Sign.typ_unify thy (ty1, ty) env
   443           handle Type.TUNIFY =>
   444             error ("Type unificaton failed, while unifying defining equations\n"
   445             ^ (cat_lines o map Display.string_of_thm) thms
   446             ^ "\nwith types\n"
   447             ^ (cat_lines o map (Code_Unit.string_of_typ thy)) (ty1 :: tys));
   448         val (env, _) = fold unify tys (Vartab.empty, maxidx)
   449         val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   450           cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   451       in map (Thm.instantiate (instT, [])) thms' end;
   452 
   453 fun certify_const thy const thms =
   454   let
   455     fun cert thm = if const = const_of_func thy thm
   456       then thm else error ("Wrong head of defining equation,\nexpected constant "
   457         ^ Code_Unit.string_of_const thy const ^ "\n" ^ Display.string_of_thm thm)
   458   in map cert thms end;
   459 
   460 
   461 
   462 (** operational sort algebra and class discipline **)
   463 
   464 local
   465 
   466 fun aggr_neutr f y [] = y
   467   | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
   468 
   469 fun aggregate f [] = NONE
   470   | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
   471 
   472 fun inter_sorts algebra =
   473   aggregate (map2 (curry (Sorts.inter_sort algebra)));
   474 
   475 fun specific_constraints thy (class, tyco) =
   476   let
   477     val vs = Name.invents Name.context "" (Sign.arity_number thy tyco);
   478     val classparams = (map fst o these o try (#params o AxClass.get_info thy)) class;
   479     val funcs = classparams
   480       |> map_filter (fn c => try (AxClass.param_of_inst thy) (c, tyco))
   481       |> map (Symtab.lookup ((the_funcs o the_exec) thy))
   482       |> (map o Option.map) (Susp.force o snd)
   483       |> maps these
   484       |> map (Thm.transfer thy);
   485     fun sorts_of [Type (_, tys)] = map (snd o dest_TVar) tys
   486       | sorts_of tys = map (snd o dest_TVar) tys;
   487     val sorts = map (sorts_of o Sign.const_typargs thy o const_of thy) funcs;
   488   in sorts end;
   489 
   490 fun weakest_constraints thy algebra (class, tyco) =
   491   let
   492     val all_superclasses = Sorts.complete_sort algebra [class];
   493   in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) all_superclasses)
   494    of SOME sorts => sorts
   495     | NONE => Sorts.mg_domain algebra tyco [class]
   496   end;
   497 
   498 fun strongest_constraints thy algebra (class, tyco) =
   499   let
   500     val all_subclasses = class :: Graph.all_preds ((#classes o Sorts.rep_algebra) algebra) [class];
   501     val inst_subclasses = filter (can (Sorts.mg_domain algebra tyco) o single) all_subclasses;
   502   in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) inst_subclasses)
   503    of SOME sorts => sorts
   504     | NONE => replicate
   505         (Sign.arity_number thy tyco) (Sorts.minimize_sort algebra (Sorts.all_classes algebra))
   506   end;
   507 
   508 fun get_algebra thy (class, tyco) =
   509   let
   510     val base_algebra = Sign.classes_of thy;
   511   in if can (Sorts.mg_domain base_algebra tyco) [class]
   512     then base_algebra
   513     else let
   514       val superclasses = Sorts.super_classes base_algebra class;
   515       val sorts = inter_sorts base_algebra
   516           (map_filter (fn class => try (Sorts.mg_domain base_algebra tyco) [class]) superclasses)
   517         |> the_default (replicate (Sign.arity_number thy tyco) [])
   518     in
   519       base_algebra
   520       |> Sorts.add_arities (Syntax.pp_global thy) (tyco, [(class, sorts)])
   521     end
   522   end;
   523 
   524 fun gen_classparam_typ constr thy class (c, tyco) = 
   525   let
   526     val algebra = get_algebra thy (class, tyco);
   527     val cs = these (try (#params o AxClass.get_info thy) class);
   528     val SOME ty = AList.lookup (op =) cs c;
   529     val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
   530       (constr thy algebra (class, tyco));
   531     val ty_inst = Type (tyco, map TFree sort_args);
   532   in Logic.varifyT (map_type_tfree (K ty_inst) ty) end;
   533 
   534 fun retrieve_algebra thy operational =
   535   Sorts.subalgebra (Syntax.pp_global thy) operational
   536     (weakest_constraints thy (Sign.classes_of thy))
   537     (Sign.classes_of thy);
   538 
   539 in
   540 
   541 fun coregular_algebra thy = retrieve_algebra thy (K true) |> snd;
   542 fun operational_algebra thy =
   543   let
   544     fun add_iff_operational class =
   545       can (AxClass.get_info thy) class ? cons class;
   546     val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
   547   in retrieve_algebra thy (member (op =) operational_classes) end;
   548 
   549 val classparam_weakest_typ = gen_classparam_typ weakest_constraints;
   550 val classparam_strongest_typ = gen_classparam_typ strongest_constraints;
   551 
   552 fun assert_func_typ thm =
   553   let
   554     val thy = Thm.theory_of_thm thm;
   555     fun check_typ_classparam tyco (c, thm) =
   556           let
   557             val SOME class = AxClass.class_of_param thy c;
   558             val (_, ty) = const_of thy thm;
   559             val ty_decl = classparam_weakest_typ thy class (c, tyco);
   560             val ty_strongest = classparam_strongest_typ thy class (c, tyco);
   561             fun constrain thm = 
   562               let
   563                 val max = Thm.maxidx_of thm + 1;
   564                 val ty_decl' = Logic.incr_tvar max ty_decl;
   565                 val (_, ty') = const_of thy thm;
   566                 val (env, _) = Sign.typ_unify thy (ty_decl', ty') (Vartab.empty, max);
   567                 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   568                   cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   569               in Thm.instantiate (instT, []) thm end;
   570           in if Sign.typ_instance thy (ty_strongest, ty)
   571             then if Sign.typ_instance thy (ty, ty_decl)
   572             then thm
   573             else (warning ("Constraining type\n" ^ Code_Unit.string_of_typ thy ty
   574               ^ "\nof defining equation\n"
   575               ^ Display.string_of_thm thm
   576               ^ "\nto permitted most general type\n"
   577               ^ Code_Unit.string_of_typ thy ty_decl);
   578               constrain thm)
   579             else Code_Unit.bad_thm ("Type\n" ^ Code_Unit.string_of_typ thy ty
   580               ^ "\nof defining equation\n"
   581               ^ Display.string_of_thm thm
   582               ^ "\nis incompatible with permitted least general type\n"
   583               ^ Code_Unit.string_of_typ thy ty_strongest)
   584           end;
   585     fun check_typ_fun (c, thm) =
   586       let
   587         val (_, ty) = const_of thy thm;
   588         val ty_decl = Sign.the_const_type thy c;
   589       in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
   590         then thm
   591         else Code_Unit.bad_thm ("Type\n" ^ Code_Unit.string_of_typ thy ty
   592            ^ "\nof defining equation\n"
   593            ^ Display.string_of_thm thm
   594            ^ "\nis incompatible with declared function type\n"
   595            ^ Code_Unit.string_of_typ thy ty_decl)
   596       end;
   597     fun check_typ (c, thm) =
   598       case AxClass.inst_of_param thy c
   599        of SOME (c, tyco) => check_typ_classparam tyco (c, thm)
   600         | NONE => check_typ_fun (c, thm);
   601   in check_typ (const_of_func thy thm, thm) end;
   602 
   603 val mk_func = Code_Unit.error_thm (assert_func_typ o Code_Unit.mk_func);
   604 val mk_liberal_func = Code_Unit.warning_thm (assert_func_typ o Code_Unit.mk_func);
   605 val mk_default_func = Code_Unit.try_thm (assert_func_typ o Code_Unit.mk_func);
   606 
   607 end; (*local*)
   608 
   609 
   610 (** interfaces and attributes **)
   611 
   612 fun delete_force msg key xs =
   613   if AList.defined (op =) xs key then AList.delete (op =) key xs
   614   else error ("No such " ^ msg ^ ": " ^ quote key);
   615 
   616 fun get_datatype thy tyco =
   617   case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   618    of SOME spec => spec
   619     | NONE => Sign.arity_number thy tyco
   620         |> Name.invents Name.context Name.aT
   621         |> map (rpair [])
   622         |> rpair [];
   623 
   624 fun get_datatype_of_constr thy c =
   625   case (snd o strip_type o Sign.the_const_type thy) c
   626    of Type (tyco, _) => if member (op =)
   627        ((the_default [] o Option.map (map fst o snd) o Symtab.lookup ((the_dtyps o the_exec) thy)) tyco) c
   628        then SOME tyco else NONE
   629     | _ => NONE;
   630 
   631 fun get_constr_typ thy c =
   632   case get_datatype_of_constr thy c
   633    of SOME tyco => let
   634           val (vs, cos) = get_datatype thy tyco;
   635           val SOME tys = AList.lookup (op =) cos c;
   636           val ty = tys ---> Type (tyco, map TFree vs);
   637         in SOME (Logic.varifyT ty) end
   638     | NONE => NONE;
   639 
   640 val get_case_data = Symtab.lookup o fst o the_cases o the_exec;
   641 
   642 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
   643 
   644 fun gen_add_func strict default thm thy =
   645   case (if strict then SOME o mk_func else mk_liberal_func) thm
   646    of SOME func =>
   647         let
   648           val c = const_of_func thy func;
   649           val _ = if strict andalso (is_some o AxClass.class_of_param thy) c
   650             then error ("Rejected polymorphic equation for overloaded constant:\n"
   651               ^ Display.string_of_thm thm)
   652             else ();
   653           val _ = if strict andalso (is_some o get_datatype_of_constr thy) c
   654             then error ("Rejected equation for datatype constructor:\n"
   655               ^ Display.string_of_thm func)
   656             else ();
   657         in
   658           (map_exec_purge (SOME [c]) o map_funcs) (Symtab.map_default
   659             (c, (true, Susp.value [])) (add_thm default func)) thy
   660         end
   661     | NONE => thy;
   662 
   663 val add_func = gen_add_func true false;
   664 val add_liberal_func = gen_add_func false false;
   665 val add_default_func = gen_add_func false true;
   666 
   667 fun del_func thm thy = case mk_liberal_func thm
   668  of SOME func => let
   669         val c = const_of_func thy func;
   670       in map_exec_purge (SOME [c]) (map_funcs
   671         (Symtab.map_entry c (del_thm func))) thy
   672       end
   673   | NONE => thy;
   674 
   675 fun del_funcs c = map_exec_purge (SOME [c])
   676   (map_funcs (Symtab.map_entry c (K (false, Susp.value []))));
   677 
   678 fun add_funcl (c, lthms) thy =
   679   let
   680     val lthms' = certificate thy (fn thy => certify_const thy c) lthms;
   681       (*FIXME must check compatibility with sort algebra;
   682         alas, naive checking results in non-termination!*)
   683   in
   684     map_exec_purge (SOME [c])
   685       (map_funcs (Symtab.map_default (c, (true, Susp.value []))
   686         (add_lthms lthms'))) thy
   687   end;
   688 
   689 val add_default_func_attr = Attrib.internal (fn _ => Thm.declaration_attribute
   690   (fn thm => Context.mapping (add_default_func thm) I));
   691 
   692 structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
   693 
   694 fun add_datatype raw_cs thy =
   695   let
   696     val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
   697     val (tyco, vs_cos) = Code_Unit.constrset_of_consts thy cs;
   698     val cs' = map fst (snd vs_cos);
   699     val purge_cs = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   700      of SOME (vs, cos) => if null cos then NONE else SOME (cs' @ map fst cos)
   701       | NONE => NONE;
   702   in
   703     thy
   704     |> map_exec_purge purge_cs (map_dtyps (Symtab.update (tyco, vs_cos))
   705         #> map_funcs (fold (Symtab.delete_safe o fst) cs))
   706     |> TypeInterpretation.data (tyco, serial ())
   707   end;
   708 
   709 fun type_interpretation f =  TypeInterpretation.interpretation
   710   (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
   711 
   712 fun add_datatype_cmd raw_cs thy =
   713   let
   714     val cs = map (Code_Unit.read_bare_const thy) raw_cs;
   715   in add_datatype cs thy end;
   716 
   717 fun add_case thm thy =
   718   let
   719     val entry as (c, _) = Code_Unit.case_cert thm;
   720   in
   721     (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
   722   end;
   723 
   724 fun add_undefined c thy =
   725   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   726 
   727 val map_pre = map_exec_purge NONE o map_thmproc o apfst o apfst;
   728 val map_post = map_exec_purge NONE o map_thmproc o apfst o apsnd;
   729 
   730 fun add_inline thm thy = (map_pre o MetaSimplifier.add_simp)
   731   (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
   732     (*fully applied in order to get right context for mk_rew!*)
   733 
   734 fun del_inline thm thy = (map_pre o MetaSimplifier.del_simp)
   735   (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
   736     (*fully applied in order to get right context for mk_rew!*)
   737 
   738 fun add_post thm thy = (map_post o MetaSimplifier.add_simp)
   739   (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
   740     (*fully applied in order to get right context for mk_rew!*)
   741 
   742 fun del_post thm thy = (map_post o MetaSimplifier.del_simp)
   743   (Code_Unit.error_thm Code_Unit.mk_rew thm) thy;
   744     (*fully applied in order to get right context for mk_rew!*)
   745   
   746 fun add_functrans (name, f) =
   747   (map_exec_purge NONE o map_thmproc o apsnd)
   748     (AList.update (op =) (name, (serial (), f)));
   749 
   750 fun del_functrans name =
   751   (map_exec_purge NONE o map_thmproc o apsnd)
   752     (delete_force "function transformer" name);
   753 
   754 val _ = Context.>> (Context.map_theory
   755   (let
   756     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   757     fun add_simple_attribute (name, f) =
   758       add_attribute (name, Scan.succeed (mk_attribute f));
   759     fun add_del_attribute (name, (add, del)) =
   760       add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
   761         || Scan.succeed (mk_attribute add))
   762   in
   763     TypeInterpretation.init
   764     #> add_del_attribute ("func", (add_func, del_func))
   765     #> add_del_attribute ("inline", (add_inline, del_inline))
   766     #> add_del_attribute ("post", (add_post, del_post))
   767   end));
   768 
   769 
   770 (** post- and preprocessing **)
   771 
   772 local
   773 
   774 fun apply_functrans thy [] = []
   775   | apply_functrans thy (thms as thm :: _) =
   776       let
   777         val const = const_of_func thy thm;
   778         val functrans = (map (fn (_, (_, f)) => f thy) o #functrans
   779           o the_thmproc o the_exec) thy;
   780         val thms' = perhaps (perhaps_loop (perhaps_apply functrans)) thms;
   781       in certify_const thy const thms' end;
   782 
   783 fun rhs_conv conv thm =
   784   let
   785     val thm' = (conv o Thm.rhs_of) thm;
   786   in Thm.transitive thm thm' end
   787 
   788 fun term_of_conv thy f =
   789   Thm.cterm_of thy
   790   #> f
   791   #> Thm.prop_of
   792   #> Logic.dest_equals
   793   #> snd;
   794 
   795 in
   796 
   797 fun preprocess thy thms =
   798   let
   799     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   800   in
   801     thms
   802     |> apply_functrans thy
   803     |> map (Code_Unit.rewrite_func pre)
   804     (*FIXME - must check gere: rewrite rule, defining equation, proper constant *)
   805     |> map (AxClass.unoverload thy)
   806     |> common_typ_funcs
   807   end;
   808 
   809 
   810 fun preprocess_conv ct =
   811   let
   812     val thy = Thm.theory_of_cterm ct;
   813     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   814   in
   815     ct
   816     |> Simplifier.rewrite pre
   817     |> rhs_conv (AxClass.unoverload_conv thy)
   818   end;
   819 
   820 fun preprocess_term thy = term_of_conv thy preprocess_conv;
   821 
   822 fun postprocess_conv ct =
   823   let
   824     val thy = Thm.theory_of_cterm ct;
   825     val post = (Simplifier.theory_context thy o #post o the_thmproc o the_exec) thy;
   826   in
   827     ct
   828     |> AxClass.overload_conv thy
   829     |> rhs_conv (Simplifier.rewrite post)
   830   end;
   831 
   832 fun postprocess_term thy = term_of_conv thy postprocess_conv;
   833 
   834 end; (*local*)
   835 
   836 fun default_typ_proto thy c = case AxClass.inst_of_param thy c
   837  of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
   838       (c, tyco) |> SOME
   839   | NONE => (case AxClass.class_of_param thy c
   840      of SOME class => SOME (Term.map_type_tvar
   841           (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
   842       | NONE => get_constr_typ thy c);
   843 
   844 local
   845 
   846 fun get_funcs thy const =
   847   Symtab.lookup ((the_funcs o the_exec) thy) const
   848   |> Option.map (Susp.force o snd)
   849   |> these
   850   |> map (Thm.transfer thy);
   851 
   852 in
   853 
   854 fun these_funcs thy const =
   855   let
   856     fun drop_refl thy = filter_out (is_equal o Term.fast_term_ord o Logic.dest_equals
   857       o ObjectLogic.drop_judgment thy o Thm.plain_prop_of);
   858   in
   859     get_funcs thy const
   860     |> preprocess thy
   861     |> drop_refl thy
   862   end;
   863 
   864 fun default_typ thy c = case default_typ_proto thy c
   865  of SOME ty => Code_Unit.typscheme thy (c, ty)
   866   | NONE => (case get_funcs thy c
   867      of thm :: _ => snd (Code_Unit.head_func (AxClass.unoverload thy thm))
   868       | [] => Code_Unit.typscheme thy (c, Sign.the_const_type thy c));
   869 
   870 end; (*local*)
   871 
   872 end; (*struct*)
   873 
   874 
   875 (** type-safe interfaces for data depedent on executable content **)
   876 
   877 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
   878 struct
   879 
   880 type T = Data.T;
   881 exception Data of T;
   882 fun dest (Data x) = x
   883 
   884 val kind = Code.declare_data (Data Data.empty)
   885   (fn thy => fn cs => fn Data x => Data (Data.purge thy cs x));
   886 
   887 val data_op = (kind, Data, dest);
   888 
   889 val get = Code.get_data data_op;
   890 val change = Code.change_data data_op;
   891 fun change_yield thy = Code.change_yield_data data_op thy;
   892 
   893 end;
   894 
   895 structure Code : CODE = struct open Code; end;