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