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