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