src/Pure/drule.ML
author blanchet
Mon May 19 23:43:53 2014 +0200 (2014-05-19)
changeset 57008 10f68b83b474
parent 56436 30ccec1e82fb
child 58950 d07464875dd4
permissions -rw-r--r--
use E 1.8's auto scheduler option
     1 (*  Title:      Pure/drule.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3 
     4 Derived rules and other operations on theorems.
     5 *)
     6 
     7 infix 0 RS RSN RL RLN MRS OF COMP INCR_COMP COMP_INCR;
     8 
     9 signature BASIC_DRULE =
    10 sig
    11   val mk_implies: cterm * cterm -> cterm
    12   val list_implies: cterm list * cterm -> cterm
    13   val strip_imp_prems: cterm -> cterm list
    14   val strip_imp_concl: cterm -> cterm
    15   val cprems_of: thm -> cterm list
    16   val cterm_fun: (term -> term) -> (cterm -> cterm)
    17   val ctyp_fun: (typ -> typ) -> (ctyp -> ctyp)
    18   val forall_intr_list: cterm list -> thm -> thm
    19   val forall_intr_vars: thm -> thm
    20   val forall_elim_list: cterm list -> thm -> thm
    21   val gen_all: thm -> thm
    22   val lift_all: cterm -> thm -> thm
    23   val implies_elim_list: thm -> thm list -> thm
    24   val implies_intr_list: cterm list -> thm -> thm
    25   val instantiate_normalize: (ctyp * ctyp) list * (cterm * cterm) list -> thm -> thm
    26   val zero_var_indexes_list: thm list -> thm list
    27   val zero_var_indexes: thm -> thm
    28   val implies_intr_hyps: thm -> thm
    29   val rotate_prems: int -> thm -> thm
    30   val rearrange_prems: int list -> thm -> thm
    31   val RSN: thm * (int * thm) -> thm
    32   val RS: thm * thm -> thm
    33   val RLN: thm list * (int * thm list) -> thm list
    34   val RL: thm list * thm list -> thm list
    35   val MRS: thm list * thm -> thm
    36   val OF: thm * thm list -> thm
    37   val COMP: thm * thm -> thm
    38   val INCR_COMP: thm * thm -> thm
    39   val COMP_INCR: thm * thm -> thm
    40   val cterm_instantiate: (cterm * cterm) list -> thm -> thm
    41   val size_of_thm: thm -> int
    42   val reflexive_thm: thm
    43   val symmetric_thm: thm
    44   val transitive_thm: thm
    45   val extensional: thm -> thm
    46   val asm_rl: thm
    47   val cut_rl: thm
    48   val revcut_rl: thm
    49   val thin_rl: thm
    50   val instantiate': ctyp option list -> cterm option list -> thm -> thm
    51 end;
    52 
    53 signature DRULE =
    54 sig
    55   include BASIC_DRULE
    56   val generalize: string list * string list -> thm -> thm
    57   val list_comb: cterm * cterm list -> cterm
    58   val strip_comb: cterm -> cterm * cterm list
    59   val strip_type: ctyp -> ctyp list * ctyp
    60   val beta_conv: cterm -> cterm -> cterm
    61   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    62   val flexflex_unique: thm -> thm
    63   val export_without_context: thm -> thm
    64   val export_without_context_open: thm -> thm
    65   val store_thm: binding -> thm -> thm
    66   val store_standard_thm: binding -> thm -> thm
    67   val store_thm_open: binding -> thm -> thm
    68   val store_standard_thm_open: binding -> thm -> thm
    69   val multi_resolve: thm list -> thm -> thm Seq.seq
    70   val multi_resolves: thm list -> thm list -> thm Seq.seq
    71   val compose: thm * int * thm -> thm
    72   val equals_cong: thm
    73   val imp_cong: thm
    74   val swap_prems_eq: thm
    75   val imp_cong_rule: thm -> thm -> thm
    76   val arg_cong_rule: cterm -> thm -> thm
    77   val binop_cong_rule: cterm -> thm -> thm -> thm
    78   val fun_cong_rule: thm -> cterm -> thm
    79   val beta_eta_conversion: cterm -> thm
    80   val eta_long_conversion: cterm -> thm
    81   val eta_contraction_rule: thm -> thm
    82   val norm_hhf_eq: thm
    83   val norm_hhf_eqs: thm list
    84   val is_norm_hhf: term -> bool
    85   val norm_hhf: theory -> term -> term
    86   val norm_hhf_cterm: cterm -> cterm
    87   val protect: cterm -> cterm
    88   val protectI: thm
    89   val protectD: thm
    90   val protect_cong: thm
    91   val implies_intr_protected: cterm list -> thm -> thm
    92   val termI: thm
    93   val mk_term: cterm -> thm
    94   val dest_term: thm -> cterm
    95   val cterm_rule: (thm -> thm) -> cterm -> cterm
    96   val dummy_thm: thm
    97   val sort_constraintI: thm
    98   val sort_constraint_eq: thm
    99   val with_subgoal: int -> (thm -> thm) -> thm -> thm
   100   val comp_no_flatten: thm * int -> int -> thm -> thm
   101   val rename_bvars: (string * string) list -> thm -> thm
   102   val rename_bvars': string option list -> thm -> thm
   103   val incr_indexes: thm -> thm -> thm
   104   val incr_indexes2: thm -> thm -> thm -> thm
   105   val triv_forall_equality: thm
   106   val distinct_prems_rl: thm
   107   val equal_intr_rule: thm
   108   val equal_elim_rule1: thm
   109   val equal_elim_rule2: thm
   110   val remdups_rl: thm
   111   val abs_def: thm -> thm
   112 end;
   113 
   114 structure Drule: DRULE =
   115 struct
   116 
   117 
   118 (** some cterm->cterm operations: faster than calling cterm_of! **)
   119 
   120 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   121 fun strip_imp_prems ct =
   122   let val (cA, cB) = Thm.dest_implies ct
   123   in cA :: strip_imp_prems cB end
   124   handle TERM _ => [];
   125 
   126 (* A1==>...An==>B  goes to B, where B is not an implication *)
   127 fun strip_imp_concl ct =
   128   (case Thm.term_of ct of
   129     Const ("Pure.imp", _) $ _ $ _ => strip_imp_concl (Thm.dest_arg ct)
   130   | _ => ct);
   131 
   132 (*The premises of a theorem, as a cterm list*)
   133 val cprems_of = strip_imp_prems o cprop_of;
   134 
   135 fun cterm_fun f ct = Thm.cterm_of (Thm.theory_of_cterm ct) (f (Thm.term_of ct));
   136 fun ctyp_fun f cT = Thm.ctyp_of (Thm.theory_of_ctyp cT) (f (Thm.typ_of cT));
   137 
   138 fun certify t = Thm.cterm_of (Context.the_theory (Context.the_thread_data ())) t;
   139 
   140 val implies = certify Logic.implies;
   141 fun mk_implies (A, B) = Thm.apply (Thm.apply implies A) B;
   142 
   143 (*cterm version of list_implies: [A1,...,An], B  goes to [|A1;==>;An|]==>B *)
   144 fun list_implies([], B) = B
   145   | list_implies(A::AS, B) = mk_implies (A, list_implies(AS,B));
   146 
   147 (*cterm version of list_comb: maps  (f, [t1,...,tn])  to  f(t1,...,tn) *)
   148 fun list_comb (f, []) = f
   149   | list_comb (f, t::ts) = list_comb (Thm.apply f t, ts);
   150 
   151 (*cterm version of strip_comb: maps  f(t1,...,tn)  to  (f, [t1,...,tn]) *)
   152 fun strip_comb ct =
   153   let
   154     fun stripc (p as (ct, cts)) =
   155       let val (ct1, ct2) = Thm.dest_comb ct
   156       in stripc (ct1, ct2 :: cts) end handle CTERM _ => p
   157   in stripc (ct, []) end;
   158 
   159 (* cterm version of strip_type: maps  [T1,...,Tn]--->T  to   ([T1,T2,...,Tn], T) *)
   160 fun strip_type cT = (case Thm.typ_of cT of
   161     Type ("fun", _) =>
   162       let
   163         val [cT1, cT2] = Thm.dest_ctyp cT;
   164         val (cTs, cT') = strip_type cT2
   165       in (cT1 :: cTs, cT') end
   166   | _ => ([], cT));
   167 
   168 (*Beta-conversion for cterms, where x is an abstraction. Simply returns the rhs
   169   of the meta-equality returned by the beta_conversion rule.*)
   170 fun beta_conv x y =
   171   Thm.dest_arg (cprop_of (Thm.beta_conversion false (Thm.apply x y)));
   172 
   173 
   174 
   175 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   176      Used for establishing default types (of variables) and sorts (of
   177      type variables) when reading another term.
   178      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   179 ***)
   180 
   181 fun types_sorts thm =
   182   let
   183     val vars = Thm.fold_terms Term.add_vars thm [];
   184     val frees = Thm.fold_terms Term.add_frees thm [];
   185     val tvars = Thm.fold_terms Term.add_tvars thm [];
   186     val tfrees = Thm.fold_terms Term.add_tfrees thm [];
   187     fun types (a, i) =
   188       if i < 0 then AList.lookup (op =) frees a else AList.lookup (op =) vars (a, i);
   189     fun sorts (a, i) =
   190       if i < 0 then AList.lookup (op =) tfrees a else AList.lookup (op =) tvars (a, i);
   191   in (types, sorts) end;
   192 
   193 
   194 
   195 
   196 (** Standardization of rules **)
   197 
   198 (*Generalization over a list of variables*)
   199 val forall_intr_list = fold_rev Thm.forall_intr;
   200 
   201 (*Generalization over Vars -- canonical order*)
   202 fun forall_intr_vars th =
   203   fold Thm.forall_intr
   204     (map (Thm.cterm_of (Thm.theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th [])) th;
   205 
   206 fun outer_params t =
   207   let val vs = Term.strip_all_vars t
   208   in Name.variant_list [] (map (Name.clean o #1) vs) ~~ map #2 vs end;
   209 
   210 (*generalize outermost parameters*)
   211 fun gen_all th =
   212   let
   213     val thy = Thm.theory_of_thm th;
   214     val {prop, maxidx, ...} = Thm.rep_thm th;
   215     val cert = Thm.cterm_of thy;
   216     fun elim (x, T) = Thm.forall_elim (cert (Var ((x, maxidx + 1), T)));
   217   in fold elim (outer_params prop) th end;
   218 
   219 (*lift vars wrt. outermost goal parameters
   220   -- reverses the effect of gen_all modulo higher-order unification*)
   221 fun lift_all goal th =
   222   let
   223     val thy = Theory.merge (Thm.theory_of_cterm goal, Thm.theory_of_thm th);
   224     val cert = Thm.cterm_of thy;
   225     val maxidx = Thm.maxidx_of th;
   226     val ps = outer_params (Thm.term_of goal)
   227       |> map (fn (x, T) => Var ((x, maxidx + 1), Logic.incr_tvar (maxidx + 1) T));
   228     val Ts = map Term.fastype_of ps;
   229     val inst = Thm.fold_terms Term.add_vars th [] |> map (fn (xi, T) =>
   230       (cert (Var (xi, T)), cert (Term.list_comb (Var (xi, Ts ---> T), ps))));
   231   in
   232     th |> Thm.instantiate ([], inst)
   233     |> fold_rev (Thm.forall_intr o cert) ps
   234   end;
   235 
   236 (*direct generalization*)
   237 fun generalize names th = Thm.generalize names (Thm.maxidx_of th + 1) th;
   238 
   239 (*specialization over a list of cterms*)
   240 val forall_elim_list = fold Thm.forall_elim;
   241 
   242 (*maps A1,...,An |- B  to  [| A1;...;An |] ==> B*)
   243 val implies_intr_list = fold_rev Thm.implies_intr;
   244 
   245 (*maps [| A1;...;An |] ==> B and [A1,...,An]  to  B*)
   246 fun implies_elim_list impth ths = fold Thm.elim_implies ths impth;
   247 
   248 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   249 fun zero_var_indexes_list [] = []
   250   | zero_var_indexes_list ths =
   251       let
   252         val thy = Theory.merge_list (map Thm.theory_of_thm ths);
   253         val certT = Thm.ctyp_of thy and cert = Thm.cterm_of thy;
   254         val (instT, inst) = Term_Subst.zero_var_indexes_inst (map Thm.full_prop_of ths);
   255         val cinstT = map (fn (v, T) => (certT (TVar v), certT T)) instT;
   256         val cinst = map (fn (v, t) => (cert (Var v), cert t)) inst;
   257       in map (Thm.adjust_maxidx_thm ~1 o Thm.instantiate (cinstT, cinst)) ths end;
   258 
   259 val zero_var_indexes = singleton zero_var_indexes_list;
   260 
   261 
   262 (** Standard form of object-rule: no hypotheses, flexflex constraints,
   263     Frees, or outer quantifiers; all generality expressed by Vars of index 0.**)
   264 
   265 (*Discharge all hypotheses.*)
   266 fun implies_intr_hyps th =
   267   fold Thm.implies_intr (#hyps (Thm.crep_thm th)) th;
   268 
   269 (*Squash a theorem's flexflex constraints provided it can be done uniquely.
   270   This step can lose information.*)
   271 fun flexflex_unique th =
   272   if null (Thm.tpairs_of th) then th else
   273     case distinct Thm.eq_thm (Seq.list_of (Thm.flexflex_rule th)) of
   274       [th] => th
   275     | []   => raise THM("flexflex_unique: impossible constraints", 0, [th])
   276     |  _   => raise THM("flexflex_unique: multiple unifiers", 0, [th]);
   277 
   278 
   279 (* old-style export without context *)
   280 
   281 val export_without_context_open =
   282   implies_intr_hyps
   283   #> Thm.forall_intr_frees
   284   #> `Thm.maxidx_of
   285   #-> (fn maxidx =>
   286     Thm.forall_elim_vars (maxidx + 1)
   287     #> Thm.strip_shyps
   288     #> zero_var_indexes
   289     #> Thm.varifyT_global);
   290 
   291 val export_without_context =
   292   flexflex_unique
   293   #> export_without_context_open
   294   #> Thm.close_derivation;
   295 
   296 
   297 (*Rotates a rule's premises to the left by k*)
   298 fun rotate_prems 0 = I
   299   | rotate_prems k = Thm.permute_prems 0 k;
   300 
   301 fun with_subgoal i f = rotate_prems (i - 1) #> f #> rotate_prems (1 - i);
   302 
   303 (*Permute prems, where the i-th position in the argument list (counting from 0)
   304   gives the position within the original thm to be transferred to position i.
   305   Any remaining trailing positions are left unchanged.*)
   306 val rearrange_prems =
   307   let
   308     fun rearr new [] thm = thm
   309       | rearr new (p :: ps) thm =
   310           rearr (new + 1)
   311             (map (fn q => if new <= q andalso q < p then q + 1 else q) ps)
   312             (Thm.permute_prems (new + 1) (new - p) (Thm.permute_prems new (p - new) thm))
   313   in rearr 0 end;
   314 
   315 
   316 (*Resolution: multiple arguments, multiple results*)
   317 local
   318   fun res th i rule =
   319     Thm.biresolution false [(false, th)] i rule handle THM _ => Seq.empty;
   320 
   321   fun multi_res _ [] rule = Seq.single rule
   322     | multi_res i (th :: ths) rule = Seq.maps (res th i) (multi_res (i + 1) ths rule);
   323 in
   324   val multi_resolve = multi_res 1;
   325   fun multi_resolves facts rules = Seq.maps (multi_resolve facts) (Seq.of_list rules);
   326 end;
   327 
   328 (*Resolution: exactly one resolvent must be produced*)
   329 fun tha RSN (i, thb) =
   330   (case Seq.chop 2 (Thm.biresolution false [(false, tha)] i thb) of
   331     ([th], _) => th
   332   | ([], _) => raise THM ("RSN: no unifiers", i, [tha, thb])
   333   | _ => raise THM ("RSN: multiple unifiers", i, [tha, thb]));
   334 
   335 (*Resolution: P==>Q, Q==>R gives P==>R*)
   336 fun tha RS thb = tha RSN (1,thb);
   337 
   338 (*For joining lists of rules*)
   339 fun thas RLN (i, thbs) =
   340   let val resolve = Thm.biresolution false (map (pair false) thas) i
   341       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   342   in maps resb thbs end;
   343 
   344 fun thas RL thbs = thas RLN (1, thbs);
   345 
   346 (*Isar-style multi-resolution*)
   347 fun bottom_rl OF rls =
   348   (case Seq.chop 2 (multi_resolve rls bottom_rl) of
   349     ([th], _) => th
   350   | ([], _) => raise THM ("OF: no unifiers", 0, bottom_rl :: rls)
   351   | _ => raise THM ("OF: multiple unifiers", 0, bottom_rl :: rls));
   352 
   353 (*Resolve a list of rules against bottom_rl from right to left;
   354   makes proof trees*)
   355 fun rls MRS bottom_rl = bottom_rl OF rls;
   356 
   357 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   358   with no lifting or renaming!  Q may contain ==> or meta-quants
   359   ALWAYS deletes premise i *)
   360 fun compose (tha, i, thb) =
   361   Thm.bicompose {flatten = true, match = false, incremented = false} (false, tha, 0) i thb
   362   |> Seq.list_of |> distinct Thm.eq_thm
   363   |> (fn [th] => th | _ => raise THM ("compose: unique result expected", i, [tha, thb]));
   364 
   365 
   366 (** theorem equality **)
   367 
   368 (*Useful "distance" function for BEST_FIRST*)
   369 val size_of_thm = size_of_term o Thm.full_prop_of;
   370 
   371 
   372 
   373 (*** Meta-Rewriting Rules ***)
   374 
   375 val read_prop = certify o Simple_Syntax.read_prop;
   376 
   377 fun store_thm name th =
   378   Context.>>> (Context.map_theory_result (Global_Theory.store_thm (name, th)));
   379 
   380 fun store_thm_open name th =
   381   Context.>>> (Context.map_theory_result (Global_Theory.store_thm_open (name, th)));
   382 
   383 fun store_standard_thm name th = store_thm name (export_without_context th);
   384 fun store_standard_thm_open name thm = store_thm_open name (export_without_context_open thm);
   385 
   386 val reflexive_thm =
   387   let val cx = certify (Var(("x",0),TVar(("'a",0),[])))
   388   in store_standard_thm_open (Binding.make ("reflexive", @{here})) (Thm.reflexive cx) end;
   389 
   390 val symmetric_thm =
   391   let
   392     val xy = read_prop "x::'a == y::'a";
   393     val thm = Thm.implies_intr xy (Thm.symmetric (Thm.assume xy));
   394   in store_standard_thm_open (Binding.make ("symmetric", @{here})) thm end;
   395 
   396 val transitive_thm =
   397   let
   398     val xy = read_prop "x::'a == y::'a";
   399     val yz = read_prop "y::'a == z::'a";
   400     val xythm = Thm.assume xy;
   401     val yzthm = Thm.assume yz;
   402     val thm = Thm.implies_intr yz (Thm.transitive xythm yzthm);
   403   in store_standard_thm_open (Binding.make ("transitive", @{here})) thm end;
   404 
   405 fun extensional eq =
   406   let val eq' =
   407     Thm.abstract_rule "x" (Thm.dest_arg (fst (Thm.dest_equals (cprop_of eq)))) eq
   408   in Thm.equal_elim (Thm.eta_conversion (cprop_of eq')) eq' end;
   409 
   410 val equals_cong =
   411   store_standard_thm_open (Binding.make ("equals_cong", @{here}))
   412     (Thm.reflexive (read_prop "x::'a == y::'a"));
   413 
   414 val imp_cong =
   415   let
   416     val ABC = read_prop "A ==> B::prop == C::prop"
   417     val AB = read_prop "A ==> B"
   418     val AC = read_prop "A ==> C"
   419     val A = read_prop "A"
   420   in
   421     store_standard_thm_open (Binding.make ("imp_cong", @{here}))
   422       (Thm.implies_intr ABC (Thm.equal_intr
   423         (Thm.implies_intr AB (Thm.implies_intr A
   424           (Thm.equal_elim (Thm.implies_elim (Thm.assume ABC) (Thm.assume A))
   425             (Thm.implies_elim (Thm.assume AB) (Thm.assume A)))))
   426         (Thm.implies_intr AC (Thm.implies_intr A
   427           (Thm.equal_elim (Thm.symmetric (Thm.implies_elim (Thm.assume ABC) (Thm.assume A)))
   428             (Thm.implies_elim (Thm.assume AC) (Thm.assume A)))))))
   429   end;
   430 
   431 val swap_prems_eq =
   432   let
   433     val ABC = read_prop "A ==> B ==> C"
   434     val BAC = read_prop "B ==> A ==> C"
   435     val A = read_prop "A"
   436     val B = read_prop "B"
   437   in
   438     store_standard_thm_open (Binding.make ("swap_prems_eq", @{here}))
   439       (Thm.equal_intr
   440         (Thm.implies_intr ABC (Thm.implies_intr B (Thm.implies_intr A
   441           (Thm.implies_elim (Thm.implies_elim (Thm.assume ABC) (Thm.assume A)) (Thm.assume B)))))
   442         (Thm.implies_intr BAC (Thm.implies_intr A (Thm.implies_intr B
   443           (Thm.implies_elim (Thm.implies_elim (Thm.assume BAC) (Thm.assume B)) (Thm.assume A))))))
   444   end;
   445 
   446 val imp_cong_rule = Thm.combination o Thm.combination (Thm.reflexive implies);
   447 
   448 fun arg_cong_rule ct th = Thm.combination (Thm.reflexive ct) th;    (*AP_TERM in LCF/HOL*)
   449 fun fun_cong_rule th ct = Thm.combination th (Thm.reflexive ct);    (*AP_THM in LCF/HOL*)
   450 fun binop_cong_rule ct th1 th2 = Thm.combination (arg_cong_rule ct th1) th2;
   451 
   452 local
   453   val dest_eq = Thm.dest_equals o cprop_of
   454   val rhs_of = snd o dest_eq
   455 in
   456 fun beta_eta_conversion t =
   457   let val thm = Thm.beta_conversion true t
   458   in Thm.transitive thm (Thm.eta_conversion (rhs_of thm)) end
   459 end;
   460 
   461 fun eta_long_conversion ct =
   462   Thm.transitive
   463     (beta_eta_conversion ct)
   464     (Thm.symmetric (beta_eta_conversion (cterm_fun (Envir.eta_long []) ct)));
   465 
   466 (*Contract all eta-redexes in the theorem, lest they give rise to needless abstractions*)
   467 fun eta_contraction_rule th =
   468   Thm.equal_elim (Thm.eta_conversion (cprop_of th)) th;
   469 
   470 
   471 (* abs_def *)
   472 
   473 (*
   474    f ?x1 ... ?xn == u
   475   --------------------
   476    f == %x1 ... xn. u
   477 *)
   478 
   479 local
   480 
   481 fun contract_lhs th =
   482   Thm.transitive (Thm.symmetric (beta_eta_conversion
   483     (fst (Thm.dest_equals (cprop_of th))))) th;
   484 
   485 fun var_args ct =
   486   (case try Thm.dest_comb ct of
   487     SOME (f, arg) =>
   488       (case Thm.term_of arg of
   489         Var ((x, _), _) => update (eq_snd (op aconvc)) (x, arg) (var_args f)
   490       | _ => [])
   491   | NONE => []);
   492 
   493 in
   494 
   495 fun abs_def th =
   496   let
   497     val th' = contract_lhs th;
   498     val args = var_args (Thm.lhs_of th');
   499   in contract_lhs (fold (uncurry Thm.abstract_rule) args th') end;
   500 
   501 end;
   502 
   503 
   504 
   505 (*** Some useful meta-theorems ***)
   506 
   507 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   508 val asm_rl =
   509   store_standard_thm_open (Binding.make ("asm_rl", @{here}))
   510     (Thm.trivial (read_prop "?psi"));
   511 
   512 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   513 val cut_rl =
   514   store_standard_thm_open (Binding.make ("cut_rl", @{here}))
   515     (Thm.trivial (read_prop "?psi ==> ?theta"));
   516 
   517 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   518      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   519 val revcut_rl =
   520   let
   521     val V = read_prop "V";
   522     val VW = read_prop "V ==> W";
   523   in
   524     store_standard_thm_open (Binding.make ("revcut_rl", @{here}))
   525       (Thm.implies_intr V
   526         (Thm.implies_intr VW (Thm.implies_elim (Thm.assume VW) (Thm.assume V))))
   527   end;
   528 
   529 (*for deleting an unwanted assumption*)
   530 val thin_rl =
   531   let
   532     val V = read_prop "V";
   533     val W = read_prop "W";
   534     val thm = Thm.implies_intr V (Thm.implies_intr W (Thm.assume W));
   535   in store_standard_thm_open (Binding.make ("thin_rl", @{here})) thm end;
   536 
   537 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   538 val triv_forall_equality =
   539   let
   540     val V = read_prop "V";
   541     val QV = read_prop "!!x::'a. V";
   542     val x = certify (Free ("x", Term.aT []));
   543   in
   544     store_standard_thm_open (Binding.make ("triv_forall_equality", @{here}))
   545       (Thm.equal_intr (Thm.implies_intr QV (Thm.forall_elim x (Thm.assume QV)))
   546         (Thm.implies_intr V (Thm.forall_intr x (Thm.assume V))))
   547   end;
   548 
   549 (* (PROP ?Phi ==> PROP ?Phi ==> PROP ?Psi) ==>
   550    (PROP ?Phi ==> PROP ?Psi)
   551 *)
   552 val distinct_prems_rl =
   553   let
   554     val AAB = read_prop "Phi ==> Phi ==> Psi";
   555     val A = read_prop "Phi";
   556   in
   557     store_standard_thm_open (Binding.make ("distinct_prems_rl", @{here}))
   558       (implies_intr_list [AAB, A]
   559         (implies_elim_list (Thm.assume AAB) [Thm.assume A, Thm.assume A]))
   560   end;
   561 
   562 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   563    ==> PROP ?phi == PROP ?psi
   564    Introduction rule for == as a meta-theorem.
   565 *)
   566 val equal_intr_rule =
   567   let
   568     val PQ = read_prop "phi ==> psi";
   569     val QP = read_prop "psi ==> phi";
   570   in
   571     store_standard_thm_open (Binding.make ("equal_intr_rule", @{here}))
   572       (Thm.implies_intr PQ
   573         (Thm.implies_intr QP (Thm.equal_intr (Thm.assume PQ) (Thm.assume QP))))
   574   end;
   575 
   576 (* PROP ?phi == PROP ?psi ==> PROP ?phi ==> PROP ?psi *)
   577 val equal_elim_rule1 =
   578   let
   579     val eq = read_prop "phi::prop == psi::prop";
   580     val P = read_prop "phi";
   581   in
   582     store_standard_thm_open (Binding.make ("equal_elim_rule1", @{here}))
   583       (Thm.equal_elim (Thm.assume eq) (Thm.assume P) |> implies_intr_list [eq, P])
   584   end;
   585 
   586 (* PROP ?psi == PROP ?phi ==> PROP ?phi ==> PROP ?psi *)
   587 val equal_elim_rule2 =
   588   store_standard_thm_open (Binding.make ("equal_elim_rule2", @{here}))
   589     (symmetric_thm RS equal_elim_rule1);
   590 
   591 (* PROP ?phi ==> PROP ?phi ==> PROP ?psi ==> PROP ?psi *)
   592 val remdups_rl =
   593   let
   594     val P = read_prop "phi";
   595     val Q = read_prop "psi";
   596     val thm = implies_intr_list [P, P, Q] (Thm.assume Q);
   597   in store_standard_thm_open (Binding.make ("remdups_rl", @{here})) thm end;
   598 
   599 
   600 
   601 (** embedded terms and types **)
   602 
   603 local
   604   val A = certify (Free ("A", propT));
   605   val axiom = Thm.unvarify_global o Thm.axiom (Context.the_theory (Context.the_thread_data ()));
   606   val prop_def = axiom "Pure.prop_def";
   607   val term_def = axiom "Pure.term_def";
   608   val sort_constraint_def = axiom "Pure.sort_constraint_def";
   609   val C = Thm.lhs_of sort_constraint_def;
   610   val T = Thm.dest_arg C;
   611   val CA = mk_implies (C, A);
   612 in
   613 
   614 (* protect *)
   615 
   616 val protect = Thm.apply (certify Logic.protectC);
   617 
   618 val protectI =
   619   store_standard_thm (Binding.conceal (Binding.make ("protectI", @{here})))
   620     (Thm.equal_elim (Thm.symmetric prop_def) (Thm.assume A));
   621 
   622 val protectD =
   623   store_standard_thm (Binding.conceal (Binding.make ("protectD", @{here})))
   624     (Thm.equal_elim prop_def (Thm.assume (protect A)));
   625 
   626 val protect_cong =
   627   store_standard_thm_open (Binding.make ("protect_cong", @{here}))
   628     (Thm.reflexive (protect A));
   629 
   630 fun implies_intr_protected asms th =
   631   let val asms' = map protect asms in
   632     implies_elim_list
   633       (implies_intr_list asms th)
   634       (map (fn asm' => Thm.assume asm' RS protectD) asms')
   635     |> implies_intr_list asms'
   636   end;
   637 
   638 
   639 (* term *)
   640 
   641 val termI =
   642   store_standard_thm (Binding.conceal (Binding.make ("termI", @{here})))
   643     (Thm.equal_elim (Thm.symmetric term_def) (Thm.forall_intr A (Thm.trivial A)));
   644 
   645 fun mk_term ct =
   646   let
   647     val thy = Thm.theory_of_cterm ct;
   648     val cert = Thm.cterm_of thy;
   649     val certT = Thm.ctyp_of thy;
   650     val T = Thm.typ_of (Thm.ctyp_of_term ct);
   651     val a = certT (TVar (("'a", 0), []));
   652     val x = cert (Var (("x", 0), T));
   653   in Thm.instantiate ([(a, certT T)], [(x, ct)]) termI end;
   654 
   655 fun dest_term th =
   656   let val cprop = strip_imp_concl (Thm.cprop_of th) in
   657     if can Logic.dest_term (Thm.term_of cprop) then
   658       Thm.dest_arg cprop
   659     else raise THM ("dest_term", 0, [th])
   660   end;
   661 
   662 fun cterm_rule f = dest_term o f o mk_term;
   663 
   664 val dummy_thm = mk_term (certify Term.dummy_prop);
   665 
   666 
   667 (* sort_constraint *)
   668 
   669 val sort_constraintI =
   670   store_standard_thm (Binding.conceal (Binding.make ("sort_constraintI", @{here})))
   671     (Thm.equal_elim (Thm.symmetric sort_constraint_def) (mk_term T));
   672 
   673 val sort_constraint_eq =
   674   store_standard_thm (Binding.conceal (Binding.make ("sort_constraint_eq", @{here})))
   675     (Thm.equal_intr
   676       (Thm.implies_intr CA (Thm.implies_elim (Thm.assume CA)
   677         (Thm.unvarify_global sort_constraintI)))
   678       (implies_intr_list [A, C] (Thm.assume A)));
   679 
   680 end;
   681 
   682 
   683 (* HHF normalization *)
   684 
   685 (* (PROP ?phi ==> (!!x. PROP ?psi x)) == (!!x. PROP ?phi ==> PROP ?psi x) *)
   686 val norm_hhf_eq =
   687   let
   688     val aT = TFree ("'a", []);
   689     val x = Free ("x", aT);
   690     val phi = Free ("phi", propT);
   691     val psi = Free ("psi", aT --> propT);
   692 
   693     val cx = certify x;
   694     val cphi = certify phi;
   695     val lhs = certify (Logic.mk_implies (phi, Logic.all x (psi $ x)));
   696     val rhs = certify (Logic.all x (Logic.mk_implies (phi, psi $ x)));
   697   in
   698     Thm.equal_intr
   699       (Thm.implies_elim (Thm.assume lhs) (Thm.assume cphi)
   700         |> Thm.forall_elim cx
   701         |> Thm.implies_intr cphi
   702         |> Thm.forall_intr cx
   703         |> Thm.implies_intr lhs)
   704       (Thm.implies_elim
   705           (Thm.assume rhs |> Thm.forall_elim cx) (Thm.assume cphi)
   706         |> Thm.forall_intr cx
   707         |> Thm.implies_intr cphi
   708         |> Thm.implies_intr rhs)
   709     |> store_standard_thm_open (Binding.make ("norm_hhf_eq", @{here}))
   710   end;
   711 
   712 val norm_hhf_prop = Logic.dest_equals (Thm.prop_of norm_hhf_eq);
   713 val norm_hhf_eqs = [norm_hhf_eq, sort_constraint_eq];
   714 
   715 fun is_norm_hhf (Const ("Pure.sort_constraint", _)) = false
   716   | is_norm_hhf (Const ("Pure.imp", _) $ _ $ (Const ("Pure.all", _) $ _)) = false
   717   | is_norm_hhf (Abs _ $ _) = false
   718   | is_norm_hhf (t $ u) = is_norm_hhf t andalso is_norm_hhf u
   719   | is_norm_hhf (Abs (_, _, t)) = is_norm_hhf t
   720   | is_norm_hhf _ = true;
   721 
   722 fun norm_hhf thy t =
   723   if is_norm_hhf t then t
   724   else Pattern.rewrite_term thy [norm_hhf_prop] [] t;
   725 
   726 fun norm_hhf_cterm ct =
   727   if is_norm_hhf (Thm.term_of ct) then ct
   728   else cterm_fun (Pattern.rewrite_term (Thm.theory_of_cterm ct) [norm_hhf_prop] []) ct;
   729 
   730 
   731 (* var indexes *)
   732 
   733 fun incr_indexes th = Thm.incr_indexes (Thm.maxidx_of th + 1);
   734 
   735 fun incr_indexes2 th1 th2 =
   736   Thm.incr_indexes (Int.max (Thm.maxidx_of th1, Thm.maxidx_of th2) + 1);
   737 
   738 local
   739 
   740 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   741 fun comp incremented th1 th2 =
   742   Thm.bicompose {flatten = true, match = false, incremented = incremented} (false, th1, 0) 1 th2
   743   |> Seq.list_of |> distinct Thm.eq_thm
   744   |> (fn [th] => th | _ => raise THM ("COMP", 1, [th1, th2]));
   745 
   746 in
   747 
   748 fun th1 COMP th2 = comp false th1 th2;
   749 fun th1 INCR_COMP th2 = comp true (incr_indexes th2 th1) th2;
   750 fun th1 COMP_INCR th2 = comp true th1 (incr_indexes th1 th2);
   751 
   752 end;
   753 
   754 fun comp_no_flatten (th, n) i rule =
   755   (case distinct Thm.eq_thm (Seq.list_of
   756       (Thm.bicompose {flatten = false, match = false, incremented = true}
   757         (false, th, n) i (incr_indexes th rule))) of
   758     [th'] => th'
   759   | [] => raise THM ("comp_no_flatten", i, [th, rule])
   760   | _ => raise THM ("comp_no_flatten: unique result expected", i, [th, rule]));
   761 
   762 
   763 
   764 (** variations on Thm.instantiate **)
   765 
   766 fun instantiate_normalize instpair th =
   767   Thm.adjust_maxidx_thm ~1 (Thm.instantiate instpair th COMP_INCR asm_rl);
   768 
   769 (*Left-to-right replacements: tpairs = [..., (vi, ti), ...].
   770   Instantiates distinct Vars by terms, inferring type instantiations.*)
   771 local
   772   fun add_types (ct, cu) (thy, tye, maxidx) =
   773     let
   774       val {t, T, maxidx = maxt, ...} = Thm.rep_cterm ct;
   775       val {t = u, T = U, maxidx = maxu, ...} = Thm.rep_cterm cu;
   776       val maxi = Int.max (maxidx, Int.max (maxt, maxu));
   777       val thy' = Theory.merge (thy, Theory.merge (Thm.theory_of_cterm ct, Thm.theory_of_cterm cu));
   778       val (tye', maxi') = Sign.typ_unify thy' (T, U) (tye, maxi)
   779         handle Type.TUNIFY => raise TYPE ("Ill-typed instantiation:\nType\n" ^
   780           Syntax.string_of_typ_global thy' (Envir.norm_type tye T) ^
   781           "\nof variable " ^
   782           Syntax.string_of_term_global thy' (Term.map_types (Envir.norm_type tye) t) ^
   783           "\ncannot be unified with type\n" ^
   784           Syntax.string_of_typ_global thy' (Envir.norm_type tye U) ^ "\nof term " ^
   785           Syntax.string_of_term_global thy' (Term.map_types (Envir.norm_type tye) u),
   786           [T, U], [t, u])
   787     in (thy', tye', maxi') end;
   788 in
   789 
   790 fun cterm_instantiate [] th = th
   791   | cterm_instantiate ctpairs th =
   792       let
   793         val (thy, tye, _) = fold_rev add_types ctpairs (Thm.theory_of_thm th, Vartab.empty, 0);
   794         val certT = ctyp_of thy;
   795         val instT =
   796           Vartab.fold (fn (xi, (S, T)) =>
   797             cons (certT (TVar (xi, S)), certT (Envir.norm_type tye T))) tye [];
   798         val inst = map (pairself (Thm.instantiate_cterm (instT, []))) ctpairs;
   799       in instantiate_normalize (instT, inst) th end
   800       handle TERM (msg, _) => raise THM (msg, 0, [th])
   801         | TYPE (msg, _, _) => raise THM (msg, 0, [th]);
   802 end;
   803 
   804 
   805 (* instantiate by left-to-right occurrence of variables *)
   806 
   807 fun instantiate' cTs cts thm =
   808   let
   809     fun err msg =
   810       raise TYPE ("instantiate': " ^ msg,
   811         map_filter (Option.map Thm.typ_of) cTs,
   812         map_filter (Option.map Thm.term_of) cts);
   813 
   814     fun inst_of (v, ct) =
   815       (Thm.cterm_of (Thm.theory_of_cterm ct) (Var v), ct)
   816         handle TYPE (msg, _, _) => err msg;
   817 
   818     fun tyinst_of (v, cT) =
   819       (Thm.ctyp_of (Thm.theory_of_ctyp cT) (TVar v), cT)
   820         handle TYPE (msg, _, _) => err msg;
   821 
   822     fun zip_vars xs ys =
   823       zip_options xs ys handle ListPair.UnequalLengths =>
   824         err "more instantiations than variables in thm";
   825 
   826     (*instantiate types first!*)
   827     val thm' =
   828       if forall is_none cTs then thm
   829       else Thm.instantiate
   830         (map tyinst_of (zip_vars (rev (Thm.fold_terms Term.add_tvars thm [])) cTs), []) thm;
   831     val thm'' =
   832       if forall is_none cts then thm'
   833       else Thm.instantiate
   834         ([], map inst_of (zip_vars (rev (Thm.fold_terms Term.add_vars thm' [])) cts)) thm';
   835     in thm'' end;
   836 
   837 
   838 
   839 (** renaming of bound variables **)
   840 
   841 (* replace bound variables x_i in thm by y_i *)
   842 (* where vs = [(x_1, y_1), ..., (x_n, y_n)]  *)
   843 
   844 fun rename_bvars [] thm = thm
   845   | rename_bvars vs thm =
   846       let
   847         val cert = Thm.cterm_of (Thm.theory_of_thm thm);
   848         fun ren (Abs (x, T, t)) = Abs (AList.lookup (op =) vs x |> the_default x, T, ren t)
   849           | ren (t $ u) = ren t $ ren u
   850           | ren t = t;
   851       in Thm.equal_elim (Thm.reflexive (cert (ren (Thm.prop_of thm)))) thm end;
   852 
   853 
   854 (* renaming in left-to-right order *)
   855 
   856 fun rename_bvars' xs thm =
   857   let
   858     val cert = Thm.cterm_of (Thm.theory_of_thm thm);
   859     val prop = Thm.prop_of thm;
   860     fun rename [] t = ([], t)
   861       | rename (x' :: xs) (Abs (x, T, t)) =
   862           let val (xs', t') = rename xs t
   863           in (xs', Abs (the_default x x', T, t')) end
   864       | rename xs (t $ u) =
   865           let
   866             val (xs', t') = rename xs t;
   867             val (xs'', u') = rename xs' u
   868           in (xs'', t' $ u') end
   869       | rename xs t = (xs, t);
   870   in case rename xs prop of
   871       ([], prop') => Thm.equal_elim (Thm.reflexive (cert prop')) thm
   872     | _ => error "More names than abstractions in theorem"
   873   end;
   874 
   875 end;
   876 
   877 structure Basic_Drule: BASIC_DRULE = Drule;
   878 open Basic_Drule;