src/Pure/Isar/code.ML
author wenzelm
Tue Sep 29 11:49:22 2009 +0200 (2009-09-29)
changeset 32738 15bb09ca0378
parent 32662 2faf1148c062
child 32872 019201eb7e07
permissions -rw-r--r--
explicit indication of Unsynchronized.ref;
     1 (*  Title:      Pure/Isar/code.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Abstract executable code of theory.  Management of data dependent on
     5 executable code.  Cache assumes non-concurrent processing of a single theory.
     6 *)
     7 
     8 signature CODE =
     9 sig
    10   (*constants*)
    11   val check_const: theory -> term -> string
    12   val read_bare_const: theory -> string -> string * typ
    13   val read_const: theory -> string -> string
    14   val string_of_const: theory -> string -> string
    15   val args_number: theory -> string -> int
    16   val typscheme: theory -> string * typ -> (string * sort) list * typ
    17 
    18   (*constructor sets*)
    19   val constrset_of_consts: theory -> (string * typ) list
    20     -> string * ((string * sort) list * (string * typ list) list)
    21 
    22   (*code equations*)
    23   val mk_eqn: theory -> thm * bool -> thm * bool
    24   val mk_eqn_warning: theory -> thm -> (thm * bool) option
    25   val mk_eqn_liberal: theory -> thm -> (thm * bool) option
    26   val assert_eqn: theory -> thm * bool -> thm * bool
    27   val assert_eqns_const: theory -> string
    28     -> (thm * bool) list -> (thm * bool) list
    29   val const_typ_eqn: theory -> thm -> string * typ
    30   val typscheme_eqn: theory -> thm -> (string * sort) list * typ
    31 
    32   (*executable code*)
    33   val add_datatype: (string * typ) list -> theory -> theory
    34   val add_datatype_cmd: string list -> theory -> theory
    35   val type_interpretation:
    36     (string * ((string * sort) list * (string * typ list) list)
    37       -> theory -> theory) -> theory -> theory
    38   val add_eqn: thm -> theory -> theory
    39   val add_eqnl: string * (thm * bool) list lazy -> theory -> theory
    40   val add_nbe_eqn: thm -> theory -> theory
    41   val add_default_eqn: thm -> theory -> theory
    42   val add_default_eqn_attribute: attribute
    43   val add_default_eqn_attrib: Attrib.src
    44   val del_eqn: thm -> theory -> theory
    45   val del_eqns: string -> theory -> theory
    46   val add_case: thm -> theory -> theory
    47   val add_undefined: string -> theory -> theory
    48   val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
    49   val get_datatype_of_constr: theory -> string -> string option
    50   val these_eqns: theory -> string -> (thm * bool) list
    51   val all_eqns: theory -> (thm * bool) list
    52   val get_case_scheme: theory -> string -> (int * (int * string list)) option
    53   val undefineds: theory -> string list
    54   val print_codesetup: theory -> unit
    55 
    56   (*infrastructure*)
    57   val set_code_target_attr: (string -> thm -> theory -> theory) -> theory -> theory
    58   val purge_data: theory -> theory
    59 end;
    60 
    61 signature CODE_DATA_ARGS =
    62 sig
    63   type T
    64   val empty: T
    65   val purge: theory -> string list -> T -> T
    66 end;
    67 
    68 signature CODE_DATA =
    69 sig
    70   type T
    71   val get: theory -> T
    72   val change: theory -> (T -> T) -> T
    73   val change_yield: theory -> (T -> 'a * T) -> 'a * T
    74 end;
    75 
    76 signature PRIVATE_CODE =
    77 sig
    78   include CODE
    79   val declare_data: Object.T -> (theory -> string list -> Object.T -> Object.T)
    80     -> serial
    81   val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    82     -> theory -> 'a
    83   val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    84     -> theory -> ('a -> 'a) -> 'a
    85   val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    86     -> theory -> ('a -> 'b * 'a) -> 'b * 'a
    87 end;
    88 
    89 structure Code : PRIVATE_CODE =
    90 struct
    91 
    92 (** auxiliary **)
    93 
    94 (* printing *)
    95 
    96 fun string_of_typ thy = setmp show_sorts true (Syntax.string_of_typ_global thy);
    97 
    98 fun string_of_const thy c = case AxClass.inst_of_param thy c
    99  of SOME (c, tyco) => Sign.extern_const thy c ^ " " ^ enclose "[" "]" (Sign.extern_type thy tyco)
   100   | NONE => Sign.extern_const thy c;
   101 
   102 
   103 (* constants *)
   104 
   105 fun check_bare_const thy t = case try dest_Const t
   106  of SOME c_ty => c_ty
   107   | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   108 
   109 fun check_const thy = AxClass.unoverload_const thy o check_bare_const thy;
   110 
   111 fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
   112 
   113 fun read_const thy = AxClass.unoverload_const thy o read_bare_const thy;
   114 
   115 fun typscheme thy (c, ty) =
   116   let
   117     val ty' = Logic.unvarifyT ty;
   118   in (map dest_TFree (Sign.const_typargs thy (c, ty')), Type.strip_sorts ty') end;
   119 
   120 
   121 (** data store **)
   122 
   123 (* code equations *)
   124 
   125 type eqns = bool * (thm * bool) list lazy;
   126   (*default flag, theorems with proper flag (perhaps lazy)*)
   127 
   128 fun pretty_lthms ctxt r = case Lazy.peek r
   129  of SOME thms => map (Display.pretty_thm ctxt o fst) (Exn.release thms)
   130   | NONE => [Pretty.str "[...]"];
   131 
   132 fun certificate thy f r =
   133   case Lazy.peek r
   134    of SOME thms => (Lazy.value o f thy) (Exn.release thms)
   135     | NONE => let
   136         val thy_ref = Theory.check_thy thy;
   137       in Lazy.lazy (fn () => (f (Theory.deref thy_ref) o Lazy.force) r) end;
   138 
   139 fun add_drop_redundant thy (thm, proper) thms =
   140   let
   141     val args_of = snd o strip_comb o map_types Type.strip_sorts
   142       o fst o Logic.dest_equals o Thm.plain_prop_of;
   143     val args = args_of thm;
   144     val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
   145     fun matches_args args' = length args <= length args' andalso
   146       Pattern.matchess thy (args, (map incr_idx o curry Library.take (length args)) args');
   147     fun drop (thm', proper') = if (proper orelse not proper')
   148       andalso matches_args (args_of thm') then 
   149         (warning ("Code generator: dropping redundant code equation\n" ^
   150             Display.string_of_thm_global thy thm'); true)
   151       else false;
   152   in (thm, proper) :: filter_out drop thms end;
   153 
   154 fun add_thm thy _ thm (false, thms) = (false, Lazy.map_force (add_drop_redundant thy thm) thms)
   155   | add_thm thy true thm (true, thms) = (true, Lazy.map_force (fn thms => thms @ [thm]) thms)
   156   | add_thm thy false thm (true, thms) = (false, Lazy.value [thm]);
   157 
   158 fun add_lthms lthms _ = (false, lthms);
   159 
   160 fun del_thm thm = (apsnd o Lazy.map_force) (remove (eq_fst Thm.eq_thm_prop) (thm, true));
   161 
   162 
   163 (* executable code data *)
   164 
   165 datatype spec = Spec of {
   166   history_concluded: bool,
   167   eqns: ((bool * eqns) * (serial * eqns) list) Symtab.table
   168     (*with explicit history*),
   169   dtyps: ((serial * ((string * sort) list * (string * typ list) list)) list) Symtab.table
   170     (*with explicit history*),
   171   cases: (int * (int * string list)) Symtab.table * unit Symtab.table
   172 };
   173 
   174 fun make_spec (history_concluded, (eqns, (dtyps, cases))) =
   175   Spec { history_concluded = history_concluded, eqns = eqns, dtyps = dtyps, cases = cases };
   176 fun map_spec f (Spec { history_concluded = history_concluded, eqns = eqns,
   177   dtyps = dtyps, cases = cases }) =
   178   make_spec (f (history_concluded, (eqns, (dtyps, cases))));
   179 fun merge_spec (Spec { history_concluded = _, eqns = eqns1,
   180     dtyps = dtyps1, cases = (cases1, undefs1) },
   181   Spec { history_concluded = _, eqns = eqns2,
   182     dtyps = dtyps2, cases = (cases2, undefs2) }) =
   183   let
   184     fun merge_eqns ((_, history1), (_, history2)) =
   185       let
   186         val raw_history = AList.merge (op = : serial * serial -> bool)
   187           (K true) (history1, history2)
   188         val filtered_history = filter_out (fst o snd) raw_history
   189         val history = if null filtered_history
   190           then raw_history else filtered_history;
   191       in ((false, (snd o hd) history), history) end;
   192     val eqns = Symtab.join (K merge_eqns) (eqns1, eqns2);
   193     val dtyps = Symtab.join (K (AList.merge (op =) (K true))) (dtyps1, dtyps2);
   194     val cases = (Symtab.merge (K true) (cases1, cases2),
   195       Symtab.merge (K true) (undefs1, undefs2));
   196   in make_spec (false, (eqns, (dtyps, cases))) end;
   197 
   198 fun history_concluded (Spec { history_concluded, ... }) = history_concluded;
   199 fun the_eqns (Spec { eqns, ... }) = eqns;
   200 fun the_dtyps (Spec { dtyps, ... }) = dtyps;
   201 fun the_cases (Spec { cases, ... }) = cases;
   202 val map_history_concluded = map_spec o apfst;
   203 val map_eqns = map_spec o apsnd o apfst;
   204 val map_dtyps = map_spec o apsnd o apsnd o apfst;
   205 val map_cases = map_spec o apsnd o apsnd o apsnd;
   206 
   207 
   208 (* data slots dependent on executable code *)
   209 
   210 (*private copy avoids potential conflict of table exceptions*)
   211 structure Datatab = Table(type key = int val ord = int_ord);
   212 
   213 local
   214 
   215 type kind = {
   216   empty: Object.T,
   217   purge: theory -> string list -> Object.T -> Object.T
   218 };
   219 
   220 val kinds = Unsynchronized.ref (Datatab.empty: kind Datatab.table);
   221 val kind_keys = Unsynchronized.ref ([]: serial list);
   222 
   223 fun invoke f k = case Datatab.lookup (! kinds) k
   224  of SOME kind => f kind
   225   | NONE => sys_error "Invalid code data identifier";
   226 
   227 in
   228 
   229 fun declare_data empty purge =
   230   let
   231     val k = serial ();
   232     val kind = {empty = empty, purge = purge};
   233     val _ = Unsynchronized.change kinds (Datatab.update (k, kind));
   234     val _ = Unsynchronized.change kind_keys (cons k);
   235   in k end;
   236 
   237 fun invoke_init k = invoke (fn kind => #empty kind) k;
   238 
   239 fun invoke_purge_all thy cs =
   240   fold (fn k => Datatab.map_entry k
   241     (invoke (fn kind => #purge kind thy cs) k)) (! kind_keys);
   242 
   243 end; (*local*)
   244 
   245 
   246 (* theory store *)
   247 
   248 local
   249 
   250 type data = Object.T Datatab.table;
   251 val empty_data = Datatab.empty : data;
   252 
   253 structure Code_Data = TheoryDataFun
   254 (
   255   type T = spec * data Unsynchronized.ref;
   256   val empty = (make_spec (false,
   257     (Symtab.empty, (Symtab.empty, (Symtab.empty, Symtab.empty)))), Unsynchronized.ref empty_data);
   258   fun copy (spec, data) = (spec, Unsynchronized.ref (! data));
   259   val extend = copy;
   260   fun merge pp ((spec1, data1), (spec2, data2)) =
   261     (merge_spec (spec1, spec2), Unsynchronized.ref empty_data);
   262 );
   263 
   264 fun thy_data f thy = f ((snd o Code_Data.get) thy);
   265 
   266 fun get_ensure_init kind data_ref =
   267   case Datatab.lookup (! data_ref) kind
   268    of SOME x => x
   269     | NONE => let val y = invoke_init kind
   270         in (Unsynchronized.change data_ref (Datatab.update (kind, y)); y) end;
   271 
   272 in
   273 
   274 (* access to executable code *)
   275 
   276 val the_exec = fst o Code_Data.get;
   277 
   278 fun complete_class_params thy cs =
   279   fold (fn c => case AxClass.inst_of_param thy c
   280    of NONE => insert (op =) c
   281     | SOME (c', _) => insert (op =) c' #> insert (op =) c) cs [];
   282 
   283 fun map_exec_purge touched f thy =
   284   Code_Data.map (fn (exec, data) => (f exec, Unsynchronized.ref (case touched
   285    of SOME cs => invoke_purge_all thy (complete_class_params thy cs) (! data)
   286     | NONE => empty_data))) thy;
   287 
   288 val purge_data = (Code_Data.map o apsnd) (K (Unsynchronized.ref empty_data));
   289 
   290 fun change_eqns delete c f = (map_exec_purge (SOME [c]) o map_eqns
   291   o (if delete then Symtab.map_entry c else Symtab.map_default (c, ((false, (true, Lazy.value [])), [])))
   292     o apfst) (fn (_, eqns) => (true, f eqns));
   293 
   294 fun del_eqns c = change_eqns true c (K (false, Lazy.value []));
   295 
   296 
   297 (* tackling equation history *)
   298 
   299 fun get_eqns thy c =
   300   Symtab.lookup ((the_eqns o the_exec) thy) c
   301   |> Option.map (Lazy.force o snd o snd o fst)
   302   |> these;
   303 
   304 fun continue_history thy = if (history_concluded o the_exec) thy
   305   then thy
   306     |> (Code_Data.map o apfst o map_history_concluded) (K false)
   307     |> SOME
   308   else NONE;
   309 
   310 fun conclude_history thy = if (history_concluded o the_exec) thy
   311   then NONE
   312   else thy
   313     |> (Code_Data.map o apfst)
   314         ((map_eqns o Symtab.map) (fn ((changed, current), history) =>
   315           ((false, current),
   316             if changed then (serial (), current) :: history else history))
   317         #> map_history_concluded (K true))
   318     |> SOME;
   319 
   320 val _ = Context.>> (Context.map_theory (Code_Data.init
   321   #> Theory.at_begin continue_history
   322   #> Theory.at_end conclude_history));
   323 
   324 
   325 (* access to data dependent on abstract executable code *)
   326 
   327 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
   328 
   329 fun change_data (kind, mk, dest) =
   330   let
   331     fun chnge data_ref f =
   332       let
   333         val data = get_ensure_init kind data_ref;
   334         val data' = f (dest data);
   335       in (Unsynchronized.change data_ref (Datatab.update (kind, mk data')); data') end;
   336   in thy_data chnge end;
   337 
   338 fun change_yield_data (kind, mk, dest) =
   339   let
   340     fun chnge data_ref f =
   341       let
   342         val data = get_ensure_init kind data_ref;
   343         val (x, data') = f (dest data);
   344       in (x, (Unsynchronized.change data_ref (Datatab.update (kind, mk data')); data')) end;
   345   in thy_data chnge end;
   346 
   347 end; (*local*)
   348 
   349 
   350 (** foundation **)
   351 
   352 (* constants *)
   353 
   354 fun args_number thy = length o fst o strip_type o Sign.the_const_type thy;
   355 
   356 
   357 (* datatypes *)
   358 
   359 fun constrset_of_consts thy cs =
   360   let
   361     val _ = map (fn (c, _) => if (is_some o AxClass.class_of_param thy) c
   362       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) cs;
   363     fun no_constr (c, ty) = error ("Not a datatype constructor: " ^ string_of_const thy c
   364       ^ " :: " ^ string_of_typ thy ty);
   365     fun last_typ c_ty ty =
   366       let
   367         val frees = OldTerm.typ_tfrees ty;
   368         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
   369           handle TYPE _ => no_constr c_ty
   370         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr c_ty else ();
   371         val _ = if length frees <> length vs then no_constr c_ty else ();
   372       in (tyco, vs) end;
   373     fun ty_sorts (c, ty) =
   374       let
   375         val ty_decl = (Logic.unvarifyT o Sign.the_const_type thy) c;
   376         val (tyco, _) = last_typ (c, ty) ty_decl;
   377         val (_, vs) = last_typ (c, ty) ty;
   378       in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
   379     fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
   380       let
   381         val _ = if (tyco' : string) <> tyco
   382           then error "Different type constructors in constructor set"
   383           else ();
   384         val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
   385       in ((tyco, sorts), c :: cs) end;
   386     fun inst vs' (c, (vs, ty)) =
   387       let
   388         val the_v = the o AList.lookup (op =) (vs ~~ vs');
   389         val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
   390       in (c, (fst o strip_type) ty') end;
   391     val c' :: cs' = map ty_sorts cs;
   392     val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
   393     val vs = Name.names Name.context Name.aT sorts;
   394     val cs''' = map (inst vs) cs'';
   395   in (tyco, (vs, rev cs''')) end;
   396 
   397 fun get_datatype thy tyco =
   398   case these (Symtab.lookup ((the_dtyps o the_exec) thy) tyco)
   399    of (_, spec) :: _ => spec
   400     | [] => Sign.arity_number thy tyco
   401         |> Name.invents Name.context Name.aT
   402         |> map (rpair [])
   403         |> rpair [];
   404 
   405 fun get_datatype_of_constr thy c =
   406   case (snd o strip_type o Sign.the_const_type thy) c
   407    of Type (tyco, _) => if member (op =) ((map fst o snd o get_datatype thy) tyco) c
   408        then SOME tyco else NONE
   409     | _ => NONE;
   410 
   411 fun is_constr thy = is_some o get_datatype_of_constr thy;
   412 
   413 
   414 (* code equations *)
   415 
   416 exception BAD_THM of string;
   417 fun bad_thm msg = raise BAD_THM msg;
   418 fun error_thm f thm = f thm handle BAD_THM msg => error msg;
   419 fun warning_thm f thm = SOME (f thm) handle BAD_THM msg => (warning msg; NONE)
   420 fun try_thm f thm = SOME (f thm) handle BAD_THM _ => NONE;
   421 
   422 fun is_linear thm =
   423   let val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm
   424   in not (has_duplicates (op =) ((fold o fold_aterms)
   425     (fn Var (v, _) => cons v | _ => I) args [])) end;
   426 
   427 fun gen_assert_eqn thy is_constr_pat (thm, proper) =
   428   let
   429     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   430       handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm_global thy thm)
   431            | THM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm_global thy thm);
   432     fun vars_of t = fold_aterms (fn Var (v, _) => insert (op =) v
   433       | Free _ => bad_thm ("Illegal free variable in equation\n"
   434           ^ Display.string_of_thm_global thy thm)
   435       | _ => I) t [];
   436     fun tvars_of t = fold_term_types (fn _ =>
   437       fold_atyps (fn TVar (v, _) => insert (op =) v
   438         | TFree _ => bad_thm 
   439       ("Illegal free type variable in equation\n" ^ Display.string_of_thm_global thy thm))) t [];
   440     val lhs_vs = vars_of lhs;
   441     val rhs_vs = vars_of rhs;
   442     val lhs_tvs = tvars_of lhs;
   443     val rhs_tvs = tvars_of rhs;
   444     val _ = if null (subtract (op =) lhs_vs rhs_vs)
   445       then ()
   446       else bad_thm ("Free variables on right hand side of equation\n"
   447         ^ Display.string_of_thm_global thy thm);
   448     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
   449       then ()
   450       else bad_thm ("Free type variables on right hand side of equation\n"
   451         ^ Display.string_of_thm_global thy thm)
   452     val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
   453     val (c, ty) = case head
   454      of Const (c_ty as (_, ty)) => (AxClass.unoverload_const thy c_ty, ty)
   455       | _ => bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm_global thy thm);
   456     fun check _ (Abs _) = bad_thm
   457           ("Abstraction on left hand side of equation\n"
   458             ^ Display.string_of_thm_global thy thm)
   459       | check 0 (Var _) = ()
   460       | check _ (Var _) = bad_thm
   461           ("Variable with application on left hand side of equation\n"
   462             ^ Display.string_of_thm_global thy thm)
   463       | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
   464       | check n (Const (c_ty as (c, ty))) = if n = (length o fst o strip_type) ty
   465           then if not proper orelse is_constr_pat (AxClass.unoverload_const thy c_ty)
   466             then ()
   467             else bad_thm (quote c ^ " is not a constructor, on left hand side of equation\n"
   468               ^ Display.string_of_thm_global thy thm)
   469           else bad_thm
   470             ("Partially applied constant " ^ quote c ^ " on left hand side of equation\n"
   471                ^ Display.string_of_thm_global thy thm);
   472     val _ = map (check 0) args;
   473     val _ = if not proper orelse is_linear thm then ()
   474       else bad_thm ("Duplicate variables on left hand side of equation\n"
   475         ^ Display.string_of_thm_global thy thm);
   476     val _ = if (is_none o AxClass.class_of_param thy) c
   477       then ()
   478       else bad_thm ("Polymorphic constant as head in equation\n"
   479         ^ Display.string_of_thm_global thy thm)
   480     val _ = if not (is_constr thy c)
   481       then ()
   482       else bad_thm ("Constructor as head in equation\n"
   483         ^ Display.string_of_thm_global thy thm)
   484     val ty_decl = Sign.the_const_type thy c;
   485     val _ = if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
   486       then () else bad_thm ("Type\n" ^ string_of_typ thy ty
   487            ^ "\nof equation\n"
   488            ^ Display.string_of_thm_global thy thm
   489            ^ "\nis incompatible with declared function type\n"
   490            ^ string_of_typ thy ty_decl)
   491   in (thm, proper) end;
   492 
   493 fun assert_eqn thy = error_thm (gen_assert_eqn thy (is_constr thy));
   494 
   495 fun meta_rewrite thy = LocalDefs.meta_rewrite_rule (ProofContext.init thy);
   496 
   497 fun mk_eqn thy = error_thm (gen_assert_eqn thy (K true)) o
   498   apfst (meta_rewrite thy);
   499 
   500 fun mk_eqn_warning thy = Option.map (fn (thm, _) => (thm, is_linear thm))
   501   o warning_thm (gen_assert_eqn thy (K true)) o rpair false o meta_rewrite thy;
   502 
   503 fun mk_eqn_liberal thy = Option.map (fn (thm, _) => (thm, is_linear thm))
   504   o try_thm (gen_assert_eqn thy (K true)) o rpair false o meta_rewrite thy;
   505 
   506 (*those following are permissive wrt. to overloaded constants!*)
   507 
   508 val head_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   509 fun const_typ_eqn thy thm =
   510   let
   511     val (c, ty) = head_eqn thm;
   512     val c' = AxClass.unoverload_const thy (c, ty);
   513   in (c', ty) end;
   514 
   515 fun typscheme_eqn thy = typscheme thy o const_typ_eqn thy;
   516 fun const_eqn thy = fst o const_typ_eqn thy;
   517 
   518 fun assert_eqns_const thy c eqns =
   519   let
   520     fun cert (eqn as (thm, _)) = if c = const_eqn thy thm
   521       then eqn else error ("Wrong head of code equation,\nexpected constant "
   522         ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy thm)
   523   in map (cert o assert_eqn thy) eqns end;
   524 
   525 fun same_typscheme thy thms =
   526   let
   527     fun tvars_of T = rev (Term.add_tvarsT T []);
   528     val vss = map (tvars_of o snd o head_eqn) thms;
   529     fun inter_sorts vs =
   530       fold (curry (Sorts.inter_sort (Sign.classes_of thy)) o snd) vs [];
   531     val sorts = map_transpose inter_sorts vss;
   532     val vts = Name.names Name.context Name.aT sorts
   533       |> map (fn (v, sort) => TVar ((v, 0), sort));
   534   in map2 (fn vs => Thm.certify_instantiate (vs ~~ vts, [])) vss thms end;
   535 
   536 fun these_eqns thy c =
   537   get_eqns thy c
   538   |> (map o apfst) (Thm.transfer thy)
   539   |> burrow_fst (same_typscheme thy);
   540 
   541 fun all_eqns thy =
   542   Symtab.dest ((the_eqns o the_exec) thy)
   543   |> maps (Lazy.force o snd o snd o fst o snd);
   544 
   545 
   546 (* cases *)
   547 
   548 fun case_certificate thm =
   549   let
   550     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
   551       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.plain_prop_of) thm;
   552     val _ = case head of Free _ => true
   553       | Var _ => true
   554       | _ => raise TERM ("case_cert", []);
   555     val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
   556     val (Const (case_const, _), raw_params) = strip_comb case_expr;
   557     val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
   558     val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
   559     val params = map (fst o dest_Var) (nth_drop n raw_params);
   560     fun dest_case t =
   561       let
   562         val (head' $ t_co, rhs) = Logic.dest_equals t;
   563         val _ = if head' = head then () else raise TERM ("case_cert", []);
   564         val (Const (co, _), args) = strip_comb t_co;
   565         val (Var (param, _), args') = strip_comb rhs;
   566         val _ = if args' = args then () else raise TERM ("case_cert", []);
   567       in (param, co) end;
   568     fun analyze_cases cases =
   569       let
   570         val co_list = fold (AList.update (op =) o dest_case) cases [];
   571       in map (the o AList.lookup (op =) co_list) params end;
   572     fun analyze_let t =
   573       let
   574         val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
   575         val _ = if head' = head then () else raise TERM ("case_cert", []);
   576         val _ = if arg' = arg then () else raise TERM ("case_cert", []);
   577         val _ = if [param'] = params then () else raise TERM ("case_cert", []);
   578       in [] end;
   579     fun analyze (cases as [let_case]) =
   580           (analyze_cases cases handle Bind => analyze_let let_case)
   581       | analyze cases = analyze_cases cases;
   582   in (case_const, (n, analyze cases)) end;
   583 
   584 fun case_cert thm = case_certificate thm
   585   handle Bind => error "bad case certificate"
   586        | TERM _ => error "bad case certificate";
   587 
   588 fun get_case_scheme thy = Symtab.lookup ((fst o the_cases o the_exec) thy);
   589 
   590 val undefineds = Symtab.keys o snd o the_cases o the_exec;
   591 
   592 
   593 (* diagnostic *)
   594 
   595 fun print_codesetup thy =
   596   let
   597     val ctxt = ProofContext.init thy;
   598     val exec = the_exec thy;
   599     fun pretty_eqn (s, (_, lthms)) =
   600       (Pretty.block o Pretty.fbreaks) (
   601         Pretty.str s :: pretty_lthms ctxt lthms
   602       );
   603     fun pretty_dtyp (s, []) =
   604           Pretty.str s
   605       | pretty_dtyp (s, cos) =
   606           (Pretty.block o Pretty.breaks) (
   607             Pretty.str s
   608             :: Pretty.str "="
   609             :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str (string_of_const thy c)
   610                  | (c, tys) =>
   611                      (Pretty.block o Pretty.breaks)
   612                         (Pretty.str (string_of_const thy c)
   613                           :: Pretty.str "of"
   614                           :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
   615           );
   616     val eqns = the_eqns exec
   617       |> Symtab.dest
   618       |> (map o apfst) (string_of_const thy)
   619       |> (map o apsnd) (snd o fst)
   620       |> sort (string_ord o pairself fst);
   621     val dtyps = the_dtyps exec
   622       |> Symtab.dest
   623       |> map (fn (dtco, (_, (vs, cos)) :: _) =>
   624           (string_of_typ thy (Type (dtco, map TFree vs)), cos))
   625       |> sort (string_ord o pairself fst)
   626   in
   627     (Pretty.writeln o Pretty.chunks) [
   628       Pretty.block (
   629         Pretty.str "code equations:"
   630         :: Pretty.fbrk
   631         :: (Pretty.fbreaks o map pretty_eqn) eqns
   632       ),
   633       Pretty.block (
   634         Pretty.str "datatypes:"
   635         :: Pretty.fbrk
   636         :: (Pretty.fbreaks o map pretty_dtyp) dtyps
   637       )
   638     ]
   639   end;
   640 
   641 
   642 (** declaring executable ingredients **)
   643 
   644 (* datatypes *)
   645 
   646 structure Type_Interpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
   647 
   648 fun add_datatype raw_cs thy =
   649   let
   650     val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
   651     val (tyco, vs_cos) = constrset_of_consts thy cs;
   652     val old_cs = (map fst o snd o get_datatype thy) tyco;
   653     fun drop_outdated_cases cases = fold Symtab.delete_safe
   654       (Symtab.fold (fn (c, (_, (_, cos))) =>
   655         if exists (member (op =) old_cs) cos
   656           then insert (op =) c else I) cases []) cases;
   657   in
   658     thy
   659     |> fold (del_eqns o fst) cs
   660     |> map_exec_purge NONE
   661         ((map_dtyps o Symtab.map_default (tyco, [])) (cons (serial (), vs_cos))
   662         #> (map_cases o apfst) drop_outdated_cases)
   663     |> Type_Interpretation.data (tyco, serial ())
   664   end;
   665 
   666 fun type_interpretation f =  Type_Interpretation.interpretation
   667   (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
   668 
   669 fun add_datatype_cmd raw_cs thy =
   670   let
   671     val cs = map (read_bare_const thy) raw_cs;
   672   in add_datatype cs thy end;
   673 
   674 
   675 (* code equations *)
   676 
   677 fun gen_add_eqn default (eqn as (thm, _)) thy =
   678   let val c = const_eqn thy thm
   679   in change_eqns false c (add_thm thy default eqn) thy end;
   680 
   681 fun add_eqn thm thy =
   682   gen_add_eqn false (mk_eqn thy (thm, true)) thy;
   683 
   684 fun add_warning_eqn thm thy =
   685   case mk_eqn_warning thy thm
   686    of SOME eqn => gen_add_eqn false eqn thy
   687     | NONE => thy;
   688 
   689 fun add_default_eqn thm thy =
   690   case mk_eqn_liberal thy thm
   691    of SOME eqn => gen_add_eqn true eqn thy
   692     | NONE => thy;
   693 
   694 fun add_nbe_eqn thm thy =
   695   gen_add_eqn false (mk_eqn thy (thm, false)) thy;
   696 
   697 fun add_eqnl (c, lthms) thy =
   698   let
   699     val lthms' = certificate thy (fn thy => assert_eqns_const thy c) lthms;
   700   in change_eqns false c (add_lthms lthms') thy end;
   701 
   702 val add_default_eqn_attribute = Thm.declaration_attribute
   703   (fn thm => Context.mapping (add_default_eqn thm) I);
   704 val add_default_eqn_attrib = Attrib.internal (K add_default_eqn_attribute);
   705 
   706 fun del_eqn thm thy = case mk_eqn_liberal thy thm
   707  of SOME (thm, _) => change_eqns true (const_eqn thy thm) (del_thm thm) thy
   708   | NONE => thy;
   709 
   710 (* c.f. src/HOL/Tools/recfun_codegen.ML *)
   711 
   712 structure Code_Target_Attr = TheoryDataFun (
   713   type T = (string -> thm -> theory -> theory) option;
   714   val empty = NONE;
   715   val copy = I;
   716   val extend = I;
   717   fun merge _ (NONE, f2) = f2
   718     | merge _ (f1, _) = f1;
   719 );
   720 
   721 fun set_code_target_attr f = Code_Target_Attr.map (K (SOME f));
   722 
   723 fun code_target_attr prefix thm thy =
   724   let
   725     val attr = the_default ((K o K) I) (Code_Target_Attr.get thy);
   726   in thy |> add_warning_eqn thm |> attr prefix thm end;
   727 
   728 (* setup *)
   729 
   730 val _ = Context.>> (Context.map_theory
   731   (let
   732     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   733     val code_attribute_parser =
   734       Args.del |-- Scan.succeed (mk_attribute del_eqn)
   735       || Args.$$$ "nbe" |-- Scan.succeed (mk_attribute add_nbe_eqn)
   736       || (Args.$$$ "target" |-- Args.colon |-- Args.name >>
   737            (mk_attribute o code_target_attr))
   738       || Scan.succeed (mk_attribute add_warning_eqn);
   739   in
   740     Type_Interpretation.init
   741     #> Attrib.setup (Binding.name "code") (Scan.lift code_attribute_parser)
   742         "declare theorems for code generation"
   743   end));
   744 
   745 
   746 (* cases *)
   747 
   748 fun add_case thm thy =
   749   let
   750     val (c, (k, case_pats)) = case_cert thm;
   751     val _ = case filter_out (is_constr thy) case_pats
   752      of [] => ()
   753       | cs => error ("Non-constructor(s) in case certificate: " ^ commas (map quote cs));
   754     val entry = (1 + Int.max (1, length case_pats), (k, case_pats))
   755   in (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update (c, entry)) thy end;
   756 
   757 fun add_undefined c thy =
   758   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   759 
   760 end; (*struct*)
   761 
   762 
   763 (** type-safe interfaces for data dependent on executable code **)
   764 
   765 functor Code_Data_Fun(Data: CODE_DATA_ARGS): CODE_DATA =
   766 struct
   767 
   768 type T = Data.T;
   769 exception Data of T;
   770 fun dest (Data x) = x
   771 
   772 val kind = Code.declare_data (Data Data.empty)
   773   (fn thy => fn cs => fn Data x => Data (Data.purge thy cs x));
   774 
   775 val data_op = (kind, Data, dest);
   776 
   777 val get = Code.get_data data_op;
   778 val change = Code.change_data data_op;
   779 fun change_yield thy = Code.change_yield_data data_op thy;
   780 
   781 end;
   782 
   783 (** datastructure to log definitions for preprocessing of the predicate compiler **)
   784 (* obviously a clone of Named_Thms *)
   785 
   786 signature PREDICATE_COMPILE_PREPROC_CONST_DEFS =
   787 sig
   788   val get: Proof.context -> thm list
   789   val add_thm: thm -> Context.generic -> Context.generic
   790   val del_thm: thm -> Context.generic -> Context.generic
   791   
   792   val add_attribute : attribute
   793   val del_attribute : attribute
   794   
   795   val add_attrib : Attrib.src
   796   
   797   val setup: theory -> theory
   798 end;
   799 
   800 structure Predicate_Compile_Preproc_Const_Defs : PREDICATE_COMPILE_PREPROC_CONST_DEFS =
   801 struct
   802 
   803 structure Data = GenericDataFun
   804 (
   805   type T = thm list;
   806   val empty = [];
   807   val extend = I;
   808   fun merge _ = Thm.merge_thms;
   809 );
   810 
   811 val get = Data.get o Context.Proof;
   812 
   813 val add_thm = Data.map o Thm.add_thm;
   814 val del_thm = Data.map o Thm.del_thm;
   815 
   816 val add_attribute = Thm.declaration_attribute add_thm;
   817 val del_attribute = Thm.declaration_attribute del_thm;
   818 
   819 val add_attrib = Attrib.internal (K add_attribute)
   820 
   821 val setup =
   822   Attrib.setup (Binding.name "pred_compile_preproc") (Attrib.add_del add_attribute del_attribute)
   823     ("declaration of definition for preprocessing of the predicate compiler") #>
   824   PureThy.add_thms_dynamic (Binding.name "pred_compile_preproc", Data.get);
   825 
   826 end;
   827 
   828 structure Code : CODE = struct open Code; end;