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