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