src/Pure/Isar/code.ML
author haftmann
Wed Nov 28 09:01:42 2007 +0100 (2007-11-28)
changeset 25485 33840a854e63
parent 25462 dad0291cb76a
child 25501 845883bd3a6b
permissions -rw-r--r--
tuned interfaces of class module
     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 ch r f = let val x = f (! r) in (r := x; x) end;
   387 fun thy_data f thy = f ((snd o CodeData.get) thy);
   388 
   389 fun get_ensure_init kind data_ref =
   390   case Datatab.lookup (! data_ref) kind
   391    of SOME x => x
   392     | NONE => let val y = invoke_empty kind
   393         in (change data_ref (Datatab.update (kind, y)); y) end;
   394 
   395 in
   396 
   397 (* access to executable content *)
   398 
   399 val the_exec = fst o CodeData.get;
   400 
   401 fun map_exec_purge touched f thy =
   402   CodeData.map (fn (exec, data) => 
   403     (f exec, ref (invoke_purge_all (SOME thy) touched (! data)))) thy;
   404 
   405 
   406 (* access to data dependent on abstract executable content *)
   407 
   408 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
   409 
   410 fun change_data (kind, mk, dest) =
   411   let
   412     fun chnge data_ref f =
   413       let
   414         val data = get_ensure_init kind data_ref;
   415         val data' = f (dest data);
   416       in (change data_ref (Datatab.update (kind, mk data')); data') end;
   417   in thy_data chnge end;
   418 
   419 fun change_yield_data (kind, mk, dest) =
   420   let
   421     fun chnge data_ref f =
   422       let
   423         val data = get_ensure_init kind data_ref;
   424         val (x, data') = f (dest data);
   425       in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
   426   in thy_data chnge end;
   427 
   428 end; (*local*)
   429 
   430 
   431 (* print executable content *)
   432 
   433 fun print_codesetup thy =
   434   let
   435     val ctxt = ProofContext.init thy;
   436     val exec = the_exec thy;
   437     fun pretty_func (s, lthms) =
   438       (Pretty.block o Pretty.fbreaks) (
   439         Pretty.str s :: pretty_sdthms ctxt lthms
   440       );
   441     fun pretty_dtyp (s, []) =
   442           Pretty.str s
   443       | pretty_dtyp (s, cos) =
   444           (Pretty.block o Pretty.breaks) (
   445             Pretty.str s
   446             :: Pretty.str "="
   447             :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str c
   448                  | (c, tys) =>
   449                      (Pretty.block o Pretty.breaks)
   450                         (Pretty.str (CodeUnit.string_of_const thy c)
   451                           :: Pretty.str "of" :: map (Pretty.quote o Sign.pretty_typ thy) tys)) cos)
   452           );
   453     val inlines = (#inlines o the_thmproc) exec;
   454     val inline_procs = (map fst o #inline_procs o the_thmproc) exec;
   455     val preprocs = (map fst o #preprocs o the_thmproc) exec;
   456     val funs = the_funcs exec
   457       |> Symtab.dest
   458       |> (map o apsnd) snd
   459       |> (map o apfst) (CodeUnit.string_of_const thy)
   460       |> sort (string_ord o pairself fst);
   461     val dtyps = the_dtyps exec
   462       |> Symtab.dest
   463       |> map (fn (dtco, (vs, cos)) => (Sign.string_of_typ thy (Type (dtco, map TFree vs)), cos))
   464       |> sort (string_ord o pairself fst)
   465   in
   466     (Pretty.writeln o Pretty.chunks) [
   467       Pretty.block (
   468         Pretty.str "defining equations:"
   469         :: Pretty.fbrk
   470         :: (Pretty.fbreaks o map pretty_func) funs
   471       ),
   472       Pretty.block (
   473         Pretty.str "inlining theorems:"
   474         :: Pretty.fbrk
   475         :: (Pretty.fbreaks o map (ProofContext.pretty_thm ctxt)) inlines
   476       ),
   477       Pretty.block (
   478         Pretty.str "inlining procedures:"
   479         :: Pretty.fbrk
   480         :: (Pretty.fbreaks o map Pretty.str) inline_procs
   481       ),
   482       Pretty.block (
   483         Pretty.str "preprocessors:"
   484         :: Pretty.fbrk
   485         :: (Pretty.fbreaks o map Pretty.str) preprocs
   486       ),
   487       Pretty.block (
   488         Pretty.str "datatypes:"
   489         :: Pretty.fbrk
   490         :: (Pretty.fbreaks o map pretty_dtyp) dtyps
   491       )
   492     ]
   493   end;
   494 
   495 
   496 
   497 (** theorem transformation and certification **)
   498 
   499 fun common_typ_funcs [] = []
   500   | common_typ_funcs [thm] = [thm]
   501   | common_typ_funcs (thms as thm :: _) =
   502       let
   503         val thy = Thm.theory_of_thm thm;
   504         fun incr_thm thm max =
   505           let
   506             val thm' = incr_indexes max thm;
   507             val max' = Thm.maxidx_of thm' + 1;
   508           in (thm', max') end;
   509         val (thms', maxidx) = fold_map incr_thm thms 0;
   510         val ty1 :: tys = map (snd o CodeUnit.head_func) thms';
   511         fun unify ty env = Sign.typ_unify thy (ty1, ty) env
   512           handle Type.TUNIFY =>
   513             error ("Type unificaton failed, while unifying defining equations\n"
   514             ^ (cat_lines o map Display.string_of_thm) thms
   515             ^ "\nwith types\n"
   516             ^ (cat_lines o map (CodeUnit.string_of_typ thy)) (ty1 :: tys));
   517         val (env, _) = fold unify tys (Vartab.empty, maxidx)
   518         val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   519           cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   520       in map (Thm.instantiate (instT, [])) thms' end;
   521 
   522 fun const_of_func thy = Class.unoverload_const thy o CodeUnit.head_func;
   523 
   524 fun certify_const thy const thms =
   525   let
   526     fun cert thm = if const = const_of_func thy thm
   527       then thm else error ("Wrong head of defining equation,\nexpected constant "
   528         ^ CodeUnit.string_of_const thy const ^ "\n" ^ string_of_thm thm)
   529   in map cert thms end;
   530 
   531 
   532 
   533 (** operational sort algebra and class discipline **)
   534 
   535 local
   536 
   537 fun aggr_neutr f y [] = y
   538   | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
   539 
   540 fun aggregate f [] = NONE
   541   | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
   542 
   543 fun inter_sorts algebra =
   544   aggregate (map2 (curry (Sorts.inter_sort algebra)));
   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_filter (fn c => try (Class.param_of_inst 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 algebra (class, tyco) =
   562   let
   563     val all_superclasses = Sorts.complete_sort algebra [class];
   564   in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) all_superclasses)
   565    of SOME sorts => sorts
   566     | NONE => Sorts.mg_domain algebra tyco [class]
   567   end;
   568 
   569 fun strongest_constraints thy algebra (class, tyco) =
   570   let
   571     val all_subclasses = class :: Graph.all_preds ((#classes o Sorts.rep_algebra) algebra) [class];
   572     val inst_subclasses = filter (can (Sorts.mg_domain algebra tyco) o single) all_subclasses;
   573   in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) inst_subclasses)
   574    of SOME sorts => sorts
   575     | NONE => replicate
   576         (Sign.arity_number thy tyco) (Sorts.minimize_sort algebra (Sorts.all_classes algebra))
   577   end;
   578 
   579 fun get_algebra thy (class, tyco) =
   580   let
   581     val base_algebra = Sign.classes_of thy;
   582   in if can (Sorts.mg_domain base_algebra tyco) [class]
   583     then base_algebra
   584     else let
   585       val superclasses = Sorts.super_classes base_algebra class;
   586       val sorts = inter_sorts base_algebra
   587           (map_filter (fn class => try (Sorts.mg_domain base_algebra tyco) [class]) superclasses)
   588         |> the_default (replicate (Sign.arity_number thy tyco) [])
   589     in
   590       base_algebra
   591       |> Sorts.add_arities (Sign.pp thy) (tyco, [(class, sorts)])
   592     end
   593   end;
   594 
   595 fun gen_classparam_typ constr thy class (c, tyco) = 
   596   let
   597     val algebra = get_algebra thy (class, tyco);
   598     val cs = these (try (#params o AxClass.get_info thy) class);
   599     val SOME ty = AList.lookup (op =) cs c;
   600     val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
   601       (constr thy algebra (class, tyco));
   602     val ty_inst = Type (tyco, map TFree sort_args);
   603   in Logic.varifyT (map_type_tfree (K ty_inst) ty) end;
   604 
   605 fun retrieve_algebra thy operational =
   606   Sorts.subalgebra (Sign.pp thy) operational
   607     (weakest_constraints thy (Sign.classes_of thy))
   608     (Sign.classes_of thy);
   609 
   610 in
   611 
   612 fun coregular_algebra thy = retrieve_algebra thy (K true) |> snd;
   613 fun operational_algebra thy =
   614   let
   615     fun add_iff_operational class =
   616       can (AxClass.get_info thy) class ? cons class;
   617     val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
   618   in retrieve_algebra thy (member (op =) operational_classes) end;
   619 
   620 val classparam_weakest_typ = gen_classparam_typ weakest_constraints;
   621 val classparam_strongest_typ = gen_classparam_typ strongest_constraints;
   622 
   623 fun assert_func_typ thm =
   624   let
   625     val thy = Thm.theory_of_thm thm;
   626     fun check_typ_classparam tyco (c, thm) =
   627           let
   628             val SOME class = AxClass.class_of_param thy c;
   629             val (_, ty) = CodeUnit.head_func thm;
   630             val ty_decl = classparam_weakest_typ thy class (c, tyco);
   631             val ty_strongest = classparam_strongest_typ thy class (c, tyco);
   632             fun constrain thm = 
   633               let
   634                 val max = Thm.maxidx_of thm + 1;
   635                 val ty_decl' = Logic.incr_tvar max ty_decl;
   636                 val (_, ty') = CodeUnit.head_func thm;
   637                 val (env, _) = Sign.typ_unify thy (ty_decl', ty') (Vartab.empty, max);
   638                 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   639                   cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   640               in Thm.instantiate (instT, []) thm end;
   641           in if Sign.typ_instance thy (ty_strongest, ty)
   642             then if Sign.typ_instance thy (ty, ty_decl)
   643             then thm
   644             else (warning ("Constraining type\n" ^ CodeUnit.string_of_typ thy ty
   645               ^ "\nof defining equation\n"
   646               ^ string_of_thm thm
   647               ^ "\nto permitted most general type\n"
   648               ^ CodeUnit.string_of_typ thy ty_decl);
   649               constrain thm)
   650             else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
   651               ^ "\nof defining equation\n"
   652               ^ string_of_thm thm
   653               ^ "\nis incompatible with permitted least general type\n"
   654               ^ CodeUnit.string_of_typ thy ty_strongest)
   655           end;
   656     fun check_typ_fun (c, thm) =
   657       let
   658         val (_, ty) = CodeUnit.head_func thm;
   659         val ty_decl = Sign.the_const_type thy c;
   660       in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
   661         then thm
   662         else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
   663            ^ "\nof defining equation\n"
   664            ^ string_of_thm thm
   665            ^ "\nis incompatible with declared function type\n"
   666            ^ CodeUnit.string_of_typ thy ty_decl)
   667       end;
   668     fun check_typ (c, thm) =
   669       case Class.inst_of_param thy c
   670        of SOME (c, tyco) => check_typ_classparam tyco (c, thm)
   671         | NONE => check_typ_fun (c, thm);
   672   in check_typ (const_of_func thy thm, thm) end;
   673 
   674 val mk_func = CodeUnit.error_thm (assert_func_typ o CodeUnit.mk_func);
   675 val mk_liberal_func = CodeUnit.warning_thm (assert_func_typ o CodeUnit.mk_func);
   676 val mk_default_func = CodeUnit.try_thm (assert_func_typ o CodeUnit.mk_func);
   677 
   678 end;
   679 
   680 
   681 
   682 (** interfaces and attributes **)
   683 
   684 fun delete_force msg key xs =
   685   if AList.defined (op =) xs key then AList.delete (op =) key xs
   686   else error ("No such " ^ msg ^ ": " ^ quote key);
   687 
   688 fun get_datatype thy tyco =
   689   case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   690    of SOME spec => spec
   691     | NONE => Sign.arity_number thy tyco
   692         |> Name.invents Name.context Name.aT
   693         |> map (rpair [])
   694         |> rpair [];
   695 
   696 fun get_datatype_of_constr thy c =
   697   case (snd o strip_type o Sign.the_const_type thy) c
   698    of Type (tyco, _) => if member (op =)
   699        ((the_default [] o Option.map (map fst o snd) o Symtab.lookup ((the_dtyps o the_exec) thy)) tyco) c
   700        then SOME tyco else NONE
   701     | _ => NONE;
   702 
   703 fun get_constr_typ thy c =
   704   case get_datatype_of_constr thy c
   705    of SOME tyco => let
   706           val (vs, cos) = get_datatype thy tyco;
   707           val SOME tys = AList.lookup (op =) cos c;
   708           val ty = tys ---> Type (tyco, map TFree vs);
   709         in SOME (Logic.varifyT ty) end
   710     | NONE => NONE;
   711 
   712 val get_case_data = Symtab.lookup o fst o the_cases o the_exec;
   713 
   714 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
   715 
   716 fun add_func thm thy =
   717   let
   718     val func = mk_func thm;
   719     val c = const_of_func thy func;
   720     val _ = if (is_some o AxClass.class_of_param thy) c
   721       then error ("Rejected polymorphic equation for overloaded constant:\n"
   722         ^ string_of_thm thm)
   723       else ();
   724     val _ = if (is_some o get_datatype_of_constr thy) c
   725       then error ("Rejected equation for datatype constructor:\n"
   726         ^ string_of_thm func)
   727       else ();
   728   in
   729     (map_exec_purge (SOME [c]) o map_funcs) (Symtab.map_default
   730       (c, (false, (Susp.value [], []))) (apsnd (add_thm func))) thy
   731   end;
   732 
   733 fun add_liberal_func thm thy =
   734   case mk_liberal_func thm
   735    of SOME func => let
   736           val c = const_of_func thy func
   737         in if (is_some o AxClass.class_of_param thy) c
   738           orelse (is_some o get_datatype_of_constr thy) c
   739           then thy
   740           else map_exec_purge (SOME [c]) (map_funcs
   741             (Symtab.map_default
   742               (c, (false, (Susp.value [], []))) (apsnd (add_thm func)))) thy
   743         end
   744     | NONE => thy;
   745 
   746 fun add_default_func thm thy =
   747   case mk_default_func thm
   748    of SOME func => let
   749           val c = const_of_func thy func
   750         in if (is_some o AxClass.class_of_param thy) c
   751           orelse (is_some o get_datatype_of_constr thy) c
   752           then thy
   753           else map_exec_purge (SOME [c]) (map_funcs
   754           (Symtab.map_default
   755             (c, (false, (Susp.value [], []))) (apsnd (add_thm func)))) thy
   756         end
   757     | NONE => thy;
   758 
   759 fun del_func thm thy =
   760   case mk_liberal_func thm
   761    of SOME func => let
   762           val c = const_of_func thy func;
   763         in map_exec_purge (SOME [c]) (map_funcs
   764           (Symtab.map_entry c (apsnd (del_thm func)))) thy
   765         end
   766     | NONE => thy;
   767 
   768 fun add_funcl (const, lthms) thy =
   769   let
   770     val lthms' = certificate thy (fn thy => certify_const thy const) lthms;
   771       (*FIXME must check compatibility with sort algebra;
   772         alas, naive checking results in non-termination!*)
   773   in
   774     map_exec_purge (SOME [const])
   775       (map_funcs (Symtab.map_default (const, (false, (Susp.value [], [])))
   776       (apsnd (add_lthms lthms')))) thy
   777   end;
   778 
   779 val add_default_func_attr = Attrib.internal (fn _ => Thm.declaration_attribute
   780   (fn thm => Context.mapping (add_default_func thm) I));
   781 
   782 structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
   783 
   784 fun add_datatype raw_cs thy =
   785   let
   786     val cs = map (fn c_ty as (_, ty) => (Class.unoverload_const thy c_ty, ty)) raw_cs;
   787     val (tyco, vs_cos) = CodeUnit.constrset_of_consts thy cs;
   788     val cs' = map fst (snd vs_cos);
   789     val purge_cs = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   790      of SOME (vs, cos) => if null cos then NONE else SOME (cs' @ map fst cos)
   791       | NONE => NONE;
   792   in
   793     thy
   794     |> map_exec_purge purge_cs (map_dtyps (Symtab.update (tyco, vs_cos))
   795         #> map_funcs (fold (Symtab.delete_safe o fst) cs))
   796     |> TypeInterpretation.data (tyco, serial ())
   797   end;
   798 
   799 fun type_interpretation f =  TypeInterpretation.interpretation
   800   (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
   801 
   802 fun add_datatype_cmd raw_cs thy =
   803   let
   804     val cs = map (CodeUnit.read_bare_const thy) raw_cs;
   805   in add_datatype cs thy end;
   806 
   807 fun add_case thm thy =
   808   let
   809     val entry as (c, _) = CodeUnit.case_cert thm;
   810   in
   811     (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
   812   end;
   813 
   814 fun add_undefined c thy =
   815   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   816 
   817 fun add_inline thm thy =
   818   (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
   819     (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   820         (*fully applied in order to get right context for mk_rew!*)
   821 
   822 fun del_inline thm thy =
   823   (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
   824     (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   825         (*fully applied in order to get right context for mk_rew!*)
   826 
   827 fun add_inline_proc (name, f) =
   828   (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
   829     (AList.update (op =) (name, (serial (), f)));
   830 
   831 fun del_inline_proc name =
   832   (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
   833     (delete_force "inline procedure" name);
   834 
   835 fun add_preproc (name, f) =
   836   (map_exec_purge NONE o map_thmproc o apfst o apsnd)
   837     (AList.update (op =) (name, (serial (), f)));
   838 
   839 fun del_preproc name =
   840   (map_exec_purge NONE o map_thmproc o apfst o apsnd)
   841     (delete_force "preprocessor" name);
   842 
   843 fun add_post thm thy =
   844   (map_exec_purge NONE o map_thmproc o apsnd)
   845     (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   846         (*fully applied in order to get right context for mk_rew!*)
   847 
   848 fun del_post thm thy =
   849   (map_exec_purge NONE o map_thmproc o apsnd)
   850     (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
   851         (*fully applied in order to get right context for mk_rew!*)
   852 
   853 val _ = Context.add_setup
   854   (let
   855     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   856     fun add_simple_attribute (name, f) =
   857       add_attribute (name, Scan.succeed (mk_attribute f));
   858     fun add_del_attribute (name, (add, del)) =
   859       add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
   860         || Scan.succeed (mk_attribute add))
   861   in
   862     TypeInterpretation.init
   863     #> add_del_attribute ("func", (add_func, del_func))
   864     #> add_del_attribute ("inline", (add_inline, del_inline))
   865     #> add_del_attribute ("post", (add_post, del_post))
   866   end);
   867 
   868 
   869 (** post- and preprocessing **)
   870 
   871 local
   872 
   873 fun gen_apply_inline_proc prep post thy f x =
   874   let
   875     val cts = prep x;
   876     val rews = map CodeUnit.assert_rew (f thy cts);
   877   in post rews x end;
   878 
   879 val apply_inline_proc = gen_apply_inline_proc (maps
   880   ((fn [args, rhs] => rhs :: (snd o Drule.strip_comb) args) o snd o Drule.strip_comb o Thm.cprop_of))
   881   (fn rews => map (CodeUnit.rewrite_func rews));
   882 val apply_inline_proc_cterm = gen_apply_inline_proc single
   883   (MetaSimplifier.rewrite false);
   884 
   885 fun apply_preproc thy f [] = []
   886   | apply_preproc thy f (thms as (thm :: _)) =
   887       let
   888         val const = const_of_func thy thm;
   889         val thms' = f thy thms;
   890       in certify_const thy const thms' end;
   891 
   892 fun rhs_conv conv thm =
   893   let
   894     val thm' = (conv o Thm.rhs_of) thm;
   895   in Thm.transitive thm thm' end
   896 
   897 fun term_of_conv thy f =
   898   Thm.cterm_of thy
   899   #> f
   900   #> Thm.prop_of
   901   #> Logic.dest_equals
   902   #> snd;
   903 
   904 in
   905 
   906 fun preprocess thy thms =
   907   thms
   908   |> fold (fn (_, (_, f)) => apply_preproc thy f) ((#preprocs o the_thmproc o the_exec) thy)
   909   |> map (CodeUnit.rewrite_func ((#inlines o the_thmproc o the_exec) thy))
   910   |> fold (fn (_, (_, f)) => apply_inline_proc thy f) ((#inline_procs o the_thmproc o the_exec) thy)
   911 (*FIXME - must check: rewrite rule, defining equation, proper constant |> map (snd o check_func false thy) *)
   912   |> common_typ_funcs
   913   |> map (Class.unoverload thy);
   914 
   915 fun preprocess_conv ct =
   916   let
   917     val thy = Thm.theory_of_cterm ct;
   918   in
   919     ct
   920     |> MetaSimplifier.rewrite false ((#inlines o the_thmproc o the_exec) thy)
   921     |> fold (fn (_, (_, f)) => rhs_conv (apply_inline_proc_cterm thy f))
   922         ((#inline_procs o the_thmproc o the_exec) thy)
   923     |> rhs_conv (Class.unoverload_conv thy)
   924   end;
   925 
   926 fun preprocess_term thy = term_of_conv thy preprocess_conv;
   927 
   928 fun postprocess_conv ct =
   929   let
   930     val thy = Thm.theory_of_cterm ct;
   931   in
   932     ct
   933     |> Class.overload_conv thy
   934     |> rhs_conv (MetaSimplifier.rewrite false ((#posts o the_thmproc o the_exec) thy))
   935   end;
   936 
   937 fun postprocess_term thy = term_of_conv thy postprocess_conv;
   938 
   939 end; (*local*)
   940 
   941 fun default_typ_proto thy c = case Class.inst_of_param thy c
   942  of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
   943       (c, tyco) |> SOME
   944   | NONE => (case AxClass.class_of_param thy c
   945      of SOME class => SOME (Term.map_type_tvar
   946           (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
   947       | NONE => get_constr_typ thy c);
   948 
   949 local
   950 
   951 fun get_funcs thy const =
   952   Symtab.lookup ((the_funcs o the_exec) thy) const
   953   |> Option.map (Susp.force o fst o snd)
   954   |> these
   955   |> map (Thm.transfer thy);
   956 
   957 in
   958 
   959 fun these_funcs thy const =
   960   let
   961     fun drop_refl thy = filter_out (is_equal o Term.fast_term_ord o Logic.dest_equals
   962       o ObjectLogic.drop_judgment thy o Thm.plain_prop_of);
   963   in
   964     get_funcs thy const
   965     |> preprocess thy
   966     |> drop_refl thy
   967   end;
   968 
   969 fun default_typ thy c = case default_typ_proto thy c
   970  of SOME ty => ty
   971   | NONE => (case get_funcs thy c
   972      of thm :: _ => snd (CodeUnit.head_func (Class.unoverload thy thm))
   973       | [] => Sign.the_const_type thy c);
   974 
   975 end; (*local*)
   976 
   977 end; (*struct*)
   978 
   979 
   980 (** type-safe interfaces for data depedent on executable content **)
   981 
   982 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
   983 struct
   984 
   985 type T = Data.T;
   986 exception Data of T;
   987 fun dest (Data x) = x
   988 
   989 val kind = Code.declare_data (Data Data.empty)
   990   (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)))
   991   (fn thy_opt => fn cs => fn Data x => Data (Data.purge thy_opt cs x));
   992 
   993 val data_op = (kind, Data, dest);
   994 
   995 val get = Code.get_data data_op;
   996 val change = Code.change_data data_op;
   997 fun change_yield thy = Code.change_yield_data data_op thy;
   998 
   999 end;
  1000 
  1001 structure Code : CODE =
  1002 struct
  1003 
  1004 open Code;
  1005 
  1006 end;