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