src/Pure/drule.ML
author wenzelm
Mon Nov 09 15:40:26 1998 +0100 (1998-11-09)
changeset 5838 a4122945d638
parent 5688 7f582495967c
child 5903 5d9beee36fbe
permissions -rw-r--r--
added metacuts_tac;
     1 (*  Title:      Pure/drule.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1993  University of Cambridge
     5 
     6 Derived rules and other operations on theorems.
     7 *)
     8 
     9 infix 0 RS RSN RL RLN MRS MRL COMP;
    10 
    11 signature DRULE =
    12 sig
    13   val dest_implies      : cterm -> cterm * cterm
    14   val skip_flexpairs	: cterm -> cterm
    15   val strip_imp_prems	: cterm -> cterm list
    16   val cprems_of		: thm -> cterm list
    17   val read_insts	:
    18           Sign.sg -> (indexname -> typ option) * (indexname -> sort option)
    19                   -> (indexname -> typ option) * (indexname -> sort option)
    20                   -> string list -> (string*string)list
    21                   -> (indexname*ctyp)list * (cterm*cterm)list
    22   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    23   val forall_intr_list	: cterm list -> thm -> thm
    24   val forall_intr_frees	: thm -> thm
    25   val forall_intr_vars	: thm -> thm
    26   val forall_elim_list	: cterm list -> thm -> thm
    27   val forall_elim_var	: int -> thm -> thm
    28   val forall_elim_vars	: int -> thm -> thm
    29   val freeze_thaw	: thm -> thm * (thm -> thm)
    30   val implies_elim_list	: thm -> thm list -> thm
    31   val implies_intr_list	: cterm list -> thm -> thm
    32   val zero_var_indexes	: thm -> thm
    33   val standard		: thm -> thm
    34   val rotate_prems      : int -> thm -> thm
    35   val assume_ax		: theory -> string -> thm
    36   val RSN		: thm * (int * thm) -> thm
    37   val RS		: thm * thm -> thm
    38   val RLN		: thm list * (int * thm list) -> thm list
    39   val RL		: thm list * thm list -> thm list
    40   val MRS		: thm list * thm -> thm
    41   val MRL		: thm list list * thm list -> thm list
    42   val compose		: thm * int * thm -> thm list
    43   val COMP		: thm * thm -> thm
    44   val read_instantiate_sg: Sign.sg -> (string*string)list -> thm -> thm
    45   val read_instantiate	: (string*string)list -> thm -> thm
    46   val cterm_instantiate	: (cterm*cterm)list -> thm -> thm
    47   val weak_eq_thm	: thm * thm -> bool
    48   val eq_thm_sg		: thm * thm -> bool
    49   val size_of_thm	: thm -> int
    50   val reflexive_thm	: thm
    51   val symmetric_thm	: thm
    52   val transitive_thm	: thm
    53   val refl_implies      : thm
    54   val symmetric_fun     : thm -> thm
    55   val rewrite_rule_aux	: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    56   val rewrite_thm	: bool * bool * bool
    57                           -> (meta_simpset -> thm -> thm option)
    58                           -> meta_simpset -> thm -> thm
    59   val rewrite_cterm	: bool * bool * bool
    60                           -> (meta_simpset -> thm -> thm option)
    61                           -> meta_simpset -> cterm -> thm
    62   val rewrite_goals_rule_aux: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    63   val rewrite_goal_rule	: bool* bool * bool
    64                           -> (meta_simpset -> thm -> thm option)
    65                           -> meta_simpset -> int -> thm -> thm
    66   val equal_abs_elim	: cterm  -> thm -> thm
    67   val equal_abs_elim_list: cterm list -> thm -> thm
    68   val flexpair_abs_elim_list: cterm list -> thm -> thm
    69   val asm_rl		: thm
    70   val cut_rl		: thm
    71   val revcut_rl		: thm
    72   val thin_rl		: thm
    73   val triv_forall_equality: thm
    74   val swap_prems_rl     : thm
    75   val equal_intr_rule   : thm
    76   val triv_goal		: thm
    77   val rev_triv_goal	: thm
    78   val mk_triv_goal      : cterm -> thm
    79   val instantiate'	: ctyp option list -> cterm option list -> thm -> thm
    80   val unvarifyT		: thm -> thm
    81   val unvarify		: thm -> thm
    82 end;
    83 
    84 structure Drule : DRULE =
    85 struct
    86 
    87 
    88 (** some cterm->cterm operations: much faster than calling cterm_of! **)
    89 
    90 (** SAME NAMES as in structure Logic: use compound identifiers! **)
    91 
    92 (*dest_implies for cterms. Note T=prop below*)
    93 fun dest_implies ct =
    94     case term_of ct of 
    95 	(Const("==>", _) $ _ $ _) => 
    96 	    let val (ct1,ct2) = dest_comb ct
    97 	    in  (#2 (dest_comb ct1), ct2)  end	     
    98       | _ => raise TERM ("dest_implies", [term_of ct]) ;
    99 
   100 
   101 (*Discard flexflex pairs; return a cterm*)
   102 fun skip_flexpairs ct =
   103     case term_of ct of
   104 	(Const("==>", _) $ (Const("=?=",_)$_$_) $ _) =>
   105 	    skip_flexpairs (#2 (dest_implies ct))
   106       | _ => ct;
   107 
   108 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   109 fun strip_imp_prems ct =
   110     let val (cA,cB) = dest_implies ct
   111     in  cA :: strip_imp_prems cB  end
   112     handle TERM _ => [];
   113 
   114 (* A1==>...An==>B  goes to B, where B is not an implication *)
   115 fun strip_imp_concl ct =
   116     case term_of ct of (Const("==>", _) $ _ $ _) => 
   117 	strip_imp_concl (#2 (dest_comb ct))
   118   | _ => ct;
   119 
   120 (*The premises of a theorem, as a cterm list*)
   121 val cprems_of = strip_imp_prems o skip_flexpairs o cprop_of;
   122 
   123 
   124 (** reading of instantiations **)
   125 
   126 fun absent ixn =
   127   error("No such variable in term: " ^ Syntax.string_of_vname ixn);
   128 
   129 fun inst_failure ixn =
   130   error("Instantiation of " ^ Syntax.string_of_vname ixn ^ " fails");
   131 
   132 fun read_insts sign (rtypes,rsorts) (types,sorts) used insts =
   133 let val {tsig,...} = Sign.rep_sg sign
   134     fun split([],tvs,vs) = (tvs,vs)
   135       | split((sv,st)::l,tvs,vs) = (case Symbol.explode sv of
   136                   "'"::cs => split(l,(Syntax.indexname cs,st)::tvs,vs)
   137                 | cs => split(l,tvs,(Syntax.indexname cs,st)::vs));
   138     val (tvs,vs) = split(insts,[],[]);
   139     fun readT((a,i),st) =
   140         let val ixn = ("'" ^ a,i);
   141             val S = case rsorts ixn of Some S => S | None => absent ixn;
   142             val T = Sign.read_typ (sign,sorts) st;
   143         in if Type.typ_instance(tsig,T,TVar(ixn,S)) then (ixn,T)
   144            else inst_failure ixn
   145         end
   146     val tye = map readT tvs;
   147     fun mkty(ixn,st) = (case rtypes ixn of
   148                           Some T => (ixn,(st,typ_subst_TVars tye T))
   149                         | None => absent ixn);
   150     val ixnsTs = map mkty vs;
   151     val ixns = map fst ixnsTs
   152     and sTs  = map snd ixnsTs
   153     val (cts,tye2) = read_def_cterms(sign,types,sorts) used false sTs;
   154     fun mkcVar(ixn,T) =
   155         let val U = typ_subst_TVars tye2 T
   156         in cterm_of sign (Var(ixn,U)) end
   157     val ixnTs = ListPair.zip(ixns, map snd sTs)
   158 in (map (fn (ixn,T) => (ixn,ctyp_of sign T)) (tye2 @ tye),
   159     ListPair.zip(map mkcVar ixnTs,cts))
   160 end;
   161 
   162 
   163 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   164      Used for establishing default types (of variables) and sorts (of
   165      type variables) when reading another term.
   166      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   167 ***)
   168 
   169 fun types_sorts thm =
   170     let val {prop,hyps,...} = rep_thm thm;
   171         val big = list_comb(prop,hyps); (* bogus term! *)
   172         val vars = map dest_Var (term_vars big);
   173         val frees = map dest_Free (term_frees big);
   174         val tvars = term_tvars big;
   175         val tfrees = term_tfrees big;
   176         fun typ(a,i) = if i<0 then assoc(frees,a) else assoc(vars,(a,i));
   177         fun sort(a,i) = if i<0 then assoc(tfrees,a) else assoc(tvars,(a,i));
   178     in (typ,sort) end;
   179 
   180 (** Standardization of rules **)
   181 
   182 (*Generalization over a list of variables, IGNORING bad ones*)
   183 fun forall_intr_list [] th = th
   184   | forall_intr_list (y::ys) th =
   185         let val gth = forall_intr_list ys th
   186         in  forall_intr y gth   handle THM _ =>  gth  end;
   187 
   188 (*Generalization over all suitable Free variables*)
   189 fun forall_intr_frees th =
   190     let val {prop,sign,...} = rep_thm th
   191     in  forall_intr_list
   192          (map (cterm_of sign) (sort (make_ord atless) (term_frees prop)))
   193          th
   194     end;
   195 
   196 (*Replace outermost quantified variable by Var of given index.
   197     Could clash with Vars already present.*)
   198 fun forall_elim_var i th =
   199     let val {prop,sign,...} = rep_thm th
   200     in case prop of
   201           Const("all",_) $ Abs(a,T,_) =>
   202               forall_elim (cterm_of sign (Var((a,i), T)))  th
   203         | _ => raise THM("forall_elim_var", i, [th])
   204     end;
   205 
   206 (*Repeat forall_elim_var until all outer quantifiers are removed*)
   207 fun forall_elim_vars i th =
   208     forall_elim_vars i (forall_elim_var i th)
   209         handle THM _ => th;
   210 
   211 (*Specialization over a list of cterms*)
   212 fun forall_elim_list cts th = foldr (uncurry forall_elim) (rev cts, th);
   213 
   214 (* maps [A1,...,An], B   to   [| A1;...;An |] ==> B  *)
   215 fun implies_intr_list cAs th = foldr (uncurry implies_intr) (cAs,th);
   216 
   217 (* maps [| A1;...;An |] ==> B and [A1,...,An]   to   B *)
   218 fun implies_elim_list impth ths = foldl (uncurry implies_elim) (impth,ths);
   219 
   220 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   221 fun zero_var_indexes th =
   222     let val {prop,sign,...} = rep_thm th;
   223         val vars = term_vars prop
   224         val bs = foldl add_new_id ([], map (fn Var((a,_),_)=>a) vars)
   225         val inrs = add_term_tvars(prop,[]);
   226         val nms' = rev(foldl add_new_id ([], map (#1 o #1) inrs));
   227         val tye = ListPair.map (fn ((v,rs),a) => (v, TVar((a,0),rs)))
   228 	             (inrs, nms')
   229         val ctye = map (fn (v,T) => (v,ctyp_of sign T)) tye;
   230         fun varpairs([],[]) = []
   231           | varpairs((var as Var(v,T)) :: vars, b::bs) =
   232                 let val T' = typ_subst_TVars tye T
   233                 in (cterm_of sign (Var(v,T')),
   234                     cterm_of sign (Var((b,0),T'))) :: varpairs(vars,bs)
   235                 end
   236           | varpairs _ = raise TERM("varpairs", []);
   237     in instantiate (ctye, varpairs(vars,rev bs)) th end;
   238 
   239 
   240 (*Standard form of object-rule: no hypotheses, Frees, or outer quantifiers;
   241     all generality expressed by Vars having index 0.*)
   242 fun standard th =
   243   let val {maxidx,...} = rep_thm th
   244   in
   245     th |> implies_intr_hyps
   246        |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
   247        |> Thm.strip_shyps |> Thm.implies_intr_shyps
   248        |> zero_var_indexes |> Thm.varifyT |> Thm.compress
   249   end;
   250 
   251 
   252 (*Convert all Vars in a theorem to Frees.  Also return a function for 
   253   reversing that operation.  DOES NOT WORK FOR TYPE VARIABLES.
   254   Similar code in type/freeze_thaw*)
   255 fun freeze_thaw th =
   256   let val fth = freezeT th
   257       val {prop,sign,...} = rep_thm fth
   258       val used = add_term_names (prop, [])
   259       and vars = term_vars prop
   260       fun newName (Var(ix,_), (pairs,used)) = 
   261 	    let val v = variant used (string_of_indexname ix)
   262 	    in  ((ix,v)::pairs, v::used)  end;
   263       val (alist, _) = foldr newName (vars, ([], used))
   264       fun mk_inst (Var(v,T)) = 
   265 	  (cterm_of sign (Var(v,T)),
   266 	   cterm_of sign (Free(the (assoc(alist,v)), T)))
   267       val insts = map mk_inst vars
   268       fun thaw th' = 
   269 	  th' |> forall_intr_list (map #2 insts)
   270 	      |> forall_elim_list (map #1 insts)
   271   in  (instantiate ([],insts) fth, thaw)  end;
   272 
   273 
   274 (*Rotates a rule's premises to the left by k.  Does nothing if k=0 or
   275   if k equals the number of premises.  Useful, for instance, with etac.
   276   Similar to tactic/defer_tac*)
   277 fun rotate_prems k rl = 
   278     let val (rl',thaw) = freeze_thaw rl
   279 	val hyps = strip_imp_prems (adjust_maxidx (cprop_of rl'))
   280 	val hyps' = List.drop(hyps, k)
   281     in  implies_elim_list rl' (map assume hyps)
   282         |> implies_intr_list (hyps' @ List.take(hyps, k))
   283         |> thaw |> varifyT
   284     end;
   285 
   286 
   287 (*Assume a new formula, read following the same conventions as axioms.
   288   Generalizes over Free variables,
   289   creates the assumption, and then strips quantifiers.
   290   Example is [| ALL x:?A. ?P(x) |] ==> [| ?P(?a) |]
   291              [ !(A,P,a)[| ALL x:A. P(x) |] ==> [| P(a) |] ]    *)
   292 fun assume_ax thy sP =
   293     let val sign = sign_of thy
   294         val prop = Logic.close_form (term_of (read_cterm sign (sP, propT)))
   295     in forall_elim_vars 0 (assume (cterm_of sign prop))  end;
   296 
   297 (*Resolution: exactly one resolvent must be produced.*)
   298 fun tha RSN (i,thb) =
   299   case Seq.chop (2, biresolution false [(false,tha)] i thb) of
   300       ([th],_) => th
   301     | ([],_)   => raise THM("RSN: no unifiers", i, [tha,thb])
   302     |      _   => raise THM("RSN: multiple unifiers", i, [tha,thb]);
   303 
   304 (*resolution: P==>Q, Q==>R gives P==>R. *)
   305 fun tha RS thb = tha RSN (1,thb);
   306 
   307 (*For joining lists of rules*)
   308 fun thas RLN (i,thbs) =
   309   let val resolve = biresolution false (map (pair false) thas) i
   310       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   311   in  List.concat (map resb thbs)  end;
   312 
   313 fun thas RL thbs = thas RLN (1,thbs);
   314 
   315 (*Resolve a list of rules against bottom_rl from right to left;
   316   makes proof trees*)
   317 fun rls MRS bottom_rl =
   318   let fun rs_aux i [] = bottom_rl
   319         | rs_aux i (rl::rls) = rl RSN (i, rs_aux (i+1) rls)
   320   in  rs_aux 1 rls  end;
   321 
   322 (*As above, but for rule lists*)
   323 fun rlss MRL bottom_rls =
   324   let fun rs_aux i [] = bottom_rls
   325         | rs_aux i (rls::rlss) = rls RLN (i, rs_aux (i+1) rlss)
   326   in  rs_aux 1 rlss  end;
   327 
   328 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   329   with no lifting or renaming!  Q may contain ==> or meta-quants
   330   ALWAYS deletes premise i *)
   331 fun compose(tha,i,thb) =
   332     Seq.list_of (bicompose false (false,tha,0) i thb);
   333 
   334 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   335 fun tha COMP thb =
   336     case compose(tha,1,thb) of
   337         [th] => th
   338       | _ =>   raise THM("COMP", 1, [tha,thb]);
   339 
   340 (*Instantiate theorem th, reading instantiations under signature sg*)
   341 fun read_instantiate_sg sg sinsts th =
   342     let val ts = types_sorts th;
   343         val used = add_term_tvarnames(#prop(rep_thm th),[]);
   344     in  instantiate (read_insts sg ts ts used sinsts) th  end;
   345 
   346 (*Instantiate theorem th, reading instantiations under theory of th*)
   347 fun read_instantiate sinsts th =
   348     read_instantiate_sg (#sign (rep_thm th)) sinsts th;
   349 
   350 
   351 (*Left-to-right replacements: tpairs = [...,(vi,ti),...].
   352   Instantiates distinct Vars by terms, inferring type instantiations. *)
   353 local
   354   fun add_types ((ct,cu), (sign,tye,maxidx)) =
   355     let val {sign=signt, t=t, T= T, maxidx=maxt,...} = rep_cterm ct
   356         and {sign=signu, t=u, T= U, maxidx=maxu,...} = rep_cterm cu;
   357         val maxi = Int.max(maxidx, Int.max(maxt, maxu));
   358         val sign' = Sign.merge(sign, Sign.merge(signt, signu))
   359         val (tye',maxi') = Type.unify (#tsig(Sign.rep_sg sign')) maxi tye (T,U)
   360           handle Type.TUNIFY => raise TYPE("add_types", [T,U], [t,u])
   361     in  (sign', tye', maxi')  end;
   362 in
   363 fun cterm_instantiate ctpairs0 th =
   364   let val (sign,tye,_) = foldr add_types (ctpairs0, (#sign(rep_thm th),[],0))
   365       val tsig = #tsig(Sign.rep_sg sign);
   366       fun instT(ct,cu) = let val inst = subst_TVars tye
   367                          in (cterm_fun inst ct, cterm_fun inst cu) end
   368       fun ctyp2 (ix,T) = (ix, ctyp_of sign T)
   369   in  instantiate (map ctyp2 tye, map instT ctpairs0) th  end
   370   handle TERM _ =>
   371            raise THM("cterm_instantiate: incompatible signatures",0,[th])
   372        | TYPE (msg, _, _) => raise THM("cterm_instantiate: " ^ msg, 0, [th])
   373 end;
   374 
   375 
   376 (** theorem equality **)
   377 
   378 (*Do the two theorems have the same signature?*)
   379 fun eq_thm_sg (th1,th2) = Sign.eq_sg(#sign(rep_thm th1), #sign(rep_thm th2));
   380 
   381 (*Useful "distance" function for BEST_FIRST*)
   382 val size_of_thm = size_of_term o #prop o rep_thm;
   383 
   384 
   385 (** Mark Staples's weaker version of eq_thm: ignores variable renaming and
   386     (some) type variable renaming **)
   387 
   388  (* Can't use term_vars, because it sorts the resulting list of variable names.
   389     We instead need the unique list noramlised by the order of appearance
   390     in the term. *)
   391 fun term_vars' (t as Var(v,T)) = [t]
   392   | term_vars' (Abs(_,_,b)) = term_vars' b
   393   | term_vars' (f$a) = (term_vars' f) @ (term_vars' a)
   394   | term_vars' _ = [];
   395 
   396 fun forall_intr_vars th =
   397   let val {prop,sign,...} = rep_thm th;
   398       val vars = distinct (term_vars' prop);
   399   in forall_intr_list (map (cterm_of sign) vars) th end;
   400 
   401 fun weak_eq_thm (tha,thb) =
   402     eq_thm(forall_intr_vars (freezeT tha), forall_intr_vars (freezeT thb));
   403 
   404 
   405 
   406 (*** Meta-Rewriting Rules ***)
   407 
   408 val proto_sign = sign_of ProtoPure.thy;
   409 
   410 fun read_prop s = read_cterm proto_sign (s, propT);
   411 
   412 fun store_thm name thm = PureThy.smart_store_thm (name, standard thm);
   413 
   414 val reflexive_thm =
   415   let val cx = cterm_of proto_sign (Var(("x",0),TVar(("'a",0),logicS)))
   416   in store_thm "reflexive" (Thm.reflexive cx) end;
   417 
   418 val symmetric_thm =
   419   let val xy = read_prop "x::'a::logic == y"
   420   in store_thm "symmetric" 
   421       (Thm.implies_intr_hyps(Thm.symmetric(Thm.assume xy)))
   422    end;
   423 
   424 val transitive_thm =
   425   let val xy = read_prop "x::'a::logic == y"
   426       val yz = read_prop "y::'a::logic == z"
   427       val xythm = Thm.assume xy and yzthm = Thm.assume yz
   428   in store_thm "transitive" (Thm.implies_intr yz (Thm.transitive xythm yzthm))
   429   end;
   430 
   431 fun symmetric_fun thm = thm RS symmetric_thm;
   432 
   433 (** Below, a "conversion" has type cterm -> thm **)
   434 
   435 val refl_implies = reflexive (cterm_of proto_sign implies);
   436 
   437 (*In [A1,...,An]==>B, rewrite the selected A's only -- for rewrite_goals_tac*)
   438 (*Do not rewrite flex-flex pairs*)
   439 fun goals_conv pred cv =
   440   let fun gconv i ct =
   441         let val (A,B) = dest_implies ct
   442             val (thA,j) = case term_of A of
   443                   Const("=?=",_)$_$_ => (reflexive A, i)
   444                 | _ => (if pred i then cv A else reflexive A, i+1)
   445         in  combination (combination refl_implies thA) (gconv j B) end
   446         handle TERM _ => reflexive ct
   447   in gconv 1 end;
   448 
   449 (*Use a conversion to transform a theorem*)
   450 fun fconv_rule cv th = equal_elim (cv (cprop_of th)) th;
   451 
   452 (*rewriting conversion*)
   453 fun rew_conv mode prover mss = rewrite_cterm mode mss prover;
   454 
   455 (*Rewrite a theorem*)
   456 fun rewrite_rule_aux _ []   th = th
   457   | rewrite_rule_aux prover thms th =
   458       fconv_rule (rew_conv (true,false,false) prover (Thm.mss_of thms)) th;
   459 
   460 fun rewrite_thm mode prover mss = fconv_rule (rew_conv mode prover mss);
   461 fun rewrite_cterm mode prover mss = Thm.rewrite_cterm mode mss prover;
   462 
   463 (*Rewrite the subgoals of a proof state (represented by a theorem) *)
   464 fun rewrite_goals_rule_aux _ []   th = th
   465   | rewrite_goals_rule_aux prover thms th =
   466       fconv_rule (goals_conv (K true) (rew_conv (true, true, false) prover
   467         (Thm.mss_of thms))) th;
   468 
   469 (*Rewrite the subgoal of a proof state (represented by a theorem) *)
   470 fun rewrite_goal_rule mode prover mss i thm =
   471   if 0 < i  andalso  i <= nprems_of thm
   472   then fconv_rule (goals_conv (fn j => j=i) (rew_conv mode prover mss)) thm
   473   else raise THM("rewrite_goal_rule",i,[thm]);
   474 
   475 
   476 (** Derived rules mainly for METAHYPS **)
   477 
   478 (*Given the term "a", takes (%x.t)==(%x.u) to t[a/x]==u[a/x]*)
   479 fun equal_abs_elim ca eqth =
   480   let val {sign=signa, t=a, ...} = rep_cterm ca
   481       and combth = combination eqth (reflexive ca)
   482       val {sign,prop,...} = rep_thm eqth
   483       val (abst,absu) = Logic.dest_equals prop
   484       val cterm = cterm_of (Sign.merge (sign,signa))
   485   in  transitive (symmetric (beta_conversion (cterm (abst$a))))
   486            (transitive combth (beta_conversion (cterm (absu$a))))
   487   end
   488   handle THM _ => raise THM("equal_abs_elim", 0, [eqth]);
   489 
   490 (*Calling equal_abs_elim with multiple terms*)
   491 fun equal_abs_elim_list cts th = foldr (uncurry equal_abs_elim) (rev cts, th);
   492 
   493 local
   494   val alpha = TVar(("'a",0), [])     (*  type ?'a::{}  *)
   495   fun err th = raise THM("flexpair_inst: ", 0, [th])
   496   fun flexpair_inst def th =
   497     let val {prop = Const _ $ t $ u,  sign,...} = rep_thm th
   498         val cterm = cterm_of sign
   499         fun cvar a = cterm(Var((a,0),alpha))
   500         val def' = cterm_instantiate [(cvar"t", cterm t), (cvar"u", cterm u)]
   501                    def
   502     in  equal_elim def' th
   503     end
   504     handle THM _ => err th | bind => err th
   505 in
   506 val flexpair_intr = flexpair_inst (symmetric ProtoPure.flexpair_def)
   507 and flexpair_elim = flexpair_inst ProtoPure.flexpair_def
   508 end;
   509 
   510 (*Version for flexflex pairs -- this supports lifting.*)
   511 fun flexpair_abs_elim_list cts =
   512     flexpair_intr o equal_abs_elim_list cts o flexpair_elim;
   513 
   514 
   515 (*** Some useful meta-theorems ***)
   516 
   517 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   518 val asm_rl =
   519   store_thm "asm_rl" (trivial(read_prop "PROP ?psi"));
   520 
   521 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   522 val cut_rl =
   523   store_thm "cut_rl"
   524     (trivial(read_prop "PROP ?psi ==> PROP ?theta"));
   525 
   526 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   527      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   528 val revcut_rl =
   529   let val V = read_prop "PROP V"
   530       and VW = read_prop "PROP V ==> PROP W";
   531   in
   532     store_thm "revcut_rl"
   533       (implies_intr V (implies_intr VW (implies_elim (assume VW) (assume V))))
   534   end;
   535 
   536 (*for deleting an unwanted assumption*)
   537 val thin_rl =
   538   let val V = read_prop "PROP V"
   539       and W = read_prop "PROP W";
   540   in  store_thm "thin_rl" (implies_intr V (implies_intr W (assume W)))
   541   end;
   542 
   543 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   544 val triv_forall_equality =
   545   let val V  = read_prop "PROP V"
   546       and QV = read_prop "!!x::'a. PROP V"
   547       and x  = read_cterm proto_sign ("x", TFree("'a",logicS));
   548   in
   549     store_thm "triv_forall_equality"
   550       (equal_intr (implies_intr QV (forall_elim x (assume QV)))
   551         (implies_intr V  (forall_intr x (assume V))))
   552   end;
   553 
   554 (* (PROP ?PhiA ==> PROP ?PhiB ==> PROP ?Psi) ==>
   555    (PROP ?PhiB ==> PROP ?PhiA ==> PROP ?Psi)
   556    `thm COMP swap_prems_rl' swaps the first two premises of `thm'
   557 *)
   558 val swap_prems_rl =
   559   let val cmajor = read_prop "PROP PhiA ==> PROP PhiB ==> PROP Psi";
   560       val major = assume cmajor;
   561       val cminor1 = read_prop "PROP PhiA";
   562       val minor1 = assume cminor1;
   563       val cminor2 = read_prop "PROP PhiB";
   564       val minor2 = assume cminor2;
   565   in store_thm "swap_prems_rl"
   566        (implies_intr cmajor (implies_intr cminor2 (implies_intr cminor1
   567          (implies_elim (implies_elim major minor1) minor2))))
   568   end;
   569 
   570 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   571    ==> PROP ?phi == PROP ?psi
   572    Introduction rule for == as a meta-theorem.  
   573 *)
   574 val equal_intr_rule =
   575   let val PQ = read_prop "PROP phi ==> PROP psi"
   576       and QP = read_prop "PROP psi ==> PROP phi"
   577   in
   578     store_thm "equal_intr_rule"
   579       (implies_intr PQ (implies_intr QP (equal_intr (assume PQ) (assume QP))))
   580   end;
   581 
   582 
   583 (* GOAL (PROP A) <==> PROP A *)
   584 
   585 local
   586   val A = read_prop "PROP A";
   587   val G = read_prop "GOAL (PROP A)";
   588   val (G_def, _) = freeze_thaw ProtoPure.Goal_def;
   589 in
   590   val triv_goal = store_thm "triv_goal" (Thm.equal_elim (Thm.symmetric G_def) (Thm.assume A));
   591   val rev_triv_goal = store_thm "rev_triv_goal" (Thm.equal_elim G_def (Thm.assume G));
   592 end;
   593 
   594 
   595 
   596 (** variations on instantiate **)
   597 
   598 (* collect vars *)
   599 
   600 val add_tvarsT = foldl_atyps (fn (vs, TVar v) => v ins vs | (vs, _) => vs);
   601 val add_tvars = foldl_types add_tvarsT;
   602 val add_vars = foldl_aterms (fn (vs, Var v) => v ins vs | (vs, _) => vs);
   603 
   604 fun tvars_of thm = rev (add_tvars ([], #prop (Thm.rep_thm thm)));
   605 fun vars_of thm = rev (add_vars ([], #prop (Thm.rep_thm thm)));
   606 
   607 
   608 (* instantiate by left-to-right occurrence of variables *)
   609 
   610 fun instantiate' cTs cts thm =
   611   let
   612     fun err msg =
   613       raise TYPE ("instantiate': " ^ msg,
   614         mapfilter (apsome Thm.typ_of) cTs,
   615         mapfilter (apsome Thm.term_of) cts);
   616 
   617     fun inst_of (v, ct) =
   618       (Thm.cterm_of (#sign (Thm.rep_cterm ct)) (Var v), ct)
   619         handle TYPE (msg, _, _) => err msg;
   620 
   621     fun zip_vars _ [] = []
   622       | zip_vars (_ :: vs) (None :: opt_ts) = zip_vars vs opt_ts
   623       | zip_vars (v :: vs) (Some t :: opt_ts) = (v, t) :: zip_vars vs opt_ts
   624       | zip_vars [] _ = err "more instantiations than variables in thm";
   625 
   626     (*instantiate types first!*)
   627     val thm' =
   628       if forall is_none cTs then thm
   629       else Thm.instantiate (zip_vars (map fst (tvars_of thm)) cTs, []) thm;
   630     in
   631       if forall is_none cts then thm'
   632       else Thm.instantiate ([], map inst_of (zip_vars (vars_of thm') cts)) thm'
   633     end;
   634 
   635 
   636 (* unvarify(T) *)
   637 
   638 (*assume thm in standard form, i.e. no frees, 0 var indexes*)
   639 
   640 fun unvarifyT thm =
   641   let
   642     val cT = Thm.ctyp_of (Thm.sign_of_thm thm);
   643     val tfrees = map (fn ((x, _), S) => Some (cT (TFree (x, S)))) (tvars_of thm);
   644   in instantiate' tfrees [] thm end;
   645 
   646 fun unvarify raw_thm =
   647   let
   648     val thm = unvarifyT raw_thm;
   649     val ct = Thm.cterm_of (Thm.sign_of_thm thm);
   650     val frees = map (fn ((x, _), T) => Some (ct (Free (x, T)))) (vars_of thm);
   651   in instantiate' [] frees thm end;
   652 
   653 
   654 (* mk_triv_goal *)
   655 
   656 (*make an initial proof state, "PROP A ==> (PROP A)" *)
   657 fun mk_triv_goal ct = instantiate' [] [Some ct] triv_goal;
   658 
   659 
   660 end;
   661 
   662 open Drule;