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