src/Pure/thm.ML
author nipkow
Wed Oct 07 18:17:37 1998 +0200 (1998-10-07)
changeset 5623 75b513db9a3a
parent 5494 2df1a9d43e3c
child 5624 4813dd0fe6e5
permissions -rw-r--r--
Tuned simplifier not to re-normalized already normalized terms.
wenzelm@250
     1
(*  Title:      Pure/thm.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@250
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
lcp@229
     4
    Copyright   1994  University of Cambridge
lcp@229
     5
wenzelm@1160
     6
The core of Isabelle's Meta Logic: certified types and terms, meta
paulson@1529
     7
theorems, meta rules (including resolution and simplification).
clasohm@0
     8
*)
clasohm@0
     9
wenzelm@250
    10
signature THM =
paulson@1503
    11
  sig
wenzelm@1160
    12
  (*certified types*)
wenzelm@387
    13
  type ctyp
wenzelm@1238
    14
  val rep_ctyp          : ctyp -> {sign: Sign.sg, T: typ}
wenzelm@1238
    15
  val typ_of            : ctyp -> typ
wenzelm@1238
    16
  val ctyp_of           : Sign.sg -> typ -> ctyp
wenzelm@1238
    17
  val read_ctyp         : Sign.sg -> string -> ctyp
wenzelm@1160
    18
wenzelm@1160
    19
  (*certified terms*)
wenzelm@1160
    20
  type cterm
clasohm@1493
    21
  exception CTERM of string
wenzelm@4270
    22
  val rep_cterm         : cterm -> {sign: Sign.sg, t: term, T: typ, maxidx: int}
wenzelm@4288
    23
  val crep_cterm        : cterm -> {sign: Sign.sg, t: term, T: ctyp, maxidx: int}
wenzelm@1238
    24
  val term_of           : cterm -> term
wenzelm@1238
    25
  val cterm_of          : Sign.sg -> term -> cterm
paulson@2671
    26
  val ctyp_of_term      : cterm -> ctyp
wenzelm@1238
    27
  val read_cterm        : Sign.sg -> string * typ -> cterm
wenzelm@1238
    28
  val cterm_fun         : (term -> term) -> (cterm -> cterm)
clasohm@1493
    29
  val dest_comb         : cterm -> cterm * cterm
clasohm@1493
    30
  val dest_abs          : cterm -> cterm * cterm
clasohm@1703
    31
  val adjust_maxidx     : cterm -> cterm
clasohm@1516
    32
  val capply            : cterm -> cterm -> cterm
clasohm@1517
    33
  val cabs              : cterm -> cterm -> cterm
wenzelm@1238
    34
  val read_def_cterm    :
wenzelm@1160
    35
    Sign.sg * (indexname -> typ option) * (indexname -> sort option) ->
wenzelm@1160
    36
    string list -> bool -> string * typ -> cterm * (indexname * typ) list
nipkow@4281
    37
  val read_def_cterms   :
nipkow@4281
    38
    Sign.sg * (indexname -> typ option) * (indexname -> sort option) ->
nipkow@4281
    39
    string list -> bool -> (string * typ)list
nipkow@4281
    40
    -> cterm list * (indexname * typ)list
wenzelm@1160
    41
paulson@2671
    42
  (*proof terms [must DUPLICATE declaration as a specification]*)
paulson@1597
    43
  datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
wenzelm@2386
    44
  val keep_derivs       : deriv_kind ref
paulson@1529
    45
  datatype rule = 
wenzelm@2386
    46
      MinProof                          
wenzelm@4999
    47
    | Oracle		  of string * Sign.sg * Object.T
wenzelm@4182
    48
    | Axiom               of string
paulson@2671
    49
    | Theorem             of string       
paulson@2671
    50
    | Assume              of cterm
paulson@2671
    51
    | Implies_intr        of cterm
paulson@1529
    52
    | Implies_intr_shyps
paulson@1529
    53
    | Implies_intr_hyps
paulson@1529
    54
    | Implies_elim 
paulson@2671
    55
    | Forall_intr         of cterm
paulson@2671
    56
    | Forall_elim         of cterm
paulson@2671
    57
    | Reflexive           of cterm
paulson@1529
    58
    | Symmetric 
paulson@1529
    59
    | Transitive
paulson@2671
    60
    | Beta_conversion     of cterm
paulson@1529
    61
    | Extensional
paulson@2671
    62
    | Abstract_rule       of string * cterm
paulson@1529
    63
    | Combination
paulson@1529
    64
    | Equal_intr
paulson@1529
    65
    | Equal_elim
paulson@2671
    66
    | Trivial             of cterm
paulson@2671
    67
    | Lift_rule           of cterm * int 
paulson@2671
    68
    | Assumption          of int * Envir.env option
paulson@2671
    69
    | Rotate_rule         of int * int
paulson@2671
    70
    | Instantiate         of (indexname * ctyp) list * (cterm * cterm) list
paulson@2671
    71
    | Bicompose           of bool * bool * int * int * Envir.env
paulson@2671
    72
    | Flexflex_rule       of Envir.env            
wenzelm@4182
    73
    | Class_triv          of class       
paulson@1529
    74
    | VarifyT
paulson@1529
    75
    | FreezeT
paulson@2671
    76
    | RewriteC            of cterm
paulson@2671
    77
    | CongC               of cterm
paulson@2671
    78
    | Rewrite_cterm       of cterm
paulson@2671
    79
    | Rename_params_rule  of string list * int;
paulson@1529
    80
paulson@1597
    81
  type deriv   (* = rule mtree *)
paulson@1529
    82
wenzelm@1160
    83
  (*meta theorems*)
wenzelm@1160
    84
  type thm
wenzelm@1160
    85
  exception THM of string * int * thm list
paulson@1529
    86
  val rep_thm           : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
wenzelm@2386
    87
                                  shyps: sort list, hyps: term list, 
wenzelm@2386
    88
                                  prop: term}
paulson@1529
    89
  val crep_thm          : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
wenzelm@2386
    90
                                  shyps: sort list, hyps: cterm list, 
wenzelm@2386
    91
                                  prop: cterm}
wenzelm@3994
    92
  val eq_thm		: thm * thm -> bool
wenzelm@3967
    93
  val sign_of_thm       : thm -> Sign.sg
wenzelm@4254
    94
  val transfer_sg	: Sign.sg -> thm -> thm
wenzelm@3895
    95
  val transfer		: theory -> thm -> thm
wenzelm@1238
    96
  val tpairs_of         : thm -> (term * term) list
wenzelm@1238
    97
  val prems_of          : thm -> term list
wenzelm@1238
    98
  val nprems_of         : thm -> int
wenzelm@1238
    99
  val concl_of          : thm -> term
wenzelm@1238
   100
  val cprop_of          : thm -> cterm
wenzelm@1238
   101
  val extra_shyps       : thm -> sort list
wenzelm@3061
   102
  val force_strip_shyps : bool ref      (* FIXME tmp (since 1995/08/01) *)
wenzelm@1238
   103
  val strip_shyps       : thm -> thm
wenzelm@1238
   104
  val implies_intr_shyps: thm -> thm
wenzelm@3812
   105
  val get_axiom         : theory -> xstring -> thm
wenzelm@4847
   106
  val get_def           : theory -> xstring -> thm
paulson@1597
   107
  val name_thm          : string * thm -> thm
wenzelm@4018
   108
  val name_of_thm	: thm -> string
wenzelm@1238
   109
  val axioms_of         : theory -> (string * thm) list
wenzelm@1160
   110
wenzelm@1160
   111
  (*meta rules*)
wenzelm@1238
   112
  val assume            : cterm -> thm
paulson@1416
   113
  val compress          : thm -> thm
wenzelm@1238
   114
  val implies_intr      : cterm -> thm -> thm
wenzelm@1238
   115
  val implies_elim      : thm -> thm -> thm
wenzelm@1238
   116
  val forall_intr       : cterm -> thm -> thm
wenzelm@1238
   117
  val forall_elim       : cterm -> thm -> thm
wenzelm@1238
   118
  val reflexive         : cterm -> thm
wenzelm@1238
   119
  val symmetric         : thm -> thm
wenzelm@1238
   120
  val transitive        : thm -> thm -> thm
wenzelm@1238
   121
  val beta_conversion   : cterm -> thm
wenzelm@1238
   122
  val extensional       : thm -> thm
wenzelm@1238
   123
  val abstract_rule     : string -> cterm -> thm -> thm
wenzelm@1238
   124
  val combination       : thm -> thm -> thm
wenzelm@1238
   125
  val equal_intr        : thm -> thm -> thm
wenzelm@1238
   126
  val equal_elim        : thm -> thm -> thm
wenzelm@1238
   127
  val implies_intr_hyps : thm -> thm
wenzelm@4270
   128
  val flexflex_rule     : thm -> thm Seq.seq
wenzelm@1238
   129
  val instantiate       :
