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