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