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