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