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