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