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