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