src/Provers/splitter.ML
author nipkow
Fri May 17 11:25:07 2002 +0200 (2002-05-17 ago)
changeset 13157 4a4599f78f18
parent 10821 dcb75538f542
child 13855 644692eca537
permissions -rw-r--r--
allowed more general split rules to cope with div/mod 2
     1 (*  Title:      Provers/splitter
     2     ID:         $Id$
     3     Author:     Tobias Nipkow
     4     Copyright   1995  TU Munich
     5 
     6 Generic case-splitter, suitable for most logics.
     7 Deals with equalities of the form ?P(f args) = ...
     8 where "f args" must be a first-order term without duplicate variables.
     9 *)
    10 
    11 infix 4 addsplits delsplits;
    12 
    13 signature SPLITTER_DATA =
    14 sig
    15   structure Simplifier: SIMPLIFIER
    16   val mk_eq         : thm -> thm
    17   val meta_eq_to_iff: thm (* "x == y ==> x = y"                    *)
    18   val iffD          : thm (* "[| P = Q; Q |] ==> P"                *)
    19   val disjE         : thm (* "[| P | Q; P ==> R; Q ==> R |] ==> R" *)
    20   val conjE         : thm (* "[| P & Q; [| P; Q |] ==> R |] ==> R" *)
    21   val exE           : thm (* "[|  x. P x; !!x. P x ==> Q |] ==> Q" *)
    22   val contrapos     : thm (* "[| ~ Q; P ==> Q |] ==> ~ P"          *)
    23   val contrapos2    : thm (* "[| Q; ~ P ==> ~ Q |] ==> P"          *)
    24   val notnotD       : thm (* "~ ~ P ==> P"                         *)
    25 end
    26 
    27 signature SPLITTER =
    28 sig
    29   type simpset
    30   val split_tac       : thm list -> int -> tactic
    31   val split_inside_tac: thm list -> int -> tactic
    32   val split_asm_tac   : thm list -> int -> tactic
    33   val addsplits       : simpset * thm list -> simpset
    34   val delsplits       : simpset * thm list -> simpset
    35   val Addsplits       : thm list -> unit
    36   val Delsplits       : thm list -> unit
    37   val split_add_global: theory attribute
    38   val split_del_global: theory attribute
    39   val split_add_local: Proof.context attribute
    40   val split_del_local: Proof.context attribute
    41   val split_modifiers : (Args.T list -> (Method.modifier * Args.T list)) list
    42   val setup: (theory -> theory) list
    43 end;
    44 
    45 functor SplitterFun(Data: SPLITTER_DATA): SPLITTER =
    46 struct 
    47 
    48 structure Simplifier = Data.Simplifier;
    49 type simpset = Simplifier.simpset;
    50 
    51 val Const ("==>", _) $ (Const ("Trueprop", _) $
    52          (Const (const_not, _) $ _    )) $ _ = #prop (rep_thm(Data.notnotD));
    53 
    54 val Const ("==>", _) $ (Const ("Trueprop", _) $
    55          (Const (const_or , _) $ _ $ _)) $ _ = #prop (rep_thm(Data.disjE));
    56 
    57 fun split_format_err() = error("Wrong format for split rule");
    58 
    59 fun split_thm_info thm = case concl_of (Data.mk_eq thm) of
    60      Const("==", _)$(Var _$t)$c =>
    61         (case strip_comb t of
    62            (Const(a,_),_) => (a,case c of (Const(s,_)$_)=>s=const_not|_=> false)
    63          | _              => split_format_err())
    64    | _ => split_format_err();
    65 
    66 fun mk_case_split_tac order =
    67 let
    68 
    69 
    70 (************************************************************
    71    Create lift-theorem "trlift" :
    72 
    73    [| !!x. Q x == R x; P(%x. R x) == C |] ==> P (%x. Q x) == C
    74 
    75 *************************************************************)
    76 
    77 val meta_iffD = Data.meta_eq_to_iff RS Data.iffD;
    78 val lift =
    79   let val ct = read_cterm (#sign(rep_thm Data.iffD))
    80            ("[| !!x. (Q::('b::logic)=>('c::logic))(x) == R(x) |] ==> \
    81             \P(%x. Q(x)) == P(%x. R(x))::'a::logic",propT)
    82   in prove_goalw_cterm [] ct
    83      (fn [prem] => [rewtac prem, rtac reflexive_thm 1])
    84   end;
    85 
    86 val trlift = lift RS transitive_thm;
    87 val _ $ (P $ _) $ _ = concl_of trlift;
    88 
    89 
    90 (************************************************************************ 
    91    Set up term for instantiation of P in the lift-theorem
    92    
    93    Ts    : types of parameters (i.e. variables bound by meta-quantifiers)
    94    t     : lefthand side of meta-equality in subgoal
    95            the lift theorem is applied to (see select)
    96    pos   : "path" leading to abstraction, coded as a list
    97    T     : type of body of P(...)
    98    maxi  : maximum index of Vars
    99 *************************************************************************)
   100 
   101 fun mk_cntxt Ts t pos T maxi =
   102   let fun var (t,i) = Var(("X",i),type_of1(Ts,t));
   103       fun down [] t i = Bound 0
   104         | down (p::ps) t i =
   105             let val (h,ts) = strip_comb t
   106                 val v1 = ListPair.map var (take(p,ts), i upto (i+p-1))
   107                 val u::us = drop(p,ts)
   108                 val v2 = ListPair.map var (us, (i+p) upto (i+length(ts)-2))
   109       in list_comb(h,v1@[down ps u (i+length ts)]@v2) end;
   110   in Abs("", T, down (rev pos) t maxi) end;
   111 
   112 
   113 (************************************************************************ 
   114    Set up term for instantiation of P in the split-theorem
   115    P(...) == rhs
   116 
   117    t     : lefthand side of meta-equality in subgoal
   118            the split theorem is applied to (see select)
   119    T     : type of body of P(...)
   120    tt    : the term  Const(key,..) $ ...
   121 *************************************************************************)
   122 
   123 fun mk_cntxt_splitthm t tt T =
   124   let fun repl lev t =
   125     if incr_boundvars lev tt aconv t then Bound lev
   126     else case t of
   127         (Abs (v, T2, t)) => Abs (v, T2, repl (lev+1) t)
   128       | (Bound i) => Bound (if i>=lev then i+1 else i)
   129       | (t1 $ t2) => (repl lev t1) $ (repl lev t2)
   130       | t => t
   131   in Abs("", T, repl 0 t) end;
   132 
   133 
   134 (* add all loose bound variables in t to list is *)
   135 fun add_lbnos(is,t) = add_loose_bnos(t,0,is);
   136 
   137 (* check if the innermost abstraction that needs to be removed
   138    has a body of type T; otherwise the expansion thm will fail later on
   139 *)
   140 fun type_test(T,lbnos,apsns) =
   141   let val (_,U,_) = nth_elem(foldl Int.min (hd lbnos, tl lbnos), apsns)
   142   in T=U end;
   143 
   144 (*************************************************************************
   145    Create a "split_pack".
   146 
   147    thm   : the relevant split-theorem, i.e. P(...) == rhs , where P(...)
   148            is of the form
   149            P( Const(key,...) $ t_1 $ ... $ t_n )      (e.g. key = "if")
   150    T     : type of P(...)
   151    T'    : type of term to be scanned
   152    n     : number of arguments expected by Const(key,...)
   153    ts    : list of arguments actually found
   154    apsns : list of tuples of the form (T,U,pos), one tuple for each
   155            abstraction that is encountered on the way to the position where 
   156            Const(key, ...) $ ...  occurs, where
   157            T   : type of the variable bound by the abstraction
   158            U   : type of the abstraction's body
   159            pos : "path" leading to the body of the abstraction
   160    pos   : "path" leading to the position where Const(key, ...) $ ...  occurs.
   161    TB    : type of  Const(key,...) $ t_1 $ ... $ t_n
   162    t     : the term Const(key,...) $ t_1 $ ... $ t_n
   163 
   164    A split pack is a tuple of the form
   165    (thm, apsns, pos, TB, tt)
   166    Note : apsns is reversed, so that the outermost quantifier's position
   167           comes first ! If the terms in ts don't contain variables bound
   168           by other than meta-quantifiers, apsns is empty, because no further
   169           lifting is required before applying the split-theorem.
   170 ******************************************************************************) 
   171 
   172 fun mk_split_pack(thm, T, T', n, ts, apsns, pos, TB, t) =
   173   if n > length ts then []
   174   else let val lev = length apsns
   175            val lbnos = foldl add_lbnos ([],take(n,ts))
   176            val flbnos = filter (fn i => i < lev) lbnos
   177            val tt = incr_boundvars (~lev) t
   178        in if null flbnos then
   179             if T = T' then [(thm,[],pos,TB,tt)] else []
   180           else if type_test(T,flbnos,apsns) then [(thm, rev apsns,pos,TB,tt)]
   181                else []
   182        end;
   183 
   184 
   185 (****************************************************************************
   186    Recursively scans term for occurences of Const(key,...) $ ...
   187    Returns a list of "split-packs" (one for each occurence of Const(key,...) )
   188 
   189    cmap : association list of split-theorems that should be tried.
   190           The elements have the format (key,(thm,T,n)) , where
   191           key : the theorem's key constant ( Const(key,...) $ ... )
   192           thm : the theorem itself
   193           T   : type of P( Const(key,...) $ ... )
   194           n   : number of arguments expected by Const(key,...)
   195    Ts   : types of parameters
   196    t    : the term to be scanned
   197 ******************************************************************************)
   198 
   199 (* Simplified first-order matching;
   200    assumes that all Vars in the pattern are distinct;
   201    see Pure/pattern.ML for the full version;
   202 *)
   203 local
   204 exception MATCH
   205 in
   206 fun typ_match tsig args = (Type.typ_match tsig args)
   207                           handle Type.TYPE_MATCH => raise MATCH;
   208 fun fomatch tsig args =
   209   let
   210     fun mtch tyinsts = fn
   211         (Ts,Var(_,T), t)  => typ_match tsig (tyinsts, (T, fastype_of1(Ts,t)))
   212       | (_,Free (a,T), Free (b,U)) =>
   213           if a=b then typ_match tsig (tyinsts,(T,U)) else raise MATCH
   214       | (_,Const (a,T), Const (b,U))  =>
   215           if a=b then typ_match tsig (tyinsts,(T,U)) else raise MATCH
   216       | (_,Bound i, Bound j)  =>  if  i=j  then tyinsts else raise MATCH
   217       | (Ts,Abs(_,T,t), Abs(_,U,u))  =>
   218           mtch (typ_match tsig (tyinsts,(T,U))) (U::Ts,t,u)
   219       | (Ts, f$t, g$u) => mtch (mtch tyinsts (Ts,f,g)) (Ts, t, u)
   220       | _ => raise MATCH
   221   in (mtch Vartab.empty args; true) handle MATCH => false end;
   222 end
   223 
   224 fun split_posns cmap sg Ts t =
   225   let
   226     val T' = fastype_of1 (Ts, t);
   227     fun posns Ts pos apsns (Abs (_, T, t)) =
   228           let val U = fastype_of1 (T::Ts,t)
   229           in posns (T::Ts) (0::pos) ((T, U, pos)::apsns) t end
   230       | posns Ts pos apsns t =
   231           let
   232             val (h, ts) = strip_comb t
   233             fun iter((i, a), t) = (i+1, (posns Ts (i::pos) apsns t) @ a);
   234             val a = case h of
   235               Const(c, cT) =>
   236                 let fun find [] = []
   237                       | find ((gcT, pat, thm, T, n)::tups) =
   238                           let val t2 = list_comb (h, take (n, ts))
   239                           in if Sign.typ_instance sg (cT, gcT)
   240                                 andalso fomatch (Sign.tsig_of sg) (Ts,pat,t2)
   241                              then mk_split_pack(thm,T,T',n,ts,apsns,pos,type_of1(Ts,t2),t2)
   242                              else find tups
   243                           end
   244                 in find (assocs cmap c) end
   245             | _ => []
   246           in snd(foldl iter ((0, a), ts)) end
   247   in posns Ts [] [] t end;
   248 
   249 
   250 fun nth_subgoal i thm = nth_elem(i-1,prems_of thm);
   251 
   252 fun shorter((_,ps,pos,_,_),(_,qs,qos,_,_)) =
   253   prod_ord (int_ord o pairself length) (order o pairself length)
   254     ((ps, pos), (qs, qos));
   255 
   256 
   257 
   258 (************************************************************
   259    call split_posns with appropriate parameters
   260 *************************************************************)
   261 
   262 fun select cmap state i =
   263   let val sg = #sign(rep_thm state)
   264       val goali = nth_subgoal i state
   265       val Ts = rev(map #2 (Logic.strip_params goali))
   266       val _ $ t $ _ = Logic.strip_assums_concl goali;
   267   in (Ts,t, sort shorter (split_posns cmap sg Ts t)) end;
   268 
   269 
   270 (*************************************************************
   271    instantiate lift theorem
   272 
   273    if t is of the form
   274    ... ( Const(...,...) $ Abs( .... ) ) ...
   275    then
   276    P = %a.  ... ( Const(...,...) $ a ) ...
   277    where a has type T --> U
   278 
   279    Ts      : types of parameters
   280    t       : lefthand side of meta-equality in subgoal
   281              the split theorem is applied to (see cmap)
   282    T,U,pos : see mk_split_pack
   283    state   : current proof state
   284    lift    : the lift theorem
   285    i       : no. of subgoal
   286 **************************************************************)
   287 
   288 fun inst_lift Ts t (T, U, pos) state i =
   289   let
   290     val cert = cterm_of (sign_of_thm state);
   291     val cntxt = mk_cntxt Ts t pos (T --> U) (#maxidx(rep_thm trlift));    
   292   in cterm_instantiate [(cert P, cert cntxt)] trlift
   293   end;
   294 
   295 
   296 (*************************************************************
   297    instantiate split theorem
   298 
   299    Ts    : types of parameters
   300    t     : lefthand side of meta-equality in subgoal
   301            the split theorem is applied to (see cmap)
   302    tt    : the term  Const(key,..) $ ...
   303    thm   : the split theorem
   304    TB    : type of body of P(...)
   305    state : current proof state
   306    i     : number of subgoal
   307 **************************************************************)
   308 
   309 fun inst_split Ts t tt thm TB state i =
   310   let 
   311     val thm' = Thm.lift_rule (state, i) thm;
   312     val (P, _) = strip_comb (fst (Logic.dest_equals
   313       (Logic.strip_assums_concl (#prop (rep_thm thm')))));
   314     val cert = cterm_of (sign_of_thm state);
   315     val cntxt = mk_cntxt_splitthm t tt TB;
   316     val abss = foldl (fn (t, T) => Abs ("", T, t));
   317   in cterm_instantiate [(cert P, cert (abss (cntxt, Ts)))] thm'
   318   end;
   319 
   320 
   321 (*****************************************************************************
   322    The split-tactic
   323    
   324    splits : list of split-theorems to be tried
   325    i      : number of subgoal the tactic should be applied to
   326 *****************************************************************************)
   327 
   328 fun split_tac [] i = no_tac
   329   | split_tac splits i =
   330   let val splits = map Data.mk_eq splits;
   331       fun add_thm(cmap,thm) =
   332             (case concl_of thm of _$(t as _$lhs)$_ =>
   333                (case strip_comb lhs of (Const(a,aT),args) =>
   334                   let val info = (aT,lhs,thm,fastype_of t,length args)
   335                   in case assoc(cmap,a) of
   336                        Some infos => overwrite(cmap,(a,info::infos))
   337                      | None => (a,[info])::cmap
   338                   end
   339                 | _ => split_format_err())
   340              | _ => split_format_err())
   341       val cmap = foldl add_thm ([],splits);
   342       fun lift_tac Ts t p st = rtac (inst_lift Ts t p st i) i st
   343       fun lift_split_tac state =
   344             let val (Ts, t, splits) = select cmap state i
   345             in case splits of
   346                  [] => no_tac state
   347                | (thm, apsns, pos, TB, tt)::_ =>
   348                    (case apsns of
   349                       [] => compose_tac (false, inst_split Ts t tt thm TB state i, 0) i state
   350                     | p::_ => EVERY [lift_tac Ts t p,
   351                                      rtac reflexive_thm (i+1),
   352                                      lift_split_tac] state)
   353             end
   354   in COND (has_fewer_prems i) no_tac 
   355           (rtac meta_iffD i THEN lift_split_tac)
   356   end;
   357 
   358 in split_tac end;
   359 
   360 
   361 val split_tac        = mk_case_split_tac              int_ord;
   362 
   363 val split_inside_tac = mk_case_split_tac (rev_order o int_ord);
   364 
   365 
   366 (*****************************************************************************
   367    The split-tactic for premises
   368    
   369    splits : list of split-theorems to be tried
   370 ****************************************************************************)
   371 fun split_asm_tac []     = K no_tac
   372   | split_asm_tac splits = 
   373 
   374   let val cname_list = map (fst o split_thm_info) splits;
   375       fun is_case (a,_) = a mem cname_list;
   376       fun tac (t,i) = 
   377 	  let val n = find_index (exists_Const is_case) 
   378 				 (Logic.strip_assums_hyp t);
   379 	      fun first_prem_is_disj (Const ("==>", _) $ (Const ("Trueprop", _)
   380 				 $ (Const (s, _) $ _ $ _ )) $ _ ) = (s=const_or)
   381 	      |   first_prem_is_disj (Const("all",_)$Abs(_,_,t)) = 
   382 					first_prem_is_disj t
   383 	      |   first_prem_is_disj _ = false;
   384       (* does not work properly if the split variable is bound by a quantfier *)
   385 	      fun flat_prems_tac i = SUBGOAL (fn (t,i) => 
   386 			   (if first_prem_is_disj t
   387 			    then EVERY[etac Data.disjE i,rotate_tac ~1 i,
   388 				       rotate_tac ~1  (i+1),
   389 				       flat_prems_tac (i+1)]
   390 			    else all_tac) 
   391 			   THEN REPEAT (eresolve_tac [Data.conjE,Data.exE] i)
   392 			   THEN REPEAT (dresolve_tac [Data.notnotD]   i)) i;
   393 	  in if n<0 then no_tac else DETERM (EVERY'
   394 		[rotate_tac n, etac Data.contrapos2,
   395 		 split_tac splits, 
   396 		 rotate_tac ~1, etac Data.contrapos, rotate_tac ~1, 
   397 		 flat_prems_tac] i)
   398 	  end;
   399   in SUBGOAL tac
   400   end;
   401 
   402 fun gen_split_tac [] = K no_tac
   403   | gen_split_tac (split::splits) =
   404       let val (_,asm) = split_thm_info split
   405       in (if asm then split_asm_tac else split_tac) [split] ORELSE'
   406          gen_split_tac splits
   407       end;
   408 
   409 (** declare split rules **)
   410 
   411 (* addsplits / delsplits *)
   412 
   413 fun split_name name asm = "split " ^ name ^ (if asm then " asm" else "");
   414 
   415 fun ss addsplits splits =
   416   let fun addsplit (ss,split) =
   417         let val (name,asm) = split_thm_info split
   418         in Simplifier.addloop(ss,(split_name name asm,
   419 		       (if asm then split_asm_tac else split_tac) [split])) end
   420   in foldl addsplit (ss,splits) end;
   421 
   422 fun ss delsplits splits =
   423   let fun delsplit(ss,split) =
   424         let val (name,asm) = split_thm_info split
   425         in Simplifier.delloop(ss,split_name name asm)
   426   end in foldl delsplit (ss,splits) end;
   427 
   428 fun Addsplits splits = (Simplifier.simpset_ref() := 
   429 			Simplifier.simpset() addsplits splits);
   430 fun Delsplits splits = (Simplifier.simpset_ref() := 
   431 			Simplifier.simpset() delsplits splits);
   432 
   433 
   434 (* attributes *)
   435 
   436 val splitN = "split";
   437 
   438 val split_add_global = Simplifier.change_global_ss (op addsplits);
   439 val split_del_global = Simplifier.change_global_ss (op delsplits);
   440 val split_add_local = Simplifier.change_local_ss (op addsplits);
   441 val split_del_local = Simplifier.change_local_ss (op delsplits);
   442 
   443 val split_attr =
   444  (Attrib.add_del_args split_add_global split_del_global,
   445   Attrib.add_del_args split_add_local split_del_local);
   446 
   447 
   448 (* methods *)
   449 
   450 val split_modifiers =
   451  [Args.$$$ splitN -- Args.colon >> K ((I, split_add_local): Method.modifier),
   452   Args.$$$ splitN -- Args.add -- Args.colon >> K (I, split_add_local),
   453   Args.$$$ splitN -- Args.del -- Args.colon >> K (I, split_del_local)];
   454 
   455 val split_args = #2 oo Method.syntax Attrib.local_thms;
   456 
   457 fun split_meth ths = Method.SIMPLE_METHOD' HEADGOAL (CHANGED_PROP o gen_split_tac ths);
   458 
   459 
   460 
   461 (** theory setup **)
   462 
   463 val setup =
   464  [Attrib.add_attributes [(splitN, split_attr, "declaration of case split rule")],
   465   Method.add_methods [(splitN, split_meth oo split_args, "apply case split rule")]];
   466 
   467 end;