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