src/Pure/drule.ML
author wenzelm
Mon Nov 26 18:33:21 2001 +0100 (2001-11-26 ago)
changeset 12297 2ce7b42b0a64
parent 12283 d42aa776889e
child 12373 704e50ab65af
permissions -rw-r--r--
added remdups_rl;
     1 (*  Title:      Pure/drule.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1993  University of Cambridge
     5 
     6 Derived rules and other operations on theorems.
     7 *)
     8 
     9 infix 0 RS RSN RL RLN MRS MRL OF COMP;
    10 
    11 signature BASIC_DRULE =
    12 sig
    13   val mk_implies        : cterm * cterm -> cterm
    14   val list_implies      : cterm list * cterm -> cterm
    15   val dest_implies      : cterm -> cterm * cterm
    16   val dest_equals       : cterm -> cterm * cterm
    17   val skip_flexpairs    : cterm -> cterm
    18   val strip_imp_prems   : cterm -> cterm list
    19   val strip_imp_concl   : cterm -> cterm
    20   val cprems_of         : thm -> cterm list
    21   val read_insts        :
    22           Sign.sg -> (indexname -> typ option) * (indexname -> sort option)
    23                   -> (indexname -> typ option) * (indexname -> sort option)
    24                   -> string list -> (string*string)list
    25                   -> (indexname*ctyp)list * (cterm*cterm)list
    26   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    27   val strip_shyps_warning : thm -> thm
    28   val forall_intr_list  : cterm list -> thm -> thm
    29   val forall_intr_frees : thm -> thm
    30   val forall_intr_vars  : thm -> thm
    31   val forall_elim_list  : cterm list -> thm -> thm
    32   val forall_elim_var   : int -> thm -> thm
    33   val forall_elim_vars  : int -> thm -> thm
    34   val forall_elim_vars_safe  : thm -> thm
    35   val freeze_thaw       : thm -> thm * (thm -> thm)
    36   val implies_elim_list : thm -> thm list -> thm
    37   val implies_intr_list : cterm list -> thm -> thm
    38   val instantiate       :
    39     (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
    40   val zero_var_indexes  : thm -> thm
    41   val standard          : thm -> thm
    42   val standard'         : thm -> thm
    43   val rotate_prems      : int -> thm -> thm
    44   val rearrange_prems   : int list -> thm -> thm
    45   val assume_ax         : theory -> string -> thm
    46   val RSN               : thm * (int * thm) -> thm
    47   val RS                : thm * thm -> thm
    48   val RLN               : thm list * (int * thm list) -> thm list
    49   val RL                : thm list * thm list -> thm list
    50   val MRS               : thm list * thm -> thm
    51   val MRL               : thm list list * thm list -> thm list
    52   val OF                : thm * thm list -> thm
    53   val compose           : thm * int * thm -> thm list
    54   val COMP              : thm * thm -> thm
    55   val read_instantiate_sg: Sign.sg -> (string*string)list -> thm -> thm
    56   val read_instantiate  : (string*string)list -> thm -> thm
    57   val cterm_instantiate : (cterm*cterm)list -> thm -> thm
    58   val weak_eq_thm       : thm * thm -> bool
    59   val eq_thm_sg         : thm * thm -> bool
    60   val size_of_thm       : thm -> int
    61   val reflexive_thm     : thm
    62   val symmetric_thm     : thm
    63   val transitive_thm    : thm
    64   val refl_implies      : thm
    65   val symmetric_fun     : thm -> thm
    66   val extensional       : thm -> thm
    67   val imp_cong          : thm
    68   val swap_prems_eq     : thm
    69   val equal_abs_elim    : cterm  -> thm -> thm
    70   val equal_abs_elim_list: cterm list -> thm -> thm
    71   val flexpair_abs_elim_list: cterm list -> thm -> thm
    72   val asm_rl            : thm
    73   val cut_rl            : thm
    74   val revcut_rl         : thm
    75   val thin_rl           : thm
    76   val triv_forall_equality: thm
    77   val swap_prems_rl     : thm
    78   val equal_intr_rule   : thm
    79   val inst              : string -> string -> thm -> thm
    80   val instantiate'      : ctyp option list -> cterm option list -> thm -> thm
    81   val incr_indexes_wrt  : int list -> ctyp list -> cterm list -> thm list -> thm -> thm
    82 end;
    83 
    84 signature DRULE =
    85 sig
    86   include BASIC_DRULE
    87   val rule_attribute: ('a -> thm -> thm) -> 'a attribute
    88   val tag_rule: tag -> thm -> thm
    89   val untag_rule: string -> thm -> thm
    90   val tag: tag -> 'a attribute
    91   val untag: string -> 'a attribute
    92   val get_kind: thm -> string
    93   val kind: string -> 'a attribute
    94   val theoremK: string
    95   val lemmaK: string
    96   val corollaryK: string
    97   val internalK: string
    98   val kind_internal: 'a attribute
    99   val has_internal: tag list -> bool
   100   val impose_hyps: cterm list -> thm -> thm
   101   val close_derivation: thm -> thm
   102   val local_standard: thm -> thm
   103   val compose_single: thm * int * thm -> thm
   104   val add_rules: thm list -> thm list -> thm list
   105   val del_rules: thm list -> thm list -> thm list
   106   val merge_rules: thm list * thm list -> thm list
   107   val norm_hhf_eq: thm
   108   val triv_goal: thm
   109   val rev_triv_goal: thm
   110   val implies_intr_goals: cterm list -> thm -> thm
   111   val freeze_all: thm -> thm
   112   val mk_triv_goal: cterm -> thm
   113   val add_tvarsT: (indexname * sort) list * typ -> (indexname * sort) list
   114   val add_tvars: (indexname * sort) list * term -> (indexname * sort) list
   115   val add_vars: (indexname * typ) list * term -> (indexname * typ) list
   116   val add_frees: (string * typ) list * term -> (string * typ) list
   117   val tvars_of_terms: term list -> (indexname * sort) list
   118   val vars_of_terms: term list -> (indexname * typ) list
   119   val tvars_of: thm -> (indexname * sort) list
   120   val vars_of: thm -> (indexname * typ) list
   121   val unvarifyT: thm -> thm
   122   val unvarify: thm -> thm
   123   val tvars_intr_list: string list -> thm -> thm
   124   val remdups_rl: thm
   125   val conj_intr: thm -> thm -> thm
   126   val conj_intr_list: thm list -> thm
   127   val conj_elim: thm -> thm * thm
   128   val conj_elim_list: thm -> thm list
   129   val conj_elim_precise: int -> thm -> thm list
   130   val conj_intr_thm: thm
   131 end;
   132 
   133 structure Drule: DRULE =
   134 struct
   135 
   136 
   137 (** some cterm->cterm operations: much faster than calling cterm_of! **)
   138 
   139 (** SAME NAMES as in structure Logic: use compound identifiers! **)
   140 
   141 (*dest_implies for cterms. Note T=prop below*)
   142 fun dest_implies ct =
   143     case term_of ct of
   144         (Const("==>", _) $ _ $ _) =>
   145             let val (ct1,ct2) = Thm.dest_comb ct
   146             in  (#2 (Thm.dest_comb ct1), ct2)  end
   147       | _ => raise TERM ("dest_implies", [term_of ct]) ;
   148 
   149 fun dest_equals ct =
   150     case term_of ct of
   151         (Const("==", _) $ _ $ _) =>
   152             let val (ct1,ct2) = Thm.dest_comb ct
   153             in  (#2 (Thm.dest_comb ct1), ct2)  end
   154       | _ => raise TERM ("dest_equals", [term_of ct]) ;
   155 
   156 
   157 (*Discard flexflex pairs; return a cterm*)
   158 fun skip_flexpairs ct =
   159     case term_of ct of
   160         (Const("==>", _) $ (Const("=?=",_)$_$_) $ _) =>
   161             skip_flexpairs (#2 (dest_implies ct))
   162       | _ => ct;
   163 
   164 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   165 fun strip_imp_prems ct =
   166     let val (cA,cB) = dest_implies ct
   167     in  cA :: strip_imp_prems cB  end
   168     handle TERM _ => [];
   169 
   170 (* A1==>...An==>B  goes to B, where B is not an implication *)
   171 fun strip_imp_concl ct =
   172     case term_of ct of (Const("==>", _) $ _ $ _) =>
   173         strip_imp_concl (#2 (Thm.dest_comb ct))
   174   | _ => ct;
   175 
   176 (*The premises of a theorem, as a cterm list*)
   177 val cprems_of = strip_imp_prems o skip_flexpairs o cprop_of;
   178 
   179 val proto_sign = Theory.sign_of ProtoPure.thy;
   180 
   181 val implies = cterm_of proto_sign Term.implies;
   182 
   183 (*cterm version of mk_implies*)
   184 fun mk_implies(A,B) = Thm.capply (Thm.capply implies A) B;
   185 
   186 (*cterm version of list_implies: [A1,...,An], B  goes to [|A1;==>;An|]==>B *)
   187 fun list_implies([], B) = B
   188   | list_implies(A::AS, B) = mk_implies (A, list_implies(AS,B));
   189 
   190 
   191 (** reading of instantiations **)
   192 
   193 fun absent ixn =
   194   error("No such variable in term: " ^ Syntax.string_of_vname ixn);
   195 
   196 fun inst_failure ixn =
   197   error("Instantiation of " ^ Syntax.string_of_vname ixn ^ " fails");
   198 
   199 fun read_insts sign (rtypes,rsorts) (types,sorts) used insts =
   200 let
   201     fun split([],tvs,vs) = (tvs,vs)
   202       | split((sv,st)::l,tvs,vs) = (case Symbol.explode sv of
   203                   "'"::cs => split(l,(Syntax.indexname cs,st)::tvs,vs)
   204                 | cs => split(l,tvs,(Syntax.indexname cs,st)::vs));
   205     val (tvs,vs) = split(insts,[],[]);
   206     fun readT((a,i),st) =
   207         let val ixn = ("'" ^ a,i);
   208             val S = case rsorts ixn of Some S => S | None => absent ixn;
   209             val T = Sign.read_typ (sign,sorts) st;
   210         in if Sign.typ_instance sign (T, TVar(ixn,S)) then (ixn,T)
   211            else inst_failure ixn
   212         end
   213     val tye = map readT tvs;
   214     fun mkty(ixn,st) = (case rtypes ixn of
   215                           Some T => (ixn,(st,typ_subst_TVars tye T))
   216                         | None => absent ixn);
   217     val ixnsTs = map mkty vs;
   218     val ixns = map fst ixnsTs
   219     and sTs  = map snd ixnsTs
   220     val (cts,tye2) = read_def_cterms(sign,types,sorts) used false sTs;
   221     fun mkcVar(ixn,T) =
   222         let val U = typ_subst_TVars tye2 T
   223         in cterm_of sign (Var(ixn,U)) end
   224     val ixnTs = ListPair.zip(ixns, map snd sTs)
   225 in (map (fn (ixn,T) => (ixn,ctyp_of sign T)) (tye2 @ tye),
   226     ListPair.zip(map mkcVar ixnTs,cts))
   227 end;
   228 
   229 
   230 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   231      Used for establishing default types (of variables) and sorts (of
   232      type variables) when reading another term.
   233      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   234 ***)
   235 
   236 fun types_sorts thm =
   237     let val {prop,hyps,...} = rep_thm thm;
   238         val big = list_comb(prop,hyps); (* bogus term! *)
   239         val vars = map dest_Var (term_vars big);
   240         val frees = map dest_Free (term_frees big);
   241         val tvars = term_tvars big;
   242         val tfrees = term_tfrees big;
   243         fun typ(a,i) = if i<0 then assoc(frees,a) else assoc(vars,(a,i));
   244         fun sort(a,i) = if i<0 then assoc(tfrees,a) else assoc(tvars,(a,i));
   245     in (typ,sort) end;
   246 
   247 
   248 
   249 (** basic attributes **)
   250 
   251 (* dependent rules *)
   252 
   253 fun rule_attribute f (x, thm) = (x, (f x thm));
   254 
   255 
   256 (* add / delete tags *)
   257 
   258 fun map_tags f thm =
   259   Thm.put_name_tags (Thm.name_of_thm thm, f (#2 (Thm.get_name_tags thm))) thm;
   260 
   261 fun tag_rule tg = map_tags (fn tgs => if tg mem tgs then tgs else tgs @ [tg]);
   262 fun untag_rule s = map_tags (filter_out (equal s o #1));
   263 
   264 fun tag tg x = rule_attribute (K (tag_rule tg)) x;
   265 fun untag s x = rule_attribute (K (untag_rule s)) x;
   266 
   267 fun simple_tag name x = tag (name, []) x;
   268 
   269 
   270 (* theorem kinds *)
   271 
   272 val theoremK = "theorem";
   273 val lemmaK = "lemma";
   274 val corollaryK = "corollary";
   275 val internalK = "internal";
   276 
   277 fun get_kind thm =
   278   (case Library.assoc (#2 (Thm.get_name_tags thm), "kind") of
   279     Some (k :: _) => k
   280   | _ => "unknown");
   281 
   282 fun kind_rule k = tag_rule ("kind", [k]) o untag_rule "kind";
   283 fun kind k x = rule_attribute (K (kind_rule k)) x;
   284 fun kind_internal x = kind internalK x;
   285 fun has_internal tags = exists (equal internalK o fst) tags;
   286 
   287 
   288 
   289 (** Standardization of rules **)
   290 
   291 (*Strip extraneous shyps as far as possible*)
   292 fun strip_shyps_warning thm =
   293   let
   294     val str_of_sort = Sign.str_of_sort (Thm.sign_of_thm thm);
   295     val thm' = Thm.strip_shyps thm;
   296     val xshyps = Thm.extra_shyps thm';
   297   in
   298     if null xshyps then ()
   299     else warning ("Pending sort hypotheses: " ^ commas (map str_of_sort xshyps));
   300     thm'
   301   end;
   302 
   303 (*Generalization over a list of variables, IGNORING bad ones*)
   304 fun forall_intr_list [] th = th
   305   | forall_intr_list (y::ys) th =
   306         let val gth = forall_intr_list ys th
   307         in  forall_intr y gth   handle THM _ =>  gth  end;
   308 
   309 (*Generalization over all suitable Free variables*)
   310 fun forall_intr_frees th =
   311     let val {prop,sign,...} = rep_thm th
   312     in  forall_intr_list
   313          (map (cterm_of sign) (sort (make_ord atless) (term_frees prop)))
   314          th
   315     end;
   316 
   317 val forall_elim_var = PureThy.forall_elim_var;
   318 val forall_elim_vars = PureThy.forall_elim_vars;
   319 
   320 fun forall_elim_vars_safe th =
   321   forall_elim_vars_safe (forall_elim_var (#maxidx (Thm.rep_thm th) + 1) th)
   322     handle THM _ => th;
   323 
   324 
   325 (*Specialization over a list of cterms*)
   326 fun forall_elim_list cts th = foldr (uncurry forall_elim) (rev cts, th);
   327 
   328 (* maps A1,...,An |- B   to   [| A1;...;An |] ==> B  *)
   329 fun implies_intr_list cAs th = foldr (uncurry implies_intr) (cAs,th);
   330 
   331 (* maps [| A1;...;An |] ==> B and [A1,...,An]   to   B *)
   332 fun implies_elim_list impth ths = foldl (uncurry implies_elim) (impth,ths);
   333 
   334 (* maps |- B to A1,...,An |- B *)
   335 fun impose_hyps chyps th =
   336   let val chyps' = gen_rems (op aconv o apfst Thm.term_of) (chyps, #hyps (Thm.rep_thm th))
   337   in implies_elim_list (implies_intr_list chyps' th) (map Thm.assume chyps') end;
   338 
   339 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   340 fun zero_var_indexes th =
   341     let val {prop,sign,...} = rep_thm th;
   342         val vars = term_vars prop
   343         val bs = foldl add_new_id ([], map (fn Var((a,_),_)=>a) vars)
   344         val inrs = add_term_tvars(prop,[]);
   345         val nms' = rev(foldl add_new_id ([], map (#1 o #1) inrs));
   346         val tye = ListPair.map (fn ((v,rs),a) => (v, TVar((a,0),rs)))
   347                      (inrs, nms')
   348         val ctye = map (fn (v,T) => (v,ctyp_of sign T)) tye;
   349         fun varpairs([],[]) = []
   350           | varpairs((var as Var(v,T)) :: vars, b::bs) =
   351                 let val T' = typ_subst_TVars tye T
   352                 in (cterm_of sign (Var(v,T')),
   353                     cterm_of sign (Var((b,0),T'))) :: varpairs(vars,bs)
   354                 end
   355           | varpairs _ = raise TERM("varpairs", []);
   356     in Thm.instantiate (ctye, varpairs(vars,rev bs)) th end;
   357 
   358 
   359 (*Standard form of object-rule: no hypotheses, Frees, or outer quantifiers;
   360     all generality expressed by Vars having index 0.*)
   361 
   362 fun close_derivation thm =
   363   if Thm.get_name_tags thm = ("", []) then Thm.name_thm ("", thm)
   364   else thm;
   365 
   366 fun standard' th =
   367   let val {maxidx,...} = rep_thm th in
   368     th
   369     |> implies_intr_hyps
   370     |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
   371     |> strip_shyps_warning
   372     |> zero_var_indexes |> Thm.varifyT |> Thm.compress
   373   end;
   374 
   375 val standard = close_derivation o standard';
   376 
   377 fun local_standard th =
   378   th |> strip_shyps |> zero_var_indexes
   379   |> Thm.compress |> close_derivation;
   380 
   381 
   382 (*Convert all Vars in a theorem to Frees.  Also return a function for
   383   reversing that operation.  DOES NOT WORK FOR TYPE VARIABLES.
   384   Similar code in type/freeze_thaw*)
   385 fun freeze_thaw th =
   386  let val fth = freezeT th
   387      val {prop,sign,...} = rep_thm fth
   388  in
   389    case term_vars prop of
   390        [] => (fth, fn x => x)
   391      | vars =>
   392          let fun newName (Var(ix,_), (pairs,used)) =
   393                    let val v = variant used (string_of_indexname ix)
   394                    in  ((ix,v)::pairs, v::used)  end;
   395              val (alist, _) = foldr newName
   396                                 (vars, ([], add_term_names (prop, [])))
   397              fun mk_inst (Var(v,T)) =
   398                  (cterm_of sign (Var(v,T)),
   399                   cterm_of sign (Free(the (assoc(alist,v)), T)))
   400              val insts = map mk_inst vars
   401              fun thaw th' =
   402                  th' |> forall_intr_list (map #2 insts)
   403                      |> forall_elim_list (map #1 insts)
   404          in  (Thm.instantiate ([],insts) fth, thaw)  end
   405  end;
   406 
   407 
   408 (*Rotates a rule's premises to the left by k*)
   409 val rotate_prems = permute_prems 0;
   410 
   411 (* permute prems, where the i-th position in the argument list (counting from 0)
   412    gives the position within the original thm to be transferred to position i.
   413    Any remaining trailing positions are left unchanged. *)
   414 val rearrange_prems = let
   415   fun rearr new []      thm = thm
   416   |   rearr new (p::ps) thm = rearr (new+1)
   417      (map (fn q => if new<=q andalso q<p then q+1 else q) ps)
   418      (permute_prems (new+1) (new-p) (permute_prems new (p-new) thm))
   419   in rearr 0 end;
   420 
   421 (*Assume a new formula, read following the same conventions as axioms.
   422   Generalizes over Free variables,
   423   creates the assumption, and then strips quantifiers.
   424   Example is [| ALL x:?A. ?P(x) |] ==> [| ?P(?a) |]
   425              [ !(A,P,a)[| ALL x:A. P(x) |] ==> [| P(a) |] ]    *)
   426 fun assume_ax thy sP =
   427     let val sign = Theory.sign_of thy
   428         val prop = Logic.close_form (term_of (read_cterm sign (sP, propT)))
   429     in forall_elim_vars 0 (assume (cterm_of sign prop))  end;
   430 
   431 (*Resolution: exactly one resolvent must be produced.*)
   432 fun tha RSN (i,thb) =
   433   case Seq.chop (2, biresolution false [(false,tha)] i thb) of
   434       ([th],_) => th
   435     | ([],_)   => raise THM("RSN: no unifiers", i, [tha,thb])
   436     |      _   => raise THM("RSN: multiple unifiers", i, [tha,thb]);
   437 
   438 (*resolution: P==>Q, Q==>R gives P==>R. *)
   439 fun tha RS thb = tha RSN (1,thb);
   440 
   441 (*For joining lists of rules*)
   442 fun thas RLN (i,thbs) =
   443   let val resolve = biresolution false (map (pair false) thas) i
   444       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   445   in  List.concat (map resb thbs)  end;
   446 
   447 fun thas RL thbs = thas RLN (1,thbs);
   448 
   449 (*Resolve a list of rules against bottom_rl from right to left;
   450   makes proof trees*)
   451 fun rls MRS bottom_rl =
   452   let fun rs_aux i [] = bottom_rl
   453         | rs_aux i (rl::rls) = rl RSN (i, rs_aux (i+1) rls)
   454   in  rs_aux 1 rls  end;
   455 
   456 (*As above, but for rule lists*)
   457 fun rlss MRL bottom_rls =
   458   let fun rs_aux i [] = bottom_rls
   459         | rs_aux i (rls::rlss) = rls RLN (i, rs_aux (i+1) rlss)
   460   in  rs_aux 1 rlss  end;
   461 
   462 (*A version of MRS with more appropriate argument order*)
   463 fun bottom_rl OF rls = rls MRS bottom_rl;
   464 
   465 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   466   with no lifting or renaming!  Q may contain ==> or meta-quants
   467   ALWAYS deletes premise i *)
   468 fun compose(tha,i,thb) =
   469     Seq.list_of (bicompose false (false,tha,0) i thb);
   470 
   471 fun compose_single (tha,i,thb) =
   472   (case compose (tha,i,thb) of
   473     [th] => th
   474   | _ => raise THM ("compose: unique result expected", i, [tha,thb]));
   475 
   476 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   477 fun tha COMP thb =
   478     case compose(tha,1,thb) of
   479         [th] => th
   480       | _ =>   raise THM("COMP", 1, [tha,thb]);
   481 
   482 (** theorem equality **)
   483 
   484 (*Do the two theorems have the same signature?*)
   485 fun eq_thm_sg (th1,th2) = Sign.eq_sg(#sign(rep_thm th1), #sign(rep_thm th2));
   486 
   487 (*Useful "distance" function for BEST_FIRST*)
   488 val size_of_thm = size_of_term o #prop o rep_thm;
   489 
   490 (*maintain lists of theorems --- preserving canonical order*)
   491 fun del_rules rs rules = Library.gen_rems Thm.eq_thm (rules, rs);
   492 fun add_rules rs rules = rs @ del_rules rs rules;
   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')) maxi tye (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 *)
   794 
   795 val add_tvarsT = foldl_atyps (fn (vs, TVar v) => v ins vs | (vs, _) => vs);
   796 val add_tvars = foldl_types add_tvarsT;
   797 val add_vars = foldl_aterms (fn (vs, Var v) => v ins vs | (vs, _) => vs);
   798 val add_frees = foldl_aterms (fn (vs, Free v) => v ins vs | (vs, _) => vs);
   799 
   800 fun tvars_of_terms ts = rev (foldl add_tvars ([], ts));
   801 fun vars_of_terms ts = rev (foldl add_vars ([], ts));
   802 
   803 fun tvars_of thm = tvars_of_terms [#prop (Thm.rep_thm thm)];
   804 fun vars_of thm = vars_of_terms [#prop (Thm.rep_thm thm)];
   805 
   806 
   807 (* instantiate by left-to-right occurrence of variables *)
   808 
   809 fun instantiate' cTs cts thm =
   810   let
   811     fun err msg =
   812       raise TYPE ("instantiate': " ^ msg,
   813         mapfilter (apsome Thm.typ_of) cTs,
   814         mapfilter (apsome Thm.term_of) cts);
   815 
   816     fun inst_of (v, ct) =
   817       (Thm.cterm_of (#sign (Thm.rep_cterm ct)) (Var v), ct)
   818         handle TYPE (msg, _, _) => err msg;
   819 
   820     fun zip_vars _ [] = []
   821       | zip_vars (_ :: vs) (None :: opt_ts) = zip_vars vs opt_ts
   822       | zip_vars (v :: vs) (Some t :: opt_ts) = (v, t) :: zip_vars vs opt_ts
   823       | zip_vars [] _ = err "more instantiations than variables in thm";
   824 
   825     (*instantiate types first!*)
   826     val thm' =
   827       if forall is_none cTs then thm
   828       else Thm.instantiate (zip_vars (map fst (tvars_of thm)) cTs, []) thm;
   829     in
   830       if forall is_none cts then thm'
   831       else Thm.instantiate ([], map inst_of (zip_vars (vars_of thm') cts)) thm'
   832     end;
   833 
   834 
   835 (* unvarify(T) *)
   836 
   837 (*assume thm in standard form, i.e. no frees, 0 var indexes*)
   838 
   839 fun unvarifyT thm =
   840   let
   841     val cT = Thm.ctyp_of (Thm.sign_of_thm thm);
   842     val tfrees = map (fn ((x, _), S) => Some (cT (TFree (x, S)))) (tvars_of thm);
   843   in instantiate' tfrees [] thm end;
   844 
   845 fun unvarify raw_thm =
   846   let
   847     val thm = unvarifyT raw_thm;
   848     val ct = Thm.cterm_of (Thm.sign_of_thm thm);
   849     val frees = map (fn ((x, _), T) => Some (ct (Free (x, T)))) (vars_of thm);
   850   in instantiate' [] frees thm end;
   851 
   852 
   853 (* tvars_intr_list *)
   854 
   855 fun tfrees_of thm =
   856   let val {hyps, prop, ...} = Thm.rep_thm thm
   857   in foldr Term.add_term_tfree_names (prop :: hyps, []) end;
   858 
   859 fun tvars_intr_list tfrees thm =
   860   Thm.varifyT' (tfrees_of thm \\ tfrees) thm;
   861 
   862 
   863 (* increment var indexes *)
   864 
   865 fun incr_indexes_wrt is cTs cts thms =
   866   let
   867     val maxidx =
   868       foldl Int.max (~1, is @
   869         map (maxidx_of_typ o #T o Thm.rep_ctyp) cTs @
   870         map (#maxidx o Thm.rep_cterm) cts @
   871         map (#maxidx o Thm.rep_thm) thms);
   872   in Thm.incr_indexes (maxidx + 1) end;
   873 
   874 
   875 (* freeze_all *)
   876 
   877 (*freeze all (T)Vars; assumes thm in standard form*)
   878 
   879 fun freeze_all_TVars thm =
   880   (case tvars_of thm of
   881     [] => thm
   882   | tvars =>
   883       let val cert = Thm.ctyp_of (Thm.sign_of_thm thm)
   884       in instantiate' (map (fn ((x, _), S) => Some (cert (TFree (x, S)))) tvars) [] thm end);
   885 
   886 fun freeze_all_Vars thm =
   887   (case vars_of thm of
   888     [] => thm
   889   | vars =>
   890       let val cert = Thm.cterm_of (Thm.sign_of_thm thm)
   891       in instantiate' [] (map (fn ((x, _), T) => Some (cert (Free (x, T)))) vars) thm end);
   892 
   893 val freeze_all = freeze_all_Vars o freeze_all_TVars;
   894 
   895 
   896 (* mk_triv_goal *)
   897 
   898 (*make an initial proof state, "PROP A ==> (PROP A)" *)
   899 fun mk_triv_goal ct = instantiate' [] [Some ct] triv_goal;
   900 
   901 
   902 
   903 (** meta-level conjunction **)
   904 
   905 local
   906   val A = read_prop "PROP A";
   907   val B = read_prop "PROP B";
   908   val C = read_prop "PROP C";
   909   val ABC = read_prop "PROP A ==> PROP B ==> PROP C";
   910 
   911   val proj1 =
   912     forall_intr_list [A, B] (implies_intr_list [A, B] (Thm.assume A))
   913     |> forall_elim_vars 0;
   914 
   915   val proj2 =
   916     forall_intr_list [A, B] (implies_intr_list [A, B] (Thm.assume B))
   917     |> forall_elim_vars 0;
   918 
   919   val conj_intr_rule =
   920     forall_intr_list [A, B] (implies_intr_list [A, B]
   921       (Thm.forall_intr C (Thm.implies_intr ABC
   922         (implies_elim_list (Thm.assume ABC) [Thm.assume A, Thm.assume B]))))
   923     |> forall_elim_vars 0;
   924 
   925   val incr = incr_indexes_wrt [] [] [];
   926 in
   927 
   928 fun conj_intr tha thb = thb COMP (tha COMP incr [tha, thb] conj_intr_rule);
   929 val conj_intr_list = foldr1 (uncurry conj_intr);
   930 
   931 fun conj_elim th =
   932   let val th' = forall_elim_var (#maxidx (Thm.rep_thm th) + 1) th
   933   in (incr [th'] proj1 COMP th', incr [th'] proj2 COMP th') end;
   934 
   935 fun conj_elim_list th =
   936   let val (th1, th2) = conj_elim th
   937   in conj_elim_list th1 @ conj_elim_list th2 end handle THM _ => [th];
   938 
   939 fun conj_elim_precise 1 th = [th]
   940   | conj_elim_precise n th =
   941       let val (th1, th2) = conj_elim th
   942       in th1 :: conj_elim_precise (n - 1) th2 end;
   943 
   944 val conj_intr_thm = store_standard_thm_open "conjunctionI"
   945   (implies_intr_list [A, B] (conj_intr (Thm.assume A) (Thm.assume B)));
   946 
   947 end;
   948 
   949 end;
   950 
   951 structure BasicDrule: BASIC_DRULE = Drule;
   952 open BasicDrule;