src/HOL/Import/shuffler.ML
author wenzelm
Tue Sep 18 18:05:37 2007 +0200 (2007-09-18)
changeset 24634 38db11874724
parent 22902 ac833b4bb7ee
child 26277 461e11226111
permissions -rw-r--r--
simplified PrintMode interfaces;
     1 (*  Title:      HOL/Import/shuffler.ML
     2     ID:         $Id$
     3     Author:     Sebastian Skalberg, TU Muenchen
     4 
     5 Package for proving two terms equal by normalizing (hence the
     6 "shuffler" name).  Uses the simplifier for the normalization.
     7 *)
     8 
     9 signature Shuffler =
    10 sig
    11     val debug      : bool ref
    12 
    13     val norm_term  : theory -> term -> thm
    14     val make_equal : theory -> term -> term -> thm option
    15     val set_prop   : theory -> term -> (string * thm) list -> (string * thm) option
    16 
    17     val find_potential: theory -> term -> (string * thm) list
    18 
    19     val gen_shuffle_tac: theory -> bool -> (string * thm) list -> int -> tactic
    20 
    21     val shuffle_tac: (string * thm) list -> int -> tactic
    22     val search_tac : (string * thm) list -> int -> tactic
    23 
    24     val print_shuffles: theory -> unit
    25 
    26     val add_shuffle_rule: thm -> theory -> theory
    27     val shuffle_attr: attribute
    28 
    29     val setup      : theory -> theory
    30 end
    31 
    32 structure Shuffler :> Shuffler =
    33 struct
    34 
    35 val debug = ref false
    36 
    37 fun if_debug f x = if !debug then f x else ()
    38 val message = if_debug writeln
    39 
    40 (*Prints exceptions readably to users*)
    41 fun print_sign_exn_unit sign e =
    42   case e of
    43      THM (msg,i,thms) =>
    44          (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
    45           List.app print_thm thms)
    46    | THEORY (msg,thys) =>
    47          (writeln ("Exception THEORY raised:\n" ^ msg);
    48           List.app (writeln o Context.str_of_thy) thys)
    49    | TERM (msg,ts) =>
    50          (writeln ("Exception TERM raised:\n" ^ msg);
    51           List.app (writeln o Sign.string_of_term sign) ts)
    52    | TYPE (msg,Ts,ts) =>
    53          (writeln ("Exception TYPE raised:\n" ^ msg);
    54           List.app (writeln o Sign.string_of_typ sign) Ts;
    55           List.app (writeln o Sign.string_of_term sign) ts)
    56    | e => raise e
    57 
    58 (*Prints an exception, then fails*)
    59 fun print_sign_exn sign e = (print_sign_exn_unit sign e; raise e)
    60 
    61 val string_of_thm = PrintMode.setmp [] string_of_thm;
    62 val string_of_cterm = PrintMode.setmp [] string_of_cterm;
    63 
    64 fun mk_meta_eq th =
    65     (case concl_of th of
    66          Const("Trueprop",_) $ (Const("op =",_) $ _ $ _) => th RS eq_reflection
    67        | Const("==",_) $ _ $ _ => th
    68        | _ => raise THM("Not an equality",0,[th]))
    69     handle _ => raise THM("Couldn't make meta equality",0,[th])
    70 
    71 fun mk_obj_eq th =
    72     (case concl_of th of
    73          Const("Trueprop",_) $ (Const("op =",_) $ _ $ _) => th
    74        | Const("==",_) $ _ $ _ => th RS meta_eq_to_obj_eq
    75        | _ => raise THM("Not an equality",0,[th]))
    76     handle _ => raise THM("Couldn't make object equality",0,[th])
    77 
    78 structure ShuffleData = TheoryDataFun
    79 (
    80   type T = thm list
    81   val empty = []
    82   val copy = I
    83   val extend = I
    84   fun merge _ = Library.gen_union Thm.eq_thm
    85 )
    86 
    87 fun print_shuffles thy =
    88   Pretty.writeln (Pretty.big_list "Shuffle theorems:"
    89     (map Display.pretty_thm (ShuffleData.get thy)))
    90 
    91 val weaken =
    92     let
    93         val cert = cterm_of ProtoPure.thy
    94         val P = Free("P",propT)
    95         val Q = Free("Q",propT)
    96         val PQ = Logic.mk_implies(P,Q)
    97         val PPQ = Logic.mk_implies(P,PQ)
    98         val cP = cert P
    99         val cQ = cert Q
   100         val cPQ = cert PQ
   101         val cPPQ = cert PPQ
   102         val th1 = assume cPQ |> implies_intr_list [cPQ,cP]
   103         val th3 = assume cP
   104         val th4 = implies_elim_list (assume cPPQ) [th3,th3]
   105                                     |> implies_intr_list [cPPQ,cP]
   106     in
   107         equal_intr th4 th1 |> standard
   108     end
   109 
   110 val imp_comm =
   111     let
   112         val cert = cterm_of ProtoPure.thy
   113         val P = Free("P",propT)
   114         val Q = Free("Q",propT)
   115         val R = Free("R",propT)
   116         val PQR = Logic.mk_implies(P,Logic.mk_implies(Q,R))
   117         val QPR = Logic.mk_implies(Q,Logic.mk_implies(P,R))
   118         val cP = cert P
   119         val cQ = cert Q
   120         val cPQR = cert PQR
   121         val cQPR = cert QPR
   122         val th1 = implies_elim_list (assume cPQR) [assume cP,assume cQ]
   123                                     |> implies_intr_list [cPQR,cQ,cP]
   124         val th2 = implies_elim_list (assume cQPR) [assume cQ,assume cP]
   125                                     |> implies_intr_list [cQPR,cP,cQ]
   126     in
   127         equal_intr th1 th2 |> standard
   128     end
   129 
   130 val def_norm =
   131     let
   132         val cert = cterm_of ProtoPure.thy
   133         val aT = TFree("'a",[])
   134         val bT = TFree("'b",[])
   135         val v = Free("v",aT)
   136         val P = Free("P",aT-->bT)
   137         val Q = Free("Q",aT-->bT)
   138         val cvPQ = cert (list_all ([("v",aT)],Logic.mk_equals(P $ Bound 0,Q $ Bound 0)))
   139         val cPQ = cert (Logic.mk_equals(P,Q))
   140         val cv = cert v
   141         val rew = assume cvPQ
   142                          |> forall_elim cv
   143                          |> abstract_rule "v" cv
   144         val (lhs,rhs) = Logic.dest_equals(concl_of rew)
   145         val th1 = transitive (transitive
   146                                   (eta_conversion (cert lhs) |> symmetric)
   147                                   rew)
   148                              (eta_conversion (cert rhs))
   149                              |> implies_intr cvPQ
   150         val th2 = combination (assume cPQ) (reflexive cv)
   151                               |> forall_intr cv
   152                               |> implies_intr cPQ
   153     in
   154         equal_intr th1 th2 |> standard
   155     end
   156 
   157 val all_comm =
   158     let
   159         val cert = cterm_of ProtoPure.thy
   160         val xT = TFree("'a",[])
   161         val yT = TFree("'b",[])
   162         val P = Free("P",xT-->yT-->propT)
   163         val lhs = all xT $ (Abs("x",xT,all yT $ (Abs("y",yT,P $ Bound 1 $ Bound 0))))
   164         val rhs = all yT $ (Abs("y",yT,all xT $ (Abs("x",xT,P $ Bound 0 $ Bound 1))))
   165         val cl = cert lhs
   166         val cr = cert rhs
   167         val cx = cert (Free("x",xT))
   168         val cy = cert (Free("y",yT))
   169         val th1 = assume cr
   170                          |> forall_elim_list [cy,cx]
   171                          |> forall_intr_list [cx,cy]
   172                          |> implies_intr cr
   173         val th2 = assume cl
   174                          |> forall_elim_list [cx,cy]
   175                          |> forall_intr_list [cy,cx]
   176                          |> implies_intr cl
   177     in
   178         equal_intr th1 th2 |> standard
   179     end
   180 
   181 val equiv_comm =
   182     let
   183         val cert = cterm_of ProtoPure.thy
   184         val T    = TFree("'a",[])
   185         val t    = Free("t",T)
   186         val u    = Free("u",T)
   187         val ctu  = cert (Logic.mk_equals(t,u))
   188         val cut  = cert (Logic.mk_equals(u,t))
   189         val th1  = assume ctu |> symmetric |> implies_intr ctu
   190         val th2  = assume cut |> symmetric |> implies_intr cut
   191     in
   192         equal_intr th1 th2 |> standard
   193     end
   194 
   195 (* This simplification procedure rewrites !!x y. P x y
   196 deterministicly, in order for the normalization function, defined
   197 below, to handle nested quantifiers robustly *)
   198 
   199 local
   200 
   201 exception RESULT of int
   202 
   203 fun find_bound n (Bound i) = if i = n then raise RESULT 0
   204                              else if i = n+1 then raise RESULT 1
   205                              else ()
   206   | find_bound n (t $ u) = (find_bound n t; find_bound n u)
   207   | find_bound n (Abs(_,_,t)) = find_bound (n+1) t
   208   | find_bound _ _ = ()
   209 
   210 fun swap_bound n (Bound i) = if i = n then Bound (n+1)
   211                              else if i = n+1 then Bound n
   212                              else Bound i
   213   | swap_bound n (t $ u) = (swap_bound n t $ swap_bound n u)
   214   | swap_bound n (Abs(x,xT,t)) = Abs(x,xT,swap_bound (n+1) t)
   215   | swap_bound n t = t
   216 
   217 fun rew_th thy (xv as (x,xT)) (yv as (y,yT)) t =
   218     let
   219         val lhs = list_all ([xv,yv],t)
   220         val rhs = list_all ([yv,xv],swap_bound 0 t)
   221         val rew = Logic.mk_equals (lhs,rhs)
   222         val init = trivial (cterm_of thy rew)
   223     in
   224         (all_comm RS init handle e => (message "rew_th"; OldGoals.print_exn e))
   225     end
   226 
   227 fun quant_rewrite thy assumes (t as Const("all",T1) $ (Abs(x,xT,Const("all",T2) $ Abs(y,yT,body)))) =
   228     let
   229         val res = (find_bound 0 body;2) handle RESULT i => i
   230     in
   231         case res of
   232             0 => SOME (rew_th thy (x,xT) (y,yT) body)
   233           | 1 => if string_ord(y,x) = LESS
   234                  then
   235                      let
   236                          val newt = Const("all",T1) $ (Abs(y,xT,Const("all",T2) $ Abs(x,yT,body)))
   237                          val t_th    = reflexive (cterm_of thy t)
   238                          val newt_th = reflexive (cterm_of thy newt)
   239                      in
   240                          SOME (transitive t_th newt_th)
   241                      end
   242                  else NONE
   243           | _ => error "norm_term (quant_rewrite) internal error"
   244      end
   245   | quant_rewrite _ _ _ = (warning "quant_rewrite: Unknown lhs"; NONE)
   246 
   247 fun freeze_thaw_term t =
   248     let
   249         val tvars = term_tvars t
   250         val tfree_names = add_term_tfree_names(t,[])
   251         val (type_inst,_) =
   252             Library.foldl (fn ((inst,used),(w as (v,_),S)) =>
   253                       let
   254                           val v' = Name.variant used v
   255                       in
   256                           ((w,TFree(v',S))::inst,v'::used)
   257                       end)
   258                   (([],tfree_names),tvars)
   259         val t' = subst_TVars type_inst t
   260     in
   261         (t',map (fn (w,TFree(v,S)) => (v,TVar(w,S))
   262                   | _ => error "Internal error in Shuffler.freeze_thaw") type_inst)
   263     end
   264 
   265 fun inst_tfrees thy [] thm = thm
   266   | inst_tfrees thy ((name,U)::rest) thm =
   267     let
   268         val cU = ctyp_of thy U
   269         val tfrees = add_term_tfrees (prop_of thm,[])
   270         val (rens, thm') = Thm.varifyT'
   271     (remove (op = o apsnd fst) name tfrees) thm
   272         val mid =
   273             case rens of
   274                 [] => thm'
   275               | [((_, S), idx)] => instantiate
   276             ([(ctyp_of thy (TVar (idx, S)), cU)], []) thm'
   277               | _ => error "Shuffler.inst_tfrees internal error"
   278     in
   279         inst_tfrees thy rest mid
   280     end
   281 
   282 fun is_Abs (Abs _) = true
   283   | is_Abs _ = false
   284 
   285 fun eta_redex (t $ Bound 0) =
   286     let
   287         fun free n (Bound i) = i = n
   288           | free n (t $ u) = free n t orelse free n u
   289           | free n (Abs(_,_,t)) = free (n+1) t
   290           | free n _ = false
   291     in
   292         not (free 0 t)
   293     end
   294   | eta_redex _ = false
   295 
   296 fun eta_contract thy assumes origt =
   297     let
   298         val (typet,Tinst) = freeze_thaw_term origt
   299         val (init,thaw) = freeze_thaw (reflexive (cterm_of thy typet))
   300         val final = inst_tfrees thy Tinst o thaw
   301         val t = #1 (Logic.dest_equals (prop_of init))
   302         val _ =
   303             let
   304                 val lhs = #1 (Logic.dest_equals (prop_of (final init)))
   305             in
   306                 if not (lhs aconv origt)
   307                 then (writeln "Something is utterly wrong: (orig,lhs,frozen type,t,tinst)";
   308                       writeln (string_of_cterm (cterm_of thy origt));
   309                       writeln (string_of_cterm (cterm_of thy lhs));
   310                       writeln (string_of_cterm (cterm_of thy typet));
   311                       writeln (string_of_cterm (cterm_of thy t));
   312                       app (fn (n,T) => writeln (n ^ ": " ^ (string_of_ctyp (ctyp_of thy T)))) Tinst;
   313                       writeln "done")
   314                 else ()
   315             end
   316     in
   317         case t of
   318             Const("all",_) $ (Abs(x,xT,Const("==",eqT) $ P $ Q)) =>
   319             ((if eta_redex P andalso eta_redex Q
   320               then
   321                   let
   322                       val cert = cterm_of thy
   323                       val v = Free(Name.variant (add_term_free_names(t,[])) "v",xT)
   324                       val cv = cert v
   325                       val ct = cert t
   326                       val th = (assume ct)
   327                                    |> forall_elim cv
   328                                    |> abstract_rule x cv
   329                       val ext_th = eta_conversion (cert (Abs(x,xT,P)))
   330                       val th' = transitive (symmetric ext_th) th
   331                       val cu = cert (prop_of th')
   332                       val uth = combination (assume cu) (reflexive cv)
   333                       val uth' = (beta_conversion false (cert (Abs(x,xT,Q) $ v)))
   334                                      |> transitive uth
   335                                      |> forall_intr cv
   336                                      |> implies_intr cu
   337                       val rew_th = equal_intr (th' |> implies_intr ct) uth'
   338                       val res = final rew_th
   339                       val lhs = (#1 (Logic.dest_equals (prop_of res)))
   340                   in
   341                        SOME res
   342                   end
   343               else NONE)
   344              handle e => OldGoals.print_exn e)
   345           | _ => NONE
   346        end
   347 
   348 fun beta_fun thy assume t =
   349     SOME (beta_conversion true (cterm_of thy t))
   350 
   351 val meta_sym_rew = thm "refl"
   352 
   353 fun equals_fun thy assume t =
   354     case t of
   355         Const("op ==",_) $ u $ v => if Term.term_ord (u,v) = LESS then SOME (meta_sym_rew) else NONE
   356       | _ => NONE
   357 
   358 fun eta_expand thy assumes origt =
   359     let
   360         val (typet,Tinst) = freeze_thaw_term origt
   361         val (init,thaw) = freeze_thaw (reflexive (cterm_of thy typet))
   362         val final = inst_tfrees thy Tinst o thaw
   363         val t = #1 (Logic.dest_equals (prop_of init))
   364         val _ =
   365             let
   366                 val lhs = #1 (Logic.dest_equals (prop_of (final init)))
   367             in
   368                 if not (lhs aconv origt)
   369                 then (writeln "Something is utterly wrong: (orig,lhs,frozen type,t,tinst)";
   370                       writeln (string_of_cterm (cterm_of thy origt));
   371                       writeln (string_of_cterm (cterm_of thy lhs));
   372                       writeln (string_of_cterm (cterm_of thy typet));
   373                       writeln (string_of_cterm (cterm_of thy t));
   374                       app (fn (n,T) => writeln (n ^ ": " ^ (string_of_ctyp (ctyp_of thy T)))) Tinst;
   375                       writeln "done")
   376                 else ()
   377             end
   378     in
   379         case t of
   380             Const("==",T) $ P $ Q =>
   381             if is_Abs P orelse is_Abs Q
   382             then (case domain_type T of
   383                       Type("fun",[aT,bT]) =>
   384                       let
   385                           val cert = cterm_of thy
   386                           val vname = Name.variant (add_term_free_names(t,[])) "v"
   387                           val v = Free(vname,aT)
   388                           val cv = cert v
   389                           val ct = cert t
   390                           val th1 = (combination (assume ct) (reflexive cv))
   391                                         |> forall_intr cv
   392                                         |> implies_intr ct
   393                           val concl = cert (concl_of th1)
   394                           val th2 = (assume concl)
   395                                         |> forall_elim cv
   396                                         |> abstract_rule vname cv
   397                           val (lhs,rhs) = Logic.dest_equals (prop_of th2)
   398                           val elhs = eta_conversion (cert lhs)
   399                           val erhs = eta_conversion (cert rhs)
   400                           val th2' = transitive
   401                                          (transitive (symmetric elhs) th2)
   402                                          erhs
   403                           val res = equal_intr th1 (th2' |> implies_intr concl)
   404                           val res' = final res
   405                       in
   406                           SOME res'
   407                       end
   408                     | _ => NONE)
   409             else NONE
   410           | _ => (error ("Bad eta_expand argument" ^ (string_of_cterm (cterm_of thy t))); NONE)
   411     end
   412     handle e => (writeln "eta_expand internal error"; OldGoals.print_exn e)
   413 
   414 fun mk_tfree s = TFree("'"^s,[])
   415 fun mk_free s t = Free (s,t)
   416 val xT = mk_tfree "a"
   417 val yT = mk_tfree "b"
   418 val P  = mk_free "P" (xT-->yT-->propT)
   419 val Q  = mk_free "Q" (xT-->yT)
   420 val R  = mk_free "R" (xT-->yT)
   421 val S  = mk_free "S" xT
   422 val S'  = mk_free "S'" xT
   423 in
   424 fun beta_simproc thy = Simplifier.simproc_i
   425                       thy
   426                       "Beta-contraction"
   427                       [Abs("x",xT,Q) $ S]
   428                       beta_fun
   429 
   430 fun equals_simproc thy = Simplifier.simproc_i
   431                       thy
   432                       "Ordered rewriting of meta equalities"
   433                       [Const("op ==",xT) $ S $ S']
   434                       equals_fun
   435 
   436 fun quant_simproc thy = Simplifier.simproc_i
   437                            thy
   438                            "Ordered rewriting of nested quantifiers"
   439                            [all xT $ (Abs("x",xT,all yT $ (Abs("y",yT,P $ Bound 1 $ Bound 0))))]
   440                            quant_rewrite
   441 fun eta_expand_simproc thy = Simplifier.simproc_i
   442                          thy
   443                          "Smart eta-expansion by equivalences"
   444                          [Logic.mk_equals(Q,R)]
   445                          eta_expand
   446 fun eta_contract_simproc thy = Simplifier.simproc_i
   447                          thy
   448                          "Smart handling of eta-contractions"
   449                          [all xT $ (Abs("x",xT,Logic.mk_equals(Q $ Bound 0,R $ Bound 0)))]
   450                          eta_contract
   451 end
   452 
   453 (* Disambiguates the names of bound variables in a term, returning t
   454 == t' where all the names of bound variables in t' are unique *)
   455 
   456 fun disamb_bound thy t =
   457     let
   458 
   459         fun F (t $ u,idx) =
   460             let
   461                 val (t',idx') = F (t,idx)
   462                 val (u',idx'') = F (u,idx')
   463             in
   464                 (t' $ u',idx'')
   465             end
   466           | F (Abs(x,xT,t),idx) =
   467             let
   468                 val x' = "x" ^ (LargeInt.toString idx) (* amazing *)
   469                 val (t',idx') = F (t,idx+1)
   470             in
   471                 (Abs(x',xT,t'),idx')
   472             end
   473           | F arg = arg
   474         val (t',_) = F (t,0)
   475         val ct = cterm_of thy t
   476         val ct' = cterm_of thy t'
   477         val res = transitive (reflexive ct) (reflexive ct')
   478         val _ = message ("disamb_term: " ^ (string_of_thm res))
   479     in
   480         res
   481     end
   482 
   483 (* Transforms a term t to some normal form t', returning the theorem t
   484 == t'.  This is originally a help function for make_equal, but might
   485 be handy in its own right, for example for indexing terms. *)
   486 
   487 fun norm_term thy t =
   488     let
   489         val norms = ShuffleData.get thy
   490         val ss = Simplifier.theory_context thy empty_ss
   491           setmksimps single
   492           addsimps (map (Thm.transfer thy) norms)
   493           addsimprocs [quant_simproc thy, eta_expand_simproc thy,eta_contract_simproc thy]
   494         fun chain f th =
   495             let
   496                 val rhs = Thm.rhs_of th
   497             in
   498                 transitive th (f rhs)
   499             end
   500         val th =
   501             t |> disamb_bound thy
   502               |> chain (Simplifier.full_rewrite ss)
   503               |> chain eta_conversion
   504               |> strip_shyps
   505         val _ = message ("norm_term: " ^ (string_of_thm th))
   506     in
   507         th
   508     end
   509     handle e => (writeln "norm_term internal error"; print_sign_exn thy e)
   510 
   511 
   512 (* Closes a theorem with respect to free and schematic variables (does
   513 not touch type variables, though). *)
   514 
   515 fun close_thm th =
   516     let
   517         val thy = Thm.theory_of_thm th
   518         val c = prop_of th
   519         val vars = add_term_frees (c,add_term_vars(c,[]))
   520     in
   521         Drule.forall_intr_list (map (cterm_of thy) vars) th
   522     end
   523     handle e => (writeln "close_thm internal error"; OldGoals.print_exn e)
   524 
   525 (* Normalizes a theorem's conclusion using norm_term. *)
   526 
   527 fun norm_thm thy th =
   528     let
   529         val c = prop_of th
   530     in
   531         equal_elim (norm_term thy c) th
   532     end
   533 
   534 (* make_equal thy t u tries to construct the theorem t == u under the
   535 signature thy.  If it succeeds, SOME (t == u) is returned, otherwise
   536 NONE is returned. *)
   537 
   538 fun make_equal thy t u =
   539     let
   540         val t_is_t' = norm_term thy t
   541         val u_is_u' = norm_term thy u
   542         val th = transitive t_is_t' (symmetric u_is_u')
   543         val _ = message ("make_equal: SOME " ^ (string_of_thm th))
   544     in
   545         SOME th
   546     end
   547     handle e as THM _ => (message "make_equal: NONE";NONE)
   548 
   549 fun match_consts ignore t (* th *) =
   550     let
   551         fun add_consts (Const (c, _), cs) =
   552             if c mem_string ignore
   553             then cs
   554             else insert (op =) c cs
   555           | add_consts (t $ u, cs) = add_consts (t, add_consts (u, cs))
   556           | add_consts (Abs (_, _, t), cs) = add_consts (t, cs)
   557           | add_consts (_, cs) = cs
   558         val t_consts = add_consts(t,[])
   559     in
   560      fn (name,th) =>
   561         let
   562             val th_consts = add_consts(prop_of th,[])
   563         in
   564             eq_set(t_consts,th_consts)
   565         end
   566     end
   567 
   568 val collect_ignored =
   569     fold_rev (fn thm => fn cs =>
   570               let
   571                   val (lhs,rhs) = Logic.dest_equals (prop_of thm)
   572                   val ignore_lhs = term_consts lhs \\ term_consts rhs
   573                   val ignore_rhs = term_consts rhs \\ term_consts lhs
   574               in
   575                   fold_rev (insert (op =)) cs (ignore_lhs @ ignore_rhs)
   576               end)
   577 
   578 (* set_prop t thms tries to make a theorem with the proposition t from
   579 one of the theorems thms, by shuffling the propositions around.  If it
   580 succeeds, SOME theorem is returned, otherwise NONE.  *)
   581 
   582 fun set_prop thy t =
   583     let
   584         val vars = add_term_frees (t,add_term_vars (t,[]))
   585         val closed_t = Library.foldr (fn (v, body) =>
   586       let val vT = type_of v in all vT $ (Abs ("x", vT, abstract_over (v, body))) end) (vars, t)
   587         val rew_th = norm_term thy closed_t
   588         val rhs = Thm.rhs_of rew_th
   589 
   590         val shuffles = ShuffleData.get thy
   591         fun process [] = NONE
   592           | process ((name,th)::thms) =
   593             let
   594                 val norm_th = Thm.varifyT (norm_thm thy (close_thm (Thm.transfer thy th)))
   595                 val triv_th = trivial rhs
   596                 val _ = message ("Shuffler.set_prop: Gluing together " ^ (string_of_thm norm_th) ^ " and " ^ (string_of_thm triv_th))
   597                 val mod_th = case Seq.pull (bicompose false (*true*) (false,norm_th,0) 1 triv_th) of
   598                                  SOME(th,_) => SOME th
   599                                | NONE => NONE
   600             in
   601                 case mod_th of
   602                     SOME mod_th =>
   603                     let
   604                         val closed_th = equal_elim (symmetric rew_th) mod_th
   605                     in
   606                         message ("Shuffler.set_prop succeeded by " ^ name);
   607                         SOME (name,forall_elim_list (map (cterm_of thy) vars) closed_th)
   608                     end
   609                   | NONE => process thms
   610             end
   611             handle e as THM _ => process thms
   612     in
   613         fn thms =>
   614            case process thms of
   615                res as SOME (name,th) => if (prop_of th) aconv t
   616                                         then res
   617                                         else error "Internal error in set_prop"
   618              | NONE => NONE
   619     end
   620     handle e => (writeln "set_prop internal error"; OldGoals.print_exn e)
   621 
   622 fun find_potential thy t =
   623     let
   624         val shuffles = ShuffleData.get thy
   625         val ignored = collect_ignored shuffles []
   626         val rel_consts = term_consts t \\ ignored
   627         val pot_thms = PureThy.thms_containing_consts thy rel_consts
   628     in
   629         List.filter (match_consts ignored t) pot_thms
   630     end
   631 
   632 fun gen_shuffle_tac thy search thms i st =
   633     let
   634         val _ = message ("Shuffling " ^ (string_of_thm st))
   635         val t = List.nth(prems_of st,i-1)
   636         val set = set_prop thy t
   637         fun process_tac thms st =
   638             case set thms of
   639                 SOME (_,th) => Seq.of_list (compose (th,i,st))
   640               | NONE => Seq.empty
   641     in
   642         (process_tac thms APPEND (if search
   643                                   then process_tac (find_potential thy t)
   644                                   else no_tac)) st
   645     end
   646 
   647 fun shuffle_tac thms i st =
   648     gen_shuffle_tac (the_context()) false thms i st
   649 
   650 fun search_tac thms i st =
   651     gen_shuffle_tac (the_context()) true thms i st
   652 
   653 fun shuffle_meth (thms:thm list) ctxt =
   654     let
   655         val thy = ProofContext.theory_of ctxt
   656     in
   657         Method.SIMPLE_METHOD' (gen_shuffle_tac thy false (map (pair "") thms))
   658     end
   659 
   660 fun search_meth ctxt =
   661     let
   662         val thy = ProofContext.theory_of ctxt
   663         val prems = Assumption.prems_of ctxt
   664     in
   665         Method.SIMPLE_METHOD' (gen_shuffle_tac thy true (map (pair "premise") prems))
   666     end
   667 
   668 fun add_shuffle_rule thm thy =
   669     let
   670         val shuffles = ShuffleData.get thy
   671     in
   672         if exists (curry Thm.eq_thm thm) shuffles
   673         then (warning ((string_of_thm thm) ^ " already known to the shuffler");
   674               thy)
   675         else ShuffleData.put (thm::shuffles) thy
   676     end
   677 
   678 val shuffle_attr = Thm.declaration_attribute (fn th => Context.mapping (add_shuffle_rule th) I);
   679 
   680 val setup =
   681   Method.add_method ("shuffle_tac",
   682     Method.thms_ctxt_args shuffle_meth,"solve goal by shuffling terms around") #>
   683   Method.add_method ("search_tac",
   684     Method.ctxt_args search_meth,"search for suitable theorems") #>
   685   add_shuffle_rule weaken #>
   686   add_shuffle_rule equiv_comm #>
   687   add_shuffle_rule imp_comm #>
   688   add_shuffle_rule Drule.norm_hhf_eq #>
   689   add_shuffle_rule Drule.triv_forall_equality #>
   690   Attrib.add_attributes [("shuffle_rule", Attrib.no_args shuffle_attr, "declare rule for shuffler")]
   691 
   692 end