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