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