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