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