src/Pure/drule.ML
author wenzelm
Sun Jul 30 12:48:55 2000 +0200 (2000-07-30)
changeset 9460 53d7ad5bec39
parent 9455 f23722b4fbe7
child 9547 8dad21f06b24
permissions -rw-r--r--
Logic.goal_const;
     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 dest_implies      : cterm -> cterm * cterm
    14   val skip_flexpairs    : cterm -> cterm
    15   val strip_imp_prems   : cterm -> cterm list
    16   val cprems_of         : thm -> cterm list
    17   val read_insts        :
    18           Sign.sg -> (indexname -> typ option) * (indexname -> sort option)
    19                   -> (indexname -> typ option) * (indexname -> sort option)
    20                   -> string list -> (string*string)list
    21                   -> (indexname*ctyp)list * (cterm*cterm)list
    22   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    23   val strip_shyps_warning : thm -> thm
    24   val forall_intr_list  : cterm list -> thm -> thm
    25   val forall_intr_frees : thm -> thm
    26   val forall_intr_vars  : thm -> thm
    27   val forall_elim_list  : cterm list -> thm -> thm
    28   val forall_elim_var   : int -> thm -> thm
    29   val forall_elim_vars  : int -> thm -> thm
    30   val freeze_thaw       : thm -> thm * (thm -> thm)
    31   val implies_elim_list : thm -> thm list -> thm
    32   val implies_intr_list : cterm list -> thm -> thm
    33   val instantiate       :
    34     (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
    35   val zero_var_indexes  : thm -> thm
    36   val standard          : thm -> thm
    37   val rotate_prems      : int -> thm -> thm
    38   val assume_ax         : theory -> string -> thm
    39   val RSN               : thm * (int * thm) -> thm
    40   val RS                : thm * thm -> thm
    41   val RLN               : thm list * (int * thm list) -> thm list
    42   val RL                : thm list * thm list -> thm list
    43   val MRS               : thm list * thm -> thm
    44   val MRL               : thm list list * thm list -> thm list
    45   val OF                : thm * thm list -> thm
    46   val compose           : thm * int * thm -> thm list
    47   val COMP              : thm * thm -> thm
    48   val read_instantiate_sg: Sign.sg -> (string*string)list -> thm -> thm
    49   val read_instantiate  : (string*string)list -> thm -> thm
    50   val cterm_instantiate : (cterm*cterm)list -> thm -> thm
    51   val weak_eq_thm       : thm * thm -> bool
    52   val eq_thm_sg         : thm * thm -> bool
    53   val size_of_thm       : thm -> int
    54   val reflexive_thm     : thm
    55   val symmetric_thm     : thm
    56   val transitive_thm    : thm
    57   val refl_implies      : thm
    58   val symmetric_fun     : thm -> thm
    59   val rewrite_rule_aux  : (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    60   val rewrite_thm       : bool * bool * bool
    61                           -> (meta_simpset -> thm -> thm option)
    62                           -> meta_simpset -> thm -> thm
    63   val rewrite_cterm     : bool * bool * bool
    64                           -> (meta_simpset -> thm -> thm option)
    65                           -> meta_simpset -> cterm -> thm
    66   val rewrite_goals_rule_aux: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    67   val rewrite_goal_rule : bool* bool * bool
    68                           -> (meta_simpset -> thm -> thm option)
    69                           -> meta_simpset -> int -> thm -> 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      : int -> thm -> thm
    83   val incr_indexes_wrt  : int list -> ctyp list -> cterm list -> thm list -> thm -> thm
    84 end;
    85 
    86 signature DRULE =
    87 sig
    88   include BASIC_DRULE
    89   val 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 tag_lemma         : 'a attribute
    95   val tag_assumption    : 'a attribute
    96   val tag_internal      : 'a attribute
    97   val has_internal	: tag list -> bool
    98   val compose_single    : thm * int * thm -> thm
    99   val merge_rules	: thm list * thm list -> thm list
   100   val triv_goal         : thm
   101   val rev_triv_goal     : thm
   102   val freeze_all        : thm -> thm
   103   val mk_triv_goal      : cterm -> thm
   104   val mk_cgoal          : cterm -> cterm
   105   val assume_goal       : cterm -> thm
   106   val tvars_of_terms    : term list -> (indexname * sort) list
   107   val vars_of_terms     : term list -> (indexname * typ) list
   108   val tvars_of          : thm -> (indexname * sort) list
   109   val vars_of           : thm -> (indexname * typ) list
   110   val unvarifyT         : thm -> thm
   111   val unvarify          : thm -> thm
   112   val tvars_intr_list	: string list -> thm -> thm
   113 end;
   114 
   115 structure Drule: DRULE =
   116 struct
   117 
   118 
   119 (** some cterm->cterm operations: much faster than calling cterm_of! **)
   120 
   121 (** SAME NAMES as in structure Logic: use compound identifiers! **)
   122 
   123 (*dest_implies for cterms. Note T=prop below*)
   124 fun dest_implies ct =
   125     case term_of ct of
   126         (Const("==>", _) $ _ $ _) =>
   127             let val (ct1,ct2) = dest_comb ct
   128             in  (#2 (dest_comb ct1), ct2)  end
   129       | _ => raise TERM ("dest_implies", [term_of ct]) ;
   130 
   131 
   132 (*Discard flexflex pairs; return a cterm*)
   133 fun skip_flexpairs ct =
   134     case term_of ct of
   135         (Const("==>", _) $ (Const("=?=",_)$_$_) $ _) =>
   136             skip_flexpairs (#2 (dest_implies ct))
   137       | _ => ct;
   138 
   139 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   140 fun strip_imp_prems ct =
   141     let val (cA,cB) = dest_implies ct
   142     in  cA :: strip_imp_prems cB  end
   143     handle TERM _ => [];
   144 
   145 (* A1==>...An==>B  goes to B, where B is not an implication *)
   146 fun strip_imp_concl ct =
   147     case term_of ct of (Const("==>", _) $ _ $ _) =>
   148         strip_imp_concl (#2 (dest_comb ct))
   149   | _ => ct;
   150 
   151 (*The premises of a theorem, as a cterm list*)
   152 val cprems_of = strip_imp_prems o skip_flexpairs o cprop_of;
   153 
   154 
   155 (** reading of instantiations **)
   156 
   157 fun absent ixn =
   158   error("No such variable in term: " ^ Syntax.string_of_vname ixn);
   159 
   160 fun inst_failure ixn =
   161   error("Instantiation of " ^ Syntax.string_of_vname ixn ^ " fails");
   162 
   163 fun read_insts sign (rtypes,rsorts) (types,sorts) used insts =
   164 let val {tsig,...} = Sign.rep_sg sign
   165     fun split([],tvs,vs) = (tvs,vs)
   166       | split((sv,st)::l,tvs,vs) = (case Symbol.explode sv of
   167                   "'"::cs => split(l,(Syntax.indexname cs,st)::tvs,vs)
   168                 | cs => split(l,tvs,(Syntax.indexname cs,st)::vs));
   169     val (tvs,vs) = split(insts,[],[]);
   170     fun readT((a,i),st) =
   171         let val ixn = ("'" ^ a,i);
   172             val S = case rsorts ixn of Some S => S | None => absent ixn;
   173             val T = Sign.read_typ (sign,sorts) st;
   174         in if Type.typ_instance(tsig,T,TVar(ixn,S)) then (ixn,T)
   175            else inst_failure ixn
   176         end
   177     val tye = map readT tvs;
   178     fun mkty(ixn,st) = (case rtypes ixn of
   179                           Some T => (ixn,(st,typ_subst_TVars tye T))
   180                         | None => absent ixn);
   181     val ixnsTs = map mkty vs;
   182     val ixns = map fst ixnsTs
   183     and sTs  = map snd ixnsTs
   184     val (cts,tye2) = read_def_cterms(sign,types,sorts) used false sTs;
   185     fun mkcVar(ixn,T) =
   186         let val U = typ_subst_TVars tye2 T
   187         in cterm_of sign (Var(ixn,U)) end
   188     val ixnTs = ListPair.zip(ixns, map snd sTs)
   189 in (map (fn (ixn,T) => (ixn,ctyp_of sign T)) (tye2 @ tye),
   190     ListPair.zip(map mkcVar ixnTs,cts))
   191 end;
   192 
   193 
   194 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   195      Used for establishing default types (of variables) and sorts (of
   196      type variables) when reading another term.
   197      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   198 ***)
   199 
   200 fun types_sorts thm =
   201     let val {prop,hyps,...} = rep_thm thm;
   202         val big = list_comb(prop,hyps); (* bogus term! *)
   203         val vars = map dest_Var (term_vars big);
   204         val frees = map dest_Free (term_frees big);
   205         val tvars = term_tvars big;
   206         val tfrees = term_tfrees big;
   207         fun typ(a,i) = if i<0 then assoc(frees,a) else assoc(vars,(a,i));
   208         fun sort(a,i) = if i<0 then assoc(tfrees,a) else assoc(tvars,(a,i));
   209     in (typ,sort) end;
   210 
   211 
   212 
   213 (** basic attributes **)
   214 
   215 (* dependent rules *)
   216 
   217 fun rule_attribute f (x, thm) = (x, (f x thm));
   218 
   219 
   220 (* add / delete tags *)
   221 
   222 fun map_tags f thm =
   223   Thm.put_name_tags (Thm.name_of_thm thm, f (#2 (Thm.get_name_tags thm))) thm;
   224 
   225 fun tag_rule tg = map_tags (fn tgs => if tg mem tgs then tgs else tgs @ [tg]);
   226 fun untag_rule s = map_tags (filter_out (equal s o #1));
   227 
   228 fun tag tg x = rule_attribute (K (tag_rule tg)) x;
   229 fun untag s x = rule_attribute (K (untag_rule s)) x;
   230 
   231 fun simple_tag name x = tag (name, []) x;
   232 
   233 fun tag_lemma x = simple_tag "lemma" x;
   234 fun tag_assumption x = simple_tag "assumption" x;
   235 
   236 val internal_tag = ("internal", []);
   237 fun tag_internal x = tag internal_tag x;
   238 fun has_internal tags = exists (equal internal_tag) tags;
   239 
   240 
   241 
   242 (** Standardization of rules **)
   243 
   244 (*Strip extraneous shyps as far as possible*)
   245 fun strip_shyps_warning thm =
   246   let
   247     val str_of_sort = Sign.str_of_sort (Thm.sign_of_thm thm);
   248     val thm' = Thm.strip_shyps thm;
   249     val xshyps = Thm.extra_shyps thm';
   250   in
   251     if null xshyps then ()
   252     else warning ("Pending sort hypotheses: " ^ commas (map str_of_sort xshyps));
   253     thm'
   254   end;
   255 
   256 (*Generalization over a list of variables, IGNORING bad ones*)
   257 fun forall_intr_list [] th = th
   258   | forall_intr_list (y::ys) th =
   259         let val gth = forall_intr_list ys th
   260         in  forall_intr y gth   handle THM _ =>  gth  end;
   261 
   262 (*Generalization over all suitable Free variables*)
   263 fun forall_intr_frees th =
   264     let val {prop,sign,...} = rep_thm th
   265     in  forall_intr_list
   266          (map (cterm_of sign) (sort (make_ord atless) (term_frees prop)))
   267          th
   268     end;
   269 
   270 val forall_elim_var = PureThy.forall_elim_var;
   271 val forall_elim_vars = PureThy.forall_elim_vars;
   272 
   273 (*Specialization over a list of cterms*)
   274 fun forall_elim_list cts th = foldr (uncurry forall_elim) (rev cts, th);
   275 
   276 (* maps [A1,...,An], B   to   [| A1;...;An |] ==> B  *)
   277 fun implies_intr_list cAs th = foldr (uncurry implies_intr) (cAs,th);
   278 
   279 (* maps [| A1;...;An |] ==> B and [A1,...,An]   to   B *)
   280 fun implies_elim_list impth ths = foldl (uncurry implies_elim) (impth,ths);
   281 
   282 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   283 fun zero_var_indexes th =
   284     let val {prop,sign,...} = rep_thm th;
   285         val vars = term_vars prop
   286         val bs = foldl add_new_id ([], map (fn Var((a,_),_)=>a) vars)
   287         val inrs = add_term_tvars(prop,[]);
   288         val nms' = rev(foldl add_new_id ([], map (#1 o #1) inrs));
   289         val tye = ListPair.map (fn ((v,rs),a) => (v, TVar((a,0),rs)))
   290                      (inrs, nms')
   291         val ctye = map (fn (v,T) => (v,ctyp_of sign T)) tye;
   292         fun varpairs([],[]) = []
   293           | varpairs((var as Var(v,T)) :: vars, b::bs) =
   294                 let val T' = typ_subst_TVars tye T
   295                 in (cterm_of sign (Var(v,T')),
   296                     cterm_of sign (Var((b,0),T'))) :: varpairs(vars,bs)
   297                 end
   298           | varpairs _ = raise TERM("varpairs", []);
   299     in Thm.instantiate (ctye, varpairs(vars,rev bs)) th end;
   300 
   301 
   302 (*Standard form of object-rule: no hypotheses, Frees, or outer quantifiers;
   303     all generality expressed by Vars having index 0.*)
   304 fun standard th =
   305   let val {maxidx,...} = rep_thm th
   306   in
   307     th |> implies_intr_hyps
   308        |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
   309        |> strip_shyps_warning
   310        |> zero_var_indexes |> Thm.varifyT |> Thm.compress
   311   end;
   312 
   313 
   314 (*Convert all Vars in a theorem to Frees.  Also return a function for
   315   reversing that operation.  DOES NOT WORK FOR TYPE VARIABLES.
   316   Similar code in type/freeze_thaw*)
   317 fun freeze_thaw th =
   318  let val fth = freezeT th
   319      val {prop,sign,...} = rep_thm fth
   320  in
   321    case term_vars prop of
   322        [] => (fth, fn x => x)
   323      | vars =>
   324          let fun newName (Var(ix,_), (pairs,used)) =
   325                    let val v = variant used (string_of_indexname ix)
   326                    in  ((ix,v)::pairs, v::used)  end;
   327              val (alist, _) = foldr newName
   328                                 (vars, ([], add_term_names (prop, [])))
   329              fun mk_inst (Var(v,T)) =
   330                  (cterm_of sign (Var(v,T)),
   331                   cterm_of sign (Free(the (assoc(alist,v)), T)))
   332              val insts = map mk_inst vars
   333              fun thaw th' =
   334                  th' |> forall_intr_list (map #2 insts)
   335                      |> forall_elim_list (map #1 insts)
   336          in  (Thm.instantiate ([],insts) fth, thaw)  end
   337  end;
   338 
   339 
   340 (*Rotates a rule's premises to the left by k*)
   341 val rotate_prems = permute_prems 0;
   342 
   343 
   344 (*Assume a new formula, read following the same conventions as axioms.
   345   Generalizes over Free variables,
   346   creates the assumption, and then strips quantifiers.
   347   Example is [| ALL x:?A. ?P(x) |] ==> [| ?P(?a) |]
   348              [ !(A,P,a)[| ALL x:A. P(x) |] ==> [| P(a) |] ]    *)
   349 fun assume_ax thy sP =
   350     let val sign = Theory.sign_of thy
   351         val prop = Logic.close_form (term_of (read_cterm sign (sP, propT)))
   352     in forall_elim_vars 0 (assume (cterm_of sign prop))  end;
   353 
   354 (*Resolution: exactly one resolvent must be produced.*)
   355 fun tha RSN (i,thb) =
   356   case Seq.chop (2, biresolution false [(false,tha)] i thb) of
   357       ([th],_) => th
   358     | ([],_)   => raise THM("RSN: no unifiers", i, [tha,thb])
   359     |      _   => raise THM("RSN: multiple unifiers", i, [tha,thb]);
   360 
   361 (*resolution: P==>Q, Q==>R gives P==>R. *)
   362 fun tha RS thb = tha RSN (1,thb);
   363 
   364 (*For joining lists of rules*)
   365 fun thas RLN (i,thbs) =
   366   let val resolve = biresolution false (map (pair false) thas) i
   367       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   368   in  List.concat (map resb thbs)  end;
   369 
   370 fun thas RL thbs = thas RLN (1,thbs);
   371 
   372 (*Resolve a list of rules against bottom_rl from right to left;
   373   makes proof trees*)
   374 fun rls MRS bottom_rl =
   375   let fun rs_aux i [] = bottom_rl
   376         | rs_aux i (rl::rls) = rl RSN (i, rs_aux (i+1) rls)
   377   in  rs_aux 1 rls  end;
   378 
   379 (*As above, but for rule lists*)
   380 fun rlss MRL bottom_rls =
   381   let fun rs_aux i [] = bottom_rls
   382         | rs_aux i (rls::rlss) = rls RLN (i, rs_aux (i+1) rlss)
   383   in  rs_aux 1 rlss  end;
   384 
   385 (*A version of MRS with more appropriate argument order*)
   386 fun bottom_rl OF rls = rls MRS bottom_rl;
   387 
   388 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   389   with no lifting or renaming!  Q may contain ==> or meta-quants
   390   ALWAYS deletes premise i *)
   391 fun compose(tha,i,thb) =
   392     Seq.list_of (bicompose false (false,tha,0) i thb);
   393 
   394 fun compose_single (tha,i,thb) =
   395   (case compose (tha,i,thb) of
   396     [th] => th
   397   | _ => raise THM ("compose: unique result expected", i, [tha,thb]));
   398 
   399 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   400 fun tha COMP thb =
   401     case compose(tha,1,thb) of
   402         [th] => th
   403       | _ =>   raise THM("COMP", 1, [tha,thb]);
   404 
   405 (** theorem equality **)
   406 
   407 (*Do the two theorems have the same signature?*)
   408 fun eq_thm_sg (th1,th2) = Sign.eq_sg(#sign(rep_thm th1), #sign(rep_thm th2));
   409 fun merge_rules (ths1, ths2) = Library.generic_merge Thm.eq_thm I I ths1 ths2;
   410 
   411 (*Useful "distance" function for BEST_FIRST*)
   412 val size_of_thm = size_of_term o #prop o rep_thm;
   413 
   414 
   415 (** Mark Staples's weaker version of eq_thm: ignores variable renaming and
   416     (some) type variable renaming **)
   417 
   418  (* Can't use term_vars, because it sorts the resulting list of variable names.
   419     We instead need the unique list noramlised by the order of appearance
   420     in the term. *)
   421 fun term_vars' (t as Var(v,T)) = [t]
   422   | term_vars' (Abs(_,_,b)) = term_vars' b
   423   | term_vars' (f$a) = (term_vars' f) @ (term_vars' a)
   424   | term_vars' _ = [];
   425 
   426 fun forall_intr_vars th =
   427   let val {prop,sign,...} = rep_thm th;
   428       val vars = distinct (term_vars' prop);
   429   in forall_intr_list (map (cterm_of sign) vars) th end;
   430 
   431 fun weak_eq_thm (tha,thb) =
   432     eq_thm(forall_intr_vars (freezeT tha), forall_intr_vars (freezeT thb));
   433 
   434 
   435 
   436 (*** Meta-Rewriting Rules ***)
   437 
   438 val proto_sign = Theory.sign_of ProtoPure.thy;
   439 
   440 fun read_prop s = read_cterm proto_sign (s, propT);
   441 
   442 fun store_thm name thm = hd (PureThy.smart_store_thms (name, [thm]));
   443 fun store_standard_thm name thm = store_thm name (standard thm);
   444 
   445 val reflexive_thm =
   446   let val cx = cterm_of proto_sign (Var(("x",0),TVar(("'a",0),logicS)))
   447   in store_standard_thm "reflexive" (Thm.reflexive cx) end;
   448 
   449 val symmetric_thm =
   450   let val xy = read_prop "x::'a::logic == y"
   451   in store_standard_thm "symmetric" (Thm.implies_intr_hyps (Thm.symmetric (Thm.assume xy))) end;
   452 
   453 val transitive_thm =
   454   let val xy = read_prop "x::'a::logic == y"
   455       val yz = read_prop "y::'a::logic == z"
   456       val xythm = Thm.assume xy and yzthm = Thm.assume yz
   457   in store_standard_thm "transitive" (Thm.implies_intr yz (Thm.transitive xythm yzthm)) end;
   458 
   459 fun symmetric_fun thm = thm RS symmetric_thm;
   460 
   461 (** Below, a "conversion" has type cterm -> thm **)
   462 
   463 val refl_implies = reflexive (cterm_of proto_sign implies);
   464 
   465 (*In [A1,...,An]==>B, rewrite the selected A's only -- for rewrite_goals_tac*)
   466 (*Do not rewrite flex-flex pairs*)
   467 fun goals_conv pred cv =
   468   let fun gconv i ct =
   469         let val (A,B) = dest_implies ct
   470             val (thA,j) = case term_of A of
   471                   Const("=?=",_)$_$_ => (reflexive A, i)
   472                 | _ => (if pred i then cv A else reflexive A, i+1)
   473         in  combination (combination refl_implies thA) (gconv j B) end
   474         handle TERM _ => reflexive ct
   475   in gconv 1 end;
   476 
   477 (*Use a conversion to transform a theorem*)
   478 fun fconv_rule cv th = equal_elim (cv (cprop_of th)) th;
   479 
   480 (*rewriting conversion*)
   481 fun rew_conv mode prover mss = rewrite_cterm mode mss prover;
   482 
   483 (*Rewrite a theorem*)
   484 fun rewrite_rule_aux _ []   th = th
   485   | rewrite_rule_aux prover thms th =
   486       fconv_rule (rew_conv (true,false,false) prover (Thm.mss_of thms)) th;
   487 
   488 fun rewrite_thm mode prover mss = fconv_rule (rew_conv mode prover mss);
   489 fun rewrite_cterm mode prover mss = Thm.rewrite_cterm mode mss prover;
   490 
   491 (*Rewrite the subgoals of a proof state (represented by a theorem) *)
   492 fun rewrite_goals_rule_aux _ []   th = th
   493   | rewrite_goals_rule_aux prover thms th =
   494       fconv_rule (goals_conv (K true) (rew_conv (true, true, false) prover
   495         (Thm.mss_of thms))) th;
   496 
   497 (*Rewrite the subgoal of a proof state (represented by a theorem) *)
   498 fun rewrite_goal_rule mode prover mss i thm =
   499   if 0 < i  andalso  i <= nprems_of thm
   500   then fconv_rule (goals_conv (fn j => j=i) (rew_conv mode prover mss)) thm
   501   else raise THM("rewrite_goal_rule",i,[thm]);
   502 
   503 
   504 (*** Some useful meta-theorems ***)
   505 
   506 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   507 val asm_rl = store_standard_thm "asm_rl" (Thm.trivial (read_prop "PROP ?psi"));
   508 val _ = store_thm "_" asm_rl;
   509 
   510 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   511 val cut_rl =
   512   store_standard_thm "cut_rl"
   513     (Thm.trivial (read_prop "PROP ?psi ==> PROP ?theta"));
   514 
   515 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   516      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   517 val revcut_rl =
   518   let val V = read_prop "PROP V"
   519       and VW = read_prop "PROP V ==> PROP W";
   520   in
   521     store_standard_thm "revcut_rl"
   522       (implies_intr V (implies_intr VW (implies_elim (assume VW) (assume V))))
   523   end;
   524 
   525 (*for deleting an unwanted assumption*)
   526 val thin_rl =
   527   let val V = read_prop "PROP V"
   528       and W = read_prop "PROP W";
   529   in  store_standard_thm "thin_rl" (implies_intr V (implies_intr W (assume W)))
   530   end;
   531 
   532 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   533 val triv_forall_equality =
   534   let val V  = read_prop "PROP V"
   535       and QV = read_prop "!!x::'a. PROP V"
   536       and x  = read_cterm proto_sign ("x", TypeInfer.logicT);
   537   in
   538     store_standard_thm "triv_forall_equality"
   539       (standard (equal_intr (implies_intr QV (forall_elim x (assume QV)))
   540         (implies_intr V  (forall_intr x (assume V)))))
   541   end;
   542 
   543 (* (PROP ?PhiA ==> PROP ?PhiB ==> PROP ?Psi) ==>
   544    (PROP ?PhiB ==> PROP ?PhiA ==> PROP ?Psi)
   545    `thm COMP swap_prems_rl' swaps the first two premises of `thm'
   546 *)
   547 val swap_prems_rl =
   548   let val cmajor = read_prop "PROP PhiA ==> PROP PhiB ==> PROP Psi";
   549       val major = assume cmajor;
   550       val cminor1 = read_prop "PROP PhiA";
   551       val minor1 = assume cminor1;
   552       val cminor2 = read_prop "PROP PhiB";
   553       val minor2 = assume cminor2;
   554   in store_standard_thm "swap_prems_rl"
   555        (implies_intr cmajor (implies_intr cminor2 (implies_intr cminor1
   556          (implies_elim (implies_elim major minor1) minor2))))
   557   end;
   558 
   559 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   560    ==> PROP ?phi == PROP ?psi
   561    Introduction rule for == as a meta-theorem.
   562 *)
   563 val equal_intr_rule =
   564   let val PQ = read_prop "PROP phi ==> PROP psi"
   565       and QP = read_prop "PROP psi ==> PROP phi"
   566   in
   567     store_standard_thm "equal_intr_rule"
   568       (implies_intr PQ (implies_intr QP (equal_intr (assume PQ) (assume QP))))
   569   end;
   570 
   571 
   572 (*** Instantiate theorem th, reading instantiations under signature sg ****)
   573 
   574 (*Version that normalizes the result: Thm.instantiate no longer does that*)
   575 fun instantiate instpair th = Thm.instantiate instpair th  COMP   asm_rl;
   576 
   577 fun read_instantiate_sg sg sinsts th =
   578     let val ts = types_sorts th;
   579         val used = add_term_tvarnames(#prop(rep_thm th),[]);
   580     in  instantiate (read_insts sg ts ts used sinsts) th  end;
   581 
   582 (*Instantiate theorem th, reading instantiations under theory of th*)
   583 fun read_instantiate sinsts th =
   584     read_instantiate_sg (#sign (rep_thm th)) sinsts th;
   585 
   586 
   587 (*Left-to-right replacements: tpairs = [...,(vi,ti),...].
   588   Instantiates distinct Vars by terms, inferring type instantiations. *)
   589 local
   590   fun add_types ((ct,cu), (sign,tye,maxidx)) =
   591     let val {sign=signt, t=t, T= T, maxidx=maxt,...} = rep_cterm ct
   592         and {sign=signu, t=u, T= U, maxidx=maxu,...} = rep_cterm cu;
   593         val maxi = Int.max(maxidx, Int.max(maxt, maxu));
   594         val sign' = Sign.merge(sign, Sign.merge(signt, signu))
   595         val (tye',maxi') = Type.unify (#tsig(Sign.rep_sg sign')) maxi tye (T,U)
   596           handle Type.TUNIFY => raise TYPE("add_types", [T,U], [t,u])
   597     in  (sign', tye', maxi')  end;
   598 in
   599 fun cterm_instantiate ctpairs0 th =
   600   let val (sign,tye,_) = foldr add_types (ctpairs0, (#sign(rep_thm th), Vartab.empty, 0))
   601       val tsig = #tsig(Sign.rep_sg sign);
   602       fun instT(ct,cu) = let val inst = subst_TVars_Vartab tye
   603                          in (cterm_fun inst ct, cterm_fun inst cu) end
   604       fun ctyp2 (ix,T) = (ix, ctyp_of sign T)
   605   in  instantiate (map ctyp2 (Vartab.dest tye), map instT ctpairs0) th  end
   606   handle TERM _ =>
   607            raise THM("cterm_instantiate: incompatible signatures",0,[th])
   608        | TYPE (msg, _, _) => raise THM(msg, 0, [th])
   609 end;
   610 
   611 
   612 (** Derived rules mainly for METAHYPS **)
   613 
   614 (*Given the term "a", takes (%x.t)==(%x.u) to t[a/x]==u[a/x]*)
   615 fun equal_abs_elim ca eqth =
   616   let val {sign=signa, t=a, ...} = rep_cterm ca
   617       and combth = combination eqth (reflexive ca)
   618       val {sign,prop,...} = rep_thm eqth
   619       val (abst,absu) = Logic.dest_equals prop
   620       val cterm = cterm_of (Sign.merge (sign,signa))
   621   in  transitive (symmetric (beta_conversion (cterm (abst$a))))
   622            (transitive combth (beta_conversion (cterm (absu$a))))
   623   end
   624   handle THM _ => raise THM("equal_abs_elim", 0, [eqth]);
   625 
   626 (*Calling equal_abs_elim with multiple terms*)
   627 fun equal_abs_elim_list cts th = foldr (uncurry equal_abs_elim) (rev cts, th);
   628 
   629 local
   630   val alpha = TVar(("'a",0), [])     (*  type ?'a::{}  *)
   631   fun err th = raise THM("flexpair_inst: ", 0, [th])
   632   fun flexpair_inst def th =
   633     let val {prop = Const _ $ t $ u,  sign,...} = rep_thm th
   634         val cterm = cterm_of sign
   635         fun cvar a = cterm(Var((a,0),alpha))
   636         val def' = cterm_instantiate [(cvar"t", cterm t), (cvar"u", cterm u)]
   637                    def
   638     in  equal_elim def' th
   639     end
   640     handle THM _ => err th | Bind => err th
   641 in
   642 val flexpair_intr = flexpair_inst (symmetric ProtoPure.flexpair_def)
   643 and flexpair_elim = flexpair_inst ProtoPure.flexpair_def
   644 end;
   645 
   646 (*Version for flexflex pairs -- this supports lifting.*)
   647 fun flexpair_abs_elim_list cts =
   648     flexpair_intr o equal_abs_elim_list cts o flexpair_elim;
   649 
   650 
   651 (*** GOAL (PROP A) <==> PROP A ***)
   652 
   653 local
   654   val A = read_prop "PROP A";
   655   val G = read_prop "GOAL (PROP A)";
   656   val (G_def, _) = freeze_thaw ProtoPure.Goal_def;
   657 in
   658   val triv_goal = store_thm "triv_goal"
   659     (tag_rule internal_tag (standard (Thm.equal_elim (Thm.symmetric G_def) (Thm.assume A))));
   660   val rev_triv_goal = store_thm "rev_triv_goal"
   661     (tag_rule internal_tag (standard (Thm.equal_elim G_def (Thm.assume G))));
   662 end;
   663 
   664 val mk_cgoal = Thm.capply (Thm.cterm_of proto_sign Logic.goal_const);
   665 fun assume_goal ct = Thm.assume (mk_cgoal ct) RS rev_triv_goal;
   666 
   667 
   668 
   669 (** variations on instantiate **)
   670 
   671 (*shorthand for instantiating just one variable in the current theory*)
   672 fun inst x t = read_instantiate_sg (sign_of (the_context())) [(x,t)];
   673 
   674 
   675 (* collect vars *)
   676 
   677 val add_tvarsT = foldl_atyps (fn (vs, TVar v) => v ins vs | (vs, _) => vs);
   678 val add_tvars = foldl_types add_tvarsT;
   679 val add_vars = foldl_aterms (fn (vs, Var v) => v ins vs | (vs, _) => vs);
   680 
   681 fun tvars_of_terms ts = rev (foldl add_tvars ([], ts));
   682 fun vars_of_terms ts = rev (foldl add_vars ([], ts));
   683 
   684 fun tvars_of thm = tvars_of_terms [#prop (Thm.rep_thm thm)];
   685 fun vars_of thm = vars_of_terms [#prop (Thm.rep_thm thm)];
   686 
   687 
   688 (* instantiate by left-to-right occurrence of variables *)
   689 
   690 fun instantiate' cTs cts thm =
   691   let
   692     fun err msg =
   693       raise TYPE ("instantiate': " ^ msg,
   694         mapfilter (apsome Thm.typ_of) cTs,
   695         mapfilter (apsome Thm.term_of) cts);
   696 
   697     fun inst_of (v, ct) =
   698       (Thm.cterm_of (#sign (Thm.rep_cterm ct)) (Var v), ct)
   699         handle TYPE (msg, _, _) => err msg;
   700 
   701     fun zip_vars _ [] = []
   702       | zip_vars (_ :: vs) (None :: opt_ts) = zip_vars vs opt_ts
   703       | zip_vars (v :: vs) (Some t :: opt_ts) = (v, t) :: zip_vars vs opt_ts
   704       | zip_vars [] _ = err "more instantiations than variables in thm";
   705 
   706     (*instantiate types first!*)
   707     val thm' =
   708       if forall is_none cTs then thm
   709       else Thm.instantiate (zip_vars (map fst (tvars_of thm)) cTs, []) thm;
   710     in
   711       if forall is_none cts then thm'
   712       else Thm.instantiate ([], map inst_of (zip_vars (vars_of thm') cts)) thm'
   713     end;
   714 
   715 
   716 (* unvarify(T) *)
   717 
   718 (*assume thm in standard form, i.e. no frees, 0 var indexes*)
   719 
   720 fun unvarifyT thm =
   721   let
   722     val cT = Thm.ctyp_of (Thm.sign_of_thm thm);
   723     val tfrees = map (fn ((x, _), S) => Some (cT (TFree (x, S)))) (tvars_of thm);
   724   in instantiate' tfrees [] thm end;
   725 
   726 fun unvarify raw_thm =
   727   let
   728     val thm = unvarifyT raw_thm;
   729     val ct = Thm.cterm_of (Thm.sign_of_thm thm);
   730     val frees = map (fn ((x, _), T) => Some (ct (Free (x, T)))) (vars_of thm);
   731   in instantiate' [] frees thm end;
   732 
   733 
   734 (* tvars_intr_list *)
   735 
   736 fun tfrees_of thm =
   737   let val {hyps, prop, ...} = Thm.rep_thm thm
   738   in foldr Term.add_term_tfree_names (prop :: hyps, []) end;
   739 
   740 fun tvars_intr_list tfrees thm =
   741   Thm.varifyT' (tfrees_of thm \\ tfrees) thm;
   742 
   743 
   744 (* increment var indexes *)
   745 
   746 fun incr_indexes 0 thm = thm
   747   | incr_indexes inc thm =
   748       let
   749         val sign = Thm.sign_of_thm thm;
   750 
   751         fun inc_tvar ((x, i), S) = Some (Thm.ctyp_of sign (TVar ((x, i + inc), S)));
   752         fun inc_var ((x, i), T) = Some (Thm.cterm_of sign (Var ((x, i + inc), T)));
   753         val thm' = instantiate' (map inc_tvar (tvars_of thm)) [] thm;
   754         val thm'' = instantiate' [] (map inc_var (vars_of thm')) thm';
   755       in thm'' end;
   756 
   757 fun incr_indexes_wrt is cTs cts thms =
   758   let
   759     val maxidx =
   760       foldl Int.max (~1, is @
   761         map (maxidx_of_typ o #T o Thm.rep_ctyp) cTs @
   762         map (#maxidx o Thm.rep_cterm) cts @
   763         map (#maxidx o Thm.rep_thm) thms);
   764   in incr_indexes (maxidx + 1) end;
   765 
   766 
   767 (* freeze_all *)
   768 
   769 (*freeze all (T)Vars; assumes thm in standard form*)
   770 
   771 fun freeze_all_TVars thm =
   772   (case tvars_of thm of
   773     [] => thm
   774   | tvars =>
   775       let val cert = Thm.ctyp_of (Thm.sign_of_thm thm)
   776       in instantiate' (map (fn ((x, _), S) => Some (cert (TFree (x, S)))) tvars) [] thm end);
   777 
   778 fun freeze_all_Vars thm =
   779   (case vars_of thm of
   780     [] => thm
   781   | vars =>
   782       let val cert = Thm.cterm_of (Thm.sign_of_thm thm)
   783       in instantiate' [] (map (fn ((x, _), T) => Some (cert (Free (x, T)))) vars) thm end);
   784 
   785 val freeze_all = freeze_all_Vars o freeze_all_TVars;
   786 
   787 
   788 (* mk_triv_goal *)
   789 
   790 (*make an initial proof state, "PROP A ==> (PROP A)" *)
   791 fun mk_triv_goal ct = instantiate' [] [Some ct] triv_goal;
   792 
   793 
   794 end;
   795 
   796 
   797 structure BasicDrule: BASIC_DRULE = Drule;
   798 open BasicDrule;