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