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