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