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