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