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