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