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