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