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