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