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