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