src/Pure/drule.ML
author wenzelm
Mon Mar 10 15:04:01 2014 +0100 (2014-03-10)
changeset 56026 893fe12639bc
parent 52467 24c6ddb48cb8
child 56245 84fc7dfa3cd4
permissions -rw-r--r--
tuned signature -- prefer Name_Space.get with its builtin error;
     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 ("==>", _) $ _ $ _ => 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.name "reflexive") (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.name "symmetric") 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.name "transitive") 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.name "equals_cong")
   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.name "imp_cong") (Thm.implies_intr ABC (Thm.equal_intr
   422       (Thm.implies_intr AB (Thm.implies_intr A
   423         (Thm.equal_elim (Thm.implies_elim (Thm.assume ABC) (Thm.assume A))
   424           (Thm.implies_elim (Thm.assume AB) (Thm.assume A)))))
   425       (Thm.implies_intr AC (Thm.implies_intr A
   426         (Thm.equal_elim (Thm.symmetric (Thm.implies_elim (Thm.assume ABC) (Thm.assume A)))
   427           (Thm.implies_elim (Thm.assume AC) (Thm.assume A)))))))
   428   end;
   429 
   430 val swap_prems_eq =
   431   let
   432     val ABC = read_prop "A ==> B ==> C"
   433     val BAC = read_prop "B ==> A ==> C"
   434     val A = read_prop "A"
   435     val B = read_prop "B"
   436   in
   437     store_standard_thm_open (Binding.name "swap_prems_eq")
   438       (Thm.equal_intr
   439         (Thm.implies_intr ABC (Thm.implies_intr B (Thm.implies_intr A
   440           (Thm.implies_elim (Thm.implies_elim (Thm.assume ABC) (Thm.assume A)) (Thm.assume B)))))
   441         (Thm.implies_intr BAC (Thm.implies_intr A (Thm.implies_intr B
   442           (Thm.implies_elim (Thm.implies_elim (Thm.assume BAC) (Thm.assume B)) (Thm.assume A))))))
   443   end;
   444 
   445 val imp_cong_rule = Thm.combination o Thm.combination (Thm.reflexive implies);
   446 
   447 fun arg_cong_rule ct th = Thm.combination (Thm.reflexive ct) th;    (*AP_TERM in LCF/HOL*)
   448 fun fun_cong_rule th ct = Thm.combination th (Thm.reflexive ct);    (*AP_THM in LCF/HOL*)
   449 fun binop_cong_rule ct th1 th2 = Thm.combination (arg_cong_rule ct th1) th2;
   450 
   451 local
   452   val dest_eq = Thm.dest_equals o cprop_of
   453   val rhs_of = snd o dest_eq
   454 in
   455 fun beta_eta_conversion t =
   456   let val thm = Thm.beta_conversion true t
   457   in Thm.transitive thm (Thm.eta_conversion (rhs_of thm)) end
   458 end;
   459 
   460 fun eta_long_conversion ct =
   461   Thm.transitive
   462     (beta_eta_conversion ct)
   463     (Thm.symmetric (beta_eta_conversion (cterm_fun (Envir.eta_long []) ct)));
   464 
   465 (*Contract all eta-redexes in the theorem, lest they give rise to needless abstractions*)
   466 fun eta_contraction_rule th =
   467   Thm.equal_elim (Thm.eta_conversion (cprop_of th)) th;
   468 
   469 
   470 (* abs_def *)
   471 
   472 (*
   473    f ?x1 ... ?xn == u
   474   --------------------
   475    f == %x1 ... xn. u
   476 *)
   477 
   478 local
   479 
   480 fun contract_lhs th =
   481   Thm.transitive (Thm.symmetric (beta_eta_conversion
   482     (fst (Thm.dest_equals (cprop_of th))))) th;
   483 
   484 fun var_args ct =
   485   (case try Thm.dest_comb ct of
   486     SOME (f, arg) =>
   487       (case Thm.term_of arg of
   488         Var ((x, _), _) => update (eq_snd (op aconvc)) (x, arg) (var_args f)
   489       | _ => [])
   490   | NONE => []);
   491 
   492 in
   493 
   494 fun abs_def th =
   495   let
   496     val th' = contract_lhs th;
   497     val args = var_args (Thm.lhs_of th');
   498   in contract_lhs (fold (uncurry Thm.abstract_rule) args th') end;
   499 
   500 end;
   501 
   502 
   503 
   504 (*** Some useful meta-theorems ***)
   505 
   506 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   507 val asm_rl = store_standard_thm_open (Binding.name "asm_rl") (Thm.trivial (read_prop "?psi"));
   508 
   509 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   510 val cut_rl =
   511   store_standard_thm_open (Binding.name "cut_rl")
   512     (Thm.trivial (read_prop "?psi ==> ?theta"));
   513 
   514 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   515      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   516 val revcut_rl =
   517   let
   518     val V = read_prop "V";
   519     val VW = read_prop "V ==> W";
   520   in
   521     store_standard_thm_open (Binding.name "revcut_rl")
   522       (Thm.implies_intr V (Thm.implies_intr VW (Thm.implies_elim (Thm.assume VW) (Thm.assume V))))
   523   end;
   524 
   525 (*for deleting an unwanted assumption*)
   526 val thin_rl =
   527   let
   528     val V = read_prop "V";
   529     val W = read_prop "W";
   530     val thm = Thm.implies_intr V (Thm.implies_intr W (Thm.assume W));
   531   in store_standard_thm_open (Binding.name "thin_rl") thm end;
   532 
   533 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   534 val triv_forall_equality =
   535   let
   536     val V = read_prop "V";
   537     val QV = read_prop "!!x::'a. V";
   538     val x = certify (Free ("x", Term.aT []));
   539   in
   540     store_standard_thm_open (Binding.name "triv_forall_equality")
   541       (Thm.equal_intr (Thm.implies_intr QV (Thm.forall_elim x (Thm.assume QV)))
   542         (Thm.implies_intr V (Thm.forall_intr x (Thm.assume V))))
   543   end;
   544 
   545 (* (PROP ?Phi ==> PROP ?Phi ==> PROP ?Psi) ==>
   546    (PROP ?Phi ==> PROP ?Psi)
   547 *)
   548 val distinct_prems_rl =
   549   let
   550     val AAB = read_prop "Phi ==> Phi ==> Psi";
   551     val A = read_prop "Phi";
   552   in
   553     store_standard_thm_open (Binding.name "distinct_prems_rl")
   554       (implies_intr_list [AAB, A] (implies_elim_list (Thm.assume AAB) [Thm.assume A, Thm.assume A]))
   555   end;
   556 
   557 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   558    ==> PROP ?phi == PROP ?psi
   559    Introduction rule for == as a meta-theorem.
   560 *)
   561 val equal_intr_rule =
   562   let
   563     val PQ = read_prop "phi ==> psi";
   564     val QP = read_prop "psi ==> phi";
   565   in
   566     store_standard_thm_open (Binding.name "equal_intr_rule")
   567       (Thm.implies_intr PQ (Thm.implies_intr QP (Thm.equal_intr (Thm.assume PQ) (Thm.assume QP))))
   568   end;
   569 
   570 (* PROP ?phi == PROP ?psi ==> PROP ?phi ==> PROP ?psi *)
   571 val equal_elim_rule1 =
   572   let
   573     val eq = read_prop "phi::prop == psi::prop";
   574     val P = read_prop "phi";
   575   in
   576     store_standard_thm_open (Binding.name "equal_elim_rule1")
   577       (Thm.equal_elim (Thm.assume eq) (Thm.assume P) |> implies_intr_list [eq, P])
   578   end;
   579 
   580 (* PROP ?psi == PROP ?phi ==> PROP ?phi ==> PROP ?psi *)
   581 val equal_elim_rule2 =
   582   store_standard_thm_open (Binding.name "equal_elim_rule2")
   583     (symmetric_thm RS equal_elim_rule1);
   584 
   585 (* PROP ?phi ==> PROP ?phi ==> PROP ?psi ==> PROP ?psi *)
   586 val remdups_rl =
   587   let
   588     val P = read_prop "phi";
   589     val Q = read_prop "psi";
   590     val thm = implies_intr_list [P, P, Q] (Thm.assume Q);
   591   in store_standard_thm_open (Binding.name "remdups_rl") thm end;
   592 
   593 
   594 
   595 (** embedded terms and types **)
   596 
   597 local
   598   val A = certify (Free ("A", propT));
   599   val axiom = Thm.unvarify_global o Thm.axiom (Context.the_theory (Context.the_thread_data ()));
   600   val prop_def = axiom "Pure.prop_def";
   601   val term_def = axiom "Pure.term_def";
   602   val sort_constraint_def = axiom "Pure.sort_constraint_def";
   603   val C = Thm.lhs_of sort_constraint_def;
   604   val T = Thm.dest_arg C;
   605   val CA = mk_implies (C, A);
   606 in
   607 
   608 (* protect *)
   609 
   610 val protect = Thm.apply (certify Logic.protectC);
   611 
   612 val protectI =
   613   store_standard_thm (Binding.conceal (Binding.name "protectI"))
   614     (Thm.equal_elim (Thm.symmetric prop_def) (Thm.assume A));
   615 
   616 val protectD =
   617   store_standard_thm (Binding.conceal (Binding.name "protectD"))
   618     (Thm.equal_elim prop_def (Thm.assume (protect A)));
   619 
   620 val protect_cong =
   621   store_standard_thm_open (Binding.name "protect_cong") (Thm.reflexive (protect A));
   622 
   623 fun implies_intr_protected asms th =
   624   let val asms' = map protect asms in
   625     implies_elim_list
   626       (implies_intr_list asms th)
   627       (map (fn asm' => Thm.assume asm' RS protectD) asms')
   628     |> implies_intr_list asms'
   629   end;
   630 
   631 
   632 (* term *)
   633 
   634 val termI =
   635   store_standard_thm (Binding.conceal (Binding.name "termI"))
   636     (Thm.equal_elim (Thm.symmetric term_def) (Thm.forall_intr A (Thm.trivial A)));
   637 
   638 fun mk_term ct =
   639   let
   640     val thy = Thm.theory_of_cterm ct;
   641     val cert = Thm.cterm_of thy;
   642     val certT = Thm.ctyp_of thy;
   643     val T = Thm.typ_of (Thm.ctyp_of_term ct);
   644     val a = certT (TVar (("'a", 0), []));
   645     val x = cert (Var (("x", 0), T));
   646   in Thm.instantiate ([(a, certT T)], [(x, ct)]) termI end;
   647 
   648 fun dest_term th =
   649   let val cprop = strip_imp_concl (Thm.cprop_of th) in
   650     if can Logic.dest_term (Thm.term_of cprop) then
   651       Thm.dest_arg cprop
   652     else raise THM ("dest_term", 0, [th])
   653   end;
   654 
   655 fun cterm_rule f = dest_term o f o mk_term;
   656 
   657 val dummy_thm = mk_term (certify Term.dummy_prop);
   658 
   659 
   660 (* sort_constraint *)
   661 
   662 val sort_constraintI =
   663   store_standard_thm (Binding.conceal (Binding.name "sort_constraintI"))
   664     (Thm.equal_elim (Thm.symmetric sort_constraint_def) (mk_term T));
   665 
   666 val sort_constraint_eq =
   667   store_standard_thm (Binding.conceal (Binding.name "sort_constraint_eq"))
   668     (Thm.equal_intr
   669       (Thm.implies_intr CA (Thm.implies_elim (Thm.assume CA)
   670         (Thm.unvarify_global sort_constraintI)))
   671       (implies_intr_list [A, C] (Thm.assume A)));
   672 
   673 end;
   674 
   675 
   676 (* HHF normalization *)
   677 
   678 (* (PROP ?phi ==> (!!x. PROP ?psi x)) == (!!x. PROP ?phi ==> PROP ?psi x) *)
   679 val norm_hhf_eq =
   680   let
   681     val aT = TFree ("'a", []);
   682     val x = Free ("x", aT);
   683     val phi = Free ("phi", propT);
   684     val psi = Free ("psi", aT --> propT);
   685 
   686     val cx = certify x;
   687     val cphi = certify phi;
   688     val lhs = certify (Logic.mk_implies (phi, Logic.all x (psi $ x)));
   689     val rhs = certify (Logic.all x (Logic.mk_implies (phi, psi $ x)));
   690   in
   691     Thm.equal_intr
   692       (Thm.implies_elim (Thm.assume lhs) (Thm.assume cphi)
   693         |> Thm.forall_elim cx
   694         |> Thm.implies_intr cphi
   695         |> Thm.forall_intr cx
   696         |> Thm.implies_intr lhs)
   697       (Thm.implies_elim
   698           (Thm.assume rhs |> Thm.forall_elim cx) (Thm.assume cphi)
   699         |> Thm.forall_intr cx
   700         |> Thm.implies_intr cphi
   701         |> Thm.implies_intr rhs)
   702     |> store_standard_thm_open (Binding.name "norm_hhf_eq")
   703   end;
   704 
   705 val norm_hhf_prop = Logic.dest_equals (Thm.prop_of norm_hhf_eq);
   706 val norm_hhf_eqs = [norm_hhf_eq, sort_constraint_eq];
   707 
   708 fun is_norm_hhf (Const ("Pure.sort_constraint", _)) = false
   709   | is_norm_hhf (Const ("==>", _) $ _ $ (Const ("all", _) $ _)) = false
   710   | is_norm_hhf (Abs _ $ _) = false
   711   | is_norm_hhf (t $ u) = is_norm_hhf t andalso is_norm_hhf u
   712   | is_norm_hhf (Abs (_, _, t)) = is_norm_hhf t
   713   | is_norm_hhf _ = true;
   714 
   715 fun norm_hhf thy t =
   716   if is_norm_hhf t then t
   717   else Pattern.rewrite_term thy [norm_hhf_prop] [] t;
   718 
   719 fun norm_hhf_cterm ct =
   720   if is_norm_hhf (Thm.term_of ct) then ct
   721   else cterm_fun (Pattern.rewrite_term (Thm.theory_of_cterm ct) [norm_hhf_prop] []) ct;
   722 
   723 
   724 (* var indexes *)
   725 
   726 fun incr_indexes th = Thm.incr_indexes (Thm.maxidx_of th + 1);
   727 
   728 fun incr_indexes2 th1 th2 =
   729   Thm.incr_indexes (Int.max (Thm.maxidx_of th1, Thm.maxidx_of th2) + 1);
   730 
   731 local
   732 
   733 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   734 fun comp incremented th1 th2 =
   735   Thm.bicompose {flatten = true, match = false, incremented = incremented} (false, th1, 0) 1 th2
   736   |> Seq.list_of |> distinct Thm.eq_thm
   737   |> (fn [th] => th | _ => raise THM ("COMP", 1, [th1, th2]));
   738 
   739 in
   740 
   741 fun th1 COMP th2 = comp false th1 th2;
   742 fun th1 INCR_COMP th2 = comp true (incr_indexes th2 th1) th2;
   743 fun th1 COMP_INCR th2 = comp true th1 (incr_indexes th1 th2);
   744 
   745 end;
   746 
   747 fun comp_no_flatten (th, n) i rule =
   748   (case distinct Thm.eq_thm (Seq.list_of
   749       (Thm.bicompose {flatten = false, match = false, incremented = true}
   750         (false, th, n) i (incr_indexes th rule))) of
   751     [th'] => th'
   752   | [] => raise THM ("comp_no_flatten", i, [th, rule])
   753   | _ => raise THM ("comp_no_flatten: unique result expected", i, [th, rule]));
   754 
   755 
   756 
   757 (** variations on Thm.instantiate **)
   758 
   759 fun instantiate_normalize instpair th =
   760   Thm.adjust_maxidx_thm ~1 (Thm.instantiate instpair th COMP_INCR asm_rl);
   761 
   762 (*Left-to-right replacements: tpairs = [..., (vi, ti), ...].
   763   Instantiates distinct Vars by terms, inferring type instantiations.*)
   764 local
   765   fun add_types (ct, cu) (thy, tye, maxidx) =
   766     let
   767       val {t, T, maxidx = maxt, ...} = Thm.rep_cterm ct;
   768       val {t = u, T = U, maxidx = maxu, ...} = Thm.rep_cterm cu;
   769       val maxi = Int.max (maxidx, Int.max (maxt, maxu));
   770       val thy' = Theory.merge (thy, Theory.merge (Thm.theory_of_cterm ct, Thm.theory_of_cterm cu));
   771       val (tye', maxi') = Sign.typ_unify thy' (T, U) (tye, maxi)
   772         handle Type.TUNIFY => raise TYPE ("Ill-typed instantiation:\nType\n" ^
   773           Syntax.string_of_typ_global thy' (Envir.norm_type tye T) ^
   774           "\nof variable " ^
   775           Syntax.string_of_term_global thy' (Term.map_types (Envir.norm_type tye) t) ^
   776           "\ncannot be unified with type\n" ^
   777           Syntax.string_of_typ_global thy' (Envir.norm_type tye U) ^ "\nof term " ^
   778           Syntax.string_of_term_global thy' (Term.map_types (Envir.norm_type tye) u),
   779           [T, U], [t, u])
   780     in (thy', tye', maxi') end;
   781 in
   782 
   783 fun cterm_instantiate [] th = th
   784   | cterm_instantiate ctpairs th =
   785       let
   786         val (thy, tye, _) = fold_rev add_types ctpairs (Thm.theory_of_thm th, Vartab.empty, 0);
   787         val certT = ctyp_of thy;
   788         val instT =
   789           Vartab.fold (fn (xi, (S, T)) =>
   790             cons (certT (TVar (xi, S)), certT (Envir.norm_type tye T))) tye [];
   791         val inst = map (pairself (Thm.instantiate_cterm (instT, []))) ctpairs;
   792       in instantiate_normalize (instT, inst) th end
   793       handle TERM (msg, _) => raise THM (msg, 0, [th])
   794         | TYPE (msg, _, _) => raise THM (msg, 0, [th]);
   795 end;
   796 
   797 
   798 (* instantiate by left-to-right occurrence of variables *)
   799 
   800 fun instantiate' cTs cts thm =
   801   let
   802     fun err msg =
   803       raise TYPE ("instantiate': " ^ msg,
   804         map_filter (Option.map Thm.typ_of) cTs,
   805         map_filter (Option.map Thm.term_of) cts);
   806 
   807     fun inst_of (v, ct) =
   808       (Thm.cterm_of (Thm.theory_of_cterm ct) (Var v), ct)
   809         handle TYPE (msg, _, _) => err msg;
   810 
   811     fun tyinst_of (v, cT) =
   812       (Thm.ctyp_of (Thm.theory_of_ctyp cT) (TVar v), cT)
   813         handle TYPE (msg, _, _) => err msg;
   814 
   815     fun zip_vars xs ys =
   816       zip_options xs ys handle ListPair.UnequalLengths =>
   817         err "more instantiations than variables in thm";
   818 
   819     (*instantiate types first!*)
   820     val thm' =
   821       if forall is_none cTs then thm
   822       else Thm.instantiate
   823         (map tyinst_of (zip_vars (rev (Thm.fold_terms Term.add_tvars thm [])) cTs), []) thm;
   824     val thm'' =
   825       if forall is_none cts then thm'
   826       else Thm.instantiate
   827         ([], map inst_of (zip_vars (rev (Thm.fold_terms Term.add_vars thm' [])) cts)) thm';
   828     in thm'' end;
   829 
   830 
   831 
   832 (** renaming of bound variables **)
   833 
   834 (* replace bound variables x_i in thm by y_i *)
   835 (* where vs = [(x_1, y_1), ..., (x_n, y_n)]  *)
   836 
   837 fun rename_bvars [] thm = thm
   838   | rename_bvars vs thm =
   839       let
   840         val cert = Thm.cterm_of (Thm.theory_of_thm thm);
   841         fun ren (Abs (x, T, t)) = Abs (AList.lookup (op =) vs x |> the_default x, T, ren t)
   842           | ren (t $ u) = ren t $ ren u
   843           | ren t = t;
   844       in Thm.equal_elim (Thm.reflexive (cert (ren (Thm.prop_of thm)))) thm end;
   845 
   846 
   847 (* renaming in left-to-right order *)
   848 
   849 fun rename_bvars' xs thm =
   850   let
   851     val cert = Thm.cterm_of (Thm.theory_of_thm thm);
   852     val prop = Thm.prop_of thm;
   853     fun rename [] t = ([], t)
   854       | rename (x' :: xs) (Abs (x, T, t)) =
   855           let val (xs', t') = rename xs t
   856           in (xs', Abs (the_default x x', T, t')) end
   857       | rename xs (t $ u) =
   858           let
   859             val (xs', t') = rename xs t;
   860             val (xs'', u') = rename xs' u
   861           in (xs'', t' $ u') end
   862       | rename xs t = (xs, t);
   863   in case rename xs prop of
   864       ([], prop') => Thm.equal_elim (Thm.reflexive (cert prop')) thm
   865     | _ => error "More names than abstractions in theorem"
   866   end;
   867 
   868 end;
   869 
   870 structure Basic_Drule: BASIC_DRULE = Drule;
   871 open Basic_Drule;