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