wenzelm@1160
   130
    (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
wenzelm@1238
   131
  val trivial           : cterm -> thm
wenzelm@1238
   132
  val class_triv        : theory -> class -> thm
wenzelm@1238
   133
  val varifyT           : thm -> thm
wenzelm@1238
   134
  val freezeT           : thm -> thm
wenzelm@1238
   135
  val dest_state        : thm * int ->
wenzelm@1160
   136
    (term * term) list * term list * term * term
wenzelm@1238
   137
  val lift_rule         : (thm * int) -> thm -> thm
wenzelm@4270
   138
  val assumption        : int -> thm -> thm Seq.seq
wenzelm@1238
   139
  val eq_assumption     : int -> thm -> thm
paulson@2671
   140
  val rotate_rule       : int -> int -> thm -> thm
wenzelm@1160
   141
  val rename_params_rule: string list * int -> thm -> thm
wenzelm@1238
   142
  val bicompose         : bool -> bool * thm * int ->
wenzelm@4270
   143
    int -> thm -> thm Seq.seq
wenzelm@1238
   144
  val biresolution      : bool -> (bool * thm) list ->
wenzelm@4270
   145
    int -> thm -> thm Seq.seq
wenzelm@1160
   146
wenzelm@1160
   147
  (*meta simplification*)
wenzelm@3550
   148
  exception SIMPLIFIER of string * thm
wenzelm@1160
   149
  type meta_simpset
wenzelm@3550
   150
  val dest_mss		: meta_simpset ->
wenzelm@3550
   151
    {simps: thm list, congs: thm list, procs: (string * cterm list) list}
wenzelm@1238
   152
  val empty_mss         : meta_simpset
wenzelm@3550
   153
  val merge_mss		: meta_simpset * meta_simpset -> meta_simpset
wenzelm@1238
   154
  val add_simps         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   155
  val del_simps         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   156
  val mss_of            : thm list -> meta_simpset
wenzelm@1238
   157
  val add_congs         : meta_simpset * thm list -> meta_simpset
oheimb@2626
   158
  val del_congs         : meta_simpset * thm list -> meta_simpset
wenzelm@2509
   159
  val add_simprocs	: meta_simpset *
wenzelm@3577
   160
    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
wenzelm@3577
   161
      -> meta_simpset
wenzelm@2509
   162
  val del_simprocs	: meta_simpset *
wenzelm@3577
   163
    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
wenzelm@3577
   164
      -> meta_simpset
wenzelm@1238
   165
  val add_prems         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   166
  val prems_of_mss      : meta_simpset -> thm list
wenzelm@1238
   167
  val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
nipkow@4679
   168
  val set_mk_sym        : meta_simpset * (thm -> thm option) -> meta_simpset
nipkow@4679
   169
  val set_mk_eq_True    : meta_simpset * (thm -> thm option) -> meta_simpset
wenzelm@2509
   170
  val set_termless      : meta_simpset * (term * term -> bool) -> meta_simpset
wenzelm@1238
   171
  val trace_simp        : bool ref
nipkow@4713
   172
  val rewrite_cterm     : bool * bool * bool -> meta_simpset ->
paulson@1529
   173
                          (meta_simpset -> thm -> thm option) -> cterm -> thm
paulson@1539
   174
wenzelm@4999
   175
  val invoke_oracle     : theory -> xstring -> Sign.sg * Object.T -> thm
wenzelm@250
   176
end;
clasohm@0
   177
wenzelm@3550
   178
structure Thm: THM =
clasohm@0
   179
struct
wenzelm@250
   180
wenzelm@387
   181
(*** Certified terms and types ***)
wenzelm@387
   182
wenzelm@250
   183
(** certified types **)
wenzelm@250
   184
wenzelm@250
   185
(*certified typs under a signature*)
wenzelm@250
   186
wenzelm@3967
   187
datatype ctyp = Ctyp of {sign_ref: Sign.sg_ref, T: typ};
wenzelm@250
   188
wenzelm@3967
   189
fun rep_ctyp (Ctyp {sign_ref, T}) = {sign = Sign.deref sign_ref, T = T};
wenzelm@250
   190
fun typ_of (Ctyp {T, ...}) = T;
wenzelm@250
   191
wenzelm@250
   192
fun ctyp_of sign T =
wenzelm@3967
   193
  Ctyp {sign_ref = Sign.self_ref sign, T = Sign.certify_typ sign T};
wenzelm@250
   194
wenzelm@250
   195
fun read_ctyp sign s =
wenzelm@3967
   196
  Ctyp {sign_ref = Sign.self_ref sign, T = Sign.read_typ (sign, K None) s};
lcp@229
   197
lcp@229
   198
lcp@229
   199
wenzelm@250
   200
(** certified terms **)
lcp@229
   201
wenzelm@250
   202
(*certified terms under a signature, with checked typ and maxidx of Vars*)
lcp@229
   203
wenzelm@3967
   204
datatype cterm = Cterm of {sign_ref: Sign.sg_ref, t: term, T: typ, maxidx: int};
lcp@229
   205
wenzelm@3967
   206
fun rep_cterm (Cterm {sign_ref, t, T, maxidx}) =
wenzelm@3967
   207
  {sign = Sign.deref sign_ref, t = t, T = T, maxidx = maxidx};
wenzelm@3967
   208
wenzelm@4288
   209
fun crep_cterm (Cterm {sign_ref, t, T, maxidx}) =
wenzelm@4288
   210
  {sign = Sign.deref sign_ref, t = t, T = Ctyp {sign_ref = sign_ref, T = T},
wenzelm@4288
   211
    maxidx = maxidx};
wenzelm@4288
   212
wenzelm@250
   213
fun term_of (Cterm {t, ...}) = t;
lcp@229
   214
wenzelm@3967
   215
fun ctyp_of_term (Cterm {sign_ref, T, ...}) = Ctyp {sign_ref = sign_ref, T = T};
paulson@2671
   216
wenzelm@250
   217
(*create a cterm by checking a "raw" term with respect to a signature*)
wenzelm@250
   218
fun cterm_of sign tm =
wenzelm@250
   219
  let val (t, T, maxidx) = Sign.certify_term sign tm
wenzelm@3967
   220
  in  Cterm {sign_ref = Sign.self_ref sign, t = t, T = T, maxidx = maxidx}
paulson@1394
   221
  end;
lcp@229
   222
wenzelm@3967
   223
fun cterm_fun f (Cterm {sign_ref, t, ...}) = cterm_of (Sign.deref sign_ref) (f t);
wenzelm@250
   224
lcp@229
   225
clasohm@1493
   226
exception CTERM of string;
clasohm@1493
   227
clasohm@1493
   228
(*Destruct application in cterms*)
wenzelm@3967
   229
fun dest_comb (Cterm {sign_ref, T, maxidx, t = A $ B}) =
clasohm@1493
   230
      let val typeA = fastype_of A;
clasohm@1493
   231
          val typeB =
clasohm@1493
   232
            case typeA of Type("fun",[S,T]) => S
clasohm@1493
   233
                        | _ => error "Function type expected in dest_comb";
clasohm@1493
   234
      in
wenzelm@3967
   235
      (Cterm {sign_ref=sign_ref, maxidx=maxidx, t=A, T=typeA},
wenzelm@3967
   236
       Cterm {sign_ref=sign_ref, maxidx=maxidx, t=B, T=typeB})
clasohm@1493
   237
      end
clasohm@1493
   238
  | dest_comb _ = raise CTERM "dest_comb";
clasohm@1493
   239
clasohm@1493
   240
(*Destruct abstraction in cterms*)
wenzelm@3967
   241
fun dest_abs (Cterm {sign_ref, T as Type("fun",[_,S]), maxidx, t=Abs(x,ty,M)}) = 
clasohm@1516
   242
      let val (y,N) = variant_abs (x,ty,M)
wenzelm@3967
   243
      in (Cterm {sign_ref = sign_ref, T = ty, maxidx = 0, t = Free(y,ty)},
wenzelm@3967
   244
          Cterm {sign_ref = sign_ref, T = S, maxidx = maxidx, t = N})
clasohm@1493
   245
      end
clasohm@1493
   246
  | dest_abs _ = raise CTERM "dest_abs";
clasohm@1493
   247
paulson@2147
   248
(*Makes maxidx precise: it is often too big*)
wenzelm@3967
   249
fun adjust_maxidx (ct as Cterm {sign_ref, T, t, maxidx, ...}) =
paulson@2147
   250
  if maxidx = ~1 then ct 
wenzelm@3967
   251
  else  Cterm {sign_ref = sign_ref, T = T, maxidx = maxidx_of_term t, t = t};
clasohm@1703
   252
clasohm@1516
   253
(*Form cterm out of a function and an argument*)
wenzelm@3967
   254
fun capply (Cterm {t=f, sign_ref=sign_ref1, T=Type("fun",[dty,rty]), maxidx=maxidx1})
wenzelm@3967
   255
           (Cterm {t=x, sign_ref=sign_ref2, T, maxidx=maxidx2}) =
wenzelm@3967
   256
      if T = dty then Cterm{t=f$x, sign_ref=Sign.merge_refs(sign_ref1,sign_ref2), T=rty,
paulson@2147
   257
                            maxidx=Int.max(maxidx1, maxidx2)}
clasohm@1516
   258
      else raise CTERM "capply: types don't agree"
clasohm@1516
   259
  | capply _ _ = raise CTERM "capply: first arg is not a function"
wenzelm@250
   260
wenzelm@3967
   261
fun cabs (Cterm {t=Free(a,ty), sign_ref=sign_ref1, T=T1, maxidx=maxidx1})
wenzelm@3967
   262
         (Cterm {t=t2, sign_ref=sign_ref2, T=T2, maxidx=maxidx2}) =
wenzelm@3967
   263
      Cterm {t=absfree(a,ty,t2), sign_ref=Sign.merge_refs(sign_ref1,sign_ref2),
paulson@2147
   264
             T = ty --> T2, maxidx=Int.max(maxidx1, maxidx2)}
clasohm@1517
   265
  | cabs _ _ = raise CTERM "cabs: first arg is not a free variable";
lcp@229
   266
wenzelm@2509
   267
wenzelm@2509
   268
wenzelm@574
   269
(** read cterms **)   (*exception ERROR*)
wenzelm@250
   270
nipkow@4281
   271
(*read terms, infer types, certify terms*)
nipkow@4281
   272
fun read_def_cterms (sign, types, sorts) used freeze sTs =
wenzelm@250
   273
  let
nipkow@4281
   274
    val syn = #syn (Sign.rep_sg sign)
nipkow@4281
   275
    fun read(s,T) =
nipkow@4281
   276
      let val T' = Sign.certify_typ sign T
nipkow@4281
   277
                   handle TYPE (msg, _, _) => error msg
nipkow@4281
   278
      in (Syntax.read syn T' s, T') end
nipkow@4281
   279
    val tsTs = map read sTs
nipkow@4281
   280
    val (ts',tye) = Sign.infer_types_simult sign types sorts used freeze tsTs;
nipkow@4281
   281
    val cts = map (cterm_of sign) ts'
wenzelm@2979
   282
      handle TYPE (msg, _, _) => error msg
wenzelm@2386
   283
           | TERM (msg, _) => error msg;
nipkow@4281
   284
  in (cts, tye) end;
nipkow@4281
   285
nipkow@4281
   286
(*read term, infer types, certify term*)
nipkow@4281
   287
fun read_def_cterm args used freeze aT =
nipkow@4281
   288
  let val ([ct],tye) = read_def_cterms args used freeze [aT]
nipkow@4281
   289
  in (ct,tye) end;
lcp@229
   290
nipkow@949
   291
fun read_cterm sign = #1 o read_def_cterm (sign, K None, K None) [] true;
lcp@229
   292
wenzelm@250
   293
wenzelm@250
   294
paulson@1529
   295
(*** Derivations ***)
paulson@1529
   296
paulson@1529
   297
(*Names of rules in derivations.  Includes logically trivial rules, if 
paulson@1529
   298
  executed in ML.*)
paulson@1529
   299
datatype rule = 
wenzelm@2386
   300
    MinProof                            (*for building minimal proof terms*)
wenzelm@4999
   301
  | Oracle              of string * Sign.sg * Object.T       (*oracles*)
paulson@1529
   302
(*Axioms/theorems*)
wenzelm@4182
   303
  | Axiom               of string
wenzelm@2386
   304
  | Theorem             of string
paulson@1529
   305
(*primitive inferences and compound versions of them*)
wenzelm@2386
   306
  | Assume              of cterm
wenzelm@2386
   307
  | Implies_intr        of cterm
paulson@1529
   308
  | Implies_intr_shyps
paulson@1529
   309
  | Implies_intr_hyps
paulson@1529
   310
  | Implies_elim 
wenzelm@2386
   311
  | Forall_intr         of cterm
wenzelm@2386
   312
  | Forall_elim         of cterm
wenzelm@2386
   313
  | Reflexive           of cterm
paulson@1529
   314
  | Symmetric 
paulson@1529
   315
  | Transitive
wenzelm@2386
   316
  | Beta_conversion     of cterm
paulson@1529
   317
  | Extensional
wenzelm@2386
   318
  | Abstract_rule       of string * cterm
paulson@1529
   319
  | Combination
paulson@1529
   320
  | Equal_intr
paulson@1529
   321
  | Equal_elim
paulson@1529
   322
(*derived rules for tactical proof*)
wenzelm@2386
   323
  | Trivial             of cterm
wenzelm@2386
   324
        (*For lift_rule, the proof state is not a premise.
wenzelm@2386
   325
          Use cterm instead of thm to avoid mutual recursion.*)
wenzelm@2386
   326
  | Lift_rule           of cterm * int 
wenzelm@2386
   327
  | Assumption          of int * Envir.env option (*includes eq_assumption*)
paulson@2671
   328
  | Rotate_rule         of int * int
wenzelm@2386
   329
  | Instantiate         of (indexname * ctyp) list * (cterm * cterm) list
wenzelm@2386
   330
  | Bicompose           of bool * bool * int * int * Envir.env
wenzelm@2386
   331
  | Flexflex_rule       of Envir.env            (*identifies unifier chosen*)
paulson@1529
   332
(*other derived rules*)
wenzelm@4182
   333
  | Class_triv          of class
paulson@1529
   334
  | VarifyT
paulson@1529
   335
  | FreezeT
paulson@1529
   336
(*for the simplifier*)
wenzelm@2386
   337
  | RewriteC            of cterm
wenzelm@2386
   338
  | CongC               of cterm
wenzelm@2386
   339
  | Rewrite_cterm       of cterm
paulson@1529
   340
(*Logical identities, recorded since they are part of the proof process*)
wenzelm@2386
   341
  | Rename_params_rule  of string list * int;
paulson@1529
   342
paulson@1529
   343
paulson@1597
   344
type deriv = rule mtree;
paulson@1529
   345
paulson@1597
   346
datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
paulson@1529
   347
paulson@1597
   348
val keep_derivs = ref MinDeriv;
paulson@1529
   349
paulson@1529
   350
paulson@1597
   351
(*Build a minimal derivation.  Keep oracles; suppress atomic inferences;
paulson@1597
   352
  retain Theorems or their underlying links; keep anything else*)
paulson@1597
   353
fun squash_derivs [] = []
paulson@1597
   354
  | squash_derivs (der::ders) =
paulson@1597
   355
     (case der of
wenzelm@2386
   356
          Join (Oracle _, _) => der :: squash_derivs ders
wenzelm@2386
   357
        | Join (Theorem _, [der']) => if !keep_derivs=ThmDeriv 
wenzelm@2386
   358
                                      then der :: squash_derivs ders
wenzelm@2386
   359
                                      else squash_derivs (der'::ders)
wenzelm@2386
   360
        | Join (Axiom _, _) => if !keep_derivs=ThmDeriv 
wenzelm@2386
   361
                               then der :: squash_derivs ders
wenzelm@2386
   362
                               else squash_derivs ders
wenzelm@2386
   363
        | Join (_, [])      => squash_derivs ders
wenzelm@2386
   364
        | _                 => der :: squash_derivs ders);
paulson@1597
   365
paulson@1529
   366
paulson@1529
   367
(*Ensure sharing of the most likely derivation, the empty one!*)
paulson@1597
   368
val min_infer = Join (MinProof, []);
paulson@1529
   369
paulson@1529
   370
(*Make a minimal inference*)
paulson@1529
   371
fun make_min_infer []    = min_infer
paulson@1529
   372
  | make_min_infer [der] = der
paulson@1597
   373
  | make_min_infer ders  = Join (MinProof, ders);
paulson@1529
   374
paulson@1597
   375
fun infer_derivs (rl, [])   = Join (rl, [])
paulson@1529
   376
  | infer_derivs (rl, ders) =
paulson@1597
   377
    if !keep_derivs=FullDeriv then Join (rl, ders)
paulson@1529
   378
    else make_min_infer (squash_derivs ders);
paulson@1529
   379
paulson@1529
   380
wenzelm@2509
   381
wenzelm@387
   382
(*** Meta theorems ***)
lcp@229
   383
clasohm@0
   384
datatype thm = Thm of
wenzelm@3967
   385
 {sign_ref: Sign.sg_ref,       (*mutable reference to signature*)
wenzelm@3967
   386
  der: deriv,                  (*derivation*)
wenzelm@3967
   387
  maxidx: int,                 (*maximum index of any Var or TVar*)
wenzelm@3967
   388
  shyps: sort list,            (*sort hypotheses*)
wenzelm@3967
   389
  hyps: term list,             (*hypotheses*)
wenzelm@3967
   390
  prop: term};                 (*conclusion*)
clasohm@0
   391
wenzelm@3967
   392
fun rep_thm (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
wenzelm@3967
   393
  {sign = Sign.deref sign_ref, der = der, maxidx = maxidx,
wenzelm@3967
   394
    shyps = shyps, hyps = hyps, prop = prop};
clasohm@0
   395
paulson@1529
   396
(*Version of rep_thm returning cterms instead of terms*)
wenzelm@3967
   397
fun crep_thm (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
wenzelm@3967
   398
  let fun ctermf max t = Cterm{sign_ref=sign_ref, t=t, T=propT, maxidx=max};
wenzelm@3967
   399
  in {sign = Sign.deref sign_ref, der = der, maxidx = maxidx, shyps = shyps,
paulson@1529
   400
      hyps = map (ctermf ~1) hyps,
paulson@1529
   401
      prop = ctermf maxidx prop}
clasohm@1517
   402
  end;
clasohm@1517
   403
wenzelm@387
   404
(*errors involving theorems*)
clasohm@0
   405
exception THM of string * int * thm list;
clasohm@0
   406
wenzelm@3994
   407
(*equality of theorems uses equality of signatures and the
wenzelm@3994
   408
  a-convertible test for terms*)
wenzelm@3994
   409
fun eq_thm (th1, th2) =
wenzelm@3994
   410
  let
wenzelm@3994
   411
    val {sign = sg1, shyps = shyps1, hyps = hyps1, prop = prop1, ...} = rep_thm th1;
wenzelm@3994
   412
    val {sign = sg2, shyps = shyps2, hyps = hyps2, prop = prop2, ...} = rep_thm th2;
wenzelm@3994
   413
  in
wenzelm@3994
   414
    Sign.eq_sg (sg1, sg2) andalso
wenzelm@3994
   415
    eq_set_sort (shyps1, shyps2) andalso
wenzelm@3994
   416
    aconvs (hyps1, hyps2) andalso
wenzelm@3994
   417
    prop1 aconv prop2
wenzelm@3994
   418
  end;
wenzelm@387
   419
wenzelm@3967
   420
fun sign_of_thm (Thm {sign_ref, ...}) = Sign.deref sign_ref;
clasohm@0
   421
wenzelm@387
   422
(*merge signatures of two theorems; raise exception if incompatible*)
wenzelm@3967
   423
fun merge_thm_sgs
wenzelm@3967
   424
    (th1 as Thm {sign_ref = sgr1, ...}, th2 as Thm {sign_ref = sgr2, ...}) =
wenzelm@3967
   425
  Sign.merge_refs (sgr1, sgr2) handle TERM (msg, _) => raise THM (msg, 0, [th1, th2]);
wenzelm@387
   426
wenzelm@3967
   427
(*transfer thm to super theory (non-destructive)*)
wenzelm@4254
   428
fun transfer_sg sign' thm =
wenzelm@3895
   429
  let
wenzelm@3967
   430
    val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
wenzelm@3967
   431
    val sign = Sign.deref sign_ref;
wenzelm@3895
   432
  in
wenzelm@4254
   433
    if Sign.eq_sg (sign, sign') then thm
wenzelm@4254
   434
    else if Sign.subsig (sign, sign') then
wenzelm@3967
   435
      Thm {sign_ref = Sign.self_ref sign', der = der, maxidx = maxidx,
wenzelm@3895
   436
        shyps = shyps, hyps = hyps, prop = prop}
wenzelm@3895
   437
    else raise THM ("transfer: not a super theory", 0, [thm])
wenzelm@3895
   438
  end;
wenzelm@387
   439
wenzelm@4254
   440
val transfer = transfer_sg o sign_of;
wenzelm@4254
   441
wenzelm@387
   442
(*maps object-rule to tpairs*)
wenzelm@387
   443
fun tpairs_of (Thm {prop, ...}) = #1 (Logic.strip_flexpairs prop);
wenzelm@387
   444
wenzelm@387
   445
(*maps object-rule to premises*)
wenzelm@387
   446
fun prems_of (Thm {prop, ...}) =
wenzelm@387
   447
  Logic.strip_imp_prems (Logic.skip_flexpairs prop);
clasohm@0
   448
clasohm@0
   449
(*counts premises in a rule*)
wenzelm@387
   450
fun nprems_of (Thm {prop, ...}) =
wenzelm@387
   451
  Logic.count_prems (Logic.skip_flexpairs prop, 0);
clasohm@0
   452
wenzelm@387
   453
(*maps object-rule to conclusion*)
wenzelm@387
   454
fun concl_of (Thm {prop, ...}) = Logic.strip_imp_concl prop;
clasohm@0
   455
wenzelm@387
   456
(*the statement of any thm is a cterm*)
wenzelm@3967
   457
fun cprop_of (Thm {sign_ref, maxidx, prop, ...}) =
wenzelm@3967
   458
  Cterm {sign_ref = sign_ref, maxidx = maxidx, T = propT, t = prop};
lcp@229
   459
wenzelm@387
   460
clasohm@0
   461
wenzelm@1238
   462
(** sort contexts of theorems **)
wenzelm@1238
   463
wenzelm@1238
   464
(* basic utils *)
wenzelm@1238
   465
wenzelm@2163
   466
(*accumulate sorts suppressing duplicates; these are coded low levelly
wenzelm@1238
   467
  to improve efficiency a bit*)
wenzelm@1238
   468
wenzelm@1238
   469
fun add_typ_sorts (Type (_, Ts), Ss) = add_typs_sorts (Ts, Ss)
paulson@2177
   470
  | add_typ_sorts (TFree (_, S), Ss) = ins_sort(S,Ss)
paulson@2177
   471
  | add_typ_sorts (TVar (_, S), Ss) = ins_sort(S,Ss)
wenzelm@1238
   472
and add_typs_sorts ([], Ss) = Ss
wenzelm@1238
   473
  | add_typs_sorts (T :: Ts, Ss) = add_typs_sorts (Ts, add_typ_sorts (T, Ss));
wenzelm@1238
   474
wenzelm@1238
   475
fun add_term_sorts (Const (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   476
  | add_term_sorts (Free (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   477
  | add_term_sorts (Var (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   478
  | add_term_sorts (Bound _, Ss) = Ss
paulson@2177
   479
  | add_term_sorts (Abs (_,T,t), Ss) = add_term_sorts (t, add_typ_sorts (T,Ss))
wenzelm@1238
   480
  | add_term_sorts (t $ u, Ss) = add_term_sorts (t, add_term_sorts (u, Ss));
wenzelm@1238
   481
wenzelm@1238
   482
fun add_terms_sorts ([], Ss) = Ss
paulson@2177
   483
  | add_terms_sorts (t::ts, Ss) = add_terms_sorts (ts, add_term_sorts (t,Ss));
wenzelm@1238
   484
wenzelm@1258
   485
fun env_codT (Envir.Envir {iTs, ...}) = map snd iTs;
wenzelm@1258
   486
wenzelm@1258
   487
fun add_env_sorts (env, Ss) =
wenzelm@1258
   488
  add_terms_sorts (map snd (Envir.alist_of env),
wenzelm@1258
   489
    add_typs_sorts (env_codT env, Ss));
wenzelm@1258
   490
wenzelm@1238
   491
fun add_thm_sorts (Thm {hyps, prop, ...}, Ss) =
wenzelm@1238
   492
  add_terms_sorts (hyps, add_term_sorts (prop, Ss));
wenzelm@1238
   493
wenzelm@1238
   494
fun add_thms_shyps ([], Ss) = Ss
wenzelm@1238
   495
  | add_thms_shyps (Thm {shyps, ...} :: ths, Ss) =
paulson@2177
   496
      add_thms_shyps (ths, union_sort(shyps,Ss));
wenzelm@1238
   497
wenzelm@1238
   498
wenzelm@1238
   499
(*get 'dangling' sort constraints of a thm*)
wenzelm@1238
   500
fun extra_shyps (th as Thm {shyps, ...}) =
wenzelm@1238
   501
  shyps \\ add_thm_sorts (th, []);
wenzelm@1238
   502
wenzelm@1238
   503
wenzelm@1238
   504
(* fix_shyps *)
wenzelm@1238
   505
wenzelm@1238
   506
(*preserve sort contexts of rule premises and substituted types*)
wenzelm@1238
   507
fun fix_shyps thms Ts thm =
wenzelm@1238
   508
  let
wenzelm@3967
   509
    val Thm {sign_ref, der, maxidx, hyps, prop, ...} = thm;
wenzelm@1238
   510
    val shyps =
wenzelm@1238
   511
      add_thm_sorts (thm, add_typs_sorts (Ts, add_thms_shyps (thms, [])));
wenzelm@1238
   512
  in
wenzelm@3967
   513
    Thm {sign_ref = sign_ref,
wenzelm@2386
   514
         der = der,             (*No new derivation, as other rules call this*)
wenzelm@2386
   515
         maxidx = maxidx,
wenzelm@2386
   516
         shyps = shyps, hyps = hyps, prop = prop}
wenzelm@1238
   517
  end;
wenzelm@1238
   518
wenzelm@1238
   519
wenzelm@1238
   520
(* strip_shyps *)       (* FIXME improve? (e.g. only minimal extra sorts) *)
wenzelm@1238
   521
wenzelm@3061
   522
val force_strip_shyps = ref true;  (* FIXME tmp (since 1995/08/01) *)
wenzelm@1238
   523
wenzelm@1238
   524
(*remove extra sorts that are known to be syntactically non-empty*)
wenzelm@1238
   525
fun strip_shyps thm =
wenzelm@1238
   526
  let
wenzelm@3967
   527
    val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
wenzelm@1238
   528
    val sorts = add_thm_sorts (thm, []);
wenzelm@3967
   529
    val maybe_empty = not o Sign.nonempty_sort (Sign.deref sign_ref) sorts;
paulson@2177
   530
    val shyps' = filter (fn S => mem_sort(S,sorts) orelse maybe_empty S) shyps;
wenzelm@1238
   531
  in
wenzelm@3967
   532
    Thm {sign_ref = sign_ref, der = der, maxidx = maxidx,
wenzelm@2386
   533
         shyps =
wenzelm@2386
   534
         (if eq_set_sort (shyps',sorts) orelse 
wenzelm@2386
   535
             not (!force_strip_shyps) then shyps'
wenzelm@3061
   536
          else    (* FIXME tmp (since 1995/08/01) *)
wenzelm@2386
   537
              (warning ("Removed sort hypotheses: " ^
wenzelm@2962
   538
                        commas (map Sorts.str_of_sort (shyps' \\ sorts)));
wenzelm@2386
   539
               warning "Let's hope these sorts are non-empty!";
wenzelm@1238
   540
           sorts)),
paulson@1529
   541
      hyps = hyps, 
paulson@1529
   542
      prop = prop}
wenzelm@1238
   543
  end;
wenzelm@1238
   544
wenzelm@1238
   545
wenzelm@1238
   546
(* implies_intr_shyps *)
wenzelm@1238
   547
wenzelm@1238
   548
(*discharge all extra sort hypotheses*)
wenzelm@1238
   549
fun implies_intr_shyps thm =
wenzelm@1238
   550
  (case extra_shyps thm of
wenzelm@1238
   551
    [] => thm
wenzelm@1238
   552
  | xshyps =>
wenzelm@1238
   553
      let
wenzelm@3967
   554
        val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
paulson@2182
   555
        val shyps' = ins_sort (logicS, shyps \\ xshyps);
wenzelm@1238
   556
        val used_names = foldr add_term_tfree_names (prop :: hyps, []);
wenzelm@1238
   557
        val names =
wenzelm@1238
   558
          tl (variantlist (replicate (length xshyps + 1) "'", used_names));
wenzelm@1238
   559
        val tfrees = map (TFree o rpair logicS) names;
wenzelm@1238
   560
wenzelm@1238
   561
        fun mk_insort (T, S) = map (Logic.mk_inclass o pair T) S;
paulson@2671
   562
        val sort_hyps = List.concat (map2 mk_insort (tfrees, xshyps));
wenzelm@1238
   563
      in
wenzelm@3967
   564
        Thm {sign_ref = sign_ref, 
wenzelm@2386
   565
             der = infer_derivs (Implies_intr_shyps, [der]), 
wenzelm@2386
   566
             maxidx = maxidx, 
wenzelm@2386
   567
             shyps = shyps',
wenzelm@2386
   568
             hyps = hyps, 
wenzelm@2386
   569
             prop = Logic.list_implies (sort_hyps, prop)}
wenzelm@1238
   570
      end);
wenzelm@1238
   571
wenzelm@1238
   572
paulson@1529
   573
(** Axioms **)
wenzelm@387
   574
wenzelm@387
   575
(*look up the named axiom in the theory*)
wenzelm@3812
   576
fun get_axiom theory raw_name =
wenzelm@387
   577
  let
wenzelm@4847
   578
    val name = Sign.intern (Theory.sign_of theory) Theory.axiomK raw_name;
wenzelm@4847
   579
wenzelm@4847
   580
    fun get_ax [] = None
paulson@1529
   581
      | get_ax (thy :: thys) =
wenzelm@4847
   582
          let val {sign, axioms, ...} = Theory.rep_theory thy in
wenzelm@4847
   583
            (case Symtab.lookup (axioms, name) of
wenzelm@4847
   584
              Some t =>
wenzelm@4847
   585
                Some (fix_shyps [] []
wenzelm@4847
   586
                  (Thm {sign_ref = Sign.self_ref sign,
wenzelm@4847
   587
                    der = infer_derivs (Axiom name, []),
wenzelm@4847
   588
                    maxidx = maxidx_of_term t,
wenzelm@4847
   589
                    shyps = [], 
wenzelm@4847
   590
                    hyps = [], 
wenzelm@4847
   591
                    prop = t}))
wenzelm@4847
   592
            | None => get_ax thys)
paulson@1529
   593
          end;
wenzelm@387
   594
  in
wenzelm@4847
   595
    (case get_ax (theory :: Theory.ancestors_of theory) of
wenzelm@4847
   596
      Some thm => thm
wenzelm@4847
   597
    | None => raise THEORY ("No axiom " ^ quote name, [theory]))
wenzelm@387
   598
  end;
wenzelm@387
   599
wenzelm@4847
   600
fun get_def thy name = get_axiom thy (name ^ "_def");
wenzelm@4847
   601
paulson@1529
   602
wenzelm@776
   603
(*return additional axioms of this theory node*)
wenzelm@776
   604
fun axioms_of thy =
wenzelm@776
   605
  map (fn (s, _) => (s, get_axiom thy s))
wenzelm@3994
   606
    (Symtab.dest (#axioms (rep_theory thy)));
wenzelm@776
   607
paulson@1597
   608
(*Attach a label to a theorem to make proof objects more readable*)
wenzelm@4018
   609
fun name_thm (name, th as Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
wenzelm@4018
   610
  (case der of
wenzelm@4018
   611
    Join (Theorem _, _) => th
wenzelm@4018
   612
  | Join (Axiom _, _) => th
wenzelm@4018
   613
  | _ => Thm {sign_ref = sign_ref, der = Join (Theorem name, [der]),
wenzelm@4018
   614
      maxidx = maxidx, shyps = shyps, hyps = hyps, prop = prop});
wenzelm@4018
   615
wenzelm@4018
   616
fun name_of_thm (Thm {der, ...}) =
wenzelm@4018
   617
  (case der of
wenzelm@4018
   618
    Join (Theorem name, _) => name
wenzelm@4182
   619
  | Join (Axiom name, _) => name
wenzelm@4018
   620
  | _ => "");
clasohm@0
   621
clasohm@0
   622
paulson@1529
   623
(*Compression of theorems -- a separate rule, not integrated with the others,
paulson@1529
   624
  as it could be slow.*)
wenzelm@3967
   625
fun compress (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) = 
wenzelm@3967
   626
    Thm {sign_ref = sign_ref, 
wenzelm@2386
   627
         der = der,     (*No derivation recorded!*)
wenzelm@2386
   628
         maxidx = maxidx,
wenzelm@2386
   629
         shyps = shyps, 
wenzelm@2386
   630
         hyps = map Term.compress_term hyps, 
wenzelm@2386
   631
         prop = Term.compress_term prop};
wenzelm@564
   632
wenzelm@387
   633
wenzelm@2509
   634
paulson@1529
   635
(*** Meta rules ***)
clasohm@0
   636
paulson@2147
   637
(*Check that term does not contain same var with different typing/sorting.
paulson@2147
   638
  If this check must be made, recalculate maxidx in hope of preventing its
paulson@2147
   639
  recurrence.*)
wenzelm@3967
   640
fun nodup_Vars (thm as Thm{sign_ref, der, maxidx, shyps, hyps, prop}) s =
paulson@2147
   641
  (Sign.nodup_Vars prop; 
wenzelm@3967
   642
   Thm {sign_ref = sign_ref, 
wenzelm@2386
   643
         der = der,     
wenzelm@2386
   644
         maxidx = maxidx_of_term prop,
wenzelm@2386
   645
         shyps = shyps, 
wenzelm@2386
   646
         hyps = hyps, 
wenzelm@2386
   647
         prop = prop})
paulson@2147
   648
  handle TYPE(msg,Ts,ts) => raise TYPE(s^": "^msg,Ts,ts);
nipkow@1495
   649
wenzelm@1220
   650
(** 'primitive' rules **)
wenzelm@1220
   651
wenzelm@1220
   652
(*discharge all assumptions t from ts*)
clasohm@0
   653
val disch = gen_rem (op aconv);
clasohm@0
   654
wenzelm@1220
   655
(*The assumption rule A|-A in a theory*)
wenzelm@5344
   656
fun assume raw_ct : thm =
wenzelm@5344
   657
  let val ct as Cterm {sign_ref, t=prop, T, maxidx} = adjust_maxidx raw_ct
wenzelm@250
   658
  in  if T<>propT then
wenzelm@250
   659
        raise THM("assume: assumptions must have type prop", 0, [])
clasohm@0
   660
      else if maxidx <> ~1 then
wenzelm@250
   661
        raise THM("assume: assumptions may not contain scheme variables",
wenzelm@250
   662
                  maxidx, [])
wenzelm@3967
   663
      else Thm{sign_ref   = sign_ref,
wenzelm@5344
   664
               der    = infer_derivs (Assume ct, []),
wenzelm@2386
   665
               maxidx = ~1, 
wenzelm@2386
   666
               shyps  = add_term_sorts(prop,[]), 
wenzelm@2386
   667
               hyps   = [prop], 
wenzelm@2386
   668
               prop   = prop}
clasohm@0
   669
  end;
clasohm@0
   670
wenzelm@1220
   671
(*Implication introduction
wenzelm@3529
   672
    [A]
wenzelm@3529
   673
     :
wenzelm@3529
   674
     B
wenzelm@1220
   675
  -------
wenzelm@1220
   676
  A ==> B
wenzelm@1220
   677
*)
wenzelm@3967
   678
fun implies_intr cA (thB as Thm{sign_ref,der,maxidx,hyps,prop,...}) : thm =
wenzelm@3967
   679
  let val Cterm {sign_ref=sign_refA, t=A, T, maxidx=maxidxA} = cA
clasohm@0
   680
  in  if T<>propT then
wenzelm@250
   681
        raise THM("implies_intr: assumptions must have type prop", 0, [thB])
wenzelm@1238
   682
      else fix_shyps [thB] []
wenzelm@3967
   683
        (Thm{sign_ref = Sign.merge_refs (sign_ref,sign_refA),  
wenzelm@2386
   684
             der = infer_derivs (Implies_intr cA, [der]),
wenzelm@2386
   685
             maxidx = Int.max(maxidxA, maxidx),
wenzelm@2386
   686
             shyps = [],
wenzelm@2386
   687
             hyps = disch(hyps,A),
wenzelm@2386
   688
             prop = implies$A$prop})
clasohm@0
   689
      handle TERM _ =>
clasohm@0
   690
        raise THM("implies_intr: incompatible signatures", 0, [thB])
clasohm@0
   691
  end;
clasohm@0
   692
paulson@1529
   693
wenzelm@1220
   694
(*Implication elimination
wenzelm@1220
   695
  A ==> B    A
wenzelm@1220
   696
  ------------
wenzelm@1220
   697
        B
wenzelm@1220
   698
*)
clasohm@0
   699
fun implies_elim thAB thA : thm =
paulson@1529
   700
    let val Thm{maxidx=maxA, der=derA, hyps=hypsA, prop=propA,...} = thA
wenzelm@3967
   701
        and Thm{sign_ref, der, maxidx, hyps, prop,...} = thAB;
wenzelm@250
   702
        fun err(a) = raise THM("implies_elim: "^a, 0, [thAB,thA])
clasohm@0
   703
    in  case prop of
wenzelm@250
   704
            imp$A$B =>
wenzelm@250
   705
                if imp=implies andalso  A aconv propA
wenzelm@1220
   706
                then fix_shyps [thAB, thA] []
wenzelm@3967
   707
                       (Thm{sign_ref= merge_thm_sgs(thAB,thA),
wenzelm@2386
   708
                            der = infer_derivs (Implies_elim, [der,derA]),
wenzelm@2386
   709
                            maxidx = Int.max(maxA,maxidx),
wenzelm@2386
   710
                            shyps = [],
wenzelm@2386
   711
                            hyps = union_term(hypsA,hyps),  (*dups suppressed*)
wenzelm@2386
   712
                            prop = B})
wenzelm@250
   713
                else err("major premise")
wenzelm@250
   714
          | _ => err("major premise")
clasohm@0
   715
    end;
wenzelm@250
   716
wenzelm@1220
   717
(*Forall introduction.  The Free or Var x must not be free in the hypotheses.
wenzelm@1220
   718
    A
wenzelm@1220
   719
  -----
wenzelm@1220
   720
  !!x.A
wenzelm@1220
   721
*)
wenzelm@3967
   722
fun forall_intr cx (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
lcp@229
   723
  let val x = term_of cx;
wenzelm@1238
   724
      fun result(a,T) = fix_shyps [th] []
wenzelm@3967
   725
        (Thm{sign_ref = sign_ref, 
wenzelm@2386
   726
             der = infer_derivs (Forall_intr cx, [der]),
wenzelm@2386
   727
             maxidx = maxidx,
wenzelm@2386
   728
             shyps = [],
wenzelm@2386
   729
             hyps = hyps,
wenzelm@2386
   730
             prop = all(T) $ Abs(a, T, abstract_over (x,prop))})
clasohm@0
   731
  in  case x of
wenzelm@250
   732
        Free(a,T) =>
wenzelm@250
   733
          if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   734
          then  raise THM("forall_intr: variable free in assumptions", 0, [th])
wenzelm@250
   735
          else  result(a,T)
clasohm@0
   736
      | Var((a,_),T) => result(a,T)
clasohm@0
   737
      | _ => raise THM("forall_intr: not a variable", 0, [th])
clasohm@0
   738
  end;
clasohm@0
   739
wenzelm@1220
   740
(*Forall elimination
wenzelm@1220
   741
  !!x.A
wenzelm@1220
   742
  ------
wenzelm@1220
   743
  A[t/x]
wenzelm@1220
   744
*)
wenzelm@3967
   745
fun forall_elim ct (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) : thm =
wenzelm@3967
   746
  let val Cterm {sign_ref=sign_reft, t, T, maxidx=maxt} = ct
clasohm@0
   747
  in  case prop of
wenzelm@2386
   748
        Const("all",Type("fun",[Type("fun",[qary,_]),_])) $ A =>
wenzelm@2386
   749
          if T<>qary then
wenzelm@2386
   750
              raise THM("forall_elim: type mismatch", 0, [th])
wenzelm@2386
   751
          else let val thm = fix_shyps [th] []
wenzelm@3967
   752
                    (Thm{sign_ref= Sign.merge_refs(sign_ref,sign_reft),
wenzelm@2386
   753
                         der = infer_derivs (Forall_elim ct, [der]),
wenzelm@2386
   754
                         maxidx = Int.max(maxidx, maxt),
wenzelm@2386
   755
                         shyps = [],
wenzelm@2386
   756
                         hyps = hyps,  
wenzelm@2386
   757
                         prop = betapply(A,t)})
wenzelm@2386
   758
               in if maxt >= 0 andalso maxidx >= 0
wenzelm@2386
   759
                  then nodup_Vars thm "forall_elim" 
wenzelm@2386
   760
                  else thm (*no new Vars: no expensive check!*)
wenzelm@2386
   761
               end
paulson@2147
   762
      | _ => raise THM("forall_elim: not quantified", 0, [th])
clasohm@0
   763
  end
clasohm@0
   764
  handle TERM _ =>
wenzelm@250
   765
         raise THM("forall_elim: incompatible signatures", 0, [th]);
clasohm@0
   766
clasohm@0
   767
wenzelm@1220
   768
(* Equality *)
clasohm@0
   769
clasohm@0
   770
(*The reflexivity rule: maps  t   to the theorem   t==t   *)
wenzelm@250
   771
fun reflexive ct =
wenzelm@3967
   772
  let val Cterm {sign_ref, t, T, maxidx} = ct
wenzelm@1238
   773
  in  fix_shyps [] []
wenzelm@3967
   774
       (Thm{sign_ref= sign_ref, 
wenzelm@2386
   775
            der = infer_derivs (Reflexive ct, []),
wenzelm@2386
   776
            shyps = [],
wenzelm@2386
   777
            hyps = [], 
wenzelm@2386
   778
            maxidx = maxidx,
wenzelm@2386
   779
            prop = Logic.mk_equals(t,t)})
clasohm@0
   780
  end;
clasohm@0
   781
clasohm@0
   782
(*The symmetry rule
wenzelm@1220
   783
  t==u
wenzelm@1220
   784
  ----
wenzelm@1220
   785
  u==t
wenzelm@1220
   786
*)
wenzelm@3967
   787
fun symmetric (th as Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
clasohm@0
   788
  case prop of
clasohm@0
   789
      (eq as Const("==",_)) $ t $ u =>
wenzelm@1238
   790
        (*no fix_shyps*)
wenzelm@3967
   791
          Thm{sign_ref = sign_ref,
wenzelm@2386
   792
              der = infer_derivs (Symmetric, [der]),
wenzelm@2386
   793
              maxidx = maxidx,
wenzelm@2386
   794
              shyps = shyps,
wenzelm@2386
   795
              hyps = hyps,
wenzelm@2386
   796
              prop = eq$u$t}
clasohm@0
   797
    | _ => raise THM("symmetric", 0, [th]);
clasohm@0
   798
clasohm@0
   799
(*The transitive rule
wenzelm@1220
   800
  t1==u    u==t2
wenzelm@1220
   801
  --------------
wenzelm@1220
   802
      t1==t2
wenzelm@1220
   803
*)
clasohm@0
   804
fun transitive th1 th2 =
paulson@1529
   805
  let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
paulson@1529
   806
      and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   807
      fun err(msg) = raise THM("transitive: "^msg, 0, [th1,th2])
clasohm@0
   808
  in case (prop1,prop2) of
clasohm@0
   809
       ((eq as Const("==",_)) $ t1 $ u, Const("==",_) $ u' $ t2) =>
nipkow@1634
   810
          if not (u aconv u') then err"middle term"
nipkow@1634
   811
          else let val thm =      
wenzelm@1220
   812
              fix_shyps [th1, th2] []
wenzelm@3967
   813
                (Thm{sign_ref= merge_thm_sgs(th1,th2), 
wenzelm@2386
   814
                     der = infer_derivs (Transitive, [der1, der2]),
paulson@2147
   815
                     maxidx = Int.max(max1,max2), 
wenzelm@2386
   816
                     shyps = [],
wenzelm@2386
   817
                     hyps = union_term(hyps1,hyps2),
wenzelm@2386
   818
                     prop = eq$t1$t2})
paulson@2139
   819
                 in if max1 >= 0 andalso max2 >= 0
paulson@2147
   820
                    then nodup_Vars thm "transitive" 
paulson@2147
   821
                    else thm (*no new Vars: no expensive check!*)
paulson@2139
   822
                 end
clasohm@0
   823
     | _ =>  err"premises"
clasohm@0
   824
  end;
clasohm@0
   825
wenzelm@1160
   826
(*Beta-conversion: maps (%x.t)(u) to the theorem (%x.t)(u) == t[u/x] *)
wenzelm@250
   827
fun beta_conversion ct =
wenzelm@3967
   828
  let val Cterm {sign_ref, t, T, maxidx} = ct
clasohm@0
   829
  in  case t of
wenzelm@1238
   830
          Abs(_,_,bodt) $ u => fix_shyps [] []
wenzelm@3967
   831
            (Thm{sign_ref = sign_ref,  
wenzelm@2386
   832
                 der = infer_derivs (Beta_conversion ct, []),
wenzelm@2386
   833
                 maxidx = maxidx,
wenzelm@2386
   834
                 shyps = [],
wenzelm@2386
   835
                 hyps = [],
wenzelm@2386
   836
                 prop = Logic.mk_equals(t, subst_bound (u,bodt))})
wenzelm@250
   837
        | _ =>  raise THM("beta_conversion: not a redex", 0, [])
clasohm@0
   838
  end;
clasohm@0
   839
clasohm@0
   840
(*The extensionality rule   (proviso: x not free in f, g, or hypotheses)
wenzelm@1220
   841
  f(x) == g(x)
wenzelm@1220
   842
  ------------
wenzelm@1220
   843
     f == g
wenzelm@1220
   844
*)
wenzelm@3967
   845
fun extensional (th as Thm{sign_ref, der, maxidx,shyps,hyps,prop}) =
clasohm@0
   846
  case prop of
clasohm@0
   847
    (Const("==",_)) $ (f$x) $ (g$y) =>
wenzelm@250
   848
      let fun err(msg) = raise THM("extensional: "^msg, 0, [th])
clasohm@0
   849
      in (if x<>y then err"different variables" else
clasohm@0
   850
          case y of
wenzelm@250
   851
                Free _ =>
wenzelm@250
   852
                  if exists (apl(y, Logic.occs)) (f::g::hyps)
wenzelm@250
   853
                  then err"variable free in hyps or functions"    else  ()
wenzelm@250
   854
              | Var _ =>
wenzelm@250
   855
                  if Logic.occs(y,f)  orelse  Logic.occs(y,g)
wenzelm@250
   856
                  then err"variable free in functions"   else  ()
wenzelm@250
   857
              | _ => err"not a variable");
wenzelm@1238
   858
          (*no fix_shyps*)
wenzelm@3967
   859
          Thm{sign_ref = sign_ref,
wenzelm@2386
   860
              der = infer_derivs (Extensional, [der]),
wenzelm@2386
   861
              maxidx = maxidx,
wenzelm@2386
   862
              shyps = shyps,
wenzelm@2386
   863
              hyps = hyps, 
paulson@1529
   864
              prop = Logic.mk_equals(f,g)}
clasohm@0
   865
      end
clasohm@0
   866
 | _ =>  raise THM("extensional: premise", 0, [th]);
clasohm@0
   867
clasohm@0
   868
(*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   869
  The bound variable will be named "a" (since x will be something like x320)
wenzelm@1220
   870
     t == u
wenzelm@1220
   871
  ------------
wenzelm@1220
   872
  %x.t == %x.u
wenzelm@1220
   873
*)
wenzelm@3967
   874
fun abstract_rule a cx (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
lcp@229
   875
  let val x = term_of cx;
wenzelm@250
   876
      val (t,u) = Logic.dest_equals prop
wenzelm@250
   877
            handle TERM _ =>
wenzelm@250
   878
                raise THM("abstract_rule: premise not an equality", 0, [th])
wenzelm@1238
   879
      fun result T = fix_shyps [th] []
wenzelm@3967
   880
          (Thm{sign_ref = sign_ref,
wenzelm@2386
   881
               der = infer_derivs (Abstract_rule (a,cx), [der]),
wenzelm@2386
   882
               maxidx = maxidx, 
wenzelm@2386
   883
               shyps = [], 
wenzelm@2386
   884
               hyps = hyps,
wenzelm@2386
   885
               prop = Logic.mk_equals(Abs(a, T, abstract_over (x,t)),
wenzelm@2386
   886
                                      Abs(a, T, abstract_over (x,u)))})
clasohm@0
   887
  in  case x of
wenzelm@250
   888
        Free(_,T) =>
wenzelm@250
   889
         if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   890
         then raise THM("abstract_rule: variable free in assumptions", 0, [th])
wenzelm@250
   891
         else result T
clasohm@0
   892
      | Var(_,T) => result T
clasohm@0
   893
      | _ => raise THM("abstract_rule: not a variable", 0, [th])
clasohm@0
   894
  end;
clasohm@0
   895
clasohm@0
   896
(*The combination rule
wenzelm@3529
   897
  f == g  t == u
wenzelm@3529
   898
  --------------
wenzelm@3529
   899
   f(t) == g(u)
wenzelm@1220
   900
*)
clasohm@0
   901
fun combination th1 th2 =
paulson@1529
   902
  let val Thm{der=der1, maxidx=max1, shyps=shyps1, hyps=hyps1, 
wenzelm@2386
   903
              prop=prop1,...} = th1
paulson@1529
   904
      and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
wenzelm@2386
   905
              prop=prop2,...} = th2
paulson@1836
   906
      fun chktypes (f,t) =
wenzelm@2386
   907
            (case fastype_of f of
wenzelm@2386
   908
                Type("fun",[T1,T2]) => 
wenzelm@2386
   909
                    if T1 <> fastype_of t then
wenzelm@2386
   910
                         raise THM("combination: types", 0, [th1,th2])
wenzelm@2386
   911
                    else ()
wenzelm@2386
   912
                | _ => raise THM("combination: not function type", 0, 
wenzelm@2386
   913
                                 [th1,th2]))
nipkow@1495
   914
  in case (prop1,prop2)  of
clasohm@0
   915
       (Const("==",_) $ f $ g, Const("==",_) $ t $ u) =>
paulson@1836
   916
          let val _   = chktypes (f,t)
wenzelm@2386
   917
              val thm = (*no fix_shyps*)
wenzelm@3967
   918
                        Thm{sign_ref = merge_thm_sgs(th1,th2), 
wenzelm@2386
   919
                            der = infer_derivs (Combination, [der1, der2]),
wenzelm@2386
   920
                            maxidx = Int.max(max1,max2), 
wenzelm@2386
   921
                            shyps = union_sort(shyps1,shyps2),
wenzelm@2386
   922
                            hyps = union_term(hyps1,hyps2),
wenzelm@2386
   923
                            prop = Logic.mk_equals(f$t, g$u)}
paulson@2139
   924
          in if max1 >= 0 andalso max2 >= 0
paulson@2139
   925
             then nodup_Vars thm "combination" 
wenzelm@2386
   926
             else thm (*no new Vars: no expensive check!*)  
paulson@2139
   927
          end
clasohm@0
   928
     | _ =>  raise THM("combination: premises", 0, [th1,th2])
clasohm@0
   929
  end;
clasohm@0
   930
clasohm@0
   931
clasohm@0
   932
(* Equality introduction
wenzelm@3529
   933
  A ==> B  B ==> A
wenzelm@3529
   934
  ----------------
wenzelm@3529
   935
       A == B
wenzelm@1220
   936
*)
clasohm@0
   937
fun equal_intr th1 th2 =
paulson@1529
   938
  let val Thm{der=der1,maxidx=max1, shyps=shyps1, hyps=hyps1, 
wenzelm@2386
   939
              prop=prop1,...} = th1
paulson@1529
   940
      and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
wenzelm@2386
   941
              prop=prop2,...} = th2;
paulson@1529
   942
      fun err(msg) = raise THM("equal_intr: "^msg, 0, [th1,th2])
paulson@1529
   943
  in case (prop1,prop2) of
paulson@1529
   944
       (Const("==>",_) $ A $ B, Const("==>",_) $ B' $ A')  =>
wenzelm@2386
   945
          if A aconv A' andalso B aconv B'
wenzelm@2386
   946
          then
wenzelm@2386
   947
            (*no fix_shyps*)
wenzelm@3967
   948
              Thm{sign_ref = merge_thm_sgs(th1,th2),
wenzelm@2386
   949
                  der = infer_derivs (Equal_intr, [der1, der2]),
wenzelm@2386
   950
                  maxidx = Int.max(max1,max2),
wenzelm@2386
   951
                  shyps = union_sort(shyps1,shyps2),
wenzelm@2386
   952
                  hyps = union_term(hyps1,hyps2),
wenzelm@2386
   953
                  prop = Logic.mk_equals(A,B)}
wenzelm@2386
   954
          else err"not equal"
paulson@1529
   955
     | _ =>  err"premises"
paulson@1529
   956
  end;
paulson@1529
   957
paulson@1529
   958
paulson@1529
   959
(*The equal propositions rule
wenzelm@3529
   960
  A == B  A
paulson@1529
   961
  ---------
paulson@1529
   962
      B
paulson@1529
   963
*)
paulson@1529
   964
fun equal_elim th1 th2 =
paulson@1529
   965
  let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
paulson@1529
   966
      and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
paulson@1529
   967
      fun err(msg) = raise THM("equal_elim: "^msg, 0, [th1,th2])
paulson@1529
   968
  in  case prop1  of
paulson@1529
   969
       Const("==",_) $ A $ B =>
paulson@1529
   970
          if not (prop2 aconv A) then err"not equal"  else
paulson@1529
   971
            fix_shyps [th1, th2] []
wenzelm@3967
   972
              (Thm{sign_ref= merge_thm_sgs(th1,th2), 
wenzelm@2386
   973
                   der = infer_derivs (Equal_elim, [der1, der2]),
wenzelm@2386
   974
                   maxidx = Int.max(max1,max2),
wenzelm@2386
   975
                   shyps = [],
wenzelm@2386
   976
                   hyps = union_term(hyps1,hyps2),
wenzelm@2386
   977
                   prop = B})
paulson@1529
   978
     | _ =>  err"major premise"
paulson@1529
   979
  end;
clasohm@0
   980
wenzelm@1220
   981
wenzelm@1220
   982
clasohm@0
   983
(**** Derived rules ****)
clasohm@0
   984
paulson@1503
   985
(*Discharge all hypotheses.  Need not verify cterms or call fix_shyps.
clasohm@0
   986
  Repeated hypotheses are discharged only once;  fold cannot do this*)
wenzelm@3967
   987
fun implies_intr_hyps (Thm{sign_ref, der, maxidx, shyps, hyps=A::As, prop}) =
wenzelm@1238
   988
      implies_intr_hyps (*no fix_shyps*)
wenzelm@3967
   989
            (Thm{sign_ref = sign_ref, 
wenzelm@2386
   990
                 der = infer_derivs (Implies_intr_hyps, [der]), 
wenzelm@2386
   991
                 maxidx = maxidx, 
wenzelm@2386
   992
                 shyps = shyps,
paulson@1529
   993
                 hyps = disch(As,A),  
wenzelm@2386
   994
                 prop = implies$A$prop})
clasohm@0
   995
  | implies_intr_hyps th = th;
clasohm@0
   996
clasohm@0
   997
(*Smash" unifies the list of term pairs leaving no flex-flex pairs.
wenzelm@250
   998
  Instantiates the theorem and deletes trivial tpairs.
clasohm@0
   999
  Resulting sequence may contain multiple elements if the tpairs are
clasohm@0
  1000
    not all flex-flex. *)
wenzelm@3967
  1001
fun flexflex_rule (th as Thm{sign_ref, der, maxidx, hyps, prop,...}) =
wenzelm@250
  1002
  let fun newthm env =
paulson@1529
  1003
          if Envir.is_empty env then th
paulson@1529
  1004
          else
wenzelm@250
  1005
          let val (tpairs,horn) =
wenzelm@250
  1006
                        Logic.strip_flexpairs (Envir.norm_term env prop)
wenzelm@250
  1007
                (*Remove trivial tpairs, of the form t=t*)
wenzelm@250
  1008
              val distpairs = filter (not o op aconv) tpairs
wenzelm@250
  1009
              val newprop = Logic.list_flexpairs(distpairs, horn)
wenzelm@1220
  1010
          in  fix_shyps [th] (env_codT env)
wenzelm@3967
  1011
                (Thm{sign_ref = sign_ref, 
wenzelm@2386
  1012
                     der = infer_derivs (Flexflex_rule env, [der]), 
wenzelm@2386
  1013
                     maxidx = maxidx_of_term newprop, 
wenzelm@2386
  1014
                     shyps = [], 
wenzelm@2386
  1015
                     hyps = hyps,
wenzelm@2386
  1016
                     prop = newprop})
wenzelm@250
  1017
          end;
clasohm@0
  1018
      val (tpairs,_) = Logic.strip_flexpairs prop
wenzelm@4270
  1019
  in Seq.map newthm
wenzelm@3967
  1020
            (Unify.smash_unifiers(Sign.deref sign_ref, Envir.empty maxidx, tpairs))
clasohm@0
  1021
  end;
clasohm@0
  1022
clasohm@0
  1023
(*Instantiation of Vars
wenzelm@1220
  1024
           A
wenzelm@1220
  1025
  -------------------
wenzelm@1220
  1026
  A[t1/v1,....,tn/vn]
wenzelm@1220
  1027
*)
clasohm@0
  1028
clasohm@0
  1029
(*Check that all the terms are Vars and are distinct*)
clasohm@0
  1030
fun instl_ok ts = forall is_Var ts andalso null(findrep ts);
clasohm@0
  1031
clasohm@0
  1032
(*For instantiate: process pair of cterms, merge theories*)
wenzelm@3967
  1033
fun add_ctpair ((ct,cu), (sign_ref,tpairs)) =
wenzelm@3967
  1034
  let val Cterm {sign_ref=sign_reft, t=t, T= T, ...} = ct
wenzelm@3967
  1035
      and Cterm {sign_ref=sign_refu, t=u, T= U, ...} = cu
wenzelm@3967
  1036
  in
wenzelm@3967
  1037
    if T=U then
wenzelm@3967
  1038
      (Sign.merge_refs (sign_ref, Sign.merge_refs (sign_reft, sign_refu)), (t,u)::tpairs)
wenzelm@3967
  1039
    else raise TYPE("add_ctpair", [T,U], [t,u])
clasohm@0
  1040
  end;
clasohm@0
  1041
wenzelm@3967
  1042
fun add_ctyp ((v,ctyp), (sign_ref',vTs)) =
wenzelm@3967
  1043
  let val Ctyp {T,sign_ref} = ctyp
wenzelm@3967
  1044
  in (Sign.merge_refs(sign_ref,sign_ref'), (v,T)::vTs) end;
clasohm@0
  1045
clasohm@0
  1046
(*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
  1047
  Instantiates distinct Vars by terms of same type.
clasohm@0
  1048
  Normalizes the new theorem! *)
paulson@1529
  1049
fun instantiate ([], []) th = th
wenzelm@3967
  1050
  | instantiate (vcTs,ctpairs)  (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
wenzelm@3967
  1051
  let val (newsign_ref,tpairs) = foldr add_ctpair (ctpairs, (sign_ref,[]));
wenzelm@3967
  1052
      val (newsign_ref,vTs) = foldr add_ctyp (vcTs, (newsign_ref,[]));
wenzelm@250
  1053
      val newprop =
wenzelm@250
  1054
            Envir.norm_term (Envir.empty 0)
wenzelm@250
  1055
              (subst_atomic tpairs
wenzelm@3967
  1056
               (Type.inst_term_tvars(Sign.tsig_of (Sign.deref newsign_ref),vTs) prop))
wenzelm@1220
  1057
      val newth =
wenzelm@1220
  1058
            fix_shyps [th] (map snd vTs)
wenzelm@3967
  1059
              (Thm{sign_ref = newsign_ref, 
wenzelm@2386
  1060
                   der = infer_derivs (Instantiate(vcTs,ctpairs), [der]), 
wenzelm@2386
  1061
                   maxidx = maxidx_of_term newprop, 
wenzelm@2386
  1062
                   shyps = [],
wenzelm@2386
  1063
                   hyps = hyps,
wenzelm@2386
  1064
                   prop = newprop})
wenzelm@250
  1065
  in  if not(instl_ok(map #1 tpairs))
nipkow@193
  1066
      then raise THM("instantiate: variables not distinct", 0, [th])
nipkow@193
  1067
      else if not(null(findrep(map #1 vTs)))
nipkow@193
  1068
      then raise THM("instantiate: type variables not distinct", 0, [th])
paulson@2147
  1069
      else nodup_Vars newth "instantiate"
clasohm@0
  1070
  end
wenzelm@250
  1071
  handle TERM _ =>
clasohm@0
  1072
           raise THM("instantiate: incompatible signatures",0,[th])
paulson@2671
  1073
       | TYPE (msg,_,_) => raise THM("instantiate: type conflict: " ^ msg, 
paulson@2671
  1074
				     0, [th]);
clasohm@0
  1075
clasohm@0
  1076
(*The trivial implication A==>A, justified by assume and forall rules.
clasohm@0
  1077
  A can contain Vars, not so for assume!   *)
wenzelm@250
  1078
fun trivial ct : thm =
wenzelm@3967
  1079
  let val Cterm {sign_ref, t=A, T, maxidx} = ct
wenzelm@250
  1080
  in  if T<>propT then
wenzelm@250
  1081
            raise THM("trivial: the term must have type prop", 0, [])
wenzelm@1238
  1082
      else fix_shyps [] []
wenzelm@3967
  1083
        (Thm{sign_ref = sign_ref, 
wenzelm@2386
  1084
             der = infer_derivs (Trivial ct, []), 
wenzelm@2386
  1085
             maxidx = maxidx, 
wenzelm@2386
  1086
             shyps = [], 
wenzelm@2386
  1087
             hyps = [],
wenzelm@2386
  1088
             prop = implies$A$A})
clasohm@0
  1089
  end;
clasohm@0
  1090
paulson@1503
  1091
(*Axiom-scheme reflecting signature contents: "OFCLASS(?'a::c, c_class)" *)
wenzelm@399
  1092
fun class_triv thy c =
paulson@1529
  1093
  let val sign = sign_of thy;
wenzelm@3967
  1094
      val Cterm {sign_ref, t, maxidx, ...} =
wenzelm@2386
  1095
          cterm_of sign (Logic.mk_inclass (TVar (("'a", 0), [c]), c))
wenzelm@2386
  1096
            handle TERM (msg, _) => raise THM ("class_triv: " ^ msg, 0, []);
wenzelm@399
  1097
  in
wenzelm@1238
  1098
    fix_shyps [] []
wenzelm@3967
  1099
      (Thm {sign_ref = sign_ref, 
wenzelm@4182
  1100
            der = infer_derivs (Class_triv c, []), 
wenzelm@2386
  1101
            maxidx = maxidx, 
wenzelm@2386
  1102
            shyps = [], 
wenzelm@2386
  1103
            hyps = [], 
wenzelm@2386
  1104
            prop = t})
wenzelm@399
  1105
  end;
wenzelm@399
  1106
wenzelm@399
  1107
clasohm@0
  1108
(* Replace all TFrees not in the hyps by new TVars *)
wenzelm@3967
  1109
fun varifyT(Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
clasohm@0
  1110
  let val tfrees = foldr add_term_tfree_names (hyps,[])
nipkow@1634
  1111
  in let val thm = (*no fix_shyps*)
wenzelm@3967
  1112
    Thm{sign_ref = sign_ref, 
wenzelm@2386
  1113
        der = infer_derivs (VarifyT, [der]), 
wenzelm@2386
  1114
        maxidx = Int.max(0,maxidx), 
wenzelm@2386
  1115
        shyps = shyps, 
wenzelm@2386
  1116
        hyps = hyps,
paulson@1529
  1117
        prop = Type.varify(prop,tfrees)}
paulson@2147
  1118
     in nodup_Vars thm "varifyT" end
nipkow@1634
  1119
(* this nodup_Vars check can be removed if thms are guaranteed not to contain
nipkow@1634
  1120
duplicate TVars with differnt sorts *)
clasohm@0
  1121
  end;
clasohm@0
  1122
clasohm@0
  1123
(* Replace all TVars by new TFrees *)
wenzelm@3967
  1124
fun freezeT(Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
paulson@3410
  1125
  let val (prop',_) = Type.freeze_thaw prop
wenzelm@1238
  1126
  in (*no fix_shyps*)
wenzelm@3967
  1127
    Thm{sign_ref = sign_ref, 
wenzelm@2386
  1128
        der = infer_derivs (FreezeT, [der]),
wenzelm@2386
  1129
        maxidx = maxidx_of_term prop',
wenzelm@2386
  1130
        shyps = shyps,
wenzelm@2386
  1131
        hyps = hyps,
paulson@1529
  1132
        prop = prop'}
wenzelm@1220
  1133
  end;
clasohm@0
  1134
clasohm@0
  1135
clasohm@0
  1136
(*** Inference rules for tactics ***)
clasohm@0
  1137
clasohm@0
  1138
(*Destruct proof state into constraints, other goals, goal(i), rest *)
clasohm@0
  1139
fun dest_state (state as Thm{prop,...}, i) =
clasohm@0
  1140
  let val (tpairs,horn) = Logic.strip_flexpairs prop
clasohm@0
  1141
  in  case  Logic.strip_prems(i, [], horn) of
clasohm@0
  1142
          (B::rBs, C) => (tpairs, rev rBs, B, C)
clasohm@0
  1143
        | _ => raise THM("dest_state", i, [state])
clasohm@0
  1144
  end
clasohm@0
  1145
  handle TERM _ => raise THM("dest_state", i, [state]);
clasohm@0
  1146
lcp@309
  1147
(*Increment variables and parameters of orule as required for
clasohm@0
  1148
  resolution with goal i of state. *)
clasohm@0
  1149
fun lift_rule (state, i) orule =
wenzelm@3967
  1150
  let val Thm{shyps=sshyps, prop=sprop, maxidx=smax, sign_ref=ssign_ref,...} = state
clasohm@0
  1151
      val (Bi::_, _) = Logic.strip_prems(i, [], Logic.skip_flexpairs sprop)
paulson@1529
  1152
        handle TERM _ => raise THM("lift_rule", i, [orule,state])
wenzelm@3967
  1153
      val ct_Bi = Cterm {sign_ref=ssign_ref, maxidx=smax, T=propT, t=Bi}
paulson@1529
  1154
      val (lift_abs,lift_all) = Logic.lift_fns(Bi,smax+1)
wenzelm@3967
  1155
      val (Thm{sign_ref, der, maxidx,shyps,hyps,prop}) = orule
clasohm@0
  1156
      val (tpairs,As,B) = Logic.strip_horn prop
wenzelm@1238
  1157
  in  (*no fix_shyps*)
wenzelm@3967
  1158
      Thm{sign_ref = merge_thm_sgs(state,orule),
wenzelm@2386
  1159
          der = infer_derivs (Lift_rule(ct_Bi, i), [der]),
wenzelm@2386
  1160
          maxidx = maxidx+smax+1,
paulson@2177
  1161
          shyps=union_sort(sshyps,shyps), 
wenzelm@2386
  1162
          hyps=hyps, 
paulson@1529
  1163
          prop = Logic.rule_of (map (pairself lift_abs) tpairs,
wenzelm@2386
  1164
                                map lift_all As,    
wenzelm@2386
  1165
                                lift_all B)}
clasohm@0
  1166
  end;
clasohm@0
  1167
clasohm@0
  1168
(*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
clasohm@0
  1169
fun assumption i state =
wenzelm@3967
  1170
  let val Thm{sign_ref,der,maxidx,hyps,prop,...} = state;
clasohm@0
  1171
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
  1172
      fun newth (env as Envir.Envir{maxidx, ...}, tpairs) =
wenzelm@1220
  1173
        fix_shyps [state] (env_codT env)
wenzelm@3967
  1174
          (Thm{sign_ref = sign_ref, 
wenzelm@2386
  1175
               der = infer_derivs (Assumption (i, Some env), [der]),
wenzelm@2386
  1176
               maxidx = maxidx,
wenzelm@2386
  1177
               shyps = [],
wenzelm@2386
  1178
               hyps = hyps,
wenzelm@2386
  1179
               prop = 
wenzelm@2386
  1180
               if Envir.is_empty env then (*avoid wasted normalizations*)
wenzelm@2386
  1181
                   Logic.rule_of (tpairs, Bs, C)
wenzelm@2386
  1182
               else (*normalize the new rule fully*)
wenzelm@2386
  1183
                   Envir.norm_term env (Logic.rule_of (tpairs, Bs, C))});
wenzelm@4270
  1184
      fun addprfs [] = Seq.empty
wenzelm@4270
  1185
        | addprfs ((t,u)::apairs) = Seq.make (fn()=> Seq.pull
wenzelm@4270
  1186
             (Seq.mapp newth
wenzelm@3967
  1187
                (Unify.unifiers(Sign.deref sign_ref,Envir.empty maxidx, (t,u)::tpairs))
wenzelm@250
  1188
                (addprfs apairs)))
clasohm@0
  1189
  in  addprfs (Logic.assum_pairs Bi)  end;
clasohm@0
  1190
wenzelm@250
  1191
(*Solve subgoal Bi of proof state B1...Bn/C by assumption.
clasohm@0
  1192
  Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
clasohm@0
  1193
fun eq_assumption i state =
wenzelm@3967
  1194
  let val Thm{sign_ref,der,maxidx,hyps,prop,...} = state;
clasohm@0
  1195
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
  1196
  in  if exists (op aconv) (Logic.assum_pairs Bi)
wenzelm@1220
  1197
      then fix_shyps [state] []
wenzelm@3967
  1198
             (Thm{sign_ref = sign_ref, 
wenzelm@2386
  1199
                  der = infer_derivs (Assumption (i,None), [der]),
wenzelm@2386
  1200
                  maxidx = maxidx,
wenzelm@2386
  1201
                  shyps = [],
wenzelm@2386
  1202
                  hyps = hyps,
wenzelm@2386
  1203
                  prop = Logic.rule_of(tpairs, Bs, C)})
clasohm@0
  1204
      else  raise THM("eq_assumption", 0, [state])
clasohm@0
  1205
  end;
clasohm@0
  1206
clasohm@0
  1207
paulson@2671
  1208
(*For rotate_tac: fast rotation of assumptions of subgoal i*)
paulson@2671
  1209
fun rotate_rule k i state =
wenzelm@3967
  1210
  let val Thm{sign_ref,der,maxidx,hyps,prop,shyps} = state;
paulson@2671
  1211
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
paulson@2671
  1212
      val params = Logic.strip_params Bi
paulson@2671
  1213
      and asms   = Logic.strip_assums_hyp Bi
paulson@2671
  1214
      and concl  = Logic.strip_assums_concl Bi
paulson@2671
  1215
      val n      = length asms
paulson@2671
  1216
      fun rot m  = if 0=m orelse m=n then Bi
paulson@2671
  1217
		   else if 0<m andalso m<n 
paulson@2671
  1218
		   then list_all 
paulson@2671
  1219
			   (params, 
paulson@2671
  1220
			    Logic.list_implies(List.drop(asms, m) @ 
paulson@2671
  1221
					       List.take(asms, m),
paulson@2671
  1222
					       concl))
paulson@2671
  1223
		   else raise THM("rotate_rule", m, [state])
wenzelm@3967
  1224
  in  Thm{sign_ref = sign_ref, 
paulson@2671
  1225
	  der = infer_derivs (Rotate_rule (k,i), [der]),
paulson@2671
  1226
	  maxidx = maxidx,
paulson@2671
  1227
	  shyps = shyps,
paulson@2671
  1228
	  hyps = hyps,
paulson@2671
  1229
	  prop = Logic.rule_of(tpairs, Bs@[rot (if k<0 then n+k else k)], C)}
paulson@2671
  1230
  end;
paulson@2671
  1231
paulson@2671
  1232
clasohm@0
  1233
(** User renaming of parameters in a subgoal **)
clasohm@0
  1234
clasohm@0
  1235
(*Calls error rather than raising an exception because it is intended
clasohm@0
  1236
  for top-level use -- exception handling would not make sense here.
clasohm@0
  1237
  The names in cs, if distinct, are used for the innermost parameters;
clasohm@0
  1238
   preceding parameters may be renamed to make all params distinct.*)
clasohm@0
  1239
fun rename_params_rule (cs, i) state =
wenzelm@3967
  1240
  let val Thm{sign_ref,der,maxidx,hyps,...} = state
clasohm@0
  1241
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
  1242
      val iparams = map #1 (Logic.strip_params Bi)
clasohm@0
  1243
      val short = length iparams - length cs
wenzelm@250
  1244
      val newnames =
wenzelm@250
  1245
            if short<0 then error"More names than abstractions!"
wenzelm@250
  1246
            else variantlist(take (short,iparams), cs) @ cs
nipkow@3037
  1247
      val freenames = map (#1 o dest_Free) (term_frees Bi)
clasohm@0
  1248
      val newBi = Logic.list_rename_params (newnames, Bi)
wenzelm@250
  1249
  in
clasohm@0
  1250
  case findrep cs of
paulson@3565
  1251
     c::_ => (warning ("Can't rename.  Bound variables not distinct: " ^ c); 
paulson@3565
  1252
	      state)
berghofe@1576
  1253
   | [] => (case cs inter_string freenames of
paulson@3565
  1254
       a::_ => (warning ("Can't rename.  Bound/Free variable clash: " ^ a); 
paulson@3565
  1255
		state)
wenzelm@1220
  1256
     | [] => fix_shyps [state] []
wenzelm@3967
  1257
                (Thm{sign_ref = sign_ref,
wenzelm@2386
  1258
                     der = infer_derivs (Rename_params_rule(cs,i), [der]),
wenzelm@2386
  1259
                     maxidx = maxidx,
wenzelm@2386
  1260
                     shyps = [],
wenzelm@2386
  1261
                     hyps = hyps,
wenzelm@2386
  1262
                     prop = Logic.rule_of(tpairs, Bs@[newBi], C)}))
clasohm@0
  1263
  end;
clasohm@0
  1264
clasohm@0
  1265
(*** Preservation of bound variable names ***)
clasohm@0
  1266
wenzelm@250
  1267
(*Scan a pair of terms; while they are similar,
clasohm@0
  1268
  accumulate corresponding bound vars in "al"*)
wenzelm@1238
  1269
fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) =
lcp@1195
  1270
      match_bvs(s, t, if x="" orelse y="" then al
wenzelm@1238
  1271
                                          else (x,y)::al)
clasohm@0
  1272
  | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
clasohm@0
  1273
  | match_bvs(_,_,al) = al;
clasohm@0
  1274
clasohm@0
  1275
(* strip abstractions created by parameters *)
clasohm@0
  1276
fun match_bvars((s,t),al) = match_bvs(strip_abs_body s, strip_abs_body t, al);
clasohm@0
  1277
clasohm@0
  1278
wenzelm@250
  1279
(* strip_apply f A(,B) strips off all assumptions/parameters from A
clasohm@0
  1280
   introduced by lifting over B, and applies f to remaining part of A*)
clasohm@0
  1281
fun strip_apply f =
clasohm@0
  1282
  let fun strip(Const("==>",_)$ A1 $ B1,
wenzelm@250
  1283
                Const("==>",_)$ _  $ B2) = implies $ A1 $ strip(B1,B2)
wenzelm@250
  1284
        | strip((c as Const("all",_)) $ Abs(a,T,t1),
wenzelm@250
  1285
                      Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
wenzelm@250
  1286
        | strip(A,_) = f A
clasohm@0
  1287
  in strip end;
clasohm@0
  1288
clasohm@0
  1289
(*Use the alist to rename all bound variables and some unknowns in a term
clasohm@0
  1290
  dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
clasohm@0
  1291
  Preserves unknowns in tpairs and on lhs of dpairs. *)
clasohm@0
  1292
fun rename_bvs([],_,_,_) = I
clasohm@0
  1293
  | rename_bvs(al,dpairs,tpairs,B) =
wenzelm@250
  1294
    let val vars = foldr add_term_vars
wenzelm@250
  1295
                        (map fst dpairs @ map fst tpairs @ map snd tpairs, [])
wenzelm@250
  1296
        (*unknowns appearing elsewhere be preserved!*)
wenzelm@250
  1297
        val vids = map (#1 o #1 o dest_Var) vars;
wenzelm@250
  1298
        fun rename(t as Var((x,i),T)) =
wenzelm@250
  1299
                (case assoc(al,x) of
berghofe@1576
  1300
                   Some(y) => if x mem_string vids orelse y mem_string vids then t
wenzelm@250
  1301
                              else Var((y,i),T)
wenzelm@250
  1302
                 | None=> t)
clasohm@0
  1303
          | rename(Abs(x,T,t)) =
berghofe@1576
  1304
              Abs(case assoc_string(al,x) of Some(y) => y | None => x,
wenzelm@250
  1305
                  T, rename t)
clasohm@0
  1306
          | rename(f$t) = rename f $ rename t
clasohm@0
  1307
          | rename(t) = t;
wenzelm@250
  1308
        fun strip_ren Ai = strip_apply rename (Ai,B)
clasohm@0
  1309
    in strip_ren end;
clasohm@0
  1310
clasohm@0
  1311
(*Function to rename bounds/unknowns in the argument, lifted over B*)
clasohm@0
  1312
fun rename_bvars(dpairs, tpairs, B) =
wenzelm@250
  1313
        rename_bvs(foldr match_bvars (dpairs,[]), dpairs, tpairs, B);
clasohm@0
  1314
clasohm@0
  1315
clasohm@0
  1316
(*** RESOLUTION ***)
clasohm@0
  1317
lcp@721
  1318
(** Lifting optimizations **)
lcp@721
  1319
clasohm@0
  1320
(*strip off pairs of assumptions/parameters in parallel -- they are
clasohm@0
  1321
  identical because of lifting*)
wenzelm@250
  1322
fun strip_assums2 (Const("==>", _) $ _ $ B1,
wenzelm@250
  1323
                   Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
clasohm@0
  1324
  | strip_assums2 (Const("all",_)$Abs(a,T,t1),
wenzelm@250
  1325
                   Const("all",_)$Abs(_,_,t2)) =
clasohm@0
  1326
      let val (B1,B2) = strip_assums2 (t1,t2)
clasohm@0
  1327
      in  (Abs(a,T,B1), Abs(a,T,B2))  end
clasohm@0
  1328
  | strip_assums2 BB = BB;
clasohm@0
  1329
clasohm@0
  1330
lcp@721
  1331
(*Faster normalization: skip assumptions that were lifted over*)
lcp@721
  1332
fun norm_term_skip env 0 t = Envir.norm_term env t
lcp@721
  1333
  | norm_term_skip env n (Const("all",_)$Abs(a,T,t)) =
lcp@721
  1334
        let val Envir.Envir{iTs, ...} = env
wenzelm@1238
  1335
            val T' = typ_subst_TVars iTs T
wenzelm@1238
  1336
            (*Must instantiate types of parameters because they are flattened;
lcp@721
  1337
              this could be a NEW parameter*)
lcp@721
  1338
        in  all T' $ Abs(a, T', norm_term_skip env n t)  end
lcp@721
  1339
  | norm_term_skip env n (Const("==>", _) $ A $ B) =
wenzelm@1238
  1340
        implies $ A $ norm_term_skip env (n-1) B
lcp@721
  1341
  | norm_term_skip env n t = error"norm_term_skip: too few assumptions??";
lcp@721
  1342
lcp@721
  1343
clasohm@0
  1344
(*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
wenzelm@250
  1345
  Unifies B with Bi, replacing subgoal i    (1 <= i <= n)
clasohm@0
  1346
  If match then forbid instantiations in proof state
clasohm@0
  1347
  If lifted then shorten the dpair using strip_assums2.
clasohm@0
  1348
  If eres_flg then simultaneously proves A1 by assumption.
wenzelm@250
  1349
  nsubgoal is the number of new subgoals (written m above).
clasohm@0
  1350
  Curried so that resolution calls dest_state only once.
clasohm@0
  1351
*)
wenzelm@4270
  1352
local exception COMPOSE
clasohm@0
  1353
in
wenzelm@250
  1354
fun bicompose_aux match (state, (stpairs, Bs, Bi, C), lifted)
clasohm@0
  1355
                        (eres_flg, orule, nsubgoal) =
paulson@1529
  1356
 let val Thm{der=sder, maxidx=smax, shyps=sshyps, hyps=shyps, ...} = state
paulson@1529
  1357
     and Thm{der=rder, maxidx=rmax, shyps=rshyps, hyps=rhyps, 
wenzelm@2386
  1358
             prop=rprop,...} = orule
paulson@1529
  1359
         (*How many hyps to skip over during normalization*)
wenzelm@1238
  1360
     and nlift = Logic.count_prems(strip_all_body Bi,
wenzelm@1238
  1361
                                   if eres_flg then ~1 else 0)
wenzelm@3967
  1362
     val sign_ref = merge_thm_sgs(state,orule);
wenzelm@3967
  1363
     val sign = Sign.deref sign_ref;
clasohm@0
  1364
     (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
wenzelm@250
  1365
     fun addth As ((env as Envir.Envir {maxidx, ...}, tpairs), thq) =
wenzelm@250
  1366
       let val normt = Envir.norm_term env;
wenzelm@250
  1367
           (*perform minimal copying here by examining env*)
wenzelm@250
  1368
           val normp =
wenzelm@250
  1369
             if Envir.is_empty env then (tpairs, Bs @ As, C)
wenzelm@250
  1370
             else
wenzelm@250
  1371
             let val ntps = map (pairself normt) tpairs
paulson@2147
  1372
             in if Envir.above (smax, env) then
wenzelm@1238
  1373
                  (*no assignments in state; normalize the rule only*)
wenzelm@1238
  1374
                  if lifted
wenzelm@1238
  1375
                  then (ntps, Bs @ map (norm_term_skip env nlift) As, C)
wenzelm@1238
  1376
                  else (ntps, Bs @ map normt As, C)
paulson@1529
  1377
                else if match then raise COMPOSE
wenzelm@250
  1378
                else (*normalize the new rule fully*)
wenzelm@250
  1379
                  (ntps, map normt (Bs @ As), normt C)
wenzelm@250
  1380
             end
wenzelm@1258
  1381
           val th = (*tuned fix_shyps*)
wenzelm@3967
  1382
             Thm{sign_ref = sign_ref,
wenzelm@2386
  1383
                 der = infer_derivs (Bicompose(match, eres_flg,
wenzelm@2386
  1384
                                               1 + length Bs, nsubgoal, env),
wenzelm@2386
  1385
                                     [rder,sder]),
wenzelm@2386
  1386
                 maxidx = maxidx,
wenzelm@2386
  1387
                 shyps = add_env_sorts (env, union_sort(rshyps,sshyps)),
wenzelm@2386
  1388
                 hyps = union_term(rhyps,shyps),
wenzelm@2386
  1389
                 prop = Logic.rule_of normp}
wenzelm@4270
  1390
        in  Seq.cons(th, thq)  end  handle COMPOSE => thq
clasohm@0
  1391
     val (rtpairs,rhorn) = Logic.strip_flexpairs(rprop);
clasohm@0
  1392
     val (rAs,B) = Logic.strip_prems(nsubgoal, [], rhorn)
clasohm@0
  1393
       handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
clasohm@0
  1394
     (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
clasohm@0
  1395
     fun newAs(As0, n, dpairs, tpairs) =
clasohm@0
  1396
       let val As1 = if !Logic.auto_rename orelse not lifted then As0
wenzelm@250
  1397
                     else map (rename_bvars(dpairs,tpairs,B)) As0
clasohm@0
  1398
       in (map (Logic.flatten_params n) As1)
wenzelm@250
  1399
          handle TERM _ =>
wenzelm@250
  1400
          raise THM("bicompose: 1st premise", 0, [orule])
clasohm@0
  1401
       end;
paulson@2147
  1402
     val env = Envir.empty(Int.max(rmax,smax));
clasohm@0
  1403
     val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
clasohm@0
  1404
     val dpairs = BBi :: (rtpairs@stpairs);
clasohm@0
  1405
     (*elim-resolution: try each assumption in turn.  Initially n=1*)
wenzelm@4270
  1406
     fun tryasms (_, _, []) = Seq.empty
clasohm@0
  1407
       | tryasms (As, n, (t,u)::apairs) =
wenzelm@4270
  1408
          (case Seq.pull(Unify.unifiers(sign, env, (t,u)::dpairs))  of
wenzelm@250
  1409
               None                   => tryasms (As, n+1, apairs)
wenzelm@250
  1410
             | cell as Some((_,tpairs),_) =>
wenzelm@4270
  1411
                   Seq.it_right (addth (newAs(As, n, [BBi,(u,t)], tpairs)))
wenzelm@4270
  1412
                       (Seq.make (fn()=> cell),
wenzelm@4270
  1413
                        Seq.make (fn()=> Seq.pull (tryasms (As, n+1, apairs)))));
clasohm@0
  1414
     fun eres [] = raise THM("bicompose: no premises", 0, [orule,state])
clasohm@0
  1415
       | eres (A1::As) = tryasms (As, 1, Logic.assum_pairs A1);
clasohm@0
  1416
     (*ordinary resolution*)
wenzelm@4270
  1417
     fun res(None) = Seq.empty
wenzelm@250
  1418
       | res(cell as Some((_,tpairs),_)) =
wenzelm@4270
  1419
             Seq.it_right (addth(newAs(rev rAs, 0, [BBi], tpairs)))
wenzelm@4270
  1420
                       (Seq.make (fn()=> cell), Seq.empty)
clasohm@0
  1421
 in  if eres_flg then eres(rev rAs)
wenzelm@4270
  1422
     else res(Seq.pull(Unify.unifiers(sign, env, dpairs)))
clasohm@0
  1423
 end;
clasohm@0
  1424
end;  (*open Sequence*)
clasohm@0
  1425
clasohm@0
  1426
clasohm@0
  1427
fun bicompose match arg i state =
clasohm@0
  1428
    bicompose_aux match (state, dest_state(state,i), false) arg;
clasohm@0
  1429
clasohm@0
  1430
(*Quick test whether rule is resolvable with the subgoal with hyps Hs
clasohm@0
  1431
  and conclusion B.  If eres_flg then checks 1st premise of rule also*)
clasohm@0
  1432
fun could_bires (Hs, B, eres_flg, rule) =
clasohm@0
  1433
    let fun could_reshyp (A1::_) = exists (apl(A1,could_unify)) Hs
wenzelm@250
  1434
          | could_reshyp [] = false;  (*no premise -- illegal*)
wenzelm@250
  1435
    in  could_unify(concl_of rule, B) andalso
wenzelm@250
  1436
        (not eres_flg  orelse  could_reshyp (prems_of rule))
clasohm@0
  1437
    end;
clasohm@0
  1438
clasohm@0
  1439
(*Bi-resolution of a state with a list of (flag,rule) pairs.
clasohm@0
  1440
  Puts the rule above:  rule/state.  Renames vars in the rules. *)
wenzelm@250
  1441
fun biresolution match brules i state =
clasohm@0
  1442
    let val lift = lift_rule(state, i);
wenzelm@250
  1443
        val (stpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
  1444
        val B = Logic.strip_assums_concl Bi;
wenzelm@250
  1445
        val Hs = Logic.strip_assums_hyp Bi;
wenzelm@250
  1446
        val comp = bicompose_aux match (state, (stpairs, Bs, Bi, C), true);
wenzelm@4270
  1447
        fun res [] = Seq.empty
wenzelm@250
  1448
          | res ((eres_flg, rule)::brules) =
wenzelm@250
  1449
              if could_bires (Hs, B, eres_flg, rule)
wenzelm@4270
  1450
              then Seq.make (*delay processing remainder till needed*)
wenzelm@250
  1451
                  (fn()=> Some(comp (eres_flg, lift rule, nprems_of rule),
wenzelm@250
  1452
                               res brules))
wenzelm@250
  1453
              else res brules
wenzelm@4270
  1454
    in  Seq.flat (res brules)  end;
clasohm@0
  1455
clasohm@0
  1456
clasohm@0
  1457
wenzelm@2509
  1458
(*** Meta Simplification ***)
clasohm@0
  1459
wenzelm@2509
  1460
(** diagnostics **)
clasohm@0
  1461
clasohm@0
  1462
exception SIMPLIFIER of string * thm;
clasohm@0
  1463
nipkow@4045
  1464
fun prnt warn a = if warn then warning a else writeln a;
nipkow@4045
  1465
nipkow@4045
  1466
fun prtm warn a sign t =
nipkow@4045
  1467
  (prnt warn a; prnt warn (Sign.string_of_term sign t));
berghofe@1580
  1468
nipkow@4679
  1469
fun prthm warn a (thm as Thm{sign_ref, prop, ...}) =
nipkow@4679
  1470
  (prtm warn a (Sign.deref sign_ref) prop);
nipkow@4679
  1471
nipkow@209
  1472
val trace_simp = ref false;
nipkow@209
  1473
nipkow@4045
  1474
fun trace warn a = if !trace_simp then prnt warn a else ();
wenzelm@3967
  1475
nipkow@4045
  1476
fun trace_term warn a sign t =
nipkow@4045
  1477
  if !trace_simp then prtm warn a sign t else ();
wenzelm@3967
  1478
nipkow@4045
  1479
fun trace_thm warn a (thm as Thm{sign_ref, prop, ...}) =
nipkow@4045
  1480
  (trace_term warn a (Sign.deref sign_ref) prop);
nipkow@209
  1481
nipkow@209
  1482
berghofe@1580
  1483
wenzelm@2509
  1484
(** meta simp sets **)
wenzelm@2509
  1485
wenzelm@2509
  1486
(* basic components *)
berghofe@1580
  1487
nipkow@4820
  1488
type rrule = {thm: thm, lhs: term, elhs: term, fo: bool, perm: bool};
wenzelm@2509
  1489
type cong = {thm: thm, lhs: term};
wenzelm@3577
  1490
type simproc =
wenzelm@3577
  1491
 {name: string, proc: Sign.sg -> thm list -> term -> thm option, lhs: cterm, id: stamp};
nipkow@288
  1492
wenzelm@3550
  1493
fun eq_rrule ({thm = Thm {prop = p1, ...}, ...}: rrule,
wenzelm@2509
  1494
  {thm = Thm {prop = p2, ...}, ...}: rrule) = p1 aconv p2;
wenzelm@2509
  1495
wenzelm@3550
  1496
fun eq_cong ({thm = Thm {prop = p1, ...}, ...}: cong,
wenzelm@3550
  1497
  {thm = Thm {prop = p2, ...}, ...}: cong) = p1 aconv p2;
wenzelm@3550
  1498
wenzelm@3550
  1499
fun eq_prem (Thm {prop = p1, ...}, Thm {prop = p2, ...}) = p1 aconv p2;
wenzelm@3550
  1500
wenzelm@3550
  1501
fun eq_simproc ({id = s1, ...}:simproc, {id = s2, ...}:simproc) = (s1 = s2);
wenzelm@3550
  1502
wenzelm@3550
  1503
fun mk_simproc (name, proc, lhs, id) =
wenzelm@3550
  1504
  {name = name, proc = proc, lhs = lhs, id = id};
wenzelm@2509
  1505
wenzelm@2509
  1506
wenzelm@2509
  1507
(* datatype mss *)
nipkow@288
  1508
wenzelm@2509
  1509
(*
wenzelm@2509
  1510
  A "mss" contains data needed during conversion:
wenzelm@2509
  1511
    rules: discrimination net of rewrite rules;
nipkow@5623
  1512
    congs: association list of congruence rules and
nipkow@5623
  1513
           a flag iff all of the congruences are 'full'.
nipkow@5623
  1514
          A congruence is 'full' if it enforces normalization of all arguments.
wenzelm@2509
  1515
    procs: discrimination net of simplification procedures
wenzelm@2509
  1516
      (functions that prove rewrite rules on the fly);
wenzelm@2509
  1517
    bounds: names of bound variables already used
wenzelm@2509
  1518
      (for generating new names when rewriting under lambda abstractions);
wenzelm@2509
  1519
    prems: current premises;
nipkow@4679
  1520
    mk_rews: mk: turns simplification thms into rewrite rules;
nipkow@4679
  1521
             mk_sym: turns == around; (needs Drule!)
nipkow@4679
  1522
             mk_eq_True: turns P into P == True - logic specific;
wenzelm@2509
  1523
    termless: relation for ordered rewriting;
nipkow@1028
  1524
*)
clasohm@0
  1525
wenzelm@2509
  1526
datatype meta_simpset =
wenzelm@2509
  1527
  Mss of {
wenzelm@2509
  1528
    rules: rrule Net.net,
nipkow@5623
  1529
    congs: (string * cong) list * bool,
wenzelm@2509
  1530
    procs: simproc Net.net,
wenzelm@2509
  1531
    bounds: string list,
wenzelm@2509
  1532
    prems: thm list,
nipkow@4679
  1533
    mk_rews: {mk: thm -> thm list,
nipkow@4679
  1534
              mk_sym: thm -> thm option,
nipkow@4679
  1535
              mk_eq_True: thm -> thm option},
wenzelm@2509
  1536
    termless: term * term -> bool};
wenzelm@2509
  1537
wenzelm@2509
  1538
fun mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless) =
wenzelm@2509
  1539
  Mss {rules = rules, congs = congs, procs = procs, bounds = bounds,
nipkow@4679
  1540
       prems=prems, mk_rews=mk_rews, termless=termless};
nipkow@4679
  1541
nipkow@4679
  1542
fun upd_rules(Mss{rules,congs,procs,bounds,prems,mk_rews,termless}, rules') =
nipkow@4679
  1543
  mk_mss(rules',congs,procs,bounds,prems,mk_rews,termless);
wenzelm@2509
  1544
wenzelm@2509
  1545
val empty_mss =
nipkow@4679
  1546
  let val mk_rews = {mk = K [], mk_sym = K None, mk_eq_True = K None}
nipkow@5623
  1547
  in mk_mss (Net.empty, ([],true), Net.empty, [], [], mk_rews, Term.termless)
nipkow@5623
  1548
  end;
wenzelm@2509
  1549
wenzelm@2509
  1550
wenzelm@2509
  1551
wenzelm@2509
  1552
(** simpset operations **)
wenzelm@2509
  1553
wenzelm@3550
  1554
(* dest_mss *)
wenzelm@3550
  1555
wenzelm@3550
  1556
fun dest_mss (Mss {rules, congs, procs, ...}) =
wenzelm@3550
  1557
  {simps = map (fn (_, {thm, ...}) => thm) (Net.dest rules),
nipkow@5623
  1558
   congs = map (fn (_, {thm, ...}) => thm) (fst congs),
wenzelm@3550
  1559
   procs =
wenzelm@3550
  1560
     map (fn (_, {name, lhs, id, ...}) => ((name, lhs), id)) (Net.dest procs)
wenzelm@3550
  1561
     |> partition_eq eq_snd
wenzelm@3550
  1562
     |> map (fn ps => (#1 (#1 (hd ps)), map (#2 o #1) ps))};
wenzelm@3550
  1563
wenzelm@3550
  1564
wenzelm@3550
  1565
(* merge_mss *)		(*NOTE: ignores mk_rews and termless of 2nd mss*)
wenzelm@3550
  1566
wenzelm@3550
  1567
fun merge_mss
nipkow@5623
  1568
 (Mss {rules = rules1, congs = (congs1,full1), procs = procs1,
nipkow@5623
  1569
       bounds = bounds1, prems = prems1, mk_rews, termless},
nipkow@5623
  1570
  Mss {rules = rules2, congs = (congs2,full2), procs = procs2,
nipkow@5623
  1571
       bounds = bounds2, prems = prems2, ...}) =
wenzelm@3550
  1572
      mk_mss
wenzelm@3550
  1573
       (Net.merge (rules1, rules2, eq_rrule),
nipkow@5623
  1574
        (generic_merge (eq_cong o pairself snd) I I congs1 congs2,
nipkow@5623
  1575
         full1 andalso full2),
wenzelm@3550
  1576
        Net.merge (procs1, procs2, eq_simproc),
wenzelm@3550
  1577
        merge_lists bounds1 bounds2,
wenzelm@3550
  1578
        generic_merge eq_prem I I prems1 prems2,
wenzelm@3550
  1579
        mk_rews, termless);
wenzelm@3550
  1580
nipkow@4679
  1581
(* add_simps *)
wenzelm@3550
  1582
nipkow@4820
  1583
fun mk_rrule2{thm,lhs,perm} =
nipkow@4820
  1584
  let val elhs = Pattern.eta_contract lhs
nipkow@4820
  1585
      val fo = Pattern.first_order elhs orelse not(Pattern.pattern elhs)
nipkow@4820
  1586
  in {thm=thm,lhs=lhs,elhs=elhs,fo=fo,perm=perm} end
nipkow@4820
  1587
nipkow@4679
  1588
fun insert_rrule(mss as Mss {rules,...},
nipkow@4820
  1589
                 rrule as {thm,lhs,perm}) =
nipkow@4679
  1590
  (trace_thm false "Adding rewrite rule:" thm;
nipkow@4820
  1591
   let val rrule2 as {elhs,...} = mk_rrule2 rrule
nipkow@4820
  1592
       val rules' = Net.insert_term ((elhs, rrule2), rules, eq_rrule)
nipkow@4679
  1593
   in upd_rules(mss,rules') end
nipkow@4679
  1594
   handle Net.INSERT =>
wenzelm@4785
  1595
     (prthm true "Ignoring duplicate rewrite rule:" thm; mss));
nipkow@4679
  1596
nipkow@4679
  1597
fun vperm (Var _, Var _) = true
nipkow@4679
  1598
  | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
nipkow@4679
  1599
  | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
nipkow@4679
  1600
  | vperm (t, u) = (t = u);
nipkow@4679
  1601
nipkow@4679
  1602
fun var_perm (t, u) =
nipkow@4679
  1603
  vperm (t, u) andalso eq_set_term (term_vars t, term_vars u);
nipkow@4679
  1604
nipkow@4679
  1605
(* FIXME: it seems that the conditions on extra variables are too liberal if
nipkow@4679
  1606
prems are nonempty: does solving the prems really guarantee instantiation of
nipkow@4679
  1607
all its Vars? Better: a dynamic check each time a rule is applied.
nipkow@4679
  1608
*)
nipkow@4679
  1609
fun rewrite_rule_extra_vars prems elhs erhs =
nipkow@4679
  1610
  not ((term_vars erhs) subset
nipkow@4679
  1611
       (union_term (term_vars elhs, List.concat(map term_vars prems))))
nipkow@4679
  1612
  orelse
nipkow@4679
  1613
  not ((term_tvars erhs) subset
nipkow@4679
  1614
       (term_tvars elhs  union  List.concat(map term_tvars prems)));
wenzelm@2509
  1615
nipkow@4716
  1616
(*Simple test for looping rewrite rules and stupid orientations*)
nipkow@4716
  1617
fun reorient sign prems lhs rhs =
nipkow@4679
  1618
   rewrite_rule_extra_vars prems lhs rhs
nipkow@4679
  1619
  orelse
nipkow@4679
  1620
   is_Var (head_of lhs)
nipkow@4679
  1621
  orelse
nipkow@4684
  1622
   (exists (apl (lhs, Logic.occs)) (rhs :: prems))
nipkow@4679
  1623
  orelse
nipkow@4679
  1624
   (null prems andalso
nipkow@4679
  1625
    Pattern.matches (#tsig (Sign.rep_sg sign)) (lhs, rhs))
nipkow@4716
  1626
    (*the condition "null prems" is necessary because conditional rewrites
nipkow@4716
  1627
      with extra variables in the conditions may terminate although
nipkow@4716
  1628
      the rhs is an instance of the lhs. Example: ?m < ?n ==> f(?n) == f(?m)*)
nipkow@4716
  1629
  orelse
nipkow@4716
  1630
   (is_Const lhs andalso not(is_Const rhs))
nipkow@4679
  1631
nipkow@4679
  1632
fun decomp_simp(thm as Thm {sign_ref, prop, ...}) =
nipkow@4679
  1633
  let val sign = Sign.deref sign_ref;
nipkow@4679
  1634
      val prems = Logic.strip_imp_prems prop;
nipkow@4679
  1635
      val concl = Logic.strip_imp_concl prop;
nipkow@4679
  1636
      val (lhs, rhs) = Logic.dest_equals concl handle TERM _ =>
nipkow@4679
  1637
        raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm)
nipkow@4679
  1638
      val elhs = Pattern.eta_contract lhs;
nipkow@4679
  1639
      val erhs = Pattern.eta_contract rhs;
nipkow@4679
  1640
      val perm = var_perm (elhs, erhs) andalso not (elhs aconv erhs)
nipkow@4679
  1641
                 andalso not (is_Var elhs)
nipkow@4679
  1642
  in (sign,prems,lhs,rhs,perm) end;
nipkow@4679
  1643
nipkow@4679
  1644
fun mk_eq_True (Mss{mk_rews={mk_eq_True,...},...}) thm =
nipkow@4713
  1645
  case mk_eq_True thm of
nipkow@4713
  1646
    None => []
nipkow@4713
  1647
  | Some eq_True => let val (_,_,lhs,_,_) = decomp_simp eq_True
nipkow@4713
  1648
                    in [{thm=eq_True, lhs=lhs, perm=false}] end;
nipkow@4713
  1649
nipkow@4713
  1650
(* create the rewrite rule and possibly also the ==True variant,
nipkow@4713
  1651
   in case there are extra vars on the rhs *)
nipkow@4713
  1652
fun rrule_eq_True(thm,lhs,rhs,mss,thm2) =
nipkow@4713
  1653
  let val rrule = {thm=thm, lhs=lhs, perm=false}
nipkow@4713
  1654
  in if (term_vars rhs)  subset (term_vars lhs) andalso
nipkow@4713
  1655
        (term_tvars rhs) subset (term_tvars lhs)
nipkow@4713
  1656
     then [rrule]
nipkow@4713
  1657
     else mk_eq_True mss thm2 @ [rrule]
nipkow@4713
  1658
  end;
nipkow@4679
  1659
nipkow@4679
  1660
fun mk_rrule mss thm =
nipkow@4679
  1661
  let val (_,prems,lhs,rhs,perm) = decomp_simp thm
nipkow@4713
  1662
  in if perm then [{thm=thm, lhs=lhs, perm=true}] else
nipkow@4679
  1663
     (* weak test for loops: *)
nipkow@4679
  1664
     if rewrite_rule_extra_vars prems lhs rhs orelse
nipkow@4679
  1665
        is_Var (head_of lhs) (* mk_cases may do this! *)
nipkow@4679
  1666
     then mk_eq_True mss thm
nipkow@4713
  1667
     else rrule_eq_True(thm,lhs,rhs,mss,thm)
clasohm@0
  1668
  end;
clasohm@0
  1669
nipkow@4679
  1670
fun orient_rrule mss thm =
nipkow@4679
  1671
  let val (sign,prems,lhs,rhs,perm) = decomp_simp thm
nipkow@4713
  1672
  in if perm then [{thm=thm,lhs=lhs,perm=true}]
nipkow@4716
  1673
     else if reorient sign prems lhs rhs
nipkow@4716
  1674
          then if reorient sign prems rhs lhs
nipkow@4679
  1675
               then mk_eq_True mss thm
nipkow@4679
  1676
               else let val Mss{mk_rews={mk_sym,...},...} = mss
nipkow@4713
  1677
                    in case mk_sym thm of
nipkow@4713
  1678
                         None => []
nipkow@4820
  1679
                       | Some thm' =>
nipkow@4820
  1680
                           let val (_,_,lhs',rhs',_) = decomp_simp thm'
nipkow@4820
  1681
                           in rrule_eq_True(thm',lhs',rhs',mss,thm) end
nipkow@4679
  1682
                    end
nipkow@4713
  1683
          else rrule_eq_True(thm,lhs,rhs,mss,thm)
nipkow@4679
  1684
  end;
wenzelm@2509
  1685
nipkow@4679
  1686
fun extract_rews(Mss{mk_rews = {mk,...},...},thms) = flat(map mk thms);
nipkow@87
  1687
nipkow@4679
  1688
fun orient_comb_simps comb mk_rrule (mss,thms) =
nipkow@4679
  1689
  let val rews = extract_rews(mss,thms)
nipkow@4713
  1690
      val rrules = flat (map mk_rrule rews)
nipkow@4679
  1691
  in foldl comb (mss,rrules) end
nipkow@4667
  1692
nipkow@4679
  1693
(* Add rewrite rules explicitly; do not reorient! *)
nipkow@4679
  1694
fun add_simps(mss,thms) =
nipkow@4679
  1695
  orient_comb_simps insert_rrule (mk_rrule mss) (mss,thms);
clasohm@0
  1696
nipkow@4679
  1697
fun mss_of thms =
nipkow@4713
  1698
  foldl insert_rrule (empty_mss, flat(map (mk_rrule empty_mss) thms));
wenzelm@2509
  1699
nipkow@4713
  1700
fun extract_safe_rrules(mss,thm) =
nipkow@4713
  1701
  flat (map (orient_rrule mss) (extract_rews(mss,[thm])));
wenzelm@2509
  1702
nipkow@4740
  1703
fun add_safe_simp(mss,thm) =
nipkow@4740
  1704
  foldl insert_rrule (mss, extract_safe_rrules(mss,thm))
nipkow@4740
  1705
wenzelm@2509
  1706
(* del_simps *)
wenzelm@2509
  1707
nipkow@4679
  1708
fun del_rrule(mss as Mss {rules,...},
nipkow@4820
  1709
              rrule as {thm, elhs, ...}) =
nipkow@4820
  1710
  (upd_rules(mss, Net.delete_term ((elhs, rrule), rules, eq_rrule))
nipkow@4679
  1711
   handle Net.DELETE =>
wenzelm@4785
  1712
     (prthm true "Rewrite rule not in simpset:" thm; mss));
nipkow@4667
  1713
nipkow@4679
  1714
fun del_simps(mss,thms) =
nipkow@4820
  1715
  orient_comb_simps del_rrule (map mk_rrule2 o mk_rrule mss) (mss,thms);
clasohm@0
  1716
wenzelm@2509
  1717
oheimb@2626
  1718
(* add_congs *)
clasohm@0
  1719
nipkow@5623
  1720
(*FIXME -> term.ML *)
nipkow@5623
  1721
fun is_Bound (Bound _) = true
nipkow@5623
  1722
fun is_Bound _         = false;
nipkow@5623
  1723
nipkow@5623
  1724
fun is_full_cong_prems [] varpairs = null varpairs
nipkow@5623
  1725
  | is_full_cong_prems (p::prems) varpairs =
nipkow@5623
  1726
    (case Logic.strip_assums_concl p of
nipkow@5623
  1727
       Const("==",_) $ lhs $ rhs =>
nipkow@5623
  1728
         let val (x,xs) = strip_comb lhs and (y,ys) = strip_comb rhs
nipkow@5623
  1729
         in is_Var x  andalso  forall is_Bound xs  andalso
nipkow@5623
  1730
            null(findrep(xs))  andalso xs=ys andalso
nipkow@5623
  1731
            (x,y) mem varpairs andalso
nipkow@5623
  1732
            is_full_cong_prems (p::prems) (varpairs\(x,y))
nipkow@5623
  1733
         end
nipkow@5623
  1734
     | _ => false);
nipkow@5623
  1735
nipkow@5623
  1736
fun is_full_cong (Thm{prop,...}) =
nipkow@5623
  1737
let val prems = Logic.strip_imp_prems prop
nipkow@5623
  1738
    and concl = Logic.strip_imp_concl prop
nipkow@5623
  1739
    val (lhs,rhs) = Logic.dest_equals concl
nipkow@5623
  1740
    val (f,xs) = strip_comb lhs
nipkow@5623
  1741
    and (g,ys) = strip_comb rhs
nipkow@5623
  1742
in
nipkow@5623
  1743
  f=g andalso null(findrep(xs@ys)) andalso length xs = length ys andalso
nipkow@5623
  1744
  is_full_cong_prems prems (xs ~~ ys)
nipkow@5623
  1745
end
nipkow@5623
  1746
nipkow@4679
  1747
fun add_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thm) =
wenzelm@2509
  1748
  let
wenzelm@2509
  1749
    val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
wenzelm@2509
  1750
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
wenzelm@2509
  1751
(*   val lhs = Pattern.eta_contract lhs; *)
wenzelm@2509
  1752
    val (a, _) = dest_Const (head_of lhs) handle TERM _ =>
wenzelm@2509
  1753
      raise SIMPLIFIER ("Congruence must start with a constant", thm);
nipkow@5623
  1754
    val (alist,full) = congs
nipkow@5623
  1755
    val full2 = full andalso is_full_cong thm
wenzelm@2509
  1756
  in
nipkow@5623
  1757
    mk_mss (rules, ((a, {lhs = lhs, thm = thm}) :: alist, full2),
nipkow@5623
  1758
            procs, bounds, prems, mk_rews, termless)
clasohm@0
  1759
  end;
clasohm@0
  1760
clasohm@0
  1761
val (op add_congs) = foldl add_cong;
clasohm@0
  1762
wenzelm@2509
  1763
oheimb@2626
  1764
(* del_congs *)
oheimb@2626
  1765
nipkow@4679
  1766
fun del_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thm) =
oheimb@2626
  1767
  let
oheimb@2626
  1768
    val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
oheimb@2626
  1769
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
oheimb@2626
  1770
(*   val lhs = Pattern.eta_contract lhs; *)
oheimb@2626
  1771
    val (a, _) = dest_Const (head_of lhs) handle TERM _ =>
oheimb@2626
  1772
      raise SIMPLIFIER ("Congruence must start with a constant", thm);
nipkow@5623
  1773
    val (alist,full) = congs
nipkow@5623
  1774
    val alist2 = filter (fn (x,_)=> x<>a) alist
nipkow@5623
  1775
    val full2 = forall (fn(_,{thm,...}) => is_full_cong thm) alist2
oheimb@2626
  1776
  in
nipkow@5623
  1777
    mk_mss (rules, (alist2,full2), procs, bounds, prems, mk_rews, termless)
oheimb@2626
  1778
  end;
oheimb@2626
  1779
oheimb@2626
  1780
val (op del_congs) = foldl del_cong;
oheimb@2626
  1781
oheimb@2626
  1782
wenzelm@2509
  1783
(* add_simprocs *)
wenzelm@2509
  1784
nipkow@4679
  1785
fun add_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless},
wenzelm@3967
  1786
    (name, lhs as Cterm {sign_ref, t, ...}, proc, id)) =
paulson@5494
  1787
  (trace_term false ("Adding simplification procedure " ^ quote name ^ " for")
wenzelm@3967
  1788
      (Sign.deref sign_ref) t;
wenzelm@2509
  1789
    mk_mss (rules, congs,
wenzelm@3550
  1790
      Net.insert_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
paulson@5494
  1791
        handle Net.INSERT => 
paulson@5494
  1792
	    (warning ("Ignoring duplicate simplification procedure \"" 
paulson@5494
  1793
	              ^ name ^ "\""); 
paulson@5494
  1794
	     procs),
wenzelm@2509
  1795
        bounds, prems, mk_rews, termless));
clasohm@0
  1796
wenzelm@3550
  1797
fun add_simproc (mss, (name, lhss, proc, id)) =
wenzelm@3550
  1798
  foldl add_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
wenzelm@3550
  1799
wenzelm@2509
  1800
val add_simprocs = foldl add_simproc;
wenzelm@2509
  1801
wenzelm@2509
  1802
wenzelm@2509
  1803
(* del_simprocs *)
clasohm@0
  1804
nipkow@4679
  1805
fun del_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless},
wenzelm@3550
  1806
    (name, lhs as Cterm {t, ...}, proc, id)) =
wenzelm@2509
  1807
  mk_mss (rules, congs,
wenzelm@3550
  1808
    Net.delete_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
paulson@5494
  1809
      handle Net.DELETE => 
paulson@5494
  1810
	  (warning ("Simplification procedure \"" ^ name ^
paulson@5494
  1811
		       "\" not in simpset"); procs),
wenzelm@3550
  1812
      bounds, prems, mk_rews, termless);
wenzelm@3550
  1813
wenzelm@3550
  1814
fun del_simproc (mss, (name, lhss, proc, id)) =
wenzelm@3550
  1815
  foldl del_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
wenzelm@2509
  1816
wenzelm@2509
  1817
val del_simprocs = foldl del_simproc;
clasohm@0
  1818
clasohm@0
  1819
wenzelm@2509
  1820
(* prems *)
wenzelm@2509
  1821
nipkow@4679
  1822
fun add_prems (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thms) =
wenzelm@2509
  1823
  mk_mss (rules, congs, procs, bounds, thms @ prems, mk_rews, termless);
wenzelm@2509
  1824
wenzelm@2509
  1825
fun prems_of_mss (Mss {prems, ...}) = prems;
wenzelm@2509
  1826
wenzelm@2509
  1827
wenzelm@2509
  1828
(* mk_rews *)
wenzelm@2509
  1829
wenzelm@2509
  1830
fun set_mk_rews
nipkow@4679
  1831
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk) =
nipkow@4679
  1832
    mk_mss (rules, congs, procs, bounds, prems,
nipkow@4679
  1833
            {mk=mk, mk_sym= #mk_sym mk_rews, mk_eq_True= #mk_eq_True mk_rews},
nipkow@4679
  1834
            termless);
wenzelm@2509
  1835
nipkow@4679
  1836
fun set_mk_sym
nipkow@4679
  1837
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk_sym) =
nipkow@4679
  1838
    mk_mss (rules, congs, procs, bounds, prems,
nipkow@4679
  1839
            {mk= #mk mk_rews, mk_sym= mk_sym, mk_eq_True= #mk_eq_True mk_rews},
nipkow@4679
  1840
            termless);
wenzelm@2509
  1841
nipkow@4679
  1842
fun set_mk_eq_True
nipkow@4679
  1843
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk_eq_True) =
nipkow@4679
  1844
    mk_mss (rules, congs, procs, bounds, prems,
nipkow@4679
  1845
            {mk= #mk mk_rews, mk_sym= #mk_sym mk_rews, mk_eq_True= mk_eq_True},
nipkow@4679
  1846
            termless);
wenzelm@2509
  1847
wenzelm@2509
  1848
(* termless *)
wenzelm@2509
  1849
wenzelm@2509
  1850
fun set_termless
wenzelm@2509
  1851
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless = _}, termless) =
wenzelm@2509
  1852
    mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless);
wenzelm@2509
  1853
wenzelm@2509
  1854
wenzelm@2509
  1855
wenzelm@2509
  1856
(** rewriting **)
wenzelm@2509
  1857
wenzelm@2509
  1858
(*
wenzelm@2509
  1859
  Uses conversions, omitting proofs for efficiency.  See:
wenzelm@2509
  1860
    L C Paulson, A higher-order implementation of rewriting,
wenzelm@2509
  1861
    Science of Computer Programming 3 (1983), pages 119-149.
wenzelm@2509
  1862
*)
clasohm@0
  1863
clasohm@0
  1864
type prover = meta_simpset -> thm -> thm option;
wenzelm@3967
  1865
type termrec = (Sign.sg_ref * term list) * term;
clasohm@0
  1866
type conv = meta_simpset -> termrec -> termrec;
clasohm@0
  1867
nipkow@5623
  1868
fun check_conv
nipkow@5623
  1869
      (thm as Thm{shyps,hyps,prop,sign_ref,der,...}, prop0, ders) =
nipkow@4045
  1870
  let fun err() = (trace_thm false "Proved wrong thm (Check subgoaler?)" thm;
wenzelm@4785
  1871
                   trace_term false "Should have proved:" (Sign.deref sign_ref) prop0;
nipkow@432
  1872
                   None)
clasohm@0
  1873
      val (lhs0,_) = Logic.dest_equals(Logic.strip_imp_concl prop0)
clasohm@0
  1874
  in case prop of
clasohm@0
  1875
       Const("==",_) $ lhs $ rhs =>
clasohm@0
  1876
         if (lhs = lhs0) orelse
nipkow@427
  1877
            (lhs aconv Envir.norm_term (Envir.empty 0) lhs0)
nipkow@4045
  1878
         then (trace_thm false "SUCCEEDED" thm; 
nipkow@4713
  1879
               Some(rhs, (shyps, hyps, der::ders)))
clasohm@0
  1880
         else err()
clasohm@0
  1881
     | _ => err()
clasohm@0
  1882
  end;
clasohm@0
  1883
nipkow@659
  1884
fun ren_inst(insts,prop,pat,obj) =
nipkow@659
  1885
  let val ren = match_bvs(pat,obj,[])
nipkow@659
  1886
      fun renAbs(Abs(x,T,b)) =
berghofe@1576
  1887
            Abs(case assoc_string(ren,x) of None => x | Some(y) => y, T, renAbs(b))
nipkow@659
  1888
        | renAbs(f$t) = renAbs(f) $ renAbs(t)
nipkow@659
  1889
        | renAbs(t) = t
nipkow@659
  1890
  in subst_vars insts (if null(ren) then prop else renAbs(prop)) end;
nipkow@678
  1891
nipkow@4820
  1892
fun incr_insts i (in1:(indexname*typ)list,in2:(indexname*term)list) =
nipkow@4820
  1893
  let fun incr ((a,n),x) = ((a,n+i),x)
nipkow@4820
  1894
  in (map incr in1, map incr in2) end;
nipkow@4820
  1895
wenzelm@1258
  1896
fun add_insts_sorts ((iTs, is), Ss) =
wenzelm@1258
  1897
  add_typs_sorts (map snd iTs, add_terms_sorts (map snd is, Ss));
wenzelm@1258
  1898
nipkow@659
  1899
wenzelm@2509
  1900
(* mk_procrule *)
wenzelm@2509
  1901
nipkow@4679
  1902
fun mk_procrule thm =
nipkow@4679
  1903
  let val (_,prems,lhs,rhs,_) = decomp_simp thm
nipkow@4679
  1904
  in if rewrite_rule_extra_vars prems lhs rhs
wenzelm@4785
  1905
     then (prthm true "Extra vars on rhs:" thm; [])
nipkow@4820
  1906
     else [mk_rrule2{thm = thm, lhs = lhs, perm = false}]
wenzelm@2509
  1907
  end;
wenzelm@2509
  1908
wenzelm@2509
  1909
wenzelm@2509
  1910
(* conversion to apply the meta simpset to a term *)
wenzelm@2509
  1911
nipkow@5623
  1912
(* Since the rewriting strategy is bottom-up, we avoid re-normalizing already
nipkow@5623
  1913
   normalized terms by carrying around the rhs of the rewrite rule just
nipkow@5623
  1914
   applied. This is called the `skeleton'. It is decomposed in parallel
nipkow@5623
  1915
   with the term. Once a Var is encountered, the corresponding term is
nipkow@5623
  1916
   already in normal form.
nipkow@5623
  1917
   skel0 is a dummy skeleton that is to enforce complete normalization.
nipkow@5623
  1918
*)
nipkow@5623
  1919
val skel0 = Bound 0;
nipkow@5623
  1920
wenzelm@2509
  1921
(*
wenzelm@2509
  1922
  we try in order:
wenzelm@2509
  1923
    (1) beta reduction
wenzelm@2509
  1924
    (2) unconditional rewrite rules
wenzelm@2509
  1925
    (3) conditional rewrite rules
wenzelm@3550
  1926
    (4) simplification procedures
nipkow@4116
  1927
nipkow@4116
  1928
  IMPORTANT: rewrite rules must not introduce new Vars or TVars!
nipkow@4116
  1929
wenzelm@2509
  1930
*)
wenzelm@2509
  1931
nipkow@4116
  1932
fun rewritec (prover,sign_reft,maxt)
nipkow@5623
  1933
             (mss as Mss{rules, procs, termless, prems, congs, ...}) 
nipkow@4713
  1934
             (t:term,etc as (shypst,hypst,ders)) =
wenzelm@3550
  1935
  let
nipkow@4713
  1936
    val signt = Sign.deref sign_reft;
nipkow@4713
  1937
    val tsigt = Sign.tsig_of signt;
nipkow@4820
  1938
    fun rew{thm as Thm{sign_ref,der,shyps,hyps,prop,maxidx,...},
nipkow@4820
  1939
            lhs, elhs, fo, perm} =
nipkow@4713
  1940
      let
nipkow@4713
  1941
        val _ = if Sign.subsig (Sign.deref sign_ref, signt) then ()
paulson@5342
  1942
                else (prthm true "Rewrite rule from different theory:" thm;
nipkow@4713
  1943
                      raise Pattern.MATCH);
nipkow@4713
  1944
        val rprop = if maxt = ~1 then prop
nipkow@4713
  1945
                    else Logic.incr_indexes([],maxt+1) prop;
nipkow@4820
  1946
        val insts = if fo then Pattern.first_order_match tsigt (elhs,t)
nipkow@4820
  1947
                          else Pattern.match             tsigt (elhs,t);
nipkow@4820
  1948
        val insts = if maxt = ~1 then insts else incr_insts (maxt+1) insts
nipkow@4820
  1949
        val prop' = ren_inst(insts,rprop,lhs,t);
nipkow@4713
  1950
        val hyps' = union_term(hyps,hypst);
nipkow@4713
  1951
        val shyps' = add_insts_sorts (insts, union_sort(shyps,shypst));
nipkow@4713
  1952
        val unconditional = (Logic.count_prems(prop',0) = 0);
nipkow@4713
  1953
        val maxidx' = if unconditional then maxt else maxidx+maxt+1
nipkow@4713
  1954
        val ct' = Cterm{sign_ref = sign_reft,       (*used for deriv only*)
nipkow@4713
  1955
                        t = prop', T = propT, maxidx = maxidx'}
nipkow@4713
  1956
        val der' = infer_derivs (RewriteC ct', [der]);
nipkow@4713
  1957
        val thm' = Thm{sign_ref = sign_reft, der = der', shyps = shyps',
nipkow@4713
  1958
                       hyps = hyps', prop = prop', maxidx = maxidx'}
nipkow@4713
  1959
        val (lhs',rhs') = Logic.dest_equals(Logic.strip_imp_concl prop')
nipkow@4713
  1960
      in
nipkow@4713
  1961
        if perm andalso not(termless(rhs',lhs')) then None
nipkow@4713
  1962
        else (trace_thm false "Applying instance of rewrite rule:" thm;
nipkow@4713
  1963
              if unconditional
nipkow@5623
  1964
              then (trace_thm false "Rewriting:" thm';
nipkow@5623
  1965
                    let val (_,rhs) = Logic.dest_equals prop
nipkow@5623
  1966
                    in Some((rhs', (shyps', hyps', der'::ders)),
nipkow@5623
  1967
                            if snd congs then rhs else skel0)
nipkow@5623
  1968
                        (* use rhs as depth-limit only if all congs are full *)
nipkow@5623
  1969
                    end)
nipkow@4713
  1970
              else (trace_thm false "Trying to rewrite:" thm';
nipkow@4713
  1971
                    case prover mss thm' of
nipkow@4713
  1972
                      None       => (trace_thm false "FAILED" thm'; None)
nipkow@5623
  1973
                    | Some(thm2) =>
nipkow@5623
  1974
                        (case check_conv(thm2,prop',ders) of
nipkow@5623
  1975
                           None => None | Some trec => Some(trec,skel0))))
oheimb@1659
  1976
      end
wenzelm@2509
  1977
nipkow@4713
  1978
    fun rews [] = None
nipkow@4713
  1979
      | rews (rrule :: rrules) =
nipkow@4713
  1980
          let val opt = rew rrule handle Pattern.MATCH => None
nipkow@4713
  1981
          in case opt of None => rews rrules | some => some end;
nipkow@4713
  1982
nipkow@4713
  1983
    fun sort_rrules rrs = let
nipkow@4820
  1984
      fun is_simple({thm as Thm{prop,...}, ...}:rrule) = case prop of 
nipkow@4713
  1985
                                      Const("==",_) $ _ $ _ => true
nipkow@4713
  1986
                                      | _                   => false 
nipkow@4713
  1987
      fun sort []        (re1,re2) = re1 @ re2
nipkow@4713
  1988
        | sort (rr::rrs) (re1,re2) = if is_simple rr 
nipkow@4713
  1989
                                     then sort rrs (rr::re1,re2)
nipkow@4713
  1990
                                     else sort rrs (re1,rr::re2)
nipkow@4713
  1991
    in sort rrs ([],[]) end
nipkow@4713
  1992
nipkow@4713
  1993
    fun proc_rews _ ([]:simproc list) = None
nipkow@4713
  1994
      | proc_rews eta_t ({name, proc, lhs = Cterm {t = plhs, ...}, ...} :: ps) =
nipkow@4713
  1995
          if Pattern.matches tsigt (plhs, t) then
nipkow@4713
  1996
            (trace_term false ("Trying procedure " ^ quote name ^ " on:") signt eta_t;
nipkow@4713
  1997
             case proc signt prems eta_t of
nipkow@4713
  1998
               None => (trace false "FAILED"; proc_rews eta_t ps)
nipkow@4713
  1999
             | Some raw_thm =>
wenzelm@4397
  2000
                 (trace_thm false ("Procedure " ^ quote name ^ " produced rewrite rule:") raw_thm;
nipkow@4713
  2001
                  (case rews (mk_procrule raw_thm) of
nipkow@4713
  2002
                    None => (trace false "IGNORED"; proc_rews eta_t ps)
nipkow@4713
  2003
                  | some => some)))
nipkow@4713
  2004
          else proc_rews eta_t ps;
nipkow@4713
  2005
  in case t of
nipkow@5623
  2006
       Abs (_, _, body) $ u => Some ((subst_bound (u, body), etc),skel0)
nipkow@4713
  2007
     | _ => (case rews (sort_rrules (Net.match_term rules t)) of
nipkow@4713
  2008
               None => proc_rews (Pattern.eta_contract t)
nipkow@4713
  2009
                                 (Net.match_term procs t)
nipkow@4713
  2010
             | some => some)
clasohm@0
  2011
  end;
clasohm@0
  2012
wenzelm@2509
  2013
wenzelm@2509
  2014
(* conversion to apply a congruence rule to a term *)
wenzelm@2509
  2015
nipkow@4713
  2016
fun congc (prover,sign_reft,maxt) {thm=cong,lhs=lhs} (t,(shypst,hypst,ders)) =
wenzelm@3967
  2017
  let val signt = Sign.deref sign_reft;
wenzelm@3967
  2018
      val tsig = Sign.tsig_of signt;
wenzelm@3967
  2019
      val Thm{sign_ref,der,shyps,hyps,maxidx,prop,...} = cong
wenzelm@3967
  2020
      val _ = if Sign.subsig(Sign.deref sign_ref,signt) then ()
nipkow@208
  2021
                 else error("Congruence rule from different theory")
paulson@2147
  2022
      val rprop = if maxt = ~1 then prop
paulson@2147
  2023
                  else Logic.incr_indexes([],maxt+1) prop;
paulson@2147
  2024
      val rlhs = if maxt = ~1 then lhs
nipkow@1065
  2025
                 else fst(Logic.dest_equals(Logic.strip_imp_concl rprop))
nipkow@1569
  2026
      val insts = Pattern.match tsig (rlhs,t)
nipkow@1569
  2027
      (* Pattern.match can raise Pattern.MATCH;
nipkow@1569
  2028
         is handled when congc is called *)
nipkow@1065
  2029
      val prop' = ren_inst(insts,rprop,rlhs,t);
paulson@2177
  2030
      val shyps' = add_insts_sorts (insts, union_sort(shyps,shypst))
paulson@1529
  2031
      val maxidx' = maxidx_of_term prop'
wenzelm@3967
  2032
      val ct' = Cterm{sign_ref = sign_reft,     (*used for deriv only*)
wenzelm@2386
  2033
                      t = prop',
wenzelm@2386
  2034
                      T = propT,
wenzelm@2386
  2035
                      maxidx = maxidx'}
wenzelm@3967
  2036
      val thm' = Thm{sign_ref = sign_reft, 
wenzelm@3550
  2037
                     der = infer_derivs (CongC ct', [der]),
wenzelm@2386
  2038
                     shyps = shyps',
wenzelm@2386
  2039
                     hyps = union_term(hyps,hypst),
paulson@1529
  2040
                     prop = prop',
wenzelm@2386
  2041
                     maxidx = maxidx'};
wenzelm@4785
  2042
      val unit = trace_thm false "Applying congruence rule:" thm';
nipkow@112
  2043
      fun err() = error("Failed congruence proof!")
clasohm@0
  2044
clasohm@0
  2045
  in case prover thm' of
nipkow@112
  2046
       None => err()
paulson@1529
  2047
     | Some(thm2) => (case check_conv(thm2,prop',ders) of
nipkow@405
  2048
                        None => err() | some => some)
clasohm@0
  2049
  end;
clasohm@0
  2050
nipkow@4713
  2051
fun bottomc ((simprem,useprem,mutsimp),prover,sign_ref,maxidx) =
nipkow@4713
  2052
  let
nipkow@5623
  2053
    fun botc fail skel mss trec =
nipkow@5623
  2054
          if is_Var skel then if fail then None else Some(trec)
nipkow@5623
  2055
          else
nipkow@5623
  2056
          (case subc skel mss trec of
wenzelm@2386
  2057
             some as Some(trec1) =>
nipkow@4116
  2058
               (case rewritec (prover,sign_ref,maxidx) mss trec1 of
nipkow@5623
  2059
                  Some(trec2,skel2) => botc false skel2 mss trec2
wenzelm@2386
  2060
                | None => some)
wenzelm@2386
  2061
           | None =>
nipkow@4116
  2062
               (case rewritec (prover,sign_ref,maxidx) mss trec of
nipkow@5623
  2063
                  Some(trec2,skel2) => botc false skel2 mss trec2
wenzelm@2386
  2064
                | None => if fail then None else Some(trec)))
clasohm@0
  2065
nipkow@5623
  2066
    and try_botc mss trec =
nipkow@5623
  2067
          (case botc true skel0 mss trec of
nipkow@5623
  2068
             Some(trec1) => trec1 | None => trec)
nipkow@405
  2069
nipkow@5623
  2070
    and subc skel
nipkow@5623
  2071
             (mss as Mss{rules,congs,procs,bounds,prems,mk_rews,termless})
nipkow@4713
  2072
             (trec as (t0:term,etc:sort list*term list * rule mtree list)) =
paulson@1529
  2073
       (case t0 of
wenzelm@2386
  2074
           Abs(a,T,t) =>
wenzelm@2386
  2075
             let val b = variant bounds a
wenzelm@2386
  2076
                 val v = Free("." ^ b,T)
wenzelm@2509
  2077
                 val mss' = mk_mss (rules, congs, procs, b :: bounds, prems, mk_rews, termless)
nipkow@5623
  2078
                 val skel' = case skel of Abs(_,_,sk) => sk | _ => skel0
nipkow@5623
  2079
             in case botc true skel' mss' (subst_bound(v,t),etc) of
nipkow@4713
  2080
                  Some(t',etc') => Some(Abs(a, T, abstract_over(v,t')), etc')
wenzelm@2386
  2081
                | None => None
wenzelm@2386
  2082
             end
wenzelm@2386
  2083
         | t$u => (case t of
nipkow@4740
  2084
             Const("==>",_)$s  => Some(impc(s,u,mss,etc))
wenzelm@2386
  2085
           | Abs(_,_,body) =>
nipkow@4713
  2086
               let val trec = (subst_bound(u,body), etc)
nipkow@5623
  2087
               in case subc skel0 mss trec of
wenzelm@2386
  2088
                    None => Some(trec)
wenzelm@2386
  2089
                  | trec => trec
wenzelm@2386
  2090
               end
wenzelm@2386
  2091
           | _  =>
wenzelm@2386
  2092
               let fun appc() =
nipkow@5623
  2093
                     let val (tskel,uskel) =
nipkow@5623
  2094
                                case skel of tskel$uskel => (tskel,uskel)
nipkow@5623
  2095
                                           | _ => (skel0,skel0)
nipkow@5623
  2096
                     in
nipkow@5623
  2097
                     (case botc true tskel mss (t,etc) of
nipkow@4713
  2098
                        Some(t1,etc1) =>
nipkow@5623
  2099
                          (case botc true uskel mss (u,etc1) of
nipkow@4713
  2100
                             Some(u1,etc2) => Some(t1$u1, etc2)
nipkow@4713
  2101
                           | None => Some(t1$u, etc1))
wenzelm@2386
  2102
                      | None =>
nipkow@5623
  2103
                          (case botc true uskel mss (u,etc) of
nipkow@4713
  2104
                             Some(u1,etc1) => Some(t$u1, etc1)
wenzelm@2386
  2105
                           | None => None))
nipkow@5623
  2106
                     end
wenzelm@2386
  2107
                   val (h,ts) = strip_comb t
wenzelm@2386
  2108
               in case h of
wenzelm@2386
  2109
                    Const(a,_) =>
nipkow@5623
  2110
                      (case assoc_string(fst congs,a) of
wenzelm@2386
  2111
                         None => appc()
nipkow@4116
  2112
                       | Some(cong) =>
nipkow@4116
  2113
                           (congc (prover mss,sign_ref,maxidx) cong trec
nipkow@4116
  2114
                            handle Pattern.MATCH => appc() ) )
wenzelm@2386
  2115
                  | _ => appc()
wenzelm@2386
  2116
               end)
wenzelm@2386
  2117
         | _ => None)
clasohm@0
  2118
nipkow@4740
  2119
    and impc args =
nipkow@4740
  2120
      if mutsimp
nipkow@4740
  2121
      then let val (prem, conc, mss, etc) = args
nipkow@4740
  2122
           in snd(mut_impc([], prem, conc, mss, etc)) end
nipkow@4740
  2123
      else nonmut_impc args
nipkow@4713
  2124
nipkow@4740
  2125
    and mut_impc (prems, prem, conc, mss, etc) =
nipkow@4740
  2126
      let val (prem1,etc1) = try_botc mss (prem,etc)
nipkow@4740
  2127
      in mut_impc1(prems, prem1, conc, mss, etc1) end
nipkow@4740
  2128
nipkow@4740
  2129
    and mut_impc1(prems, prem1, conc, mss, etc1 as (_,hyps1,_)) =
nipkow@4713
  2130
      let
nipkow@4820
  2131
        fun uncond({thm,lhs,perm}) =
nipkow@4713
  2132
          if nprems_of thm = 0 then Some lhs else None
nipkow@4713
  2133
nipkow@4740
  2134
        val (lhss1,mss1) =
nipkow@4713
  2135
          if maxidx_of_term prem1 <> ~1
nipkow@4713
  2136
          then (trace_term true "Cannot add premise as rewrite rule because it contains (type) unknowns:"
nipkow@4713
  2137
                           (Sign.deref sign_ref) prem1;
nipkow@4740
  2138
                ([],mss))
nipkow@4713
  2139
          else let val thm = assume (Cterm{sign_ref=sign_ref, t=prem1, 
nipkow@4713
  2140
                                           T=propT, maxidx= ~1})
nipkow@4713
  2141
                   val rrules1 = extract_safe_rrules(mss,thm)
nipkow@4740
  2142
                   val lhss1 = mapfilter uncond rrules1
nipkow@4713
  2143
                   val mss1 = foldl insert_rrule (add_prems(mss,[thm]),rrules1)
nipkow@4740
  2144
               in (lhss1, mss1) end
nipkow@4713
  2145
nipkow@4716
  2146
        fun disch1(conc2,(shyps2,hyps2,ders2)) =
nipkow@4713
  2147
          let val hyps2' = if gen_mem (op aconv) (prem1, hyps1)
nipkow@4713
  2148
                           then hyps2 else hyps2\prem1
nipkow@4716
  2149
          in (Logic.mk_implies(prem1,conc2),(shyps2,hyps2',ders2)) end
nipkow@4716
  2150
nipkow@4716
  2151
        fun rebuild trec2 =
nipkow@4716
  2152
          let val trec = disch1 trec2
nipkow@4713
  2153
          in case rewritec (prover,sign_ref,maxidx) mss trec of
nipkow@4713
  2154
               None => (None,trec)
nipkow@5623
  2155
             | Some((Const("==>",_)$prem$conc,etc),_) =>
nipkow@4740
  2156
                 mut_impc(prems,prem,conc,mss,etc)
nipkow@5623
  2157
             | Some(trec',_) => (None,trec')
nipkow@4713
  2158
          end
nipkow@4713
  2159
nipkow@4713
  2160
        fun simpconc() =
nipkow@4713
  2161
          case conc of
nipkow@4713
  2162
            Const("==>",_)$s$t =>
nipkow@4740
  2163
              (case mut_impc(prems@[prem1],s,t,mss1,etc1) of
nipkow@4716
  2164
                 (Some(i,prem),trec2) =>
nipkow@4716
  2165
                    let val trec2' = disch1 trec2
nipkow@4740
  2166
                    in if i=0 then mut_impc1(prems,prem,fst trec2',mss,snd trec2')
nipkow@4716
  2167
                       else (Some(i-1,prem),trec2')
nipkow@4713
  2168
                    end
nipkow@4713
  2169
               | (None,trec) => rebuild(trec))
nipkow@4713
  2170
          | _ => rebuild(try_botc mss1 (conc,etc1))
nipkow@4713
  2171
nipkow@4740
  2172
      in let val sg = Sign.deref sign_ref
nipkow@4713
  2173
                  val tsig = #tsig(Sign.rep_sg sg)
nipkow@4713
  2174
                  fun reducible t =
nipkow@4713
  2175
                    exists (fn lhs => Pattern.matches_subterm tsig (lhs,t))
nipkow@4713
  2176
                           lhss1;
nipkow@4713
  2177
              in case dropwhile (not o reducible) prems of
nipkow@4713
  2178
                   [] => simpconc()
wenzelm@4785
  2179
                 | red::rest => (trace_term false "Can now reduce premise:" sg
nipkow@4713
  2180
                                            red;
nipkow@4713
  2181
                                 (Some(length rest,prem1),(conc,etc1)))
nipkow@4713
  2182
              end
nipkow@4713
  2183
      end
clasohm@0
  2184
nipkow@4740
  2185
     (* legacy code - only for backwards compatibility *)
nipkow@4740
  2186
     and nonmut_impc(prem, conc, mss, etc as (_,hyps1,_)) =
nipkow@4740
  2187
       let val (prem1,etc1) = if simprem then try_botc mss (prem,etc)
nipkow@4740
  2188
                              else (prem,etc)
nipkow@4740
  2189
           val maxidx1 = maxidx_of_term prem1
nipkow@4740
  2190
           val mss1 =
nipkow@4740
  2191
             if not useprem then mss else
nipkow@4740
  2192
             if maxidx1 <> ~1
nipkow@4740
  2193
             then (trace_term true "Cannot add premise as rewrite rule because it contains (type) unknowns:"
nipkow@4740
  2194
                              (Sign.deref sign_ref) prem1;
nipkow@4740
  2195
                   mss)
nipkow@4740
  2196
             else let val thm = assume (Cterm{sign_ref=sign_ref, t=prem1, 
nipkow@4740
  2197
                                              T=propT, maxidx= ~1})
nipkow@4740
  2198
                  in add_safe_simp(add_prems(mss,[thm]), thm) end
nipkow@4740
  2199
           val (conc2,(shyps2,hyps2,ders2)) = try_botc mss1 (conc,etc1)
nipkow@4740
  2200
           val hyps2' = if prem1 mem hyps1 then hyps2 else hyps2\prem1
nipkow@4740
  2201
       in (Logic.mk_implies(prem1,conc2), (shyps2, hyps2', ders2)) end
nipkow@4740
  2202
paulson@1529
  2203
 in try_botc end;
clasohm@0
  2204
clasohm@0
  2205
clasohm@0
  2206
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
wenzelm@2509
  2207
wenzelm@2509
  2208
(*
wenzelm@2509
  2209
  Parameters:
nipkow@4713
  2210
    mode = (simplify A,
nipkow@4713
  2211
            use A in simplifying B,
nipkow@4713
  2212
            use prems of B (if B is again a meta-impl.) to simplify A)
nipkow@4713
  2213
           when simplifying A ==> B
wenzelm@2509
  2214
    mss: contains equality theorems of the form [|p1,...|] ==> t==u
wenzelm@2509
  2215
    prover: how to solve premises in conditional rewrites and congruences
clasohm@0
  2216
*)
wenzelm@2509
  2217
wenzelm@2509
  2218
(* FIXME: check that #bounds(mss) does not "occur" in ct alread *)
wenzelm@2509
  2219
nipkow@214
  2220
fun rewrite_cterm mode mss prover ct =
wenzelm@3967
  2221
  let val Cterm {sign_ref, t, T, maxidx} = ct;
nipkow@4713
  2222
      val (u,(shyps,hyps,ders)) = bottomc (mode,prover, sign_ref, maxidx) mss 
nipkow@4713
  2223
                                          (t, (add_term_sorts(t,[]), [], []));
clasohm@0
  2224
      val prop = Logic.mk_equals(t,u)
wenzelm@1258
  2225
  in
wenzelm@3967
  2226
      Thm{sign_ref = sign_ref, 
wenzelm@2386
  2227
          der = infer_derivs (Rewrite_cterm ct, ders),
nipkow@4116
  2228
          maxidx = maxidx,
wenzelm@2386
  2229
          shyps = shyps, 
wenzelm@2386
  2230
          hyps = hyps, 
paulson@1529
  2231
          prop = prop}
wenzelm@3967
  2232
  end;
clasohm@0
  2233
paulson@1539
  2234
wenzelm@2509
  2235
wenzelm@2509
  2236
(*** Oracles ***)
wenzelm@2509
  2237
wenzelm@3812
  2238
fun invoke_oracle thy raw_name =
wenzelm@3812
  2239
  let
wenzelm@3812
  2240
    val {sign = sg, oracles, ...} = rep_theory thy;
wenzelm@3812
  2241
    val name = Sign.intern sg Theory.oracleK raw_name;
wenzelm@3812
  2242
    val oracle =
wenzelm@3812
  2243
      (case Symtab.lookup (oracles, name) of
wenzelm@3812
  2244
        None => raise THM ("Unknown oracle: " ^ name, 0, [])
wenzelm@3812
  2245
      | Some (f, _) => f);
wenzelm@3812
  2246
  in
wenzelm@3812
  2247
    fn (sign, exn) =>
wenzelm@3812
  2248
      let
wenzelm@3967
  2249
        val sign_ref' = Sign.merge_refs (Sign.self_ref sg, Sign.self_ref sign);
wenzelm@3967
  2250
        val sign' = Sign.deref sign_ref';
wenzelm@3812
  2251
        val (prop, T, maxidx) = Sign.certify_term sign' (oracle (sign', exn));
wenzelm@3812
  2252
      in
wenzelm@3812
  2253
        if T <> propT then
wenzelm@3812
  2254
          raise THM ("Oracle's result must have type prop: " ^ name, 0, [])
wenzelm@3812
  2255
        else fix_shyps [] []
wenzelm@3967
  2256
          (Thm {sign_ref = sign_ref', 
wenzelm@4182
  2257
            der = Join (Oracle (name, sign, exn), []),
wenzelm@3812
  2258
            maxidx = maxidx,
wenzelm@3812
  2259
            shyps = [], 
wenzelm@3812
  2260
            hyps = [], 
wenzelm@3812
  2261
            prop = prop})
wenzelm@3812
  2262
      end
wenzelm@3812
  2263
  end;
wenzelm@3812
  2264
paulson@1539
  2265
clasohm@0
  2266
end;
paulson@1503
  2267
paulson@1503
  2268
open Thm;