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