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