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