src/Pure/Isar/code.ML
author haftmann
Sun Jul 28 05:32:02 2013 +0200 (2013-07-28)
changeset 52781 e78c3023162b
parent 52637 1501ebe39711
child 52788 da1fdbfebd39
permissions -rw-r--r--
silenced subsumption warnings for default code equations entirely
     1 (*  Title:      Pure/Isar/code.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Abstract executable ingredients of theory.  Management of data
     5 dependent on executable ingredients as synchronized cache; purged
     6 on any change of underlying executable ingredients.
     7 *)
     8 
     9 signature CODE =
    10 sig
    11   (*constants*)
    12   val check_const: theory -> term -> string
    13   val read_bare_const: theory -> string -> string * typ
    14   val read_const: theory -> string -> string
    15   val string_of_const: theory -> string -> string
    16   val const_typ: theory -> string -> typ
    17   val args_number: theory -> string -> int
    18 
    19   (*constructor sets*)
    20   val constrset_of_consts: theory -> (string * typ) list
    21     -> string * ((string * sort) list * (string * ((string * sort) list * typ list)) list)
    22 
    23   (*code equations and certificates*)
    24   val mk_eqn: theory -> thm * bool -> thm * bool
    25   val mk_eqn_liberal: theory -> thm -> (thm * bool) option
    26   val assert_eqn: theory -> thm * bool -> thm * bool
    27   val const_typ_eqn: theory -> thm -> string * typ
    28   val expand_eta: theory -> int -> thm -> thm
    29   type cert
    30   val empty_cert: theory -> string -> cert
    31   val cert_of_eqns: theory -> string -> (thm * bool) list -> cert
    32   val constrain_cert: theory -> sort list -> cert -> cert
    33   val conclude_cert: cert -> cert
    34   val typargs_deps_of_cert: theory -> cert -> (string * sort) list * (string * typ list) list
    35   val equations_of_cert: theory -> cert -> ((string * sort) list * typ)
    36     * (((term * string option) list * (term * string option)) * (thm option * bool)) list
    37   val bare_thms_of_cert: theory -> cert -> thm list
    38   val pretty_cert: theory -> cert -> Pretty.T list
    39 
    40   (*executable code*)
    41   val add_datatype: (string * typ) list -> theory -> theory
    42   val add_datatype_cmd: string list -> theory -> theory
    43   val datatype_interpretation:
    44     (string * ((string * sort) list * (string * ((string * sort) list * typ list)) list)
    45       -> theory -> theory) -> theory -> theory
    46   val add_abstype: thm -> theory -> theory
    47   val abstype_interpretation:
    48     (string * ((string * sort) list * ((string * ((string * sort) list * typ)) * (string * thm)))
    49       -> theory -> theory) -> theory -> theory
    50   val add_eqn: thm -> theory -> theory
    51   val add_nbe_eqn: thm -> theory -> theory
    52   val add_abs_eqn: thm -> theory -> theory
    53   val add_default_eqn: thm -> theory -> theory
    54   val add_default_eqn_attribute: attribute
    55   val add_default_eqn_attrib: Attrib.src
    56   val add_nbe_default_eqn: thm -> theory -> theory
    57   val add_nbe_default_eqn_attribute: attribute
    58   val add_nbe_default_eqn_attrib: Attrib.src
    59   val del_eqn: thm -> theory -> theory
    60   val del_eqns: string -> theory -> theory
    61   val add_case: thm -> theory -> theory
    62   val add_undefined: string -> theory -> theory
    63   val get_type: theory -> string
    64     -> ((string * sort) list * (string * ((string * sort) list * typ list)) list) * bool
    65   val get_type_of_constr_or_abstr: theory -> string -> (string * bool) option
    66   val is_constr: theory -> string -> bool
    67   val is_abstr: theory -> string -> bool
    68   val get_cert: theory -> { functrans: ((thm * bool) list -> (thm * bool) list option) list,
    69     ss: simpset } -> string -> cert
    70   val get_case_scheme: theory -> string -> (int * (int * string option list)) option
    71   val get_case_cong: theory -> string -> thm option
    72   val undefineds: theory -> string list
    73   val print_codesetup: theory -> unit
    74 end;
    75 
    76 signature CODE_DATA_ARGS =
    77 sig
    78   type T
    79   val empty: T
    80 end;
    81 
    82 signature CODE_DATA =
    83 sig
    84   type T
    85   val change: theory option -> (T -> T) -> T
    86   val change_yield: theory option -> (T -> 'a * T) -> 'a * T
    87 end;
    88 
    89 signature PRIVATE_CODE =
    90 sig
    91   include CODE
    92   val declare_data: Any.T -> serial
    93   val change_yield_data: serial * ('a -> Any.T) * (Any.T -> 'a)
    94     -> theory -> ('a -> 'b * 'a) -> 'b * 'a
    95 end;
    96 
    97 structure Code : PRIVATE_CODE =
    98 struct
    99 
   100 (** auxiliary **)
   101 
   102 (* printing *)
   103 
   104 fun string_of_typ thy =
   105   Syntax.string_of_typ (Config.put show_sorts true (Syntax.init_pretty_global thy));
   106 
   107 fun string_of_const thy c =
   108   let val ctxt = Proof_Context.init_global thy in
   109     case Axclass.inst_of_param thy c of
   110       SOME (c, tyco) =>
   111         Proof_Context.extern_const ctxt c ^ " " ^ enclose "[" "]"
   112           (Proof_Context.extern_type ctxt tyco)
   113     | NONE => Proof_Context.extern_const ctxt c
   114   end;
   115 
   116 
   117 (* constants *)
   118 
   119 fun const_typ thy = Type.strip_sorts o Sign.the_const_type thy;
   120 
   121 fun args_number thy = length o binder_types o const_typ thy;
   122 
   123 fun devarify ty =
   124   let
   125     val tys = fold_atyps (fn TVar vi_sort => AList.update (op =) vi_sort) ty [];
   126     val vs = Name.invent Name.context Name.aT (length tys);
   127     val mapping = map2 (fn v => fn (vi, sort) => (vi, TFree (v, sort))) vs tys;
   128   in Term.typ_subst_TVars mapping ty end;
   129 
   130 fun typscheme thy (c, ty) =
   131   (map dest_TFree (Sign.const_typargs thy (c, ty)), Type.strip_sorts ty);
   132 
   133 fun typscheme_equiv (ty1, ty2) =
   134   Type.raw_instance (devarify ty1, ty2) andalso Type.raw_instance (devarify ty2, ty1);
   135 
   136 fun check_bare_const thy t = case try dest_Const t
   137  of SOME c_ty => c_ty
   138   | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   139 
   140 fun check_unoverload thy (c, ty) =
   141   let
   142     val c' = Axclass.unoverload_const thy (c, ty);
   143     val ty_decl = Sign.the_const_type thy c';
   144   in
   145     if typscheme_equiv (ty_decl, Logic.varifyT_global ty)
   146     then c'
   147     else
   148       error ("Type\n" ^ string_of_typ thy ty ^
   149         "\nof constant " ^ quote c ^
   150         "\nis too specific compared to declared type\n" ^
   151         string_of_typ thy ty_decl)
   152   end; 
   153 
   154 fun check_const thy = check_unoverload thy o check_bare_const thy;
   155 
   156 fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
   157 
   158 fun read_const thy = check_unoverload thy o read_bare_const thy;
   159 
   160 
   161 (** data store **)
   162 
   163 (* datatypes *)
   164 
   165 datatype typ_spec = Constructors of (string * ((string * sort) list * typ list)) list *
   166       string list (*references to associated case constructors*)
   167   | Abstractor of (string * ((string * sort) list * typ)) * (string * thm);
   168 
   169 fun constructors_of (Constructors (cos, _)) = (cos, false)
   170   | constructors_of (Abstractor ((co, (vs, ty)), _)) = ([(co, (vs, [ty]))], true);
   171 
   172 fun case_consts_of (Constructors (_, case_consts)) = case_consts
   173   | case_consts_of (Abstractor _) = [];
   174 
   175 (* functions *)
   176 
   177 datatype fun_spec = Default of (thm * bool) list * (thm * bool) list lazy
   178       (* (cache for default equations, lazy computation of default equations)
   179          -- helps to restore natural order of default equations *)
   180   | Eqns of (thm * bool) list
   181   | Proj of term * string
   182   | Abstr of thm * string;
   183 
   184 val empty_fun_spec = Default ([], Lazy.value []);
   185 
   186 fun is_default (Default _) = true
   187   | is_default _ = false;
   188 
   189 fun associated_abstype (Abstr (_, tyco)) = SOME tyco
   190   | associated_abstype _ = NONE;
   191 
   192 
   193 (* executable code data *)
   194 
   195 datatype spec = Spec of {
   196   history_concluded: bool,
   197   functions: ((bool * fun_spec) * (serial * fun_spec) list) Symtab.table
   198     (*with explicit history*),
   199   types: ((serial * ((string * sort) list * typ_spec)) list) Symtab.table
   200     (*with explicit history*),
   201   cases: ((int * (int * string option list)) * thm) Symtab.table * unit Symtab.table
   202 };
   203 
   204 fun make_spec (history_concluded, (functions, (types, cases))) =
   205   Spec { history_concluded = history_concluded, functions = functions, types = types, cases = cases };
   206 fun map_spec f (Spec { history_concluded = history_concluded,
   207   functions = functions, types = types, cases = cases }) =
   208   make_spec (f (history_concluded, (functions, (types, cases))));
   209 fun merge_spec (Spec { history_concluded = _, functions = functions1,
   210     types = types1, cases = (cases1, undefs1) },
   211   Spec { history_concluded = _, functions = functions2,
   212     types = types2, cases = (cases2, undefs2) }) =
   213   let
   214     val types = Symtab.join (K (AList.merge (op =) (K true))) (types1, types2);
   215     val case_consts_of' = (maps case_consts_of o map (snd o snd o hd o snd) o Symtab.dest);
   216     fun merge_functions ((_, history1), (_, history2)) =
   217       let
   218         val raw_history = AList.merge (op = : serial * serial -> bool)
   219           (K true) (history1, history2);
   220         val filtered_history = filter_out (is_default o snd) raw_history;
   221         val history = if null filtered_history
   222           then raw_history else filtered_history;
   223       in ((false, (snd o hd) history), history) end;
   224     val all_datatype_specs = map (snd o snd o hd o snd) (Symtab.dest types);
   225     val all_constructors = maps (map fst o fst o constructors_of) all_datatype_specs;
   226     val invalidated_case_consts = union (op =) (case_consts_of' types1) (case_consts_of' types2)
   227       |> subtract (op =) (maps case_consts_of all_datatype_specs)
   228     val functions = Symtab.join (K merge_functions) (functions1, functions2)
   229       |> fold (fn c => Symtab.map_entry c (apfst (K (true, empty_fun_spec)))) all_constructors;
   230     val cases = (Symtab.merge (K true) (cases1, cases2)
   231       |> fold Symtab.delete invalidated_case_consts, Symtab.merge (K true) (undefs1, undefs2));
   232   in make_spec (false, (functions, (types, cases))) end;
   233 
   234 fun history_concluded (Spec { history_concluded, ... }) = history_concluded;
   235 fun the_functions (Spec { functions, ... }) = functions;
   236 fun the_types (Spec { types, ... }) = types;
   237 fun the_cases (Spec { cases, ... }) = cases;
   238 val map_history_concluded = map_spec o apfst;
   239 val map_functions = map_spec o apsnd o apfst;
   240 val map_typs = map_spec o apsnd o apsnd o apfst;
   241 val map_cases = map_spec o apsnd o apsnd o apsnd;
   242 
   243 
   244 (* data slots dependent on executable code *)
   245 
   246 (*private copy avoids potential conflict of table exceptions*)
   247 structure Datatab = Table(type key = int val ord = int_ord);
   248 
   249 local
   250 
   251 type kind = { empty: Any.T };
   252 
   253 val kinds = Synchronized.var "Code_Data" (Datatab.empty: kind Datatab.table);
   254 
   255 fun invoke f k =
   256   (case Datatab.lookup (Synchronized.value kinds) k of
   257     SOME kind => f kind
   258   | NONE => raise Fail "Invalid code data identifier");
   259 
   260 in
   261 
   262 fun declare_data empty =
   263   let
   264     val k = serial ();
   265     val kind = { empty = empty };
   266     val _ = Synchronized.change kinds (Datatab.update (k, kind));
   267   in k end;
   268 
   269 fun invoke_init k = invoke (fn kind => #empty kind) k;
   270 
   271 end; (*local*)
   272 
   273 
   274 (* theory store *)
   275 
   276 local
   277 
   278 type data = Any.T Datatab.table;
   279 fun empty_dataref () = Synchronized.var "code data" (NONE : (data * theory_ref) option);
   280 
   281 structure Code_Data = Theory_Data
   282 (
   283   type T = spec * (data * theory_ref) option Synchronized.var;
   284   val empty = (make_spec (false, (Symtab.empty,
   285     (Symtab.empty, (Symtab.empty, Symtab.empty)))), empty_dataref ());
   286   val extend : T -> T = apsnd (K (empty_dataref ()));
   287   fun merge ((spec1, _), (spec2, _)) =
   288     (merge_spec (spec1, spec2), empty_dataref ());
   289 );
   290 
   291 in
   292 
   293 
   294 (* access to executable code *)
   295 
   296 val the_exec : theory -> spec = fst o Code_Data.get;
   297 
   298 fun map_exec_purge f = Code_Data.map (fn (exec, _) => (f exec, empty_dataref ()));
   299 
   300 fun change_fun_spec delete c f = (map_exec_purge o map_functions
   301   o (if delete then Symtab.map_entry c else Symtab.map_default (c, ((false, empty_fun_spec), [])))
   302     o apfst) (fn (_, spec) => (true, f spec));
   303 
   304 
   305 (* tackling equation history *)
   306 
   307 fun continue_history thy = if (history_concluded o the_exec) thy
   308   then thy
   309     |> (Code_Data.map o apfst o map_history_concluded) (K false)
   310     |> SOME
   311   else NONE;
   312 
   313 fun conclude_history thy = if (history_concluded o the_exec) thy
   314   then NONE
   315   else thy
   316     |> (Code_Data.map o apfst)
   317         ((map_functions o Symtab.map) (fn _ => fn ((changed, current), history) =>
   318           ((false, current),
   319             if changed then (serial (), current) :: history else history))
   320         #> map_history_concluded (K true))
   321     |> SOME;
   322 
   323 val _ = Context.>> (Context.map_theory (Theory.at_begin continue_history #> Theory.at_end conclude_history));
   324 
   325 
   326 (* access to data dependent on abstract executable code *)
   327 
   328 fun change_yield_data (kind, mk, dest) theory f =
   329   let
   330     val dataref = (snd o Code_Data.get) theory;
   331     val (datatab, thy_ref) = case Synchronized.value dataref
   332      of SOME (datatab, thy_ref) => if Theory.eq_thy (theory, Theory.deref thy_ref)
   333           then (datatab, thy_ref)
   334           else (Datatab.empty, Theory.check_thy theory)
   335       | NONE => (Datatab.empty, Theory.check_thy theory)
   336     val data = case Datatab.lookup datatab kind
   337      of SOME data => data
   338       | NONE => invoke_init kind;
   339     val result as (_, data') = f (dest data);
   340     val _ = Synchronized.change dataref
   341       ((K o SOME) (Datatab.update (kind, mk data') datatab, thy_ref));
   342   in result end;
   343 
   344 end; (*local*)
   345 
   346 
   347 (** foundation **)
   348 
   349 (* datatypes *)
   350 
   351 fun no_constr thy s (c, ty) = error ("Not a datatype constructor:\n" ^ string_of_const thy c
   352   ^ " :: " ^ string_of_typ thy ty ^ "\n" ^ enclose "(" ")" s);
   353 
   354 fun analyze_constructor thy (c, ty) =
   355   let
   356     val _ = Thm.cterm_of thy (Const (c, ty));
   357     val ty_decl = Logic.unvarifyT_global (const_typ thy c);
   358     fun last_typ c_ty ty =
   359       let
   360         val tfrees = Term.add_tfreesT ty [];
   361         val (tyco, vs) = (apsnd o map) dest_TFree (dest_Type (body_type ty))
   362           handle TYPE _ => no_constr thy "bad type" c_ty
   363         val _ = if tyco = "fun" then no_constr thy "bad type" c_ty else ();
   364         val _ =
   365           if has_duplicates (eq_fst (op =)) vs
   366           then no_constr thy "duplicate type variables in datatype" c_ty else ();
   367         val _ =
   368           if length tfrees <> length vs
   369           then no_constr thy "type variables missing in datatype" c_ty else ();
   370       in (tyco, vs) end;
   371     val (tyco, _) = last_typ (c, ty) ty_decl;
   372     val (_, vs) = last_typ (c, ty) ty;
   373   in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
   374 
   375 fun constrset_of_consts thy consts =
   376   let
   377     val _ = map (fn (c, _) => if (is_some o Axclass.class_of_param thy) c
   378       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) consts;
   379     val raw_constructors = map (analyze_constructor thy) consts;
   380     val tyco = case distinct (op =) (map (fst o fst) raw_constructors)
   381      of [tyco] => tyco
   382       | [] => error "Empty constructor set"
   383       | tycos => error ("Different type constructors in constructor set: " ^ commas_quote tycos)
   384     val vs = Name.invent Name.context Name.aT (Sign.arity_number thy tyco);
   385     fun inst vs' (c, (vs, ty)) =
   386       let
   387         val the_v = the o AList.lookup (op =) (vs ~~ vs');
   388         val ty' = map_type_tfree (fn (v, _) => TFree (the_v v, [])) ty;
   389         val (vs'', ty'') = typscheme thy (c, ty');
   390       in (c, (vs'', binder_types ty'')) end;
   391     val constructors = map (inst vs o snd) raw_constructors;
   392   in (tyco, (map (rpair []) vs, constructors)) end;
   393 
   394 fun get_type_entry thy tyco = case these (Symtab.lookup ((the_types o the_exec) thy) tyco)
   395  of (_, entry) :: _ => SOME entry
   396   | _ => NONE;
   397 
   398 fun get_type thy tyco = case get_type_entry thy tyco
   399  of SOME (vs, spec) => apfst (pair vs) (constructors_of spec)
   400   | NONE => Sign.arity_number thy tyco
   401       |> Name.invent Name.context Name.aT
   402       |> map (rpair [])
   403       |> rpair []
   404       |> rpair false;
   405 
   406 fun get_abstype_spec thy tyco = case get_type_entry thy tyco
   407  of SOME (vs, Abstractor spec) => (vs, spec)
   408   | _ => error ("Not an abstract type: " ^ tyco);
   409  
   410 fun get_type_of_constr_or_abstr thy c =
   411   case (body_type o const_typ thy) c
   412    of Type (tyco, _) => let val ((_, cos), abstract) = get_type thy tyco
   413         in if member (op =) (map fst cos) c then SOME (tyco, abstract) else NONE end
   414     | _ => NONE;
   415 
   416 fun is_constr thy c = case get_type_of_constr_or_abstr thy c
   417  of SOME (_, false) => true
   418    | _ => false;
   419 
   420 fun is_abstr thy c = case get_type_of_constr_or_abstr thy c
   421  of SOME (_, true) => true
   422    | _ => false;
   423 
   424 
   425 (* bare code equations *)
   426 
   427 (* convention for variables:
   428     ?x ?'a   for free-floating theorems (e.g. in the data store)
   429     ?x  'a   for certificates
   430      x  'a   for final representation of equations
   431 *)
   432 
   433 exception BAD_THM of string;
   434 fun bad_thm msg = raise BAD_THM msg;
   435 fun error_thm f thy (thm, proper) = f (thm, proper)
   436   handle BAD_THM msg => error (msg ^ ", in theorem:\n" ^ Display.string_of_thm_global thy thm);
   437 fun error_abs_thm f thy thm = f thm
   438   handle BAD_THM msg => error (msg ^ ", in theorem:\n" ^ Display.string_of_thm_global thy thm);
   439 fun warning_thm f thy (thm, proper) = SOME (f (thm, proper))
   440   handle BAD_THM msg => (warning (msg ^ ", in theorem:\n" ^ Display.string_of_thm_global thy thm); NONE)
   441 fun try_thm f thm_proper = SOME (f thm_proper)
   442   handle BAD_THM _ => NONE;
   443 
   444 fun is_linear thm =
   445   let val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm
   446   in not (has_duplicates (op =) ((fold o fold_aterms)
   447     (fn Var (v, _) => cons v | _ => I) args [])) end;
   448 
   449 fun check_decl_ty thy (c, ty) =
   450   let
   451     val ty_decl = Sign.the_const_type thy c;
   452   in if typscheme_equiv (ty_decl, ty) then ()
   453     else bad_thm ("Type\n" ^ string_of_typ thy ty
   454       ^ "\nof constant " ^ quote c
   455       ^ "\nis too specific compared to declared type\n"
   456       ^ string_of_typ thy ty_decl)
   457   end; 
   458 
   459 fun check_eqn thy { allow_nonlinear, allow_consts, allow_pats } thm (lhs, rhs) =
   460   let
   461     fun vars_of t = fold_aterms (fn Var (v, _) => insert (op =) v
   462       | Free _ => bad_thm "Illegal free variable"
   463       | _ => I) t [];
   464     fun tvars_of t = fold_term_types (fn _ =>
   465       fold_atyps (fn TVar (v, _) => insert (op =) v
   466         | TFree _ => bad_thm "Illegal free type variable")) t [];
   467     val lhs_vs = vars_of lhs;
   468     val rhs_vs = vars_of rhs;
   469     val lhs_tvs = tvars_of lhs;
   470     val rhs_tvs = tvars_of rhs;
   471     val _ = if null (subtract (op =) lhs_vs rhs_vs)
   472       then ()
   473       else bad_thm "Free variables on right hand side of equation";
   474     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
   475       then ()
   476       else bad_thm "Free type variables on right hand side of equation";
   477     val (head, args) = strip_comb lhs;
   478     val (c, ty) = case head
   479      of Const (c_ty as (_, ty)) => (Axclass.unoverload_const thy c_ty, ty)
   480       | _ => bad_thm "Equation not headed by constant";
   481     fun check _ (Abs _) = bad_thm "Abstraction on left hand side of equation"
   482       | check 0 (Var _) = ()
   483       | check _ (Var _) = bad_thm "Variable with application on left hand side of equation"
   484       | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
   485       | check n (Const (c_ty as (c, ty))) =
   486           if allow_pats then let
   487             val c' = Axclass.unoverload_const thy c_ty
   488           in if n = (length o binder_types) ty
   489             then if allow_consts orelse is_constr thy c'
   490               then ()
   491               else bad_thm (quote c ^ " is not a constructor, on left hand side of equation")
   492             else bad_thm ("Partially applied constant " ^ quote c ^ " on left hand side of equation")
   493           end else bad_thm ("Pattern not allowed here, but constant " ^ quote c ^ " encountered on left hand side of equation")
   494     val _ = map (check 0) args;
   495     val _ = if allow_nonlinear orelse is_linear thm then ()
   496       else bad_thm "Duplicate variables on left hand side of equation";
   497     val _ = if (is_none o Axclass.class_of_param thy) c then ()
   498       else bad_thm "Overloaded constant as head in equation";
   499     val _ = if not (is_constr thy c) then ()
   500       else bad_thm "Constructor as head in equation";
   501     val _ = if not (is_abstr thy c) then ()
   502       else bad_thm "Abstractor as head in equation";
   503     val _ = check_decl_ty thy (c, ty);
   504     val _ = case strip_type ty
   505      of (Type (tyco, _) :: _, _) => (case get_type_entry thy tyco
   506        of SOME (_, Abstractor (_, (proj, _))) => if c = proj
   507             then bad_thm "Projection as head in equation"
   508             else ()
   509         | _ => ())
   510       | _ => ();
   511   in () end;
   512 
   513 fun gen_assert_eqn thy check_patterns (thm, proper) =
   514   let
   515     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   516       handle TERM _ => bad_thm "Not an equation"
   517            | THM _ => bad_thm "Not a proper equation";
   518     val _ = check_eqn thy { allow_nonlinear = not proper,
   519       allow_consts = not (proper andalso check_patterns), allow_pats = true } thm (lhs, rhs);
   520   in (thm, proper) end;
   521 
   522 fun assert_abs_eqn thy some_tyco thm =
   523   let
   524     val (full_lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   525       handle TERM _ => bad_thm "Not an equation"
   526            | THM _ => bad_thm "Not a proper equation";
   527     val (rep, lhs) = dest_comb full_lhs
   528       handle TERM _ => bad_thm "Not an abstract equation";
   529     val (rep_const, ty) = dest_Const rep
   530       handle TERM _ => bad_thm "Not an abstract equation";
   531     val (tyco, Ts) = (dest_Type o domain_type) ty
   532       handle TERM _ => bad_thm "Not an abstract equation"
   533            | TYPE _ => bad_thm "Not an abstract equation";
   534     val _ = case some_tyco of SOME tyco' => if tyco = tyco' then ()
   535           else bad_thm ("Abstract type mismatch:" ^ quote tyco ^ " vs. " ^ quote tyco')
   536       | NONE => ();
   537     val (vs', (_, (rep', _))) = case try (get_abstype_spec thy) tyco
   538      of SOME data => data
   539       | NONE => bad_thm ("Not an abstract type: " ^ tyco);
   540     val _ = if rep_const = rep' then ()
   541       else bad_thm ("Projection mismatch: " ^ quote rep_const ^ " vs. " ^ quote rep');
   542     val _ = check_eqn thy { allow_nonlinear = false,
   543       allow_consts = false, allow_pats = false } thm (lhs, rhs);
   544     val _ = if forall2 (fn T => fn (_, sort) => Sign.of_sort thy (T, sort)) Ts vs' then ()
   545       else error ("Type arguments do not satisfy sort constraints of abstype certificate.");
   546   in (thm, tyco) end;
   547 
   548 fun assert_eqn thy = error_thm (gen_assert_eqn thy true) thy;
   549 
   550 fun meta_rewrite thy = Local_Defs.meta_rewrite_rule (Proof_Context.init_global thy);
   551 
   552 fun mk_eqn thy = error_thm (gen_assert_eqn thy false) thy o
   553   apfst (meta_rewrite thy);
   554 
   555 fun mk_eqn_liberal thy = Option.map (fn (thm, _) => (thm, is_linear thm))
   556   o try_thm (gen_assert_eqn thy false) o rpair false o meta_rewrite thy;
   557 
   558 fun mk_eqn_maybe_abs thy raw_thm =
   559   let
   560     val thm = meta_rewrite thy raw_thm;
   561     val some_abs_thm = try_thm (assert_abs_eqn thy NONE) thm;
   562   in case some_abs_thm
   563    of SOME (thm, tyco) => SOME ((thm, true), SOME tyco)
   564     | NONE => (Option.map (fn (thm, _) => ((thm, is_linear thm), NONE))
   565         o warning_thm (gen_assert_eqn thy false) thy) (thm, false)
   566   end;
   567 
   568 fun mk_abs_eqn thy = error_abs_thm (assert_abs_eqn thy NONE) thy o meta_rewrite thy;
   569 
   570 val head_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   571 
   572 fun const_typ_eqn thy thm =
   573   let
   574     val (c, ty) = head_eqn thm;
   575     val c' = Axclass.unoverload_const thy (c, ty);
   576       (*permissive wrt. to overloaded constants!*)
   577   in (c', ty) end;
   578 
   579 fun const_eqn thy = fst o const_typ_eqn thy;
   580 
   581 fun const_abs_eqn thy = Axclass.unoverload_const thy o dest_Const o fst o strip_comb o snd
   582   o dest_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   583 
   584 fun mk_proj tyco vs ty abs rep =
   585   let
   586     val ty_abs = Type (tyco, map TFree vs);
   587     val xarg = Var (("x", 0), ty);
   588   in Logic.mk_equals (Const (rep, ty_abs --> ty) $ (Const (abs, ty --> ty_abs) $ xarg), xarg) end;
   589 
   590 
   591 (* technical transformations of code equations *)
   592 
   593 fun expand_eta thy k thm =
   594   let
   595     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
   596     val (_, args) = strip_comb lhs;
   597     val l = if k = ~1
   598       then (length o fst o strip_abs) rhs
   599       else Int.max (0, k - length args);
   600     val (raw_vars, _) = Term.strip_abs_eta l rhs;
   601     val vars = burrow_fst (Name.variant_list (map (fst o fst) (Term.add_vars lhs [])))
   602       raw_vars;
   603     fun expand (v, ty) thm = Drule.fun_cong_rule thm
   604       (Thm.cterm_of thy (Var ((v, 0), ty)));
   605   in
   606     thm
   607     |> fold expand vars
   608     |> Conv.fconv_rule Drule.beta_eta_conversion
   609   end;
   610 
   611 fun same_arity thy thms =
   612   let
   613     val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
   614     val k = fold (Integer.max o num_args_of o Thm.prop_of) thms 0;
   615   in map (expand_eta thy k) thms end;
   616 
   617 fun mk_desymbolization pre post mk vs =
   618   let
   619     val names = map (pre o fst o fst) vs
   620       |> map (Name.desymbolize false)
   621       |> Name.variant_list []
   622       |> map post;
   623   in map_filter (fn (((v, i), x), v') =>
   624     if v = v' andalso i = 0 then NONE
   625     else SOME (((v, i), x), mk ((v', 0), x))) (vs ~~ names)
   626   end;
   627 
   628 fun desymbolize_tvars thms =
   629   let
   630     val tvs = fold (Term.add_tvars o Thm.prop_of) thms [];
   631     val tvar_subst = mk_desymbolization (unprefix "'") (prefix "'") TVar tvs;
   632   in map (Thm.certify_instantiate (tvar_subst, [])) thms end;
   633 
   634 fun desymbolize_vars thm =
   635   let
   636     val vs = Term.add_vars (Thm.prop_of thm) [];
   637     val var_subst = mk_desymbolization I I Var vs;
   638   in Thm.certify_instantiate ([], var_subst) thm end;
   639 
   640 fun canonize_thms thy = desymbolize_tvars #> same_arity thy #> map desymbolize_vars;
   641 
   642 
   643 (* abstype certificates *)
   644 
   645 fun check_abstype_cert thy proto_thm =
   646   let
   647     val thm = (Axclass.unoverload thy o meta_rewrite thy) proto_thm;
   648     val (lhs, rhs) = Logic.dest_equals (Thm.plain_prop_of thm)
   649       handle TERM _ => bad_thm "Not an equation"
   650            | THM _ => bad_thm "Not a proper equation";
   651     val ((abs, raw_ty), ((rep, rep_ty), param)) = (apsnd (apfst dest_Const o dest_comb)
   652         o apfst dest_Const o dest_comb) lhs
   653       handle TERM _ => bad_thm "Not an abstype certificate";
   654     val _ = pairself (fn c => if (is_some o Axclass.class_of_param thy) c
   655       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) (abs, rep);
   656     val _ = check_decl_ty thy (abs, raw_ty);
   657     val _ = check_decl_ty thy (rep, rep_ty);
   658     val _ = if length (binder_types raw_ty) = 1
   659       then ()
   660       else bad_thm "Bad type for abstract constructor";
   661     val _ = (fst o dest_Var) param
   662       handle TERM _ => bad_thm "Not an abstype certificate";
   663     val _ = if param = rhs then () else bad_thm "Not an abstype certificate";
   664     val ((tyco, sorts), (abs, (vs, ty'))) =
   665       analyze_constructor thy (abs, Logic.unvarifyT_global raw_ty);
   666     val ty = domain_type ty';
   667     val (vs', _) = typscheme thy (abs, ty');
   668   in (tyco, (vs ~~ sorts, ((abs, (vs', ty)), (rep, thm)))) end;
   669 
   670 
   671 (* code equation certificates *)
   672 
   673 fun build_head thy (c, ty) =
   674   Thm.cterm_of thy (Logic.mk_equals (Free ("HEAD", ty), Const (c, ty)));
   675 
   676 fun get_head thy cert_thm =
   677   let
   678     val [head] = (#hyps o Thm.crep_thm) cert_thm;
   679     val (_, Const (c, ty)) = (Logic.dest_equals o Thm.term_of) head;
   680   in (typscheme thy (c, ty), head) end;
   681 
   682 fun typscheme_projection thy =
   683   typscheme thy o dest_Const o fst o dest_comb o fst o Logic.dest_equals;
   684 
   685 fun typscheme_abs thy =
   686   typscheme thy o dest_Const o fst o strip_comb o snd o dest_comb o fst o Logic.dest_equals o Thm.prop_of;
   687 
   688 fun constrain_thm thy vs sorts thm =
   689   let
   690     val mapping = map2 (fn (v, sort) => fn sort' =>
   691       (v, Sorts.inter_sort (Sign.classes_of thy) (sort, sort'))) vs sorts;
   692     val inst = map2 (fn (v, sort) => fn (_, sort') =>
   693       (((v, 0), sort), TFree (v, sort'))) vs mapping;
   694     val subst = (map_types o map_type_tfree)
   695       (fn (v, _) => TFree (v, the (AList.lookup (op =) mapping v)));
   696   in
   697     thm
   698     |> Thm.varifyT_global
   699     |> Thm.certify_instantiate (inst, [])
   700     |> pair subst
   701   end;
   702 
   703 fun concretify_abs thy tyco abs_thm =
   704   let
   705     val (_, ((c, _), (_, cert))) = get_abstype_spec thy tyco;
   706     val lhs = (fst o Logic.dest_equals o Thm.prop_of) abs_thm
   707     val ty = fastype_of lhs;
   708     val ty_abs = (fastype_of o snd o dest_comb) lhs;
   709     val abs = Thm.cterm_of thy (Const (c, ty --> ty_abs));
   710     val raw_concrete_thm = Drule.transitive_thm OF [Thm.symmetric cert, Thm.combination (Thm.reflexive abs) abs_thm];
   711   in (c, (Thm.varifyT_global o zero_var_indexes) raw_concrete_thm) end;
   712 
   713 fun add_rhss_of_eqn thy t =
   714   let
   715     val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals) t;
   716     fun add_const (Const (c, ty)) = insert (op =) (c, Sign.const_typargs thy (c, ty))
   717       | add_const _ = I
   718     val add_consts = fold_aterms add_const
   719   in add_consts rhs o fold add_consts args end;
   720 
   721 val dest_eqn = apfst (snd o strip_comb) o Logic.dest_equals o Logic.unvarify_global;
   722 
   723 abstype cert = Equations of thm * bool list
   724   | Projection of term * string
   725   | Abstract of thm * string
   726 with
   727 
   728 fun empty_cert thy c = 
   729   let
   730     val raw_ty = Logic.unvarifyT_global (const_typ thy c);
   731     val (vs, _) = typscheme thy (c, raw_ty);
   732     val sortargs = case Axclass.class_of_param thy c
   733      of SOME class => [[class]]
   734       | NONE => (case get_type_of_constr_or_abstr thy c
   735          of SOME (tyco, _) => (map snd o fst o the)
   736               (AList.lookup (op =) ((snd o fst o get_type thy) tyco) c)
   737           | NONE => replicate (length vs) []);
   738     val the_sort = the o AList.lookup (op =) (map fst vs ~~ sortargs);
   739     val ty = map_type_tfree (fn (v, _) => TFree (v, the_sort v)) raw_ty
   740     val chead = build_head thy (c, ty);
   741   in Equations (Thm.weaken chead Drule.dummy_thm, []) end;
   742 
   743 fun cert_of_eqns thy c [] = empty_cert thy c
   744   | cert_of_eqns thy c raw_eqns = 
   745       let
   746         val eqns = burrow_fst (canonize_thms thy) raw_eqns;
   747         val _ = map (assert_eqn thy) eqns;
   748         val (thms, propers) = split_list eqns;
   749         val _ = map (fn thm => if c = const_eqn thy thm then ()
   750           else error ("Wrong head of code equation,\nexpected constant "
   751             ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy thm)) thms;
   752         fun tvars_of T = rev (Term.add_tvarsT T []);
   753         val vss = map (tvars_of o snd o head_eqn) thms;
   754         fun inter_sorts vs =
   755           fold (curry (Sorts.inter_sort (Sign.classes_of thy)) o snd) vs [];
   756         val sorts = map_transpose inter_sorts vss;
   757         val vts = Name.invent_names Name.context Name.aT sorts;
   758         val thms' =
   759           map2 (fn vs => Thm.certify_instantiate (vs ~~ map TFree vts, [])) vss thms;
   760         val head_thm = Thm.symmetric (Thm.assume (build_head thy (head_eqn (hd thms'))));
   761         fun head_conv ct = if can Thm.dest_comb ct
   762           then Conv.fun_conv head_conv ct
   763           else Conv.rewr_conv head_thm ct;
   764         val rewrite_head = Conv.fconv_rule (Conv.arg1_conv head_conv);
   765         val cert_thm = Conjunction.intr_balanced (map rewrite_head thms');
   766       in Equations (cert_thm, propers) end;
   767 
   768 fun cert_of_proj thy c tyco =
   769   let
   770     val (vs, ((abs, (_, ty)), (rep, _))) = get_abstype_spec thy tyco;
   771     val _ = if c = rep then () else
   772       error ("Wrong head of projection,\nexpected constant " ^ string_of_const thy rep);
   773   in Projection (mk_proj tyco vs ty abs rep, tyco) end;
   774 
   775 fun cert_of_abs thy tyco c raw_abs_thm =
   776   let
   777     val abs_thm = singleton (canonize_thms thy) raw_abs_thm;
   778     val _ = assert_abs_eqn thy (SOME tyco) abs_thm;
   779     val _ = if c = const_abs_eqn thy abs_thm then ()
   780       else error ("Wrong head of abstract code equation,\nexpected constant "
   781         ^ string_of_const thy c ^ "\n" ^ Display.string_of_thm_global thy abs_thm);
   782   in Abstract (Thm.legacy_freezeT abs_thm, tyco) end;
   783 
   784 fun constrain_cert thy sorts (Equations (cert_thm, propers)) =
   785       let
   786         val ((vs, _), head) = get_head thy cert_thm;
   787         val (subst, cert_thm') = cert_thm
   788           |> Thm.implies_intr head
   789           |> constrain_thm thy vs sorts;
   790         val head' = Thm.term_of head
   791           |> subst
   792           |> Thm.cterm_of thy;
   793         val cert_thm'' = cert_thm'
   794           |> Thm.elim_implies (Thm.assume head');
   795       in Equations (cert_thm'', propers) end
   796   | constrain_cert thy _ (cert as Projection _) =
   797       cert
   798   | constrain_cert thy sorts (Abstract (abs_thm, tyco)) =
   799       Abstract (snd (constrain_thm thy (fst (typscheme_abs thy abs_thm)) sorts abs_thm), tyco);
   800 
   801 fun conclude_cert (Equations (cert_thm, propers)) =
   802       (Equations (Thm.close_derivation cert_thm, propers))
   803   | conclude_cert (cert as Projection _) =
   804       cert
   805   | conclude_cert (Abstract (abs_thm, tyco)) =
   806       (Abstract (Thm.close_derivation abs_thm, tyco));
   807 
   808 fun typscheme_of_cert thy (Equations (cert_thm, _)) =
   809       fst (get_head thy cert_thm)
   810   | typscheme_of_cert thy (Projection (proj, _)) =
   811       typscheme_projection thy proj
   812   | typscheme_of_cert thy (Abstract (abs_thm, _)) =
   813       typscheme_abs thy abs_thm;
   814 
   815 fun typargs_deps_of_cert thy (Equations (cert_thm, propers)) =
   816       let
   817         val vs = (fst o fst) (get_head thy cert_thm);
   818         val equations = if null propers then [] else
   819           Thm.prop_of cert_thm
   820           |> Logic.dest_conjunction_balanced (length propers);
   821       in (vs, fold (add_rhss_of_eqn thy) equations []) end
   822   | typargs_deps_of_cert thy (Projection (t, _)) =
   823       (fst (typscheme_projection thy t), add_rhss_of_eqn thy t [])
   824   | typargs_deps_of_cert thy (Abstract (abs_thm, tyco)) =
   825       let
   826         val vs = fst (typscheme_abs thy abs_thm);
   827         val (_, concrete_thm) = concretify_abs thy tyco abs_thm;
   828       in (vs, add_rhss_of_eqn thy (Logic.unvarify_types_global (Thm.prop_of concrete_thm)) []) end;
   829 
   830 fun equations_of_cert thy (cert as Equations (cert_thm, propers)) =
   831       let
   832         val tyscm = typscheme_of_cert thy cert;
   833         val thms = if null propers then [] else
   834           cert_thm
   835           |> Local_Defs.expand [snd (get_head thy cert_thm)]
   836           |> Thm.varifyT_global
   837           |> Conjunction.elim_balanced (length propers);
   838         fun abstractions (args, rhs) = (map (rpair NONE) args, (rhs, NONE));
   839       in (tyscm, map (abstractions o dest_eqn o Thm.prop_of) thms ~~ (map SOME thms ~~ propers)) end
   840   | equations_of_cert thy (Projection (t, tyco)) =
   841       let
   842         val (_, ((abs, _), _)) = get_abstype_spec thy tyco;
   843         val tyscm = typscheme_projection thy t;
   844         val t' = Logic.varify_types_global t;
   845         fun abstractions (args, rhs) = (map (rpair (SOME abs)) args, (rhs, NONE));
   846       in (tyscm, [((abstractions o dest_eqn) t', (NONE, true))]) end
   847   | equations_of_cert thy (Abstract (abs_thm, tyco)) =
   848       let
   849         val tyscm = typscheme_abs thy abs_thm;
   850         val (abs, concrete_thm) = concretify_abs thy tyco abs_thm;
   851         fun abstractions (args, rhs) = (map (rpair NONE) args, (rhs, (SOME abs)));
   852       in
   853         (tyscm, [((abstractions o dest_eqn o Thm.prop_of) concrete_thm,
   854           (SOME (Thm.varifyT_global abs_thm), true))])
   855       end;
   856 
   857 fun pretty_cert thy (cert as Equations _) =
   858       (map_filter (Option.map (Display.pretty_thm_global thy o Axclass.overload thy) o fst o snd)
   859          o snd o equations_of_cert thy) cert
   860   | pretty_cert thy (Projection (t, _)) =
   861       [Syntax.pretty_term_global thy (Logic.varify_types_global t)]
   862   | pretty_cert thy (Abstract (abs_thm, _)) =
   863       [(Display.pretty_thm_global thy o Axclass.overload thy o Thm.varifyT_global) abs_thm];
   864 
   865 fun bare_thms_of_cert thy (cert as Equations _) =
   866       (map_filter (fn (_, (some_thm, proper)) => if proper then some_thm else NONE)
   867         o snd o equations_of_cert thy) cert
   868   | bare_thms_of_cert thy (Projection _) = []
   869   | bare_thms_of_cert thy (Abstract (abs_thm, tyco)) =
   870       [Thm.varifyT_global (snd (concretify_abs thy tyco abs_thm))];
   871 
   872 end;
   873 
   874 
   875 (* code certificate access *)
   876 
   877 fun retrieve_raw thy c =
   878   Symtab.lookup ((the_functions o the_exec) thy) c
   879   |> Option.map (snd o fst)
   880   |> the_default empty_fun_spec
   881 
   882 fun eqn_conv conv ct =
   883   let
   884     fun lhs_conv ct = if can Thm.dest_comb ct
   885       then Conv.combination_conv lhs_conv conv ct
   886       else Conv.all_conv ct;
   887   in Conv.combination_conv (Conv.arg_conv lhs_conv) conv ct end;
   888 
   889 fun rewrite_eqn thy conv ss =
   890   let
   891     val ctxt = Proof_Context.init_global thy;
   892     val rewrite = Conv.fconv_rule (conv (Simplifier.rewrite (put_simpset ss ctxt)));
   893   in singleton (Variable.trade (K (map rewrite)) ctxt) end;
   894 
   895 fun cert_of_eqns_preprocess thy functrans ss c =
   896   (map o apfst) (Thm.transfer thy)
   897   #> perhaps (perhaps_loop (perhaps_apply functrans))
   898   #> (map o apfst) (rewrite_eqn thy eqn_conv ss) 
   899   #> (map o apfst) (Axclass.unoverload thy)
   900   #> cert_of_eqns thy c;
   901 
   902 fun get_cert thy { functrans, ss } c =
   903   case retrieve_raw thy c
   904    of Default (_, eqns_lazy) => Lazy.force eqns_lazy
   905         |> cert_of_eqns_preprocess thy functrans ss c
   906     | Eqns eqns => eqns
   907         |> cert_of_eqns_preprocess thy functrans ss c
   908     | Proj (_, tyco) =>
   909         cert_of_proj thy c tyco
   910     | Abstr (abs_thm, tyco) => abs_thm
   911         |> Thm.transfer thy
   912         |> rewrite_eqn thy Conv.arg_conv ss
   913         |> Axclass.unoverload thy
   914         |> cert_of_abs thy tyco c;
   915 
   916 
   917 (* cases *)
   918 
   919 fun case_certificate thm =
   920   let
   921     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
   922       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.plain_prop_of) thm;
   923     val _ = case head of Free _ => true
   924       | Var _ => true
   925       | _ => raise TERM ("case_cert", []);
   926     val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
   927     val (Const (case_const, _), raw_params) = strip_comb case_expr;
   928     val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
   929     val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
   930     val params = map (fst o dest_Var) (nth_drop n raw_params);
   931     fun dest_case t =
   932       let
   933         val (head' $ t_co, rhs) = Logic.dest_equals t;
   934         val _ = if head' = head then () else raise TERM ("case_cert", []);
   935         val (Const (co, _), args) = strip_comb t_co;
   936         val (Var (param, _), args') = strip_comb rhs;
   937         val _ = if args' = args then () else raise TERM ("case_cert", []);
   938       in (param, co) end;
   939     fun analyze_cases cases =
   940       let
   941         val co_list = fold (AList.update (op =) o dest_case) cases [];
   942       in map (AList.lookup (op =) co_list) params end;
   943     fun analyze_let t =
   944       let
   945         val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
   946         val _ = if head' = head then () else raise TERM ("case_cert", []);
   947         val _ = if arg' = arg then () else raise TERM ("case_cert", []);
   948         val _ = if [param'] = params then () else raise TERM ("case_cert", []);
   949       in [] end;
   950     fun analyze (cases as [let_case]) =
   951           (analyze_cases cases handle Bind => analyze_let let_case)
   952       | analyze cases = analyze_cases cases;
   953   in (case_const, (n, analyze cases)) end;
   954 
   955 fun case_cert thm = case_certificate thm
   956   handle Bind => error "bad case certificate"
   957        | TERM _ => error "bad case certificate";
   958 
   959 fun get_case_scheme thy = Option.map fst o Symtab.lookup ((fst o the_cases o the_exec) thy);
   960 fun get_case_cong thy = Option.map snd o Symtab.lookup ((fst o the_cases o the_exec) thy);
   961 
   962 val undefineds = Symtab.keys o snd o the_cases o the_exec;
   963 
   964 
   965 (* diagnostic *)
   966 
   967 fun print_codesetup thy =
   968   let
   969     val ctxt = Proof_Context.init_global thy;
   970     val exec = the_exec thy;
   971     fun pretty_equations const thms =
   972       (Pretty.block o Pretty.fbreaks)
   973         (Pretty.str (string_of_const thy const) :: map (Display.pretty_thm_item ctxt) thms);
   974     fun pretty_function (const, Default (_, eqns_lazy)) =
   975           pretty_equations const (map fst (Lazy.force eqns_lazy))
   976       | pretty_function (const, Eqns eqns) = pretty_equations const (map fst eqns)
   977       | pretty_function (const, Proj (proj, _)) = Pretty.block
   978           [Pretty.str (string_of_const thy const), Pretty.fbrk, Syntax.pretty_term ctxt proj]
   979       | pretty_function (const, Abstr (thm, _)) = pretty_equations const [thm];
   980     fun pretty_typ (tyco, vs) = Pretty.str
   981       (string_of_typ thy (Type (tyco, map TFree vs)));
   982     fun pretty_typspec (typ, (cos, abstract)) = if null cos
   983       then pretty_typ typ
   984       else (Pretty.block o Pretty.breaks) (
   985         pretty_typ typ
   986         :: Pretty.str "="
   987         :: (if abstract then [Pretty.str "(abstract)"] else [])
   988         @ separate (Pretty.str "|") (map (fn (c, (_, [])) => Pretty.str (string_of_const thy c)
   989              | (c, (_, tys)) =>
   990                  (Pretty.block o Pretty.breaks)
   991                     (Pretty.str (string_of_const thy c)
   992                       :: Pretty.str "of"
   993                       :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
   994       );
   995     fun pretty_caseparam NONE = "<ignored>"
   996       | pretty_caseparam (SOME c) = string_of_const thy c
   997     fun pretty_case (const, ((_, (_, [])), _)) = Pretty.str (string_of_const thy const)
   998       | pretty_case (const, ((_, (_, cos)), _)) = (Pretty.block o Pretty.breaks) [
   999           Pretty.str (string_of_const thy const), Pretty.str "with",
  1000           (Pretty.block o Pretty.commas o map (Pretty.str o pretty_caseparam)) cos];
  1001     val functions = the_functions exec
  1002       |> Symtab.dest
  1003       |> (map o apsnd) (snd o fst)
  1004       |> sort (string_ord o pairself fst);
  1005     val datatypes = the_types exec
  1006       |> Symtab.dest
  1007       |> map (fn (tyco, (_, (vs, spec)) :: _) =>
  1008           ((tyco, vs), constructors_of spec))
  1009       |> sort (string_ord o pairself (fst o fst));
  1010     val cases = Symtab.dest ((fst o the_cases o the_exec) thy);
  1011     val undefineds = Symtab.keys ((snd o the_cases o the_exec) thy);
  1012   in
  1013     (Pretty.writeln o Pretty.chunks) [
  1014       Pretty.block (
  1015         Pretty.str "code equations:" :: Pretty.fbrk
  1016         :: (Pretty.fbreaks o map pretty_function) functions
  1017       ),
  1018       Pretty.block (
  1019         Pretty.str "datatypes:" :: Pretty.fbrk
  1020         :: (Pretty.fbreaks o map pretty_typspec) datatypes
  1021       ),
  1022       Pretty.block (
  1023         Pretty.str "cases:" :: Pretty.fbrk
  1024         :: (Pretty.fbreaks o map pretty_case) cases
  1025       ),
  1026       Pretty.block (
  1027         Pretty.str "undefined:" :: Pretty.fbrk
  1028         :: (Pretty.commas o map (Pretty.str o string_of_const thy)) undefineds
  1029       )
  1030     ]
  1031   end;
  1032 
  1033 
  1034 (** declaring executable ingredients **)
  1035 
  1036 (* code equations *)
  1037 
  1038 fun gen_add_eqn default (raw_thm, proper) thy =
  1039   let
  1040     val thm = Thm.close_derivation raw_thm;
  1041     val c = const_eqn thy thm;
  1042     fun update_subsume thy verbose (thm, proper) eqns = 
  1043       let
  1044         val args_of = snd o take_prefix is_Var o rev o snd o strip_comb
  1045           o map_types Type.strip_sorts o fst o Logic.dest_equals o Thm.plain_prop_of;
  1046         val args = args_of thm;
  1047         val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
  1048         fun matches_args args' =
  1049           let
  1050             val k = length args' - length args
  1051           in if k >= 0
  1052             then Pattern.matchess thy (args, (map incr_idx o drop k) args')
  1053             else false
  1054           end;
  1055         fun drop (thm', proper') = if (proper orelse not proper')
  1056           andalso matches_args (args_of thm') then 
  1057             (if verbose then warning ("Code generator: dropping subsumed code equation\n" ^
  1058                 Display.string_of_thm_global thy thm') else (); true)
  1059           else false;
  1060       in (thm, proper) :: filter_out drop eqns end;
  1061     fun natural_order thy_ref eqns =
  1062       (eqns, Lazy.lazy (fn () => fold (update_subsume (Theory.deref thy_ref) false) eqns []))
  1063     fun add_eqn' true (Default (eqns, _)) =
  1064           Default (natural_order (Theory.check_thy thy) ((thm, proper) :: eqns))
  1065           (*this restores the natural order and drops syntactic redundancies*)
  1066       | add_eqn' true fun_spec = fun_spec
  1067       | add_eqn' false (Eqns eqns) = Eqns (update_subsume thy true (thm, proper) eqns)
  1068       | add_eqn' false _ = Eqns [(thm, proper)];
  1069   in change_fun_spec false c (add_eqn' default) thy end;
  1070 
  1071 fun gen_add_abs_eqn raw_thm thy =
  1072   let
  1073     val (abs_thm, tyco) = apfst Thm.close_derivation raw_thm;
  1074     val c = const_abs_eqn thy abs_thm;
  1075   in change_fun_spec false c (K (Abstr (abs_thm, tyco))) thy end;
  1076 
  1077 fun add_eqn thm thy =
  1078   gen_add_eqn false (mk_eqn thy (thm, true)) thy;
  1079 
  1080 fun add_nbe_eqn thm thy =
  1081   gen_add_eqn false (mk_eqn thy (thm, false)) thy;
  1082 
  1083 fun add_default_eqn thm thy =
  1084   case mk_eqn_liberal thy thm
  1085    of SOME eqn => gen_add_eqn true eqn thy
  1086     | NONE => thy;
  1087 
  1088 val add_default_eqn_attribute = Thm.declaration_attribute
  1089   (fn thm => Context.mapping (add_default_eqn thm) I);
  1090 val add_default_eqn_attrib = Attrib.internal (K add_default_eqn_attribute);
  1091 
  1092 fun add_nbe_default_eqn thm thy =
  1093   gen_add_eqn true (mk_eqn thy (thm, false)) thy;
  1094 
  1095 val add_nbe_default_eqn_attribute = Thm.declaration_attribute
  1096   (fn thm => Context.mapping (add_nbe_default_eqn thm) I);
  1097 val add_nbe_default_eqn_attrib = Attrib.internal (K add_nbe_default_eqn_attribute);
  1098 
  1099 fun add_abs_eqn raw_thm thy = gen_add_abs_eqn (mk_abs_eqn thy raw_thm) thy;
  1100 
  1101 fun add_eqn_maybe_abs thm thy =
  1102   case mk_eqn_maybe_abs thy thm
  1103    of SOME (eqn, NONE) => gen_add_eqn false eqn thy
  1104     | SOME ((thm, _), SOME tyco) => gen_add_abs_eqn (thm, tyco) thy
  1105     | NONE => thy;
  1106 
  1107 fun del_eqn thm thy = case mk_eqn_liberal thy thm
  1108  of SOME (thm, _) => let
  1109         fun del_eqn' (Default _) = empty_fun_spec
  1110           | del_eqn' (Eqns eqns) =
  1111               Eqns (filter_out (fn (thm', _) => Thm.eq_thm_prop (thm, thm')) eqns)
  1112           | del_eqn' spec = spec
  1113       in change_fun_spec true (const_eqn thy thm) del_eqn' thy end
  1114   | NONE => thy;
  1115 
  1116 fun del_eqns c = change_fun_spec true c (K empty_fun_spec);
  1117 
  1118 
  1119 (* cases *)
  1120 
  1121 fun case_cong thy case_const (num_args, (pos, _)) =
  1122   let
  1123     val ([x, y], ctxt) = fold_map Name.variant ["A", "A'"] Name.context;
  1124     val (zs, _) = fold_map Name.variant (replicate (num_args - 1) "") ctxt;
  1125     val (ws, vs) = chop pos zs;
  1126     val T = Logic.unvarifyT_global (Sign.the_const_type thy case_const);
  1127     val Ts = binder_types T;
  1128     val T_cong = nth Ts pos;
  1129     fun mk_prem z = Free (z, T_cong);
  1130     fun mk_concl z = list_comb (Const (case_const, T), map2 (curry Free) (ws @ z :: vs) Ts);
  1131     val (prem, concl) = pairself Logic.mk_equals (pairself mk_prem (x, y), pairself mk_concl (x, y));
  1132     fun tac { context, prems } = Simplifier.rewrite_goals_tac prems
  1133       THEN ALLGOALS (Proof_Context.fact_tac [Drule.reflexive_thm]);
  1134   in Goal.prove_sorry_global thy (x :: y :: zs) [prem] concl tac end;
  1135 
  1136 fun add_case thm thy =
  1137   let
  1138     val (case_const, (k, cos)) = case_cert thm;
  1139     val _ = case (filter_out (is_constr thy) o map_filter I) cos
  1140      of [] => ()
  1141       | cs => error ("Non-constructor(s) in case certificate: " ^ commas_quote cs);
  1142     val entry = (1 + Int.max (1, length cos), (k, cos));
  1143     fun register_case cong = (map_cases o apfst)
  1144       (Symtab.update (case_const, (entry, cong)));
  1145     fun register_for_constructors (Constructors (cos', cases)) =
  1146          Constructors (cos',
  1147            if exists (fn (co, _) => member (op =) cos (SOME co)) cos'
  1148            then insert (op =) case_const cases
  1149            else cases)
  1150       | register_for_constructors (x as Abstractor _) = x;
  1151     val register_type = (map_typs o Symtab.map)
  1152       (K ((map o apsnd o apsnd) register_for_constructors));
  1153   in
  1154     thy
  1155     |> Theory.checkpoint
  1156     |> `(fn thy => case_cong thy case_const entry)
  1157     |-> (fn cong => map_exec_purge (register_case cong #> register_type))
  1158   end;
  1159 
  1160 fun add_undefined c thy =
  1161   (map_exec_purge o map_cases o apsnd) (Symtab.update (c, ())) thy;
  1162 
  1163 
  1164 (* types *)
  1165 
  1166 fun register_type (tyco, vs_spec) thy =
  1167   let
  1168     val (old_constrs, some_old_proj) =
  1169       case these (Symtab.lookup ((the_types o the_exec) thy) tyco)
  1170        of (_, (_, Constructors (cos, _))) :: _ => (map fst cos, NONE)
  1171         | (_, (_, Abstractor ((co, _), (proj, _)))) :: _ => ([co], SOME proj)
  1172         | [] => ([], NONE);
  1173     val outdated_funs1 = (map fst o fst o constructors_of o snd) vs_spec;
  1174     val outdated_funs2 = case some_old_proj
  1175      of NONE => []
  1176       | SOME old_proj => Symtab.fold
  1177           (fn (c, ((_, spec), _)) =>
  1178             if member (op =) (the_list (associated_abstype spec)) tyco
  1179             then insert (op =) c else I)
  1180             ((the_functions o the_exec) thy) [old_proj];
  1181     fun drop_outdated_cases cases = fold Symtab.delete_safe
  1182       (Symtab.fold (fn (c, ((_, (_, cos)), _)) =>
  1183         if exists (member (op =) old_constrs) (map_filter I cos)
  1184           then insert (op =) c else I) cases []) cases;
  1185   in
  1186     thy
  1187     |> fold del_eqns (outdated_funs1 @ outdated_funs2)
  1188     |> map_exec_purge
  1189         ((map_typs o Symtab.map_default (tyco, [])) (cons (serial (), vs_spec))
  1190         #> (map_cases o apfst) drop_outdated_cases)
  1191   end;
  1192 
  1193 fun unoverload_const_typ thy (c, ty) = (Axclass.unoverload_const thy (c, ty), ty);
  1194 
  1195 structure Datatype_Interpretation =
  1196   Interpretation(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
  1197 
  1198 fun datatype_interpretation f = Datatype_Interpretation.interpretation
  1199   (fn (tyco, _) => fn thy => f (tyco, fst (get_type thy tyco)) thy);
  1200 
  1201 fun add_datatype proto_constrs thy =
  1202   let
  1203     val constrs = map (unoverload_const_typ thy) proto_constrs;
  1204     val (tyco, (vs, cos)) = constrset_of_consts thy constrs;
  1205   in
  1206     thy
  1207     |> register_type (tyco, (vs, Constructors (cos, [])))
  1208     |> Datatype_Interpretation.data (tyco, serial ())
  1209   end;
  1210 
  1211 fun add_datatype_cmd raw_constrs thy =
  1212   add_datatype (map (read_bare_const thy) raw_constrs) thy;
  1213 
  1214 structure Abstype_Interpretation =
  1215   Interpretation(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
  1216 
  1217 fun abstype_interpretation f = Abstype_Interpretation.interpretation
  1218   (fn (tyco, _) => fn thy => f (tyco, get_abstype_spec thy tyco) thy);
  1219 
  1220 fun add_abstype proto_thm thy =
  1221   let
  1222     val (tyco, (vs, (abs_ty as (abs, (_, ty)), (rep, cert)))) =
  1223       error_abs_thm (check_abstype_cert thy) thy proto_thm;
  1224   in
  1225     thy
  1226     |> register_type (tyco, (vs, Abstractor (abs_ty, (rep, cert))))
  1227     |> change_fun_spec false rep
  1228       (K (Proj (Logic.varify_types_global (mk_proj tyco vs ty abs rep), tyco)))
  1229     |> Abstype_Interpretation.data (tyco, serial ())
  1230   end;
  1231 
  1232 
  1233 (* setup *)
  1234 
  1235 val _ = Context.>> (Context.map_theory
  1236   (let
  1237     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
  1238     val code_attribute_parser =
  1239       Args.del |-- Scan.succeed (mk_attribute del_eqn)
  1240       || Args.$$$ "equation" |-- Scan.succeed (mk_attribute add_eqn)
  1241       || Args.$$$ "nbe" |-- Scan.succeed (mk_attribute add_nbe_eqn)
  1242       || Args.$$$ "abstype" |-- Scan.succeed (mk_attribute add_abstype)
  1243       || Args.$$$ "abstract" |-- Scan.succeed (mk_attribute add_abs_eqn)
  1244       || Scan.succeed (mk_attribute add_eqn_maybe_abs);
  1245   in
  1246     Datatype_Interpretation.init
  1247     #> Attrib.setup (Binding.name "code") (Scan.lift code_attribute_parser)
  1248         "declare theorems for code generation"
  1249   end));
  1250 
  1251 end; (*struct*)
  1252 
  1253 
  1254 (* type-safe interfaces for data dependent on executable code *)
  1255 
  1256 functor Code_Data(Data: CODE_DATA_ARGS): CODE_DATA =
  1257 struct
  1258 
  1259 type T = Data.T;
  1260 exception Data of T;
  1261 fun dest (Data x) = x
  1262 
  1263 val kind = Code.declare_data (Data Data.empty);
  1264 
  1265 val data_op = (kind, Data, dest);
  1266 
  1267 fun change_yield (SOME thy) f = Code.change_yield_data data_op thy f
  1268   | change_yield NONE f = f Data.empty
  1269 
  1270 fun change some_thy f = snd (change_yield some_thy (pair () o f));
  1271 
  1272 end;
  1273 
  1274 structure Code : CODE = struct open Code; end;