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