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