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