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