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