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