src/Pure/thm.ML
author paulson
Thu Dec 16 17:01:16 1999 +0100 (1999-12-16)
changeset 8066 54d37e491ac2
parent 7921 56a84b4d04b1
child 8129 29e239c7b8c2
permissions -rw-r--r--
SOUNDNESS BUG FIX for rotate_rule. The original code did not expect
nested parameters such as !!y.

Goal "!!x. x = a ==> (!!y. y ~= a ==> False)";
by (rotate_tac 1 1);
be notE 1;
ba 1;
qed "foo";

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