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