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