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