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