src/Pure/Isar/code.ML
author haftmann
Tue Nov 06 13:12:55 2007 +0100 (2007-11-06)
changeset 25312 eb9067371342
parent 24969 b38527eefb3b
child 25462 dad0291cb76a
permissions -rw-r--r--
clarified merge
     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 singly 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 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 (** code attributes **)
    82 
    83 structure CodeAttr = TheoryDataFun (
    84   type T = (string * (Args.T list -> attribute * Args.T list)) list;
    85   val empty = [];
    86   val copy = I;
    87   val extend = I;
    88   fun merge _ = AList.merge (op =) (K true);
    89 );
    90 
    91 fun add_attribute (attr as (name, _)) =
    92   let
    93     fun add_parser ("", parser) attrs = attrs @ [("", parser)]
    94       | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
    95     fun error "" = error ("Code attribute already declared")
    96       | error name = error ("Code attribute " ^ name ^ " already declared")
    97   in CodeAttr.map (fn attrs => if AList.defined (op =) attrs name
    98     then error name else add_parser attr attrs)
    99   end;
   100 
   101 val _ =
   102   let
   103     val code_attr = Attrib.syntax (Scan.peek (fn context =>
   104       List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))));
   105   in
   106     Context.add_setup (Attrib.add_attributes
   107       [("code", code_attr, "declare theorems for code generation")])
   108   end;
   109 
   110 
   111 (** certificate theorems **)
   112 
   113 fun string_of_lthms r = case Susp.peek r
   114  of SOME thms => (map string_of_thm o rev) thms
   115   | NONE => ["[...]"];
   116 
   117 fun pretty_lthms ctxt r = case Susp.peek r
   118  of SOME thms => map (ProofContext.pretty_thm ctxt) thms
   119   | NONE => [Pretty.str "[...]"];
   120 
   121 fun certificate thy f r =
   122   case Susp.peek r
   123    of SOME thms => (Susp.value o f thy) thms
   124     | NONE => let
   125         val thy_ref = Theory.check_thy thy;
   126       in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
   127 
   128 
   129 (** logical and syntactical specification of executable code **)
   130 
   131 (* pairs of (selected, deleted) defining equations *)
   132 
   133 type sdthms = thm list Susp.T * thm list;
   134 
   135 fun add_drop_redundant thm (sels, dels) =
   136   let
   137     val thy = Thm.theory_of_thm thm;
   138     val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   139     val args = args_of thm;
   140     fun matches [] _ = true
   141       | matches (Var _ :: xs) [] = matches xs []
   142       | matches (_ :: _) [] = false
   143       | matches (x :: xs) (y :: ys) = Pattern.matches thy (x, y) andalso matches xs ys;
   144     fun drop thm' = not (matches args (args_of thm'))
   145       orelse (warning ("code generator: dropping redundant defining equation\n" ^ string_of_thm thm'); false);
   146     val (keeps, drops) = List.partition drop sels;
   147   in (thm :: keeps, dels |> remove Thm.eq_thm_prop thm |> fold (insert Thm.eq_thm_prop) drops) end;
   148 
   149 fun add_thm thm (sels, dels) =
   150   apfst Susp.value (add_drop_redundant thm (Susp.force sels, dels));
   151 
   152 fun add_lthms lthms (sels, []) =
   153       (Susp.delay (fn () => fold add_drop_redundant
   154         (Susp.force lthms) (Susp.force sels, []) |> fst), [])
   155         (*FIXME*)
   156   | add_lthms lthms (sels, dels) =
   157       fold add_thm (Susp.force lthms) (sels, dels);
   158 
   159 fun del_thm thm (sels, dels) =
   160   (Susp.value (remove Thm.eq_thm_prop thm (Susp.force sels)), thm :: dels);
   161 
   162 fun pretty_sdthms ctxt (sels, _) = pretty_lthms ctxt sels;
   163 
   164 
   165 (* fundamental melting operations *)
   166 
   167 fun melt _ ([], []) = (false, [])
   168   | melt _ ([], ys) = (true, ys)
   169   | melt eq (xs, ys) = fold_rev
   170       (fn y => fn (t, xs) => (t orelse not (member eq xs y), insert eq y xs)) ys (false, xs);
   171 
   172 fun melt_alist eq_key eq (xys as (xs, ys)) =
   173   if eq_list (eq_pair eq_key eq) (xs, ys)
   174   then (false, xs)
   175   else (true, AList.merge eq_key eq xys);
   176 
   177 val melt_thms = melt Thm.eq_thm_prop;
   178 
   179 fun melt_lthms (r1, r2) =
   180   if Susp.same (r1, r2)
   181     then (false, r1)
   182   else case Susp.peek r1
   183    of SOME [] => (true, r2)
   184     | _ => case Susp.peek r2
   185        of SOME [] => (true, r1)
   186         | _ => (apsnd (Susp.delay o K)) (melt_thms (Susp.force r1, Susp.force r2));
   187 
   188 fun melt_sdthms ((sels1, dels1), (sels2, dels2)) =
   189   let
   190     val (dels_t, dels) = melt_thms (dels1, dels2);
   191   in if dels_t
   192     then let
   193       val (_, sels) = melt_thms
   194         (subtract Thm.eq_thm_prop dels2 (Susp.force sels1), Susp.force sels2);
   195       val (_, dels) = melt_thms
   196         (subtract Thm.eq_thm_prop (Susp.force sels2) dels1, dels2);
   197     in (true, ((Susp.delay o K) sels, dels)) end
   198     else let
   199       val (sels_t, sels) = melt_lthms (sels1, sels2);
   200     in (sels_t, (sels, dels)) end
   201   end;
   202 
   203 
   204 (* specification data *)
   205 
   206 fun melt_funcs tabs =
   207   let
   208     val tab' = Symtab.join (fn _ => fn ((_, a), (_, b)) => melt_sdthms (a, b)) tabs;
   209     val touched = Symtab.fold (fn (c, (true, _)) => insert (op =) c | _ => I) tab' [];
   210   in (touched, tab') end;
   211 
   212 val eq_string = op = : string * string -> bool;
   213 fun eq_dtyp ((vs1, cs1), (vs2, cs2)) = 
   214   gen_eq_set (eq_pair eq_string (gen_eq_set eq_string)) (vs1, vs2)
   215     andalso gen_eq_set (eq_fst eq_string) (cs1, cs2);
   216 fun melt_dtyps (tabs as (tab1, tab2)) =
   217   let
   218     val tycos1 = Symtab.keys tab1;
   219     val tycos2 = Symtab.keys tab2;
   220     val tycos' = filter (member eq_string tycos2) tycos1;
   221     val touched = not (gen_eq_set (op =) (tycos1, tycos2)
   222       andalso gen_eq_set (eq_pair (op =) eq_dtyp)
   223       (AList.make (the o Symtab.lookup tab1) tycos',
   224        AList.make (the o Symtab.lookup tab2) tycos'));
   225     fun join _ (cos as (_, cos2)) = if eq_dtyp cos
   226       then raise Symtab.SAME else cos2;
   227   in (touched, Symtab.join join tabs) end;
   228 
   229 fun melt_cases ((cases1, undefs1), (cases2, undefs2)) =
   230   let
   231     val touched1 = subtract (op =) (Symtab.keys cases1) (Symtab.keys cases2)
   232       @ subtract (op =) (Symtab.keys cases2) (Symtab.keys cases1);
   233     val touched2 = subtract (op =) (Symtab.keys undefs1) (Symtab.keys undefs2)
   234       @ subtract (op =) (Symtab.keys undefs2) (Symtab.keys undefs1);
   235     val touched = fold (insert (op =)) touched1 touched2;
   236   in
   237     (touched, (Symtab.merge (K true) (cases1, cases2),
   238       Symtab.merge (K true) (undefs1, undefs2)))
   239   end;
   240 
   241 datatype spec = Spec of {
   242   funcs: (bool * sdthms) Symtab.table,
   243   dtyps: ((string * sort) list * (string * typ list) list) Symtab.table,
   244   cases: (int * string list) Symtab.table * unit Symtab.table
   245 };
   246 
   247 fun mk_spec (funcs, (dtyps, cases)) =
   248   Spec { funcs = funcs, dtyps = dtyps, cases = cases };
   249 fun map_spec f (Spec { funcs = funcs, dtyps = dtyps, cases = cases }) =
   250   mk_spec (f (funcs, (dtyps, cases)));
   251 fun melt_spec (Spec { funcs = funcs1, dtyps = dtyps1, cases = cases1 },
   252   Spec { funcs = funcs2, dtyps = dtyps2, cases = cases2 }) =
   253   let
   254     val (touched_funcs, funcs) = melt_funcs (funcs1, funcs2);
   255     val (touched_dtyps, dtyps) = melt_dtyps (dtyps1, dtyps2);
   256     val (touched_cases, cases) = melt_cases (cases1, cases2);
   257     val touched = if touched_dtyps then NONE else
   258       SOME (fold (insert (op =)) touched_cases touched_funcs);
   259   in (touched, mk_spec (funcs, (dtyps, cases))) end;
   260 
   261 
   262 (* pre- and postprocessor *)
   263 
   264 datatype thmproc = Thmproc of {
   265   inlines: thm list,
   266   inline_procs: (string * (serial * (theory -> cterm list -> thm list))) list,
   267   preprocs: (string * (serial * (theory -> thm list -> thm list))) list,
   268   posts: thm list
   269 };
   270 
   271 fun mk_thmproc (((inlines, inline_procs), preprocs), posts) =
   272   Thmproc { inlines = inlines, inline_procs = inline_procs, preprocs = preprocs,
   273     posts = posts };
   274 fun map_thmproc f (Thmproc { inlines, inline_procs, preprocs, posts }) =
   275   mk_thmproc (f (((inlines, inline_procs), preprocs), posts));
   276 fun melt_thmproc (Thmproc { inlines = inlines1, inline_procs = inline_procs1,
   277     preprocs = preprocs1, posts = posts1 },
   278   Thmproc { inlines = inlines2, inline_procs = inline_procs2,
   279       preprocs = preprocs2, posts= posts2 }) =
   280     let
   281       val (touched1, inlines) = melt_thms (inlines1, inlines2);
   282       val (touched2, inline_procs) = melt_alist (op =) (eq_fst (op =)) (inline_procs1, inline_procs2);
   283       val (touched3, preprocs) = melt_alist (op =) (eq_fst (op =)) (preprocs1, preprocs2);
   284       val (_, posts) = melt_thms (posts1, posts2);
   285     in (touched1 orelse touched2 orelse touched3,
   286       mk_thmproc (((inlines, inline_procs), preprocs), posts)) 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 melt_exec (Exec { thmproc = thmproc1, spec = spec1 },
   298   Exec { thmproc = thmproc2, spec = spec2 }) =
   299   let
   300     val (touched', thmproc) = melt_thmproc (thmproc1, thmproc2);
   301     val (touched_cs, spec) = melt_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 = Thmproc 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) = melt_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 apsnd) snd
   456       |> (map o apfst) (CodeUnit.string_of_const thy)
   457       |> sort (string_ord o pairself fst);
   458     val dtyps = the_dtyps exec
   459       |> Symtab.dest
   460       |> map (fn (dtco, (vs, cos)) => (Sign.string_of_typ thy (Type (dtco, map TFree vs)), cos))
   461       |> sort (string_ord o pairself fst)
   462   in
   463     (Pretty.writeln o Pretty.chunks) [
   464       Pretty.block (
   465         Pretty.str "defining equations:"
   466         :: Pretty.fbrk
   467         :: (Pretty.fbreaks o map pretty_func) funs
   468       ),
   469       Pretty.block (
   470         Pretty.str "inlining theorems:"
   471         :: Pretty.fbrk
   472         :: (Pretty.fbreaks o map (ProofContext.pretty_thm ctxt)) inlines
   473       ),
   474       Pretty.block (
   475         Pretty.str "inlining procedures:"
   476         :: Pretty.fbrk
   477         :: (Pretty.fbreaks o map Pretty.str) inline_procs
   478       ),
   479       Pretty.block (
   480         Pretty.str "preprocessors:"
   481         :: Pretty.fbrk
   482         :: (Pretty.fbreaks o map Pretty.str) preprocs
   483       ),
   484       Pretty.block (
   485         Pretty.str "datatypes:"
   486         :: Pretty.fbrk
   487         :: (Pretty.fbreaks o map pretty_dtyp) dtyps
   488       )
   489     ]
   490   end;
   491 
   492 
   493 
   494 (** theorem transformation and certification **)
   495 
   496 fun common_typ_funcs [] = []
   497   | common_typ_funcs [thm] = [thm]
   498   | common_typ_funcs (thms as thm :: _) =
   499       let
   500         val thy = Thm.theory_of_thm thm;
   501         fun incr_thm thm max =
   502           let
   503             val thm' = incr_indexes max thm;
   504             val max' = Thm.maxidx_of thm' + 1;
   505           in (thm', max') end;
   506         val (thms', maxidx) = fold_map incr_thm thms 0;
   507         val ty1 :: tys = map (snd o CodeUnit.head_func) thms';
   508         fun unify ty env = Sign.typ_unify thy (ty1, ty) env
   509           handle Type.TUNIFY =>
   510             error ("Type unificaton failed, while unifying defining equations\n"
   511             ^ (cat_lines o map Display.string_of_thm) thms
   512             ^ "\nwith types\n"
   513             ^ (cat_lines o map (CodeUnit.string_of_typ thy)) (ty1 :: tys));
   514         val (env, _) = fold unify tys (Vartab.empty, maxidx)
   515         val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   516           cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   517       in map (Thm.instantiate (instT, [])) thms' end;
   518 
   519 fun const_of_func thy = Class.unoverload_const thy o CodeUnit.head_func;
   520 
   521 fun certify_const thy const thms =
   522   let
   523     fun cert thm = if const = const_of_func thy thm
   524       then thm else error ("Wrong head of defining equation,\nexpected constant "
   525         ^ CodeUnit.string_of_const thy const ^ "\n" ^ string_of_thm thm)
   526   in map cert thms end;
   527 
   528 
   529 
   530 (** operational sort algebra and class discipline **)
   531 
   532 local
   533 
   534 fun aggr_neutr f y [] = y
   535   | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
   536 
   537 fun aggregate f [] = NONE
   538   | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
   539 
   540 fun inter_sorts thy =
   541   let
   542     val algebra = Sign.classes_of thy;
   543     val inters = curry (Sorts.inter_sort algebra);
   544   in aggregate (map2 inters) end;
   545 
   546 fun specific_constraints thy (class, tyco) =
   547   let
   548     val vs = Name.invents Name.context "" (Sign.arity_number thy tyco);
   549     val classparams = (map fst o these o try (#params o AxClass.get_info 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 o snd)
   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 cs = these (try (#params o AxClass.get_info thy) class);
   583     val ty = (the o AList.lookup (op =) cs) c;
   584     val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
   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_info 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 Name.aT
   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, (false, (Susp.value [], []))) (apsnd (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, (false, (Susp.value [], []))) (apsnd (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, (false, (Susp.value [], []))) (apsnd (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 (apsnd (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])
   759       (map_funcs (Symtab.map_default (const, (false, (Susp.value [], [])))
   760       (apsnd (add_lthms lthms')))) thy
   761   end;
   762 
   763 val add_default_func_attr = Attrib.internal (fn _ => Thm.declaration_attribute
   764   (fn thm => Context.mapping (add_default_func thm) I));
   765 
   766 fun add_datatype raw_cs thy =
   767   let
   768     val cs = map (fn c_ty as (_, ty) => (Class.unoverload_const thy c_ty, ty)) raw_cs;
   769     val (tyco, vs_cos) = CodeUnit.constrset_of_consts thy cs;
   770     val purge_cs = map fst (snd vs_cos);
   771     val purge_cs' = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   772      of SOME (vs, cos) => if null cos then NONE else SOME (purge_cs @ map fst cos)
   773       | NONE => NONE;
   774   in
   775     thy
   776     |> map_exec_purge purge_cs' (map_dtyps (Symtab.update (tyco, vs_cos))
   777         #> map_funcs (fold (Symtab.delete_safe o fst) cs))
   778   end;
   779 
   780 fun add_datatype_cmd raw_cs thy =
   781   let
   782     val cs = map (CodeUnit.read_bare_const thy) raw_cs;
   783   in add_datatype cs thy end;
   784 
   785 fun add_case thm thy =
   786   let
   787     val entry as (c, _) = CodeUnit.case_cert thm;
   788   in
   789     (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
   790   end;
   791 
   792 fun add_undefined c thy =
   793   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   794 
   795 fun add_inline thm thy =
   796   (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
   797     (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   798         (*fully applied in order to get right context for mk_rew!*)
   799 
   800 fun del_inline thm thy =
   801   (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
   802     (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   803         (*fully applied in order to get right context for mk_rew!*)
   804 
   805 fun add_inline_proc (name, f) =
   806   (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
   807     (AList.update (op =) (name, (serial (), f)));
   808 
   809 fun del_inline_proc name =
   810   (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
   811     (delete_force "inline procedure" name);
   812 
   813 fun add_preproc (name, f) =
   814   (map_exec_purge NONE o map_thmproc o apfst o apsnd)
   815     (AList.update (op =) (name, (serial (), f)));
   816 
   817 fun del_preproc name =
   818   (map_exec_purge NONE o map_thmproc o apfst o apsnd)
   819     (delete_force "preprocessor" name);
   820 
   821 fun add_post thm thy =
   822   (map_exec_purge NONE o map_thmproc o apsnd)
   823     (insert 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 del_post thm thy =
   827   (map_exec_purge NONE o map_thmproc o apsnd)
   828     (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   829         (*fully applied in order to get right context for mk_rew!*)
   830 
   831 val _ = Context.add_setup
   832   (let
   833     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   834     fun add_simple_attribute (name, f) =
   835       add_attribute (name, Scan.succeed (mk_attribute f));
   836     fun add_del_attribute (name, (add, del)) =
   837       add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
   838         || Scan.succeed (mk_attribute add))
   839   in
   840     add_del_attribute ("func", (add_func, del_func))
   841     #> add_del_attribute ("inline", (add_inline, del_inline))
   842     #> add_del_attribute ("post", (add_post, del_post))
   843   end);
   844 
   845 
   846 (** post- and preprocessing **)
   847 
   848 local
   849 
   850 fun gen_apply_inline_proc prep post thy f x =
   851   let
   852     val cts = prep x;
   853     val rews = map CodeUnit.assert_rew (f thy cts);
   854   in post rews x end;
   855 
   856 val apply_inline_proc = gen_apply_inline_proc (maps
   857   ((fn [args, rhs] => rhs :: (snd o Drule.strip_comb) args) o snd o Drule.strip_comb o Thm.cprop_of))
   858   (fn rews => map (CodeUnit.rewrite_func rews));
   859 val apply_inline_proc_cterm = gen_apply_inline_proc single
   860   (MetaSimplifier.rewrite false);
   861 
   862 fun apply_preproc thy f [] = []
   863   | apply_preproc thy f (thms as (thm :: _)) =
   864       let
   865         val const = const_of_func thy thm;
   866         val thms' = f thy thms;
   867       in certify_const thy const thms' end;
   868 
   869 fun rhs_conv conv thm =
   870   let
   871     val thm' = (conv o Thm.rhs_of) thm;
   872   in Thm.transitive thm thm' end
   873 
   874 fun term_of_conv thy f =
   875   Thm.cterm_of thy
   876   #> f
   877   #> Thm.prop_of
   878   #> Logic.dest_equals
   879   #> snd;
   880 
   881 in
   882 
   883 fun preprocess thy thms =
   884   thms
   885   |> fold (fn (_, (_, f)) => apply_preproc thy f) ((#preprocs o the_thmproc o the_exec) thy)
   886   |> map (CodeUnit.rewrite_func ((#inlines o the_thmproc o the_exec) thy))
   887   |> fold (fn (_, (_, f)) => apply_inline_proc thy f) ((#inline_procs o the_thmproc o the_exec) thy)
   888 (*FIXME - must check: rewrite rule, defining equation, proper constant |> map (snd o check_func false thy) *)
   889   |> common_typ_funcs
   890   |> map (Conv.fconv_rule (Class.unoverload thy));
   891 
   892 fun preprocess_conv ct =
   893   let
   894     val thy = Thm.theory_of_cterm ct;
   895   in
   896     ct
   897     |> MetaSimplifier.rewrite false ((#inlines o the_thmproc o the_exec) thy)
   898     |> fold (fn (_, (_, f)) => rhs_conv (apply_inline_proc_cterm thy f))
   899         ((#inline_procs o the_thmproc o the_exec) thy)
   900     |> rhs_conv (Class.unoverload thy)
   901   end;
   902 
   903 fun preprocess_term thy = term_of_conv thy preprocess_conv;
   904 
   905 fun postprocess_conv ct =
   906   let
   907     val thy = Thm.theory_of_cterm ct;
   908   in
   909     ct
   910     |> Class.overload thy
   911     |> rhs_conv (MetaSimplifier.rewrite false ((#posts o the_thmproc o the_exec) thy))
   912   end;
   913 
   914 fun postprocess_term thy = term_of_conv thy postprocess_conv;
   915 
   916 end; (*local*)
   917 
   918 fun default_typ_proto thy c = case Class.param_const thy c
   919  of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
   920       (c, tyco) |> SOME
   921   | NONE => (case AxClass.class_of_param thy c
   922      of SOME class => SOME (Term.map_type_tvar
   923           (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
   924       | NONE => get_constr_typ thy c);
   925 
   926 local
   927 
   928 fun get_funcs thy const =
   929   Symtab.lookup ((the_funcs o the_exec) thy) const
   930   |> Option.map (Susp.force o fst o snd)
   931   |> these
   932   |> map (Thm.transfer thy);
   933 
   934 in
   935 
   936 fun these_funcs thy const =
   937   let
   938     fun drop_refl thy = filter_out (is_equal o Term.fast_term_ord o Logic.dest_equals
   939       o ObjectLogic.drop_judgment thy o Thm.plain_prop_of);
   940   in
   941     get_funcs thy const
   942     |> preprocess thy
   943     |> drop_refl thy
   944   end;
   945 
   946 fun default_typ thy c = case default_typ_proto thy c
   947  of SOME ty => ty
   948   | NONE => (case get_funcs thy c
   949      of thm :: _ => snd (CodeUnit.head_func (Conv.fconv_rule (Class.unoverload thy) thm))
   950       | [] => Sign.the_const_type thy c);
   951 
   952 end; (*local*)
   953 
   954 end; (*struct*)
   955 
   956 
   957 (** type-safe interfaces for data depedent on executable content **)
   958 
   959 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
   960 struct
   961 
   962 type T = Data.T;
   963 exception Data of T;
   964 fun dest (Data x) = x
   965 
   966 val kind = Code.declare_data (Data Data.empty)
   967   (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)))
   968   (fn thy_opt => fn cs => fn Data x => Data (Data.purge thy_opt cs x));
   969 
   970 val data_op = (kind, Data, dest);
   971 
   972 val get = Code.get_data data_op;
   973 val change = Code.change_data data_op;
   974 fun change_yield thy = Code.change_yield_data data_op thy;
   975 
   976 end;
   977 
   978 structure Code : CODE =
   979 struct
   980 
   981 open Code;
   982 
   983 end;