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