src/Pure/thm.ML
author nipkow
Wed Apr 03 14:06:34 1996 +0200 (1996-04-03)
changeset 1634 9b9cdef70669
parent 1597 54ece585bf62
child 1659 41e37e5211f2
permissions -rw-r--r--
Plugged some more loopholes with 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@250
    10
signature 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
clasohm@1493
    22
  val rep_cterm         : cterm -> {sign: Sign.sg, t: term, T: typ,
clasohm@1493
    23
                                    maxidx: int}
wenzelm@1238
    24
  val term_of           : cterm -> term
wenzelm@1238
    25
  val cterm_of          : Sign.sg -> term -> cterm
wenzelm@1238
    26
  val read_cterm        : Sign.sg -> string * typ -> cterm
paulson@1394
    27
  val read_cterms       : Sign.sg -> string list * typ list -> cterm list
wenzelm@1238
    28
  val cterm_fun         : (term -> term) -> (cterm -> cterm)
wenzelm@1238
    29
  val dest_cimplies     : cterm -> cterm * cterm
clasohm@1493
    30
  val dest_comb         : cterm -> cterm * cterm
clasohm@1493
    31
  val dest_abs          : cterm -> 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
wenzelm@1160
    37
paulson@1529
    38
  (*theories*)
paulson@1529
    39
paulson@1529
    40
  (*proof terms [must duplicate declaration as a specification]*)
paulson@1597
    41
  datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
paulson@1597
    42
  val keep_derivs	: deriv_kind ref
paulson@1529
    43
  datatype rule = 
paulson@1529
    44
      MinProof				
paulson@1597
    45
    | Oracle of theory * Sign.sg * exn
paulson@1529
    46
    | Axiom		of theory * string
paulson@1597
    47
    | Theorem		of string	
paulson@1529
    48
    | Assume		of cterm
paulson@1529
    49
    | Implies_intr	of cterm
paulson@1529
    50
    | Implies_intr_shyps
paulson@1529
    51
    | Implies_intr_hyps
paulson@1529
    52
    | Implies_elim 
paulson@1529
    53
    | Forall_intr	of cterm
paulson@1529
    54
    | Forall_elim	of cterm
paulson@1529
    55
    | Reflexive		of cterm
paulson@1529
    56
    | Symmetric 
paulson@1529
    57
    | Transitive
paulson@1529
    58
    | Beta_conversion	of cterm
paulson@1529
    59
    | Extensional
paulson@1529
    60
    | Abstract_rule	of string * cterm
paulson@1529
    61
    | Combination
paulson@1529
    62
    | Equal_intr
paulson@1529
    63
    | Equal_elim
paulson@1529
    64
    | Trivial		of cterm
paulson@1529
    65
    | Lift_rule		of cterm * int 
paulson@1529
    66
    | Assumption	of int * Envir.env option
paulson@1529
    67
    | Instantiate	of (indexname * ctyp) list * (cterm * cterm) list
paulson@1529
    68
    | Bicompose		of bool * bool * int * int * Envir.env
paulson@1529
    69
    | Flexflex_rule	of Envir.env		
paulson@1529
    70
    | Class_triv	of theory * class	
paulson@1529
    71
    | VarifyT
paulson@1529
    72
    | FreezeT
paulson@1529
    73
    | RewriteC		of cterm
paulson@1529
    74
    | CongC		of cterm
paulson@1529
    75
    | Rewrite_cterm	of cterm
paulson@1529
    76
    | Rename_params_rule of string list * int;
paulson@1529
    77
paulson@1597
    78
  type deriv   (* = rule mtree *)
paulson@1529
    79
wenzelm@1160
    80
  (*meta theorems*)
wenzelm@1160
    81
  type thm
wenzelm@1160
    82
  exception THM of string * int * thm list
paulson@1529
    83
  val rep_thm           : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
paulson@1529
    84
				  shyps: sort list, hyps: term list, 
paulson@1529
    85
				  prop: term}
paulson@1529
    86
  val crep_thm          : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
paulson@1529
    87
				  shyps: sort list, hyps: cterm list, 
paulson@1529
    88
				  prop: cterm}
wenzelm@1238
    89
  val stamps_of_thm     : thm -> string ref list
wenzelm@1238
    90
  val tpairs_of         : thm -> (term * term) list
wenzelm@1238
    91
  val prems_of          : thm -> term list
wenzelm@1238
    92
  val nprems_of         : thm -> int
wenzelm@1238
    93
  val concl_of          : thm -> term
wenzelm@1238
    94
  val cprop_of          : thm -> cterm
wenzelm@1238
    95
  val extra_shyps       : thm -> sort list
wenzelm@1238
    96
  val force_strip_shyps : bool ref      (* FIXME tmp *)
wenzelm@1238
    97
  val strip_shyps       : thm -> thm
wenzelm@1238
    98
  val implies_intr_shyps: thm -> thm
wenzelm@1238
    99
  val get_axiom         : theory -> string -> thm
paulson@1597
   100
  val name_thm          : string * thm -> thm
wenzelm@1238
   101
  val axioms_of         : theory -> (string * thm) list
wenzelm@1160
   102
wenzelm@1160
   103
  (*meta rules*)
wenzelm@1238
   104
  val assume            : cterm -> thm
paulson@1416
   105
  val compress          : thm -> thm
wenzelm@1238
   106
  val implies_intr      : cterm -> thm -> thm
wenzelm@1238
   107
  val implies_elim      : thm -> thm -> thm
wenzelm@1238
   108
  val forall_intr       : cterm -> thm -> thm
wenzelm@1238
   109
  val forall_elim       : cterm -> thm -> thm
wenzelm@1238
   110
  val flexpair_def      : thm
wenzelm@1238
   111
  val reflexive         : cterm -> thm
wenzelm@1238
   112
  val symmetric         : thm -> thm
wenzelm@1238
   113
  val transitive        : thm -> thm -> thm
wenzelm@1238
   114
  val beta_conversion   : cterm -> thm
wenzelm@1238
   115
  val extensional       : thm -> thm
wenzelm@1238
   116
  val abstract_rule     : string -> cterm -> thm -> thm
wenzelm@1238
   117
  val combination       : thm -> thm -> thm
wenzelm@1238
   118
  val equal_intr        : thm -> thm -> thm
wenzelm@1238
   119
  val equal_elim        : thm -> thm -> thm
wenzelm@1238
   120
  val implies_intr_hyps : thm -> thm
wenzelm@1238
   121
  val flexflex_rule     : thm -> thm Sequence.seq
wenzelm@1238
   122
  val instantiate       :
wenzelm@1160
   123
    (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
wenzelm@1238
   124
  val trivial           : cterm -> thm
wenzelm@1238
   125
  val class_triv        : theory -> class -> thm
wenzelm@1238
   126
  val varifyT           : thm -> thm
wenzelm@1238
   127
  val freezeT           : thm -> thm
wenzelm@1238
   128
  val dest_state        : thm * int ->
wenzelm@1160
   129
    (term * term) list * term list * term * term
wenzelm@1238
   130
  val lift_rule         : (thm * int) -> thm -> thm
wenzelm@1238
   131
  val assumption        : int -> thm -> thm Sequence.seq
wenzelm@1238
   132
  val eq_assumption     : int -> thm -> thm
wenzelm@1160
   133
  val rename_params_rule: string list * int -> thm -> thm
wenzelm@1238
   134
  val bicompose         : bool -> bool * thm * int ->
wenzelm@1160
   135
    int -> thm -> thm Sequence.seq
wenzelm@1238
   136
  val biresolution      : bool -> (bool * thm) list ->
wenzelm@1160
   137
    int -> thm -> thm Sequence.seq
wenzelm@1160
   138
wenzelm@1160
   139
  (*meta simplification*)
wenzelm@1160
   140
  type meta_simpset
wenzelm@1160
   141
  exception SIMPLIFIER of string * thm
wenzelm@1238
   142
  val empty_mss         : meta_simpset
wenzelm@1238
   143
  val add_simps         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   144
  val del_simps         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   145
  val mss_of            : thm list -> meta_simpset
wenzelm@1238
   146
  val add_congs         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   147
  val add_prems         : meta_simpset * thm list -> meta_simpset
wenzelm@1238
   148
  val prems_of_mss      : meta_simpset -> thm list
wenzelm@1238
   149
  val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
wenzelm@1238
   150
  val mk_rews_of_mss    : meta_simpset -> thm -> thm list
wenzelm@1238
   151
  val trace_simp        : bool ref
wenzelm@1238
   152
  val rewrite_cterm     : bool * bool -> meta_simpset ->
paulson@1529
   153
                          (meta_simpset -> thm -> thm option) -> cterm -> thm
paulson@1539
   154
paulson@1539
   155
  val invoke_oracle	: theory * Sign.sg * exn -> thm
wenzelm@250
   156
end;
clasohm@0
   157
paulson@1503
   158
structure Thm : THM =
clasohm@0
   159
struct
wenzelm@250
   160
wenzelm@387
   161
(*** Certified terms and types ***)
wenzelm@387
   162
wenzelm@250
   163
(** certified types **)
wenzelm@250
   164
wenzelm@250
   165
(*certified typs under a signature*)
wenzelm@250
   166
wenzelm@250
   167
datatype ctyp = Ctyp of {sign: Sign.sg, T: typ};
wenzelm@250
   168
wenzelm@250
   169
fun rep_ctyp (Ctyp args) = args;
wenzelm@250
   170
fun typ_of (Ctyp {T, ...}) = T;
wenzelm@250
   171
wenzelm@250
   172
fun ctyp_of sign T =
wenzelm@250
   173
  Ctyp {sign = sign, T = Sign.certify_typ sign T};
wenzelm@250
   174
wenzelm@250
   175
fun read_ctyp sign s =
wenzelm@250
   176
  Ctyp {sign = sign, T = Sign.read_typ (sign, K None) s};
lcp@229
   177
lcp@229
   178
lcp@229
   179
wenzelm@250
   180
(** certified terms **)
lcp@229
   181
wenzelm@250
   182
(*certified terms under a signature, with checked typ and maxidx of Vars*)
lcp@229
   183
wenzelm@250
   184
datatype cterm = Cterm of {sign: Sign.sg, t: term, T: typ, maxidx: int};
lcp@229
   185
lcp@229
   186
fun rep_cterm (Cterm args) = args;
wenzelm@250
   187
fun term_of (Cterm {t, ...}) = t;
lcp@229
   188
wenzelm@250
   189
(*create a cterm by checking a "raw" term with respect to a signature*)
wenzelm@250
   190
fun cterm_of sign tm =
wenzelm@250
   191
  let val (t, T, maxidx) = Sign.certify_term sign tm
paulson@1394
   192
  in  Cterm {sign = sign, t = t, T = T, maxidx = maxidx}
paulson@1394
   193
  end;
lcp@229
   194
wenzelm@250
   195
fun cterm_fun f (Cterm {sign, t, ...}) = cterm_of sign (f t);
wenzelm@250
   196
lcp@229
   197
wenzelm@250
   198
(*dest_implies for cterms. Note T=prop below*)
wenzelm@250
   199
fun dest_cimplies (Cterm{sign, T, maxidx, t=Const("==>", _) $ A $ B}) =
lcp@229
   200
       (Cterm{sign=sign, T=T, maxidx=maxidx, t=A},
wenzelm@250
   201
        Cterm{sign=sign, T=T, maxidx=maxidx, t=B})
wenzelm@250
   202
  | dest_cimplies ct = raise TERM ("dest_cimplies", [term_of ct]);
lcp@229
   203
clasohm@1493
   204
exception CTERM of string;
clasohm@1493
   205
clasohm@1493
   206
(*Destruct application in cterms*)
clasohm@1493
   207
fun dest_comb (Cterm{sign, T, maxidx, t = A $ B}) =
clasohm@1493
   208
      let val typeA = fastype_of A;
clasohm@1493
   209
          val typeB =
clasohm@1493
   210
            case typeA of Type("fun",[S,T]) => S
clasohm@1493
   211
                        | _ => error "Function type expected in dest_comb";
clasohm@1493
   212
      in
clasohm@1493
   213
      (Cterm {sign=sign, maxidx=maxidx, t=A, T=typeA},
clasohm@1493
   214
       Cterm {sign=sign, maxidx=maxidx, t=B, T=typeB})
clasohm@1493
   215
      end
clasohm@1493
   216
  | dest_comb _ = raise CTERM "dest_comb";
clasohm@1493
   217
clasohm@1493
   218
(*Destruct abstraction in cterms*)
clasohm@1516
   219
fun dest_abs (Cterm {sign, T as Type("fun",[_,S]), maxidx, t=Abs(x,ty,M)}) = 
clasohm@1516
   220
      let val (y,N) = variant_abs (x,ty,M)
clasohm@1516
   221
      in (Cterm {sign = sign, T = ty, maxidx = 0, t = Free(y,ty)},
clasohm@1516
   222
          Cterm {sign = sign, T = S, maxidx = maxidx, t = N})
clasohm@1493
   223
      end
clasohm@1493
   224
  | dest_abs _ = raise CTERM "dest_abs";
clasohm@1493
   225
clasohm@1516
   226
(*Form cterm out of a function and an argument*)
clasohm@1516
   227
fun capply (Cterm {t=f, sign=sign1, T=Type("fun",[dty,rty]), maxidx=maxidx1})
clasohm@1516
   228
           (Cterm {t=x, sign=sign2, T, maxidx=maxidx2}) =
clasohm@1516
   229
      if T = dty then Cterm{t=f$x, sign=Sign.merge(sign1,sign2), T=rty,
clasohm@1516
   230
                            maxidx=max[maxidx1, maxidx2]}
clasohm@1516
   231
      else raise CTERM "capply: types don't agree"
clasohm@1516
   232
  | capply _ _ = raise CTERM "capply: first arg is not a function"
wenzelm@250
   233
clasohm@1517
   234
fun cabs (Cterm {t=Free(a,ty), sign=sign1, T=T1, maxidx=maxidx1})
clasohm@1517
   235
         (Cterm {t=t2, sign=sign2, T=T2, maxidx=maxidx2}) =
clasohm@1517
   236
      Cterm {t=absfree(a,ty,t2), sign=Sign.merge(sign1,sign2),
clasohm@1517
   237
             T = ty --> T2, maxidx=max[maxidx1, maxidx2]}
clasohm@1517
   238
  | cabs _ _ = raise CTERM "cabs: first arg is not a free variable";
lcp@229
   239
wenzelm@574
   240
(** read cterms **)   (*exception ERROR*)
wenzelm@250
   241
wenzelm@250
   242
(*read term, infer types, certify term*)
nipkow@949
   243
fun read_def_cterm (sign, types, sorts) used freeze (a, T) =
wenzelm@250
   244
  let
wenzelm@574
   245
    val T' = Sign.certify_typ sign T
wenzelm@574
   246
      handle TYPE (msg, _, _) => error msg;
clasohm@623
   247
    val ts = Syntax.read (#syn (Sign.rep_sg sign)) T' a;
nipkow@949
   248
    val (_, t', tye) =
clasohm@959
   249
          Sign.infer_types sign types sorts used freeze (ts, T');
wenzelm@574
   250
    val ct = cterm_of sign t'
paulson@1394
   251
      handle TYPE arg => error (Sign.exn_type_msg sign arg)
clasohm@1460
   252
	   | TERM (msg, _) => error msg;
wenzelm@250
   253
  in (ct, tye) end;
lcp@229
   254
nipkow@949
   255
fun read_cterm sign = #1 o read_def_cterm (sign, K None, K None) [] true;
lcp@229
   256
paulson@1394
   257
(*read a list of terms, matching them against a list of expected types.
paulson@1394
   258
  NO disambiguation of alternative parses via type-checking -- it is just
paulson@1394
   259
  not practical.*)
paulson@1394
   260
fun read_cterms sign (bs, Ts) =
paulson@1394
   261
  let
paulson@1394
   262
    val {tsig, syn, ...} = Sign.rep_sg sign
paulson@1394
   263
    fun read (b,T) =
clasohm@1460
   264
	case Syntax.read syn T b of
clasohm@1460
   265
	    [t] => t
clasohm@1460
   266
	  | _   => error("Error or ambiguity in parsing of " ^ b)
paulson@1394
   267
    val (us,_) = Type.infer_types(tsig, Sign.const_type sign, 
clasohm@1460
   268
				  K None, K None, 
clasohm@1460
   269
				  [], true, 
clasohm@1460
   270
				  map (Sign.certify_typ sign) Ts, 
clasohm@1460
   271
				  map read (bs~~Ts))
paulson@1394
   272
  in  map (cterm_of sign) us  end
paulson@1394
   273
  handle TYPE arg => error (Sign.exn_type_msg sign arg)
paulson@1394
   274
       | TERM (msg, _) => error msg;
paulson@1394
   275
wenzelm@250
   276
wenzelm@250
   277
paulson@1529
   278
(*** Derivations ***)
paulson@1529
   279
paulson@1529
   280
(*Names of rules in derivations.  Includes logically trivial rules, if 
paulson@1529
   281
  executed in ML.*)
paulson@1529
   282
datatype rule = 
paulson@1529
   283
    MinProof				(*for building minimal proof terms*)
paulson@1597
   284
  | Oracle   	        of theory * Sign.sg * exn	(*oracles*)
paulson@1529
   285
(*Axioms/theorems*)
paulson@1529
   286
  | Axiom		of theory * string
paulson@1597
   287
  | Theorem		of string
paulson@1529
   288
(*primitive inferences and compound versions of them*)
paulson@1529
   289
  | Assume		of cterm
paulson@1529
   290
  | Implies_intr	of cterm
paulson@1529
   291
  | Implies_intr_shyps
paulson@1529
   292
  | Implies_intr_hyps
paulson@1529
   293
  | Implies_elim 
paulson@1529
   294
  | Forall_intr		of cterm
paulson@1529
   295
  | Forall_elim		of cterm
paulson@1529
   296
  | Reflexive		of cterm
paulson@1529
   297
  | Symmetric 
paulson@1529
   298
  | Transitive
paulson@1529
   299
  | Beta_conversion	of cterm
paulson@1529
   300
  | Extensional
paulson@1529
   301
  | Abstract_rule	of string * cterm
paulson@1529
   302
  | Combination
paulson@1529
   303
  | Equal_intr
paulson@1529
   304
  | Equal_elim
paulson@1529
   305
(*derived rules for tactical proof*)
paulson@1529
   306
  | Trivial		of cterm
paulson@1529
   307
	(*For lift_rule, the proof state is not a premise.
paulson@1529
   308
	  Use cterm instead of thm to avoid mutual recursion.*)
paulson@1529
   309
  | Lift_rule		of cterm * int 
paulson@1529
   310
  | Assumption		of int * Envir.env option (*includes eq_assumption*)
paulson@1529
   311
  | Instantiate		of (indexname * ctyp) list * (cterm * cterm) list
paulson@1529
   312
  | Bicompose		of bool * bool * int * int * Envir.env
paulson@1529
   313
  | Flexflex_rule	of Envir.env		(*identifies unifier chosen*)
paulson@1529
   314
(*other derived rules*)
paulson@1529
   315
  | Class_triv		of theory * class	(*derived rule????*)
paulson@1529
   316
  | VarifyT
paulson@1529
   317
  | FreezeT
paulson@1529
   318
(*for the simplifier*)
paulson@1529
   319
  | RewriteC		of cterm
paulson@1529
   320
  | CongC		of cterm
paulson@1529
   321
  | Rewrite_cterm	of cterm
paulson@1529
   322
(*Logical identities, recorded since they are part of the proof process*)
paulson@1529
   323
  | Rename_params_rule	of string list * int;
paulson@1529
   324
paulson@1529
   325
paulson@1597
   326
type deriv = rule mtree;
paulson@1529
   327
paulson@1597
   328
datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
paulson@1529
   329
paulson@1597
   330
val keep_derivs = ref MinDeriv;
paulson@1529
   331
paulson@1529
   332
paulson@1597
   333
(*Build a minimal derivation.  Keep oracles; suppress atomic inferences;
paulson@1597
   334
  retain Theorems or their underlying links; keep anything else*)
paulson@1597
   335
fun squash_derivs [] = []
paulson@1597
   336
  | squash_derivs (der::ders) =
paulson@1597
   337
     (case der of
paulson@1597
   338
	  Join (Oracle _, _) => der :: squash_derivs ders
paulson@1597
   339
	| Join (Theorem _, [der']) => if !keep_derivs=ThmDeriv 
paulson@1597
   340
				      then der :: squash_derivs ders
paulson@1597
   341
				      else squash_derivs (der'::ders)
paulson@1597
   342
	| Join (Axiom _, _) => if !keep_derivs=ThmDeriv 
paulson@1597
   343
			       then der :: squash_derivs ders
paulson@1597
   344
			       else squash_derivs ders
paulson@1597
   345
	| Join (_, [])      => squash_derivs ders
paulson@1597
   346
	| _                 => der :: squash_derivs ders);
paulson@1597
   347
paulson@1529
   348
paulson@1529
   349
(*Ensure sharing of the most likely derivation, the empty one!*)
paulson@1597
   350
val min_infer = Join (MinProof, []);
paulson@1529
   351
paulson@1529
   352
(*Make a minimal inference*)
paulson@1529
   353
fun make_min_infer []    = min_infer
paulson@1529
   354
  | make_min_infer [der] = der
paulson@1597
   355
  | make_min_infer ders  = Join (MinProof, ders);
paulson@1529
   356
paulson@1597
   357
fun infer_derivs (rl, [])   = Join (rl, [])
paulson@1529
   358
  | infer_derivs (rl, ders) =
paulson@1597
   359
    if !keep_derivs=FullDeriv then Join (rl, ders)
paulson@1529
   360
    else make_min_infer (squash_derivs ders);
paulson@1529
   361
paulson@1529
   362
wenzelm@387
   363
(*** Meta theorems ***)
lcp@229
   364
clasohm@0
   365
datatype thm = Thm of
clasohm@1460
   366
  {sign: Sign.sg,		(*signature for hyps and prop*)
paulson@1529
   367
   der: deriv,			(*derivation*)
clasohm@1460
   368
   maxidx: int,			(*maximum index of any Var or TVar*)
clasohm@1460
   369
   shyps: sort list,		(* FIXME comment *)
clasohm@1460
   370
   hyps: term list,		(*hypotheses*)
clasohm@1460
   371
   prop: term};			(*conclusion*)
clasohm@0
   372
wenzelm@250
   373
fun rep_thm (Thm args) = args;
clasohm@0
   374
paulson@1529
   375
(*Version of rep_thm returning cterms instead of terms*)
paulson@1529
   376
fun crep_thm (Thm {sign, der, maxidx, shyps, hyps, prop}) =
paulson@1529
   377
  let fun ctermf max t = Cterm{sign=sign, t=t, T=propT, maxidx=max};
paulson@1529
   378
  in {sign=sign, der=der, maxidx=maxidx, shyps=shyps,
paulson@1529
   379
      hyps = map (ctermf ~1) hyps,
paulson@1529
   380
      prop = ctermf maxidx prop}
clasohm@1517
   381
  end;
clasohm@1517
   382
wenzelm@387
   383
(*errors involving theorems*)
clasohm@0
   384
exception THM of string * int * thm list;
clasohm@0
   385
wenzelm@387
   386
paulson@1597
   387
val stamps_of_thm = #stamps o Sign.rep_sg o #sign o rep_thm;
clasohm@0
   388
wenzelm@387
   389
(*merge signatures of two theorems; raise exception if incompatible*)
wenzelm@387
   390
fun merge_thm_sgs (th1, th2) =
paulson@1597
   391
  Sign.merge (pairself (#sign o rep_thm) (th1, th2))
wenzelm@574
   392
    handle TERM (msg, _) => raise THM (msg, 0, [th1, th2]);
wenzelm@387
   393
wenzelm@387
   394
wenzelm@387
   395
(*maps object-rule to tpairs*)
wenzelm@387
   396
fun tpairs_of (Thm {prop, ...}) = #1 (Logic.strip_flexpairs prop);
wenzelm@387
   397
wenzelm@387
   398
(*maps object-rule to premises*)
wenzelm@387
   399
fun prems_of (Thm {prop, ...}) =
wenzelm@387
   400
  Logic.strip_imp_prems (Logic.skip_flexpairs prop);
clasohm@0
   401
clasohm@0
   402
(*counts premises in a rule*)
wenzelm@387
   403
fun nprems_of (Thm {prop, ...}) =
wenzelm@387
   404
  Logic.count_prems (Logic.skip_flexpairs prop, 0);
clasohm@0
   405
wenzelm@387
   406
(*maps object-rule to conclusion*)
wenzelm@387
   407
fun concl_of (Thm {prop, ...}) = Logic.strip_imp_concl prop;
clasohm@0
   408
wenzelm@387
   409
(*the statement of any thm is a cterm*)
wenzelm@1160
   410
fun cprop_of (Thm {sign, maxidx, prop, ...}) =
wenzelm@387
   411
  Cterm {sign = sign, maxidx = maxidx, T = propT, t = prop};
lcp@229
   412
wenzelm@387
   413
clasohm@0
   414
wenzelm@1238
   415
(** sort contexts of theorems **)
wenzelm@1238
   416
wenzelm@1238
   417
(* basic utils *)
wenzelm@1238
   418
wenzelm@1238
   419
(*accumulate sorts suppressing duplicates; these are coded low level
wenzelm@1238
   420
  to improve efficiency a bit*)
wenzelm@1238
   421
wenzelm@1238
   422
fun add_typ_sorts (Type (_, Ts), Ss) = add_typs_sorts (Ts, Ss)
wenzelm@1238
   423
  | add_typ_sorts (TFree (_, S), Ss) = S ins Ss
wenzelm@1238
   424
  | add_typ_sorts (TVar (_, S), Ss) = S ins Ss
wenzelm@1238
   425
and add_typs_sorts ([], Ss) = Ss
wenzelm@1238
   426
  | add_typs_sorts (T :: Ts, Ss) = add_typs_sorts (Ts, add_typ_sorts (T, Ss));
wenzelm@1238
   427
wenzelm@1238
   428
fun add_term_sorts (Const (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   429
  | add_term_sorts (Free (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   430
  | add_term_sorts (Var (_, T), Ss) = add_typ_sorts (T, Ss)
wenzelm@1238
   431
  | add_term_sorts (Bound _, Ss) = Ss
wenzelm@1238
   432
  | add_term_sorts (Abs (_, T, t), Ss) = add_term_sorts (t, add_typ_sorts (T, Ss))
wenzelm@1238
   433
  | add_term_sorts (t $ u, Ss) = add_term_sorts (t, add_term_sorts (u, Ss));
wenzelm@1238
   434
wenzelm@1238
   435
fun add_terms_sorts ([], Ss) = Ss
wenzelm@1238
   436
  | add_terms_sorts (t :: ts, Ss) = add_terms_sorts (ts, add_term_sorts (t, Ss));
wenzelm@1238
   437
wenzelm@1258
   438
fun env_codT (Envir.Envir {iTs, ...}) = map snd iTs;
wenzelm@1258
   439
wenzelm@1258
   440
fun add_env_sorts (env, Ss) =
wenzelm@1258
   441
  add_terms_sorts (map snd (Envir.alist_of env),
wenzelm@1258
   442
    add_typs_sorts (env_codT env, Ss));
wenzelm@1258
   443
wenzelm@1238
   444
fun add_thm_sorts (Thm {hyps, prop, ...}, Ss) =
wenzelm@1238
   445
  add_terms_sorts (hyps, add_term_sorts (prop, Ss));
wenzelm@1238
   446
wenzelm@1238
   447
fun add_thms_shyps ([], Ss) = Ss
wenzelm@1238
   448
  | add_thms_shyps (Thm {shyps, ...} :: ths, Ss) =
wenzelm@1238
   449
      add_thms_shyps (ths, shyps union Ss);
wenzelm@1238
   450
wenzelm@1238
   451
wenzelm@1238
   452
(*get 'dangling' sort constraints of a thm*)
wenzelm@1238
   453
fun extra_shyps (th as Thm {shyps, ...}) =
wenzelm@1238
   454
  shyps \\ add_thm_sorts (th, []);
wenzelm@1238
   455
wenzelm@1238
   456
wenzelm@1238
   457
(* fix_shyps *)
wenzelm@1238
   458
wenzelm@1238
   459
(*preserve sort contexts of rule premises and substituted types*)
wenzelm@1238
   460
fun fix_shyps thms Ts thm =
wenzelm@1238
   461
  let
paulson@1529
   462
    val Thm {sign, der, maxidx, hyps, prop, ...} = thm;
wenzelm@1238
   463
    val shyps =
wenzelm@1238
   464
      add_thm_sorts (thm, add_typs_sorts (Ts, add_thms_shyps (thms, [])));
wenzelm@1238
   465
  in
paulson@1529
   466
    Thm {sign = sign, 
paulson@1529
   467
	 der = der,		(*No new derivation, as other rules call this*)
paulson@1529
   468
	 maxidx = maxidx,
paulson@1529
   469
	 shyps = shyps, hyps = hyps, prop = prop}
wenzelm@1238
   470
  end;
wenzelm@1238
   471
wenzelm@1238
   472
wenzelm@1238
   473
(* strip_shyps *)       (* FIXME improve? (e.g. only minimal extra sorts) *)
wenzelm@1238
   474
wenzelm@1238
   475
val force_strip_shyps = ref true;  (* FIXME tmp *)
wenzelm@1238
   476
wenzelm@1238
   477
(*remove extra sorts that are known to be syntactically non-empty*)
wenzelm@1238
   478
fun strip_shyps thm =
wenzelm@1238
   479
  let
paulson@1529
   480
    val Thm {sign, der, maxidx, shyps, hyps, prop} = thm;
wenzelm@1238
   481
    val sorts = add_thm_sorts (thm, []);
wenzelm@1238
   482
    val maybe_empty = not o Sign.nonempty_sort sign sorts;
wenzelm@1238
   483
    val shyps' = filter (fn S => S mem sorts orelse maybe_empty S) shyps;
wenzelm@1238
   484
  in
paulson@1529
   485
    Thm {sign = sign, der = der, maxidx = maxidx,
paulson@1529
   486
	 shyps =
paulson@1529
   487
	 (if eq_set (shyps',sorts) orelse not (!force_strip_shyps) then shyps'
paulson@1529
   488
	  else    (* FIXME tmp *)
paulson@1529
   489
	      (writeln ("WARNING Removed sort hypotheses: " ^
paulson@1529
   490
			commas (map Type.str_of_sort (shyps' \\ sorts)));
paulson@1529
   491
	       writeln "WARNING Let's hope these sorts are non-empty!";
wenzelm@1238
   492
           sorts)),
paulson@1529
   493
      hyps = hyps, 
paulson@1529
   494
      prop = prop}
wenzelm@1238
   495
  end;
wenzelm@1238
   496
wenzelm@1238
   497
wenzelm@1238
   498
(* implies_intr_shyps *)
wenzelm@1238
   499
wenzelm@1238
   500
(*discharge all extra sort hypotheses*)
wenzelm@1238
   501
fun implies_intr_shyps thm =
wenzelm@1238
   502
  (case extra_shyps thm of
wenzelm@1238
   503
    [] => thm
wenzelm@1238
   504
  | xshyps =>
wenzelm@1238
   505
      let
paulson@1529
   506
        val Thm {sign, der, maxidx, shyps, hyps, prop} = thm;
wenzelm@1238
   507
        val shyps' = logicS ins (shyps \\ xshyps);
wenzelm@1238
   508
        val used_names = foldr add_term_tfree_names (prop :: hyps, []);
wenzelm@1238
   509
        val names =
wenzelm@1238
   510
          tl (variantlist (replicate (length xshyps + 1) "'", used_names));
wenzelm@1238
   511
        val tfrees = map (TFree o rpair logicS) names;
wenzelm@1238
   512
wenzelm@1238
   513
        fun mk_insort (T, S) = map (Logic.mk_inclass o pair T) S;
wenzelm@1238
   514
        val sort_hyps = flat (map2 mk_insort (tfrees, xshyps));
wenzelm@1238
   515
      in
paulson@1529
   516
        Thm {sign = sign, 
paulson@1529
   517
	     der = infer_derivs (Implies_intr_shyps, [der]), 
paulson@1529
   518
	     maxidx = maxidx, 
paulson@1529
   519
	     shyps = shyps',
paulson@1529
   520
	     hyps = hyps, 
paulson@1529
   521
	     prop = Logic.list_implies (sort_hyps, prop)}
wenzelm@1238
   522
      end);
wenzelm@1238
   523
wenzelm@1238
   524
paulson@1529
   525
(** Axioms **)
wenzelm@387
   526
wenzelm@387
   527
(*look up the named axiom in the theory*)
wenzelm@387
   528
fun get_axiom theory name =
wenzelm@387
   529
  let
wenzelm@387
   530
    fun get_ax [] = raise Match
paulson@1529
   531
      | get_ax (thy :: thys) =
paulson@1539
   532
	  let val {sign, new_axioms, parents, ...} = rep_theory thy
paulson@1529
   533
          in case Symtab.lookup (new_axioms, name) of
paulson@1529
   534
		Some t => fix_shyps [] []
paulson@1529
   535
		           (Thm {sign = sign, 
paulson@1529
   536
				 der = infer_derivs (Axiom(theory,name), []),
paulson@1529
   537
				 maxidx = maxidx_of_term t,
paulson@1529
   538
				 shyps = [], 
paulson@1529
   539
				 hyps = [], 
paulson@1529
   540
				 prop = t})
paulson@1529
   541
	      | None => get_ax parents handle Match => get_ax thys
paulson@1529
   542
          end;
wenzelm@387
   543
  in
wenzelm@387
   544
    get_ax [theory] handle Match
wenzelm@387
   545
      => raise THEORY ("get_axiom: no axiom " ^ quote name, [theory])
wenzelm@387
   546
  end;
wenzelm@387
   547
paulson@1529
   548
wenzelm@776
   549
(*return additional axioms of this theory node*)
wenzelm@776
   550
fun axioms_of thy =
wenzelm@776
   551
  map (fn (s, _) => (s, get_axiom thy s))
wenzelm@776
   552
    (Symtab.dest (#new_axioms (rep_theory thy)));
wenzelm@776
   553
paulson@1597
   554
(*Attach a label to a theorem to make proof objects more readable*)
paulson@1597
   555
fun name_thm (name, th as Thm {sign, der, maxidx, shyps, hyps, prop}) = 
paulson@1597
   556
    Thm {sign = sign, 
paulson@1597
   557
	 der = Join (Theorem name, [der]),
paulson@1597
   558
	 maxidx = maxidx,
paulson@1597
   559
	 shyps = shyps, 
paulson@1597
   560
	 hyps = hyps, 
paulson@1597
   561
	 prop = prop};
clasohm@0
   562
clasohm@0
   563
paulson@1529
   564
(*Compression of theorems -- a separate rule, not integrated with the others,
paulson@1529
   565
  as it could be slow.*)
paulson@1529
   566
fun compress (Thm {sign, der, maxidx, shyps, hyps, prop}) = 
paulson@1529
   567
    Thm {sign = sign, 
paulson@1529
   568
	 der = der,	(*No derivation recorded!*)
paulson@1529
   569
	 maxidx = maxidx,
paulson@1529
   570
	 shyps = shyps, 
paulson@1529
   571
	 hyps = map Term.compress_term hyps, 
paulson@1529
   572
	 prop = Term.compress_term prop};
wenzelm@564
   573
wenzelm@387
   574
paulson@1529
   575
(*** Meta rules ***)
clasohm@0
   576
nipkow@1495
   577
(* check that term does not contain same var with different typing/sorting *)
nipkow@1495
   578
fun nodup_Vars(thm as Thm{prop,...}) s =
nipkow@1495
   579
  Sign.nodup_Vars prop handle TYPE(msg,_,_) => raise THM(s^": "^msg,0,[thm]);
nipkow@1495
   580
wenzelm@1220
   581
(** 'primitive' rules **)
wenzelm@1220
   582
wenzelm@1220
   583
(*discharge all assumptions t from ts*)
clasohm@0
   584
val disch = gen_rem (op aconv);
clasohm@0
   585
wenzelm@1220
   586
(*The assumption rule A|-A in a theory*)
wenzelm@250
   587
fun assume ct : thm =
lcp@229
   588
  let val {sign, t=prop, T, maxidx} = rep_cterm ct
wenzelm@250
   589
  in  if T<>propT then
wenzelm@250
   590
        raise THM("assume: assumptions must have type prop", 0, [])
clasohm@0
   591
      else if maxidx <> ~1 then
wenzelm@250
   592
        raise THM("assume: assumptions may not contain scheme variables",
wenzelm@250
   593
                  maxidx, [])
paulson@1529
   594
      else Thm{sign   = sign, 
paulson@1529
   595
	       der    = infer_derivs (Assume ct, []), 
paulson@1529
   596
	       maxidx = ~1, 
paulson@1529
   597
	       shyps  = add_term_sorts(prop,[]), 
paulson@1529
   598
	       hyps   = [prop], 
paulson@1529
   599
	       prop   = prop}
clasohm@0
   600
  end;
clasohm@0
   601
wenzelm@1220
   602
(*Implication introduction
wenzelm@1220
   603
  A |- B
wenzelm@1220
   604
  -------
wenzelm@1220
   605
  A ==> B
wenzelm@1220
   606
*)
paulson@1529
   607
fun implies_intr cA (thB as Thm{sign,der,maxidx,hyps,prop,...}) : thm =
lcp@229
   608
  let val {sign=signA, t=A, T, maxidx=maxidxA} = rep_cterm cA
clasohm@0
   609
  in  if T<>propT then
wenzelm@250
   610
        raise THM("implies_intr: assumptions must have type prop", 0, [thB])
wenzelm@1238
   611
      else fix_shyps [thB] []
paulson@1529
   612
        (Thm{sign = Sign.merge (sign,signA),  
paulson@1529
   613
	     der = infer_derivs (Implies_intr cA, [der]),
paulson@1529
   614
	     maxidx = max[maxidxA, maxidx],
paulson@1529
   615
	     shyps = [],
paulson@1529
   616
	     hyps = disch(hyps,A),
paulson@1529
   617
	     prop = implies$A$prop})
clasohm@0
   618
      handle TERM _ =>
clasohm@0
   619
        raise THM("implies_intr: incompatible signatures", 0, [thB])
clasohm@0
   620
  end;
clasohm@0
   621
paulson@1529
   622
wenzelm@1220
   623
(*Implication elimination
wenzelm@1220
   624
  A ==> B    A
wenzelm@1220
   625
  ------------
wenzelm@1220
   626
        B
wenzelm@1220
   627
*)
clasohm@0
   628
fun implies_elim thAB thA : thm =
paulson@1529
   629
    let val Thm{maxidx=maxA, der=derA, hyps=hypsA, prop=propA,...} = thA
paulson@1529
   630
        and Thm{sign, der, maxidx, hyps, prop,...} = thAB;
wenzelm@250
   631
        fun err(a) = raise THM("implies_elim: "^a, 0, [thAB,thA])
clasohm@0
   632
    in  case prop of
wenzelm@250
   633
            imp$A$B =>
wenzelm@250
   634
                if imp=implies andalso  A aconv propA
wenzelm@1220
   635
                then fix_shyps [thAB, thA] []
wenzelm@1220
   636
                       (Thm{sign= merge_thm_sgs(thAB,thA),
paulson@1529
   637
			    der = infer_derivs (Implies_elim, [der,derA]),
paulson@1529
   638
			    maxidx = max[maxA,maxidx],
paulson@1529
   639
			    shyps = [],
paulson@1529
   640
			    hyps = hypsA union hyps,  (*dups suppressed*)
paulson@1529
   641
			    prop = B})
wenzelm@250
   642
                else err("major premise")
wenzelm@250
   643
          | _ => err("major premise")
clasohm@0
   644
    end;
wenzelm@250
   645
wenzelm@1220
   646
(*Forall introduction.  The Free or Var x must not be free in the hypotheses.
wenzelm@1220
   647
    A
wenzelm@1220
   648
  -----
wenzelm@1220
   649
  !!x.A
wenzelm@1220
   650
*)
paulson@1529
   651
fun forall_intr cx (th as Thm{sign,der,maxidx,hyps,prop,...}) =
lcp@229
   652
  let val x = term_of cx;
wenzelm@1238
   653
      fun result(a,T) = fix_shyps [th] []
paulson@1529
   654
        (Thm{sign = sign, 
paulson@1529
   655
	     der = infer_derivs (Forall_intr cx, [der]),
paulson@1529
   656
	     maxidx = maxidx,
paulson@1529
   657
	     shyps = [],
paulson@1529
   658
	     hyps = hyps,
paulson@1529
   659
	     prop = all(T) $ Abs(a, T, abstract_over (x,prop))})
clasohm@0
   660
  in  case x of
wenzelm@250
   661
        Free(a,T) =>
wenzelm@250
   662
          if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   663
          then  raise THM("forall_intr: variable free in assumptions", 0, [th])
wenzelm@250
   664
          else  result(a,T)
clasohm@0
   665
      | Var((a,_),T) => result(a,T)
clasohm@0
   666
      | _ => raise THM("forall_intr: not a variable", 0, [th])
clasohm@0
   667
  end;
clasohm@0
   668
wenzelm@1220
   669
(*Forall elimination
wenzelm@1220
   670
  !!x.A
wenzelm@1220
   671
  ------
wenzelm@1220
   672
  A[t/x]
wenzelm@1220
   673
*)
paulson@1529
   674
fun forall_elim ct (th as Thm{sign,der,maxidx,hyps,prop,...}) : thm =
lcp@229
   675
  let val {sign=signt, t, T, maxidx=maxt} = rep_cterm ct
clasohm@0
   676
  in  case prop of
wenzelm@250
   677
          Const("all",Type("fun",[Type("fun",[qary,_]),_])) $ A =>
wenzelm@250
   678
            if T<>qary then
wenzelm@250
   679
                raise THM("forall_elim: type mismatch", 0, [th])
nipkow@1495
   680
            else let val thm = fix_shyps [th] []
nipkow@1495
   681
                      (Thm{sign= Sign.merge(sign,signt),
paulson@1529
   682
			   der = infer_derivs (Forall_elim ct, [der]),
paulson@1529
   683
                           maxidx = max[maxidx, maxt],
paulson@1529
   684
                           shyps = [],
paulson@1529
   685
			   hyps = hyps,  
paulson@1529
   686
			   prop = betapply(A,t)})
nipkow@1495
   687
                 in nodup_Vars thm "forall_elim"; thm end
wenzelm@250
   688
        | _ => raise THM("forall_elim: not quantified", 0, [th])
clasohm@0
   689
  end
clasohm@0
   690
  handle TERM _ =>
wenzelm@250
   691
         raise THM("forall_elim: incompatible signatures", 0, [th]);
clasohm@0
   692
clasohm@0
   693
wenzelm@1220
   694
(* Equality *)
clasohm@0
   695
wenzelm@1220
   696
(* Definition of the relation =?= *)
wenzelm@1238
   697
val flexpair_def = fix_shyps [] []
paulson@1529
   698
  (Thm{sign= Sign.proto_pure, 
paulson@1597
   699
       der = Join(Axiom(pure_thy, "flexpair_def"), []),
paulson@1529
   700
       shyps = [], 
paulson@1529
   701
       hyps = [], 
paulson@1529
   702
       maxidx = 0,
paulson@1529
   703
       prop = term_of (read_cterm Sign.proto_pure
paulson@1529
   704
		       ("(?t =?= ?u) == (?t == ?u::?'a::{})", propT))});
clasohm@0
   705
clasohm@0
   706
(*The reflexivity rule: maps  t   to the theorem   t==t   *)
wenzelm@250
   707
fun reflexive ct =
lcp@229
   708
  let val {sign, t, T, maxidx} = rep_cterm ct
wenzelm@1238
   709
  in  fix_shyps [] []
paulson@1529
   710
       (Thm{sign= sign, 
paulson@1529
   711
	    der = infer_derivs (Reflexive ct, []),
paulson@1529
   712
	    shyps = [],
paulson@1529
   713
	    hyps = [], 
paulson@1529
   714
	    maxidx = maxidx,
paulson@1529
   715
	    prop = Logic.mk_equals(t,t)})
clasohm@0
   716
  end;
clasohm@0
   717
clasohm@0
   718
(*The symmetry rule
wenzelm@1220
   719
  t==u
wenzelm@1220
   720
  ----
wenzelm@1220
   721
  u==t
wenzelm@1220
   722
*)
paulson@1529
   723
fun symmetric (th as Thm{sign,der,maxidx,shyps,hyps,prop}) =
clasohm@0
   724
  case prop of
clasohm@0
   725
      (eq as Const("==",_)) $ t $ u =>
wenzelm@1238
   726
        (*no fix_shyps*)
paulson@1529
   727
	  Thm{sign = sign,
paulson@1529
   728
	      der = infer_derivs (Symmetric, [der]),
paulson@1529
   729
	      maxidx = maxidx,
paulson@1529
   730
	      shyps = shyps,
paulson@1529
   731
	      hyps = hyps,
paulson@1529
   732
	      prop = eq$u$t}
clasohm@0
   733
    | _ => raise THM("symmetric", 0, [th]);
clasohm@0
   734
clasohm@0
   735
(*The transitive rule
wenzelm@1220
   736
  t1==u    u==t2
wenzelm@1220
   737
  --------------
wenzelm@1220
   738
      t1==t2
wenzelm@1220
   739
*)
clasohm@0
   740
fun transitive th1 th2 =
paulson@1529
   741
  let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
paulson@1529
   742
      and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   743
      fun err(msg) = raise THM("transitive: "^msg, 0, [th1,th2])
clasohm@0
   744
  in case (prop1,prop2) of
clasohm@0
   745
       ((eq as Const("==",_)) $ t1 $ u, Const("==",_) $ u' $ t2) =>
nipkow@1634
   746
          if not (u aconv u') then err"middle term"
nipkow@1634
   747
          else let val thm =      
wenzelm@1220
   748
              fix_shyps [th1, th2] []
paulson@1529
   749
                (Thm{sign= merge_thm_sgs(th1,th2), 
paulson@1529
   750
		     der = infer_derivs (Transitive, [der1, der2]),
paulson@1529
   751
		     maxidx = max[max1,max2], 
paulson@1529
   752
		     shyps = [],
paulson@1529
   753
		     hyps = hyps1 union hyps2,
paulson@1529
   754
		     prop = eq$t1$t2})
nipkow@1634
   755
               in nodup_Vars thm "transitive"; thm end
clasohm@0
   756
     | _ =>  err"premises"
clasohm@0
   757
  end;
clasohm@0
   758
wenzelm@1160
   759
(*Beta-conversion: maps (%x.t)(u) to the theorem (%x.t)(u) == t[u/x] *)
wenzelm@250
   760
fun beta_conversion ct =
lcp@229
   761
  let val {sign, t, T, maxidx} = rep_cterm ct
clasohm@0
   762
  in  case t of
wenzelm@1238
   763
          Abs(_,_,bodt) $ u => fix_shyps [] []
paulson@1529
   764
            (Thm{sign = sign,  
paulson@1529
   765
		 der = infer_derivs (Beta_conversion ct, []),
paulson@1529
   766
		 maxidx = maxidx_of_term t,
paulson@1529
   767
		 shyps = [],
paulson@1529
   768
		 hyps = [],
paulson@1529
   769
		 prop = Logic.mk_equals(t, subst_bounds([u],bodt))})
wenzelm@250
   770
        | _ =>  raise THM("beta_conversion: not a redex", 0, [])
clasohm@0
   771
  end;
clasohm@0
   772
clasohm@0
   773
(*The extensionality rule   (proviso: x not free in f, g, or hypotheses)
wenzelm@1220
   774
  f(x) == g(x)
wenzelm@1220
   775
  ------------
wenzelm@1220
   776
     f == g
wenzelm@1220
   777
*)
paulson@1529
   778
fun extensional (th as Thm{sign, der, maxidx,shyps,hyps,prop}) =
clasohm@0
   779
  case prop of
clasohm@0
   780
    (Const("==",_)) $ (f$x) $ (g$y) =>
wenzelm@250
   781
      let fun err(msg) = raise THM("extensional: "^msg, 0, [th])
clasohm@0
   782
      in (if x<>y then err"different variables" else
clasohm@0
   783
          case y of
wenzelm@250
   784
                Free _ =>
wenzelm@250
   785
                  if exists (apl(y, Logic.occs)) (f::g::hyps)
wenzelm@250
   786
                  then err"variable free in hyps or functions"    else  ()
wenzelm@250
   787
              | Var _ =>
wenzelm@250
   788
                  if Logic.occs(y,f)  orelse  Logic.occs(y,g)
wenzelm@250
   789
                  then err"variable free in functions"   else  ()
wenzelm@250
   790
              | _ => err"not a variable");
wenzelm@1238
   791
          (*no fix_shyps*)
paulson@1529
   792
          Thm{sign = sign,
paulson@1529
   793
	      der = infer_derivs (Extensional, [der]),
paulson@1529
   794
	      maxidx = maxidx,
paulson@1529
   795
	      shyps = shyps,
paulson@1529
   796
	      hyps = hyps, 
paulson@1529
   797
              prop = Logic.mk_equals(f,g)}
clasohm@0
   798
      end
clasohm@0
   799
 | _ =>  raise THM("extensional: premise", 0, [th]);
clasohm@0
   800
clasohm@0
   801
(*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   802
  The bound variable will be named "a" (since x will be something like x320)
wenzelm@1220
   803
     t == u
wenzelm@1220
   804
  ------------
wenzelm@1220
   805
  %x.t == %x.u
wenzelm@1220
   806
*)
paulson@1529
   807
fun abstract_rule a cx (th as Thm{sign,der,maxidx,hyps,prop,...}) =
lcp@229
   808
  let val x = term_of cx;
wenzelm@250
   809
      val (t,u) = Logic.dest_equals prop
wenzelm@250
   810
            handle TERM _ =>
wenzelm@250
   811
                raise THM("abstract_rule: premise not an equality", 0, [th])
wenzelm@1238
   812
      fun result T = fix_shyps [th] []
paulson@1529
   813
	  (Thm{sign = sign,
paulson@1529
   814
	       der = infer_derivs (Abstract_rule (a,cx), [der]),
paulson@1529
   815
	       maxidx = maxidx, 
paulson@1529
   816
	       shyps = [], 
paulson@1529
   817
	       hyps = hyps,
paulson@1529
   818
	       prop = Logic.mk_equals(Abs(a, T, abstract_over (x,t)),
paulson@1529
   819
				      Abs(a, T, abstract_over (x,u)))})
clasohm@0
   820
  in  case x of
wenzelm@250
   821
        Free(_,T) =>
wenzelm@250
   822
         if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   823
         then raise THM("abstract_rule: variable free in assumptions", 0, [th])
wenzelm@250
   824
         else result T
clasohm@0
   825
      | Var(_,T) => result T
clasohm@0
   826
      | _ => raise THM("abstract_rule: not a variable", 0, [th])
clasohm@0
   827
  end;
clasohm@0
   828
clasohm@0
   829
(*The combination rule
wenzelm@1220
   830
  f==g    t==u
wenzelm@1220
   831
  ------------
wenzelm@1220
   832
   f(t)==g(u)
wenzelm@1220
   833
*)
clasohm@0
   834
fun combination th1 th2 =
paulson@1529
   835
  let val Thm{der=der1, maxidx=max1, shyps=shyps1, hyps=hyps1, 
paulson@1529
   836
	      prop=prop1,...} = th1
paulson@1529
   837
      and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
paulson@1529
   838
	      prop=prop2,...} = th2
nipkow@1495
   839
  in case (prop1,prop2)  of
clasohm@0
   840
       (Const("==",_) $ f $ g, Const("==",_) $ t $ u) =>
nipkow@1495
   841
          let val thm = (*no fix_shyps*)
paulson@1529
   842
             Thm{sign = merge_thm_sgs(th1,th2), 
paulson@1529
   843
		 der = infer_derivs (Combination, [der1, der2]),
paulson@1529
   844
                 maxidx = max[max1,max2], 
paulson@1529
   845
		 shyps = shyps1 union shyps2,
paulson@1529
   846
                 hyps = hyps1 union hyps2,
paulson@1529
   847
		 prop = Logic.mk_equals(f$t, g$u)}
nipkow@1495
   848
          in nodup_Vars thm "combination"; thm end
clasohm@0
   849
     | _ =>  raise THM("combination: premises", 0, [th1,th2])
clasohm@0
   850
  end;
clasohm@0
   851
clasohm@0
   852
clasohm@0
   853
(* Equality introduction
wenzelm@1220
   854
  A==>B    B==>A
wenzelm@1220
   855
  --------------
wenzelm@1220
   856
       A==B
wenzelm@1220
   857
*)
clasohm@0
   858
fun equal_intr th1 th2 =
paulson@1529
   859
  let val Thm{der=der1,maxidx=max1, shyps=shyps1, hyps=hyps1, 
paulson@1529
   860
	      prop=prop1,...} = th1
paulson@1529
   861
      and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
paulson@1529
   862
	      prop=prop2,...} = th2;
paulson@1529
   863
      fun err(msg) = raise THM("equal_intr: "^msg, 0, [th1,th2])
paulson@1529
   864
  in case (prop1,prop2) of
paulson@1529
   865
       (Const("==>",_) $ A $ B, Const("==>",_) $ B' $ A')  =>
paulson@1529
   866
	  if A aconv A' andalso B aconv B'
paulson@1529
   867
	  then
paulson@1529
   868
	    (*no fix_shyps*)
paulson@1529
   869
	      Thm{sign = merge_thm_sgs(th1,th2),
paulson@1529
   870
		  der = infer_derivs (Equal_intr, [der1, der2]),
paulson@1529
   871
		  maxidx = max[max1,max2],
paulson@1529
   872
		  shyps = shyps1 union shyps2,
paulson@1529
   873
		  hyps = hyps1 union hyps2,
paulson@1529
   874
		  prop = Logic.mk_equals(A,B)}
paulson@1529
   875
	  else err"not equal"
paulson@1529
   876
     | _ =>  err"premises"
paulson@1529
   877
  end;
paulson@1529
   878
paulson@1529
   879
paulson@1529
   880
(*The equal propositions rule
paulson@1529
   881
  A==B    A
paulson@1529
   882
  ---------
paulson@1529
   883
      B
paulson@1529
   884
*)
paulson@1529
   885
fun equal_elim th1 th2 =
paulson@1529
   886
  let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
paulson@1529
   887
      and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
paulson@1529
   888
      fun err(msg) = raise THM("equal_elim: "^msg, 0, [th1,th2])
paulson@1529
   889
  in  case prop1  of
paulson@1529
   890
       Const("==",_) $ A $ B =>
paulson@1529
   891
          if not (prop2 aconv A) then err"not equal"  else
paulson@1529
   892
            fix_shyps [th1, th2] []
paulson@1529
   893
              (Thm{sign= merge_thm_sgs(th1,th2), 
paulson@1529
   894
		   der = infer_derivs (Equal_elim, [der1, der2]),
paulson@1529
   895
		   maxidx = max[max1,max2],
paulson@1529
   896
		   shyps = [],
paulson@1529
   897
		   hyps = hyps1 union hyps2,
paulson@1529
   898
		   prop = B})
paulson@1529
   899
     | _ =>  err"major premise"
paulson@1529
   900
  end;
clasohm@0
   901
wenzelm@1220
   902
wenzelm@1220
   903
clasohm@0
   904
(**** Derived rules ****)
clasohm@0
   905
paulson@1503
   906
(*Discharge all hypotheses.  Need not verify cterms or call fix_shyps.
clasohm@0
   907
  Repeated hypotheses are discharged only once;  fold cannot do this*)
paulson@1529
   908
fun implies_intr_hyps (Thm{sign, der, maxidx, shyps, hyps=A::As, prop}) =
wenzelm@1238
   909
      implies_intr_hyps (*no fix_shyps*)
paulson@1529
   910
            (Thm{sign = sign, 
paulson@1529
   911
		 der = infer_derivs (Implies_intr_hyps, [der]), 
paulson@1529
   912
		 maxidx = maxidx, 
paulson@1529
   913
		 shyps = shyps,
paulson@1529
   914
                 hyps = disch(As,A),  
paulson@1529
   915
		 prop = implies$A$prop})
clasohm@0
   916
  | implies_intr_hyps th = th;
clasohm@0
   917
clasohm@0
   918
(*Smash" unifies the list of term pairs leaving no flex-flex pairs.
wenzelm@250
   919
  Instantiates the theorem and deletes trivial tpairs.
clasohm@0
   920
  Resulting sequence may contain multiple elements if the tpairs are
clasohm@0
   921
    not all flex-flex. *)
paulson@1529
   922
fun flexflex_rule (th as Thm{sign, der, maxidx, hyps, prop,...}) =
wenzelm@250
   923
  let fun newthm env =
paulson@1529
   924
          if Envir.is_empty env then th
paulson@1529
   925
          else
wenzelm@250
   926
          let val (tpairs,horn) =
wenzelm@250
   927
                        Logic.strip_flexpairs (Envir.norm_term env prop)
wenzelm@250
   928
                (*Remove trivial tpairs, of the form t=t*)
wenzelm@250
   929
              val distpairs = filter (not o op aconv) tpairs
wenzelm@250
   930
              val newprop = Logic.list_flexpairs(distpairs, horn)
wenzelm@1220
   931
          in  fix_shyps [th] (env_codT env)
paulson@1529
   932
                (Thm{sign = sign, 
paulson@1529
   933
		     der = infer_derivs (Flexflex_rule env, [der]), 
paulson@1529
   934
		     maxidx = maxidx_of_term newprop, 
paulson@1529
   935
		     shyps = [], 
paulson@1529
   936
		     hyps = hyps,
paulson@1529
   937
		     prop = newprop})
wenzelm@250
   938
          end;
clasohm@0
   939
      val (tpairs,_) = Logic.strip_flexpairs prop
clasohm@0
   940
  in Sequence.maps newthm
wenzelm@250
   941
            (Unify.smash_unifiers(sign, Envir.empty maxidx, tpairs))
clasohm@0
   942
  end;
clasohm@0
   943
clasohm@0
   944
(*Instantiation of Vars
wenzelm@1220
   945
           A
wenzelm@1220
   946
  -------------------
wenzelm@1220
   947
  A[t1/v1,....,tn/vn]
wenzelm@1220
   948
*)
clasohm@0
   949
clasohm@0
   950
(*Check that all the terms are Vars and are distinct*)
clasohm@0
   951
fun instl_ok ts = forall is_Var ts andalso null(findrep ts);
clasohm@0
   952
clasohm@0
   953
(*For instantiate: process pair of cterms, merge theories*)
clasohm@0
   954
fun add_ctpair ((ct,cu), (sign,tpairs)) =
lcp@229
   955
  let val {sign=signt, t=t, T= T, ...} = rep_cterm ct
lcp@229
   956
      and {sign=signu, t=u, T= U, ...} = rep_cterm cu
clasohm@0
   957
  in  if T=U  then (Sign.merge(sign, Sign.merge(signt, signu)), (t,u)::tpairs)
clasohm@0
   958
      else raise TYPE("add_ctpair", [T,U], [t,u])
clasohm@0
   959
  end;
clasohm@0
   960
clasohm@0
   961
fun add_ctyp ((v,ctyp), (sign',vTs)) =
lcp@229
   962
  let val {T,sign} = rep_ctyp ctyp
clasohm@0
   963
  in (Sign.merge(sign,sign'), (v,T)::vTs) end;
clasohm@0
   964
clasohm@0
   965
(*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
   966
  Instantiates distinct Vars by terms of same type.
clasohm@0
   967
  Normalizes the new theorem! *)
paulson@1529
   968
fun instantiate ([], []) th = th
paulson@1529
   969
  | instantiate (vcTs,ctpairs)  (th as Thm{sign,der,maxidx,hyps,prop,...}) =
clasohm@0
   970
  let val (newsign,tpairs) = foldr add_ctpair (ctpairs, (sign,[]));
clasohm@0
   971
      val (newsign,vTs) = foldr add_ctyp (vcTs, (newsign,[]));
wenzelm@250
   972
      val newprop =
wenzelm@250
   973
            Envir.norm_term (Envir.empty 0)
wenzelm@250
   974
              (subst_atomic tpairs
wenzelm@250
   975
               (Type.inst_term_tvars(#tsig(Sign.rep_sg newsign),vTs) prop))
wenzelm@1220
   976
      val newth =
wenzelm@1220
   977
            fix_shyps [th] (map snd vTs)
paulson@1529
   978
              (Thm{sign = newsign, 
paulson@1529
   979
		   der = infer_derivs (Instantiate(vcTs,ctpairs), [der]), 
paulson@1529
   980
		   maxidx = maxidx_of_term newprop, 
paulson@1529
   981
		   shyps = [],
paulson@1529
   982
		   hyps = hyps,
paulson@1529
   983
		   prop = newprop})
wenzelm@250
   984
  in  if not(instl_ok(map #1 tpairs))
nipkow@193
   985
      then raise THM("instantiate: variables not distinct", 0, [th])
nipkow@193
   986
      else if not(null(findrep(map #1 vTs)))
nipkow@193
   987
      then raise THM("instantiate: type variables not distinct", 0, [th])
nipkow@1495
   988
      else nodup_Vars newth "instantiate";
nipkow@1495
   989
      newth
clasohm@0
   990
  end
wenzelm@250
   991
  handle TERM _ =>
clasohm@0
   992
           raise THM("instantiate: incompatible signatures",0,[th])
nipkow@193
   993
       | TYPE _ => raise THM("instantiate: type conflict", 0, [th]);
clasohm@0
   994
clasohm@0
   995
(*The trivial implication A==>A, justified by assume and forall rules.
clasohm@0
   996
  A can contain Vars, not so for assume!   *)
wenzelm@250
   997
fun trivial ct : thm =
lcp@229
   998
  let val {sign, t=A, T, maxidx} = rep_cterm ct
wenzelm@250
   999
  in  if T<>propT then
wenzelm@250
  1000
            raise THM("trivial: the term must have type prop", 0, [])
wenzelm@1238
  1001
      else fix_shyps [] []
paulson@1529
  1002
        (Thm{sign = sign, 
paulson@1529
  1003
	     der = infer_derivs (Trivial ct, []), 
paulson@1529
  1004
	     maxidx = maxidx, 
paulson@1529
  1005
	     shyps = [], 
paulson@1529
  1006
	     hyps = [],
paulson@1529
  1007
	     prop = implies$A$A})
clasohm@0
  1008
  end;
clasohm@0
  1009
paulson@1503
  1010
(*Axiom-scheme reflecting signature contents: "OFCLASS(?'a::c, c_class)" *)
wenzelm@399
  1011
fun class_triv thy c =
paulson@1529
  1012
  let val sign = sign_of thy;
paulson@1529
  1013
      val Cterm {t, maxidx, ...} =
paulson@1529
  1014
	  cterm_of sign (Logic.mk_inclass (TVar (("'a", 0), [c]), c))
paulson@1529
  1015
	    handle TERM (msg, _) => raise THM ("class_triv: " ^ msg, 0, []);
wenzelm@399
  1016
  in
wenzelm@1238
  1017
    fix_shyps [] []
paulson@1529
  1018
      (Thm {sign = sign, 
paulson@1529
  1019
	    der = infer_derivs (Class_triv(thy,c), []), 
paulson@1529
  1020
	    maxidx = maxidx, 
paulson@1529
  1021
	    shyps = [], 
paulson@1529
  1022
	    hyps = [], 
paulson@1529
  1023
	    prop = t})
wenzelm@399
  1024
  end;
wenzelm@399
  1025
wenzelm@399
  1026
clasohm@0
  1027
(* Replace all TFrees not in the hyps by new TVars *)
paulson@1529
  1028
fun varifyT(Thm{sign,der,maxidx,shyps,hyps,prop}) =
clasohm@0
  1029
  let val tfrees = foldr add_term_tfree_names (hyps,[])
nipkow@1634
  1030
  in let val thm = (*no fix_shyps*)
paulson@1529
  1031
    Thm{sign = sign, 
paulson@1529
  1032
	der = infer_derivs (VarifyT, [der]), 
paulson@1529
  1033
	maxidx = max[0,maxidx], 
paulson@1529
  1034
	shyps = shyps, 
paulson@1529
  1035
	hyps = hyps,
paulson@1529
  1036
        prop = Type.varify(prop,tfrees)}
nipkow@1634
  1037
     in nodup_Vars thm "varifyT"; thm end
nipkow@1634
  1038
(* this nodup_Vars check can be removed if thms are guaranteed not to contain
nipkow@1634
  1039
duplicate TVars with differnt sorts *)
clasohm@0
  1040
  end;
clasohm@0
  1041
clasohm@0
  1042
(* Replace all TVars by new TFrees *)
paulson@1529
  1043
fun freezeT(Thm{sign,der,maxidx,shyps,hyps,prop}) =
nipkow@949
  1044
  let val prop' = Type.freeze prop
wenzelm@1238
  1045
  in (*no fix_shyps*)
paulson@1529
  1046
    Thm{sign = sign, 
paulson@1529
  1047
	der = infer_derivs (FreezeT, [der]),
paulson@1529
  1048
	maxidx = maxidx_of_term prop',
paulson@1529
  1049
	shyps = shyps,
paulson@1529
  1050
	hyps = hyps,
paulson@1529
  1051
        prop = prop'}
wenzelm@1220
  1052
  end;
clasohm@0
  1053
clasohm@0
  1054
clasohm@0
  1055
(*** Inference rules for tactics ***)
clasohm@0
  1056
clasohm@0
  1057
(*Destruct proof state into constraints, other goals, goal(i), rest *)
clasohm@0
  1058
fun dest_state (state as Thm{prop,...}, i) =
clasohm@0
  1059
  let val (tpairs,horn) = Logic.strip_flexpairs prop
clasohm@0
  1060
  in  case  Logic.strip_prems(i, [], horn) of
clasohm@0
  1061
          (B::rBs, C) => (tpairs, rev rBs, B, C)
clasohm@0
  1062
        | _ => raise THM("dest_state", i, [state])
clasohm@0
  1063
  end
clasohm@0
  1064
  handle TERM _ => raise THM("dest_state", i, [state]);
clasohm@0
  1065
lcp@309
  1066
(*Increment variables and parameters of orule as required for
clasohm@0
  1067
  resolution with goal i of state. *)
clasohm@0
  1068
fun lift_rule (state, i) orule =
paulson@1529
  1069
  let val Thm{shyps=sshyps, prop=sprop, maxidx=smax, sign=ssign,...} = state
clasohm@0
  1070
      val (Bi::_, _) = Logic.strip_prems(i, [], Logic.skip_flexpairs sprop)
paulson@1529
  1071
        handle TERM _ => raise THM("lift_rule", i, [orule,state])
paulson@1529
  1072
      val ct_Bi = Cterm {sign=ssign, maxidx=smax, T=propT, t=Bi}
paulson@1529
  1073
      val (lift_abs,lift_all) = Logic.lift_fns(Bi,smax+1)
paulson@1529
  1074
      val (Thm{sign, der, maxidx,shyps,hyps,prop}) = orule
clasohm@0
  1075
      val (tpairs,As,B) = Logic.strip_horn prop
wenzelm@1238
  1076
  in  (*no fix_shyps*)
paulson@1529
  1077
      Thm{sign = merge_thm_sgs(state,orule),
paulson@1529
  1078
	  der = infer_derivs (Lift_rule(ct_Bi, i), [der]),
paulson@1529
  1079
	  maxidx = maxidx+smax+1,
paulson@1529
  1080
          shyps=sshyps union shyps, 
paulson@1529
  1081
	  hyps=hyps, 
paulson@1529
  1082
          prop = Logic.rule_of (map (pairself lift_abs) tpairs,
paulson@1529
  1083
				map lift_all As,    
paulson@1529
  1084
				lift_all B)}
clasohm@0
  1085
  end;
clasohm@0
  1086
clasohm@0
  1087
(*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
clasohm@0
  1088
fun assumption i state =
paulson@1529
  1089
  let val Thm{sign,der,maxidx,hyps,prop,...} = state;
clasohm@0
  1090
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
  1091
      fun newth (env as Envir.Envir{maxidx, ...}, tpairs) =
wenzelm@1220
  1092
        fix_shyps [state] (env_codT env)
paulson@1529
  1093
          (Thm{sign = sign, 
paulson@1529
  1094
	       der = infer_derivs (Assumption (i, Some env), [der]),
paulson@1529
  1095
	       maxidx = maxidx,
paulson@1529
  1096
	       shyps = [],
paulson@1529
  1097
	       hyps = hyps,
paulson@1529
  1098
	       prop = 
paulson@1529
  1099
	       if Envir.is_empty env then (*avoid wasted normalizations*)
paulson@1529
  1100
		   Logic.rule_of (tpairs, Bs, C)
paulson@1529
  1101
	       else (*normalize the new rule fully*)
paulson@1529
  1102
		   Envir.norm_term env (Logic.rule_of (tpairs, Bs, C))});
clasohm@0
  1103
      fun addprfs [] = Sequence.null
clasohm@0
  1104
        | addprfs ((t,u)::apairs) = Sequence.seqof (fn()=> Sequence.pull
clasohm@0
  1105
             (Sequence.mapp newth
wenzelm@250
  1106
                (Unify.unifiers(sign,Envir.empty maxidx, (t,u)::tpairs))
wenzelm@250
  1107
                (addprfs apairs)))
clasohm@0
  1108
  in  addprfs (Logic.assum_pairs Bi)  end;
clasohm@0
  1109
wenzelm@250
  1110
(*Solve subgoal Bi of proof state B1...Bn/C by assumption.
clasohm@0
  1111
  Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
clasohm@0
  1112
fun eq_assumption i state =
paulson@1529
  1113
  let val Thm{sign,der,maxidx,hyps,prop,...} = state;
clasohm@0
  1114
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
  1115
  in  if exists (op aconv) (Logic.assum_pairs Bi)
wenzelm@1220
  1116
      then fix_shyps [state] []
paulson@1529
  1117
             (Thm{sign = sign, 
paulson@1529
  1118
		  der = infer_derivs (Assumption (i,None), [der]),
paulson@1529
  1119
		  maxidx = maxidx,
paulson@1529
  1120
		  shyps = [],
paulson@1529
  1121
		  hyps = hyps,
paulson@1529
  1122
		  prop = Logic.rule_of(tpairs, Bs, C)})
clasohm@0
  1123
      else  raise THM("eq_assumption", 0, [state])
clasohm@0
  1124
  end;
clasohm@0
  1125
clasohm@0
  1126
clasohm@0
  1127
(** User renaming of parameters in a subgoal **)
clasohm@0
  1128
clasohm@0
  1129
(*Calls error rather than raising an exception because it is intended
clasohm@0
  1130
  for top-level use -- exception handling would not make sense here.
clasohm@0
  1131
  The names in cs, if distinct, are used for the innermost parameters;
clasohm@0
  1132
   preceding parameters may be renamed to make all params distinct.*)
clasohm@0
  1133
fun rename_params_rule (cs, i) state =
paulson@1529
  1134
  let val Thm{sign,der,maxidx,hyps,prop,...} = state
clasohm@0
  1135
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
  1136
      val iparams = map #1 (Logic.strip_params Bi)
clasohm@0
  1137
      val short = length iparams - length cs
wenzelm@250
  1138
      val newnames =
wenzelm@250
  1139
            if short<0 then error"More names than abstractions!"
wenzelm@250
  1140
            else variantlist(take (short,iparams), cs) @ cs
clasohm@0
  1141
      val freenames = map (#1 o dest_Free) (term_frees prop)
clasohm@0
  1142
      val newBi = Logic.list_rename_params (newnames, Bi)
wenzelm@250
  1143
  in
clasohm@0
  1144
  case findrep cs of
clasohm@0
  1145
     c::_ => error ("Bound variables not distinct: " ^ c)
berghofe@1576
  1146
   | [] => (case cs inter_string freenames of
clasohm@0
  1147
       a::_ => error ("Bound/Free variable clash: " ^ a)
wenzelm@1220
  1148
     | [] => fix_shyps [state] []
paulson@1529
  1149
		(Thm{sign = sign,
paulson@1529
  1150
		     der = infer_derivs (Rename_params_rule(cs,i), [der]),
paulson@1529
  1151
		     maxidx = maxidx,
paulson@1529
  1152
		     shyps = [],
paulson@1529
  1153
		     hyps = hyps,
paulson@1529
  1154
		     prop = Logic.rule_of(tpairs, Bs@[newBi], C)}))
clasohm@0
  1155
  end;
clasohm@0
  1156
clasohm@0
  1157
(*** Preservation of bound variable names ***)
clasohm@0
  1158
wenzelm@250
  1159
(*Scan a pair of terms; while they are similar,
clasohm@0
  1160
  accumulate corresponding bound vars in "al"*)
wenzelm@1238
  1161
fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) =
lcp@1195
  1162
      match_bvs(s, t, if x="" orelse y="" then al
wenzelm@1238
  1163
                                          else (x,y)::al)
clasohm@0
  1164
  | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
clasohm@0
  1165
  | match_bvs(_,_,al) = al;
clasohm@0
  1166
clasohm@0
  1167
(* strip abstractions created by parameters *)
clasohm@0
  1168
fun match_bvars((s,t),al) = match_bvs(strip_abs_body s, strip_abs_body t, al);
clasohm@0
  1169
clasohm@0
  1170
wenzelm@250
  1171
(* strip_apply f A(,B) strips off all assumptions/parameters from A
clasohm@0
  1172
   introduced by lifting over B, and applies f to remaining part of A*)
clasohm@0
  1173
fun strip_apply f =
clasohm@0
  1174
  let fun strip(Const("==>",_)$ A1 $ B1,
wenzelm@250
  1175
                Const("==>",_)$ _  $ B2) = implies $ A1 $ strip(B1,B2)
wenzelm@250
  1176
        | strip((c as Const("all",_)) $ Abs(a,T,t1),
wenzelm@250
  1177
                      Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
wenzelm@250
  1178
        | strip(A,_) = f A
clasohm@0
  1179
  in strip end;
clasohm@0
  1180
clasohm@0
  1181
(*Use the alist to rename all bound variables and some unknowns in a term
clasohm@0
  1182
  dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
clasohm@0
  1183
  Preserves unknowns in tpairs and on lhs of dpairs. *)
clasohm@0
  1184
fun rename_bvs([],_,_,_) = I
clasohm@0
  1185
  | rename_bvs(al,dpairs,tpairs,B) =
wenzelm@250
  1186
    let val vars = foldr add_term_vars
wenzelm@250
  1187
                        (map fst dpairs @ map fst tpairs @ map snd tpairs, [])
wenzelm@250
  1188
        (*unknowns appearing elsewhere be preserved!*)
wenzelm@250
  1189
        val vids = map (#1 o #1 o dest_Var) vars;
wenzelm@250
  1190
        fun rename(t as Var((x,i),T)) =
wenzelm@250
  1191
                (case assoc(al,x) of
berghofe@1576
  1192
                   Some(y) => if x mem_string vids orelse y mem_string vids then t
wenzelm@250
  1193
                              else Var((y,i),T)
wenzelm@250
  1194
                 | None=> t)
clasohm@0
  1195
          | rename(Abs(x,T,t)) =
berghofe@1576
  1196
              Abs(case assoc_string(al,x) of Some(y) => y | None => x,
wenzelm@250
  1197
                  T, rename t)
clasohm@0
  1198
          | rename(f$t) = rename f $ rename t
clasohm@0
  1199
          | rename(t) = t;
wenzelm@250
  1200
        fun strip_ren Ai = strip_apply rename (Ai,B)
clasohm@0
  1201
    in strip_ren end;
clasohm@0
  1202
clasohm@0
  1203
(*Function to rename bounds/unknowns in the argument, lifted over B*)
clasohm@0
  1204
fun rename_bvars(dpairs, tpairs, B) =
wenzelm@250
  1205
        rename_bvs(foldr match_bvars (dpairs,[]), dpairs, tpairs, B);
clasohm@0
  1206
clasohm@0
  1207
clasohm@0
  1208
(*** RESOLUTION ***)
clasohm@0
  1209
lcp@721
  1210
(** Lifting optimizations **)
lcp@721
  1211
clasohm@0
  1212
(*strip off pairs of assumptions/parameters in parallel -- they are
clasohm@0
  1213
  identical because of lifting*)
wenzelm@250
  1214
fun strip_assums2 (Const("==>", _) $ _ $ B1,
wenzelm@250
  1215
                   Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
clasohm@0
  1216
  | strip_assums2 (Const("all",_)$Abs(a,T,t1),
wenzelm@250
  1217
                   Const("all",_)$Abs(_,_,t2)) =
clasohm@0
  1218
      let val (B1,B2) = strip_assums2 (t1,t2)
clasohm@0
  1219
      in  (Abs(a,T,B1), Abs(a,T,B2))  end
clasohm@0
  1220
  | strip_assums2 BB = BB;
clasohm@0
  1221
clasohm@0
  1222
lcp@721
  1223
(*Faster normalization: skip assumptions that were lifted over*)
lcp@721
  1224
fun norm_term_skip env 0 t = Envir.norm_term env t
lcp@721
  1225
  | norm_term_skip env n (Const("all",_)$Abs(a,T,t)) =
lcp@721
  1226
        let val Envir.Envir{iTs, ...} = env
wenzelm@1238
  1227
            val T' = typ_subst_TVars iTs T
wenzelm@1238
  1228
            (*Must instantiate types of parameters because they are flattened;
lcp@721
  1229
              this could be a NEW parameter*)
lcp@721
  1230
        in  all T' $ Abs(a, T', norm_term_skip env n t)  end
lcp@721
  1231
  | norm_term_skip env n (Const("==>", _) $ A $ B) =
wenzelm@1238
  1232
        implies $ A $ norm_term_skip env (n-1) B
lcp@721
  1233
  | norm_term_skip env n t = error"norm_term_skip: too few assumptions??";
lcp@721
  1234
lcp@721
  1235
clasohm@0
  1236
(*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
wenzelm@250
  1237
  Unifies B with Bi, replacing subgoal i    (1 <= i <= n)
clasohm@0
  1238
  If match then forbid instantiations in proof state
clasohm@0
  1239
  If lifted then shorten the dpair using strip_assums2.
clasohm@0
  1240
  If eres_flg then simultaneously proves A1 by assumption.
wenzelm@250
  1241
  nsubgoal is the number of new subgoals (written m above).
clasohm@0
  1242
  Curried so that resolution calls dest_state only once.
clasohm@0
  1243
*)
paulson@1529
  1244
local open Sequence; exception COMPOSE
clasohm@0
  1245
in
wenzelm@250
  1246
fun bicompose_aux match (state, (stpairs, Bs, Bi, C), lifted)
clasohm@0
  1247
                        (eres_flg, orule, nsubgoal) =
paulson@1529
  1248
 let val Thm{der=sder, maxidx=smax, shyps=sshyps, hyps=shyps, ...} = state
paulson@1529
  1249
     and Thm{der=rder, maxidx=rmax, shyps=rshyps, hyps=rhyps, 
paulson@1529
  1250
	     prop=rprop,...} = orule
paulson@1529
  1251
         (*How many hyps to skip over during normalization*)
wenzelm@1238
  1252
     and nlift = Logic.count_prems(strip_all_body Bi,
wenzelm@1238
  1253
                                   if eres_flg then ~1 else 0)
wenzelm@387
  1254
     val sign = merge_thm_sgs(state,orule);
clasohm@0
  1255
     (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
wenzelm@250
  1256
     fun addth As ((env as Envir.Envir {maxidx, ...}, tpairs), thq) =
wenzelm@250
  1257
       let val normt = Envir.norm_term env;
wenzelm@250
  1258
           (*perform minimal copying here by examining env*)
wenzelm@250
  1259
           val normp =
wenzelm@250
  1260
             if Envir.is_empty env then (tpairs, Bs @ As, C)
wenzelm@250
  1261
             else
wenzelm@250
  1262
             let val ntps = map (pairself normt) tpairs
wenzelm@1238
  1263
             in if the (Envir.minidx env) > smax then
wenzelm@1238
  1264
                  (*no assignments in state; normalize the rule only*)
wenzelm@1238
  1265
                  if lifted
wenzelm@1238
  1266
                  then (ntps, Bs @ map (norm_term_skip env nlift) As, C)
wenzelm@1238
  1267
                  else (ntps, Bs @ map normt As, C)
paulson@1529
  1268
                else if match then raise COMPOSE
wenzelm@250
  1269
                else (*normalize the new rule fully*)
wenzelm@250
  1270
                  (ntps, map normt (Bs @ As), normt C)
wenzelm@250
  1271
             end
wenzelm@1258
  1272
           val th = (*tuned fix_shyps*)
paulson@1529
  1273
             Thm{sign = sign,
paulson@1529
  1274
		 der = infer_derivs (Bicompose(match, eres_flg,
paulson@1529
  1275
					       1 + length Bs, nsubgoal, env),
paulson@1529
  1276
				     [rder,sder]),
paulson@1529
  1277
		 maxidx = maxidx,
paulson@1529
  1278
		 shyps = add_env_sorts (env, rshyps union sshyps),
paulson@1529
  1279
		 hyps = rhyps union shyps,
paulson@1529
  1280
		 prop = Logic.rule_of normp}
paulson@1529
  1281
        in  cons(th, thq)  end  handle COMPOSE => thq
clasohm@0
  1282
     val (rtpairs,rhorn) = Logic.strip_flexpairs(rprop);
clasohm@0
  1283
     val (rAs,B) = Logic.strip_prems(nsubgoal, [], rhorn)
clasohm@0
  1284
       handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
clasohm@0
  1285
     (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
clasohm@0
  1286
     fun newAs(As0, n, dpairs, tpairs) =
clasohm@0
  1287
       let val As1 = if !Logic.auto_rename orelse not lifted then As0
wenzelm@250
  1288
                     else map (rename_bvars(dpairs,tpairs,B)) As0
clasohm@0
  1289
       in (map (Logic.flatten_params n) As1)
wenzelm@250
  1290
          handle TERM _ =>
wenzelm@250
  1291
          raise THM("bicompose: 1st premise", 0, [orule])
clasohm@0
  1292
       end;
clasohm@0
  1293
     val env = Envir.empty(max[rmax,smax]);
clasohm@0
  1294
     val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
clasohm@0
  1295
     val dpairs = BBi :: (rtpairs@stpairs);
clasohm@0
  1296
     (*elim-resolution: try each assumption in turn.  Initially n=1*)
clasohm@0
  1297
     fun tryasms (_, _, []) = null
clasohm@0
  1298
       | tryasms (As, n, (t,u)::apairs) =
wenzelm@250
  1299
          (case pull(Unify.unifiers(sign, env, (t,u)::dpairs))  of
wenzelm@250
  1300
               None                   => tryasms (As, n+1, apairs)
wenzelm@250
  1301
             | cell as Some((_,tpairs),_) =>
wenzelm@250
  1302
                   its_right (addth (newAs(As, n, [BBi,(u,t)], tpairs)))
wenzelm@250
  1303
                       (seqof (fn()=> cell),
wenzelm@250
  1304
                        seqof (fn()=> pull (tryasms (As, n+1, apairs)))));
clasohm@0
  1305
     fun eres [] = raise THM("bicompose: no premises", 0, [orule,state])
clasohm@0
  1306
       | eres (A1::As) = tryasms (As, 1, Logic.assum_pairs A1);
clasohm@0
  1307
     (*ordinary resolution*)
clasohm@0
  1308
     fun res(None) = null
wenzelm@250
  1309
       | res(cell as Some((_,tpairs),_)) =
wenzelm@250
  1310
             its_right (addth(newAs(rev rAs, 0, [BBi], tpairs)))
wenzelm@250
  1311
                       (seqof (fn()=> cell), null)
clasohm@0
  1312
 in  if eres_flg then eres(rev rAs)
clasohm@0
  1313
     else res(pull(Unify.unifiers(sign, env, dpairs)))
clasohm@0
  1314
 end;
clasohm@0
  1315
end;  (*open Sequence*)
clasohm@0
  1316
clasohm@0
  1317
clasohm@0
  1318
fun bicompose match arg i state =
clasohm@0
  1319
    bicompose_aux match (state, dest_state(state,i), false) arg;
clasohm@0
  1320
clasohm@0
  1321
(*Quick test whether rule is resolvable with the subgoal with hyps Hs
clasohm@0
  1322
  and conclusion B.  If eres_flg then checks 1st premise of rule also*)
clasohm@0
  1323
fun could_bires (Hs, B, eres_flg, rule) =
clasohm@0
  1324
    let fun could_reshyp (A1::_) = exists (apl(A1,could_unify)) Hs
wenzelm@250
  1325
          | could_reshyp [] = false;  (*no premise -- illegal*)
wenzelm@250
  1326
    in  could_unify(concl_of rule, B) andalso
wenzelm@250
  1327
        (not eres_flg  orelse  could_reshyp (prems_of rule))
clasohm@0
  1328
    end;
clasohm@0
  1329
clasohm@0
  1330
(*Bi-resolution of a state with a list of (flag,rule) pairs.
clasohm@0
  1331
  Puts the rule above:  rule/state.  Renames vars in the rules. *)
wenzelm@250
  1332
fun biresolution match brules i state =
clasohm@0
  1333
    let val lift = lift_rule(state, i);
wenzelm@250
  1334
        val (stpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
  1335
        val B = Logic.strip_assums_concl Bi;
wenzelm@250
  1336
        val Hs = Logic.strip_assums_hyp Bi;
wenzelm@250
  1337
        val comp = bicompose_aux match (state, (stpairs, Bs, Bi, C), true);
wenzelm@250
  1338
        fun res [] = Sequence.null
wenzelm@250
  1339
          | res ((eres_flg, rule)::brules) =
wenzelm@250
  1340
              if could_bires (Hs, B, eres_flg, rule)
wenzelm@1160
  1341
              then Sequence.seqof (*delay processing remainder till needed*)
wenzelm@250
  1342
                  (fn()=> Some(comp (eres_flg, lift rule, nprems_of rule),
wenzelm@250
  1343
                               res brules))
wenzelm@250
  1344
              else res brules
clasohm@0
  1345
    in  Sequence.flats (res brules)  end;
clasohm@0
  1346
clasohm@0
  1347
clasohm@0
  1348
clasohm@0
  1349
(*** Meta simp sets ***)
clasohm@0
  1350
nipkow@288
  1351
type rrule = {thm:thm, lhs:term, perm:bool};
nipkow@288
  1352
type cong = {thm:thm, lhs:term};
clasohm@0
  1353
datatype meta_simpset =
nipkow@405
  1354
  Mss of {net:rrule Net.net, congs:(string * cong)list, bounds:string list,
clasohm@0
  1355
          prems: thm list, mk_rews: thm -> thm list};
clasohm@0
  1356
clasohm@0
  1357
(*A "mss" contains data needed during conversion:
clasohm@0
  1358
  net: discrimination net of rewrite rules
clasohm@0
  1359
  congs: association list of congruence rules
nipkow@405
  1360
  bounds: names of bound variables already used;
nipkow@405
  1361
          for generating new names when rewriting under lambda abstractions
clasohm@0
  1362
  mk_rews: used when local assumptions are added
clasohm@0
  1363
*)
clasohm@0
  1364
paulson@1529
  1365
val empty_mss = Mss{net = Net.empty, congs = [], bounds=[], prems = [],
clasohm@0
  1366
                    mk_rews = K[]};
clasohm@0
  1367
clasohm@0
  1368
exception SIMPLIFIER of string * thm;
clasohm@0
  1369
lcp@229
  1370
fun prtm a sign t = (writeln a; writeln(Sign.string_of_term sign t));
clasohm@0
  1371
berghofe@1580
  1372
fun prtm_warning a sign t = warning (a ^ "\n" ^ (Sign.string_of_term sign t));
berghofe@1580
  1373
nipkow@209
  1374
val trace_simp = ref false;
nipkow@209
  1375
lcp@229
  1376
fun trace_term a sign t = if !trace_simp then prtm a sign t else ();
nipkow@209
  1377
nipkow@209
  1378
fun trace_thm a (Thm{sign,prop,...}) = trace_term a sign prop;
nipkow@209
  1379
berghofe@1580
  1380
fun trace_term_warning a sign t = if !trace_simp then prtm_warning a sign t else ();
berghofe@1580
  1381
berghofe@1580
  1382
fun trace_thm_warning a (Thm{sign,prop,...}) = trace_term_warning a sign prop;
berghofe@1580
  1383
nipkow@427
  1384
fun vperm(Var _, Var _) = true
nipkow@427
  1385
  | vperm(Abs(_,_,s), Abs(_,_,t)) = vperm(s,t)
nipkow@427
  1386
  | vperm(t1$t2, u1$u2) = vperm(t1,u1) andalso vperm(t2,u2)
nipkow@427
  1387
  | vperm(t,u) = (t=u);
nipkow@288
  1388
nipkow@427
  1389
fun var_perm(t,u) = vperm(t,u) andalso
nipkow@427
  1390
                    eq_set(add_term_vars(t,[]), add_term_vars(u,[]))
nipkow@288
  1391
clasohm@0
  1392
(*simple test for looping rewrite*)
clasohm@0
  1393
fun loops sign prems (lhs,rhs) =
nipkow@1023
  1394
   is_Var(lhs)
nipkow@1023
  1395
  orelse
nipkow@1023
  1396
   (exists (apl(lhs, Logic.occs)) (rhs::prems))
nipkow@1023
  1397
  orelse
nipkow@1023
  1398
   (null(prems) andalso
nipkow@1023
  1399
    Pattern.matches (#tsig(Sign.rep_sg sign)) (lhs,rhs));
nipkow@1028
  1400
(* the condition "null(prems)" in the last case is necessary because
nipkow@1028
  1401
   conditional rewrites with extra variables in the conditions may terminate
nipkow@1028
  1402
   although the rhs is an instance of the lhs. Example:
nipkow@1028
  1403
   ?m < ?n ==> f(?n) == f(?m)
nipkow@1028
  1404
*)
clasohm@0
  1405
wenzelm@1238
  1406
fun mk_rrule raw_thm =
wenzelm@1238
  1407
  let
wenzelm@1258
  1408
      val thm = strip_shyps raw_thm;
wenzelm@1238
  1409
      val Thm{sign,prop,maxidx,...} = thm;
wenzelm@1238
  1410
      val prems = Logic.strip_imp_prems prop
nipkow@678
  1411
      val concl = Logic.strip_imp_concl prop
nipkow@678
  1412
      val (lhs,_) = Logic.dest_equals concl handle TERM _ =>
clasohm@0
  1413
                      raise SIMPLIFIER("Rewrite rule not a meta-equality",thm)
nipkow@678
  1414
      val econcl = Pattern.eta_contract concl
nipkow@678
  1415
      val (elhs,erhs) = Logic.dest_equals econcl
nipkow@678
  1416
      val perm = var_perm(elhs,erhs) andalso not(elhs aconv erhs)
nipkow@678
  1417
                                     andalso not(is_Var(elhs))
wenzelm@1220
  1418
  in
wenzelm@1258
  1419
     if not perm andalso loops sign prems (elhs,erhs) then
berghofe@1580
  1420
       (prtm_warning "ignoring looping rewrite rule" sign prop; None)
nipkow@288
  1421
     else Some{thm=thm,lhs=lhs,perm=perm}
clasohm@0
  1422
  end;
clasohm@0
  1423
nipkow@87
  1424
local
nipkow@87
  1425
 fun eq({thm=Thm{prop=p1,...},...}:rrule,
nipkow@87
  1426
        {thm=Thm{prop=p2,...},...}:rrule) = p1 aconv p2
nipkow@87
  1427
in
nipkow@87
  1428
nipkow@405
  1429
fun add_simp(mss as Mss{net,congs,bounds,prems,mk_rews},
clasohm@0
  1430
             thm as Thm{sign,prop,...}) =
nipkow@87
  1431
  case mk_rrule thm of
nipkow@87
  1432
    None => mss
nipkow@87
  1433
  | Some(rrule as {lhs,...}) =>
nipkow@209
  1434
      (trace_thm "Adding rewrite rule:" thm;
paulson@1529
  1435
       Mss{net = (Net.insert_term((lhs,rrule),net,eq)
nipkow@209
  1436
                 handle Net.INSERT =>
berghofe@1580
  1437
                  (prtm_warning "ignoring duplicate rewrite rule" sign prop;
nipkow@87
  1438
                   net)),
nipkow@405
  1439
           congs=congs, bounds=bounds, prems=prems,mk_rews=mk_rews});
nipkow@87
  1440
nipkow@405
  1441
fun del_simp(mss as Mss{net,congs,bounds,prems,mk_rews},
nipkow@87
  1442
             thm as Thm{sign,prop,...}) =
nipkow@87
  1443
  case mk_rrule thm of
nipkow@87
  1444
    None => mss
nipkow@87
  1445
  | Some(rrule as {lhs,...}) =>
paulson@1529
  1446
      Mss{net = (Net.delete_term((lhs,rrule),net,eq)
nipkow@87
  1447
                handle Net.INSERT =>
berghofe@1580
  1448
                 (prtm_warning "rewrite rule not in simpset" sign prop;
nipkow@87
  1449
                  net)),
nipkow@405
  1450
             congs=congs, bounds=bounds, prems=prems,mk_rews=mk_rews}
nipkow@87
  1451
nipkow@87
  1452
end;
clasohm@0
  1453
clasohm@0
  1454
val add_simps = foldl add_simp;
nipkow@87
  1455
val del_simps = foldl del_simp;
clasohm@0
  1456
clasohm@0
  1457
fun mss_of thms = add_simps(empty_mss,thms);
clasohm@0
  1458
nipkow@405
  1459
fun add_cong(Mss{net,congs,bounds,prems,mk_rews},thm) =
clasohm@0
  1460
  let val (lhs,_) = Logic.dest_equals(concl_of thm) handle TERM _ =>
clasohm@0
  1461
                    raise SIMPLIFIER("Congruence not a meta-equality",thm)
nipkow@678
  1462
(*      val lhs = Pattern.eta_contract lhs*)
clasohm@0
  1463
      val (a,_) = dest_Const (head_of lhs) handle TERM _ =>
clasohm@0
  1464
                  raise SIMPLIFIER("Congruence must start with a constant",thm)
nipkow@405
  1465
  in Mss{net=net, congs=(a,{lhs=lhs,thm=thm})::congs, bounds=bounds,
clasohm@0
  1466
         prems=prems, mk_rews=mk_rews}
clasohm@0
  1467
  end;
clasohm@0
  1468
clasohm@0
  1469
val (op add_congs) = foldl add_cong;
clasohm@0
  1470
nipkow@405
  1471
fun add_prems(Mss{net,congs,bounds,prems,mk_rews},thms) =
nipkow@405
  1472
  Mss{net=net, congs=congs, bounds=bounds, prems=thms@prems, mk_rews=mk_rews};
clasohm@0
  1473
clasohm@0
  1474
fun prems_of_mss(Mss{prems,...}) = prems;
clasohm@0
  1475
nipkow@405
  1476
fun set_mk_rews(Mss{net,congs,bounds,prems,...},mk_rews) =
nipkow@405
  1477
  Mss{net=net, congs=congs, bounds=bounds, prems=prems, mk_rews=mk_rews};
clasohm@0
  1478
fun mk_rews_of_mss(Mss{mk_rews,...}) = mk_rews;
clasohm@0
  1479
clasohm@0
  1480
wenzelm@250
  1481
(*** Meta-level rewriting
clasohm@0
  1482
     uses conversions, omitting proofs for efficiency.  See
wenzelm@250
  1483
        L C Paulson, A higher-order implementation of rewriting,
wenzelm@250
  1484
        Science of Computer Programming 3 (1983), pages 119-149. ***)
clasohm@0
  1485
clasohm@0
  1486
type prover = meta_simpset -> thm -> thm option;
clasohm@0
  1487
type termrec = (Sign.sg * term list) * term;
clasohm@0
  1488
type conv = meta_simpset -> termrec -> termrec;
clasohm@0
  1489
nipkow@305
  1490
datatype order = LESS | EQUAL | GREATER;
nipkow@288
  1491
nipkow@305
  1492
fun stringord(a,b:string) = if a<b then LESS  else
nipkow@305
  1493
                            if a=b then EQUAL else GREATER;
nipkow@305
  1494
nipkow@305
  1495
fun intord(i,j:int) = if i<j then LESS  else
nipkow@305
  1496
                      if i=j then EQUAL else GREATER;
nipkow@288
  1497
nipkow@427
  1498
(* NB: non-linearity of the ordering is not a soundness problem *)
nipkow@427
  1499
nipkow@305
  1500
(* FIXME: "***ABSTRACTION***" is a hack and makes the ordering non-linear *)
nipkow@305
  1501
fun string_of_hd(Const(a,_)) = a
nipkow@305
  1502
  | string_of_hd(Free(a,_))  = a
nipkow@305
  1503
  | string_of_hd(Var(v,_))   = Syntax.string_of_vname v
nipkow@305
  1504
  | string_of_hd(Bound i)    = string_of_int i
nipkow@305
  1505
  | string_of_hd(Abs _)      = "***ABSTRACTION***";
nipkow@288
  1506
nipkow@305
  1507
(* a strict (not reflexive) linear well-founded AC-compatible ordering
nipkow@305
  1508
 * for terms:
nipkow@305
  1509
 * s < t <=> 1. size(s) < size(t) or
nipkow@305
  1510
             2. size(s) = size(t) and s=f(...) and t = g(...) and f<g or
nipkow@305
  1511
             3. size(s) = size(t) and s=f(s1..sn) and t=f(t1..tn) and
nipkow@305
  1512
                (s1..sn) < (t1..tn) (lexicographically)
nipkow@305
  1513
 *)
nipkow@288
  1514
nipkow@288
  1515
(* FIXME: should really take types into account as well.
nipkow@427
  1516
 * Otherwise non-linear *)
nipkow@622
  1517
fun termord(Abs(_,_,t),Abs(_,_,u)) = termord(t,u)
nipkow@622
  1518
  | termord(t,u) =
nipkow@305
  1519
      (case intord(size_of_term t,size_of_term u) of
nipkow@305
  1520
         EQUAL => let val (f,ts) = strip_comb t and (g,us) = strip_comb u
nipkow@305
  1521
                  in case stringord(string_of_hd f, string_of_hd g) of
nipkow@305
  1522
                       EQUAL => lextermord(ts,us)
nipkow@305
  1523
                     | ord   => ord
nipkow@305
  1524
                  end
nipkow@305
  1525
       | ord => ord)
nipkow@305
  1526
and lextermord(t::ts,u::us) =
nipkow@305
  1527
      (case termord(t,u) of
nipkow@305
  1528
         EQUAL => lextermord(ts,us)
nipkow@305
  1529
       | ord   => ord)
nipkow@305
  1530
  | lextermord([],[]) = EQUAL
nipkow@305
  1531
  | lextermord _ = error("lextermord");
nipkow@288
  1532
nipkow@305
  1533
fun termless tu = (termord tu = LESS);
nipkow@288
  1534
paulson@1529
  1535
fun check_conv (thm as Thm{shyps,hyps,prop,sign,der,maxidx,...}, prop0, ders) =
nipkow@432
  1536
  let fun err() = (trace_thm "Proved wrong thm (Check subgoaler?)" thm;
nipkow@432
  1537
                   trace_term "Should have proved" sign prop0;
nipkow@432
  1538
                   None)
clasohm@0
  1539
      val (lhs0,_) = Logic.dest_equals(Logic.strip_imp_concl prop0)
clasohm@0
  1540
  in case prop of
clasohm@0
  1541
       Const("==",_) $ lhs $ rhs =>
clasohm@0
  1542
         if (lhs = lhs0) orelse
nipkow@427
  1543
            (lhs aconv Envir.norm_term (Envir.empty 0) lhs0)
paulson@1529
  1544
         then (trace_thm "SUCCEEDED" thm; 
paulson@1529
  1545
	       Some(shyps, hyps, maxidx, rhs, der::ders))
clasohm@0
  1546
         else err()
clasohm@0
  1547
     | _ => err()
clasohm@0
  1548
  end;
clasohm@0
  1549
nipkow@659
  1550
fun ren_inst(insts,prop,pat,obj) =
nipkow@659
  1551
  let val ren = match_bvs(pat,obj,[])
nipkow@659
  1552
      fun renAbs(Abs(x,T,b)) =
berghofe@1576
  1553
            Abs(case assoc_string(ren,x) of None => x | Some(y) => y, T, renAbs(b))
nipkow@659
  1554
        | renAbs(f$t) = renAbs(f) $ renAbs(t)
nipkow@659
  1555
        | renAbs(t) = t
nipkow@659
  1556
  in subst_vars insts (if null(ren) then prop else renAbs(prop)) end;
nipkow@678
  1557
wenzelm@1258
  1558
fun add_insts_sorts ((iTs, is), Ss) =
wenzelm@1258
  1559
  add_typs_sorts (map snd iTs, add_terms_sorts (map snd is, Ss));
wenzelm@1258
  1560
nipkow@659
  1561
clasohm@0
  1562
(*Conversion to apply the meta simpset to a term*)
paulson@1529
  1563
fun rewritec (prover,signt) (mss as Mss{net,...}) 
paulson@1529
  1564
             (shypst,hypst,maxidxt,t,ders) =
nipkow@678
  1565
  let val etat = Pattern.eta_contract t;
paulson@1529
  1566
      fun rew {thm as Thm{sign,der,maxidx,shyps,hyps,prop,...}, lhs, perm} =
wenzelm@250
  1567
        let val unit = if Sign.subsig(sign,signt) then ()
berghofe@1580
  1568
                  else (trace_thm_warning "rewrite rule from different theory"
clasohm@446
  1569
                          thm;
nipkow@208
  1570
                        raise Pattern.MATCH)
nipkow@1065
  1571
            val rprop = if maxidxt = ~1 then prop
nipkow@1065
  1572
                        else Logic.incr_indexes([],maxidxt+1) prop;
nipkow@1065
  1573
            val rlhs = if maxidxt = ~1 then lhs
nipkow@1065
  1574
                       else fst(Logic.dest_equals(Logic.strip_imp_concl rprop))
nipkow@1065
  1575
            val insts = Pattern.match (#tsig(Sign.rep_sg signt)) (rlhs,etat)
nipkow@1065
  1576
            val prop' = ren_inst(insts,rprop,rlhs,t);
clasohm@0
  1577
            val hyps' = hyps union hypst;
wenzelm@1258
  1578
            val shyps' = add_insts_sorts (insts, shyps union shypst);
nipkow@1065
  1579
            val maxidx' = maxidx_of_term prop'
paulson@1529
  1580
            val ct' = Cterm{sign = signt,	(*used for deriv only*)
paulson@1529
  1581
			    t = prop',
paulson@1529
  1582
			    T = propT,
paulson@1529
  1583
			    maxidx = maxidx'}
paulson@1529
  1584
	    val der' = infer_derivs (RewriteC ct', [der])
paulson@1529
  1585
            val thm' = Thm{sign = signt, 
paulson@1529
  1586
			   der = der',
paulson@1529
  1587
			   shyps = shyps',
paulson@1529
  1588
			   hyps = hyps',
paulson@1529
  1589
                           prop = prop',
paulson@1529
  1590
			   maxidx = maxidx'}
nipkow@427
  1591
            val (lhs',rhs') = Logic.dest_equals(Logic.strip_imp_concl prop')
nipkow@427
  1592
        in if perm andalso not(termless(rhs',lhs')) then None else
nipkow@427
  1593
           if Logic.count_prems(prop',0) = 0
paulson@1529
  1594
           then (trace_thm "Rewriting:" thm'; 
paulson@1529
  1595
		 Some(shyps', hyps', maxidx', rhs', der'::ders))
clasohm@0
  1596
           else (trace_thm "Trying to rewrite:" thm';
clasohm@0
  1597
                 case prover mss thm' of
clasohm@0
  1598
                   None       => (trace_thm "FAILED" thm'; None)
paulson@1529
  1599
                 | Some(thm2) => check_conv(thm2,prop',ders))
clasohm@0
  1600
        end
clasohm@0
  1601
nipkow@225
  1602
      fun rews [] = None
nipkow@225
  1603
        | rews (rrule::rrules) =
nipkow@225
  1604
            let val opt = rew rrule handle Pattern.MATCH => None
nipkow@225
  1605
            in case opt of None => rews rrules | some => some end;
clasohm@0
  1606
nipkow@678
  1607
  in case etat of
paulson@1529
  1608
       Abs(_,_,body) $ u => Some(shypst, hypst, maxidxt, 
paulson@1529
  1609
				 subst_bounds([u], body),
paulson@1529
  1610
				 ders)
nipkow@678
  1611
     | _                 => rews(Net.match_term net etat)
clasohm@0
  1612
  end;
clasohm@0
  1613
clasohm@0
  1614
(*Conversion to apply a congruence rule to a term*)
paulson@1529
  1615
fun congc (prover,signt) {thm=cong,lhs=lhs} (shypst,hypst,maxidxt,t,ders) =
paulson@1529
  1616
  let val Thm{sign,der,shyps,hyps,maxidx,prop,...} = cong
nipkow@208
  1617
      val unit = if Sign.subsig(sign,signt) then ()
nipkow@208
  1618
                 else error("Congruence rule from different theory")
nipkow@208
  1619
      val tsig = #tsig(Sign.rep_sg signt)
nipkow@1065
  1620
      val rprop = if maxidxt = ~1 then prop
nipkow@1065
  1621
                  else Logic.incr_indexes([],maxidxt+1) prop;
nipkow@1065
  1622
      val rlhs = if maxidxt = ~1 then lhs
nipkow@1065
  1623
                 else fst(Logic.dest_equals(Logic.strip_imp_concl rprop))
nipkow@1569
  1624
      val insts = Pattern.match tsig (rlhs,t)
nipkow@1569
  1625
      (* Pattern.match can raise Pattern.MATCH;
nipkow@1569
  1626
         is handled when congc is called *)
nipkow@1065
  1627
      val prop' = ren_inst(insts,rprop,rlhs,t);
paulson@1529
  1628
      val shyps' = add_insts_sorts (insts, shyps union shypst)
paulson@1529
  1629
      val maxidx' = maxidx_of_term prop'
paulson@1529
  1630
      val ct' = Cterm{sign = signt,	(*used for deriv only*)
paulson@1529
  1631
		      t = prop',
paulson@1529
  1632
		      T = propT,
paulson@1529
  1633
		      maxidx = maxidx'}
paulson@1529
  1634
      val thm' = Thm{sign = signt, 
paulson@1529
  1635
		     der = infer_derivs (CongC ct', [der]),
paulson@1529
  1636
		     shyps = shyps',
paulson@1529
  1637
		     hyps = hyps union hypst,
paulson@1529
  1638
                     prop = prop',
paulson@1529
  1639
		     maxidx = maxidx'};
clasohm@0
  1640
      val unit = trace_thm "Applying congruence rule" thm';
nipkow@112
  1641
      fun err() = error("Failed congruence proof!")
clasohm@0
  1642
clasohm@0
  1643
  in case prover thm' of
nipkow@112
  1644
       None => err()
paulson@1529
  1645
     | Some(thm2) => (case check_conv(thm2,prop',ders) of
nipkow@405
  1646
                        None => err() | some => some)
clasohm@0
  1647
  end;
clasohm@0
  1648
clasohm@0
  1649
nipkow@405
  1650
nipkow@214
  1651
fun bottomc ((simprem,useprem),prover,sign) =
paulson@1529
  1652
 let fun botc fail mss trec =
paulson@1529
  1653
	  (case subc mss trec of
paulson@1529
  1654
	     some as Some(trec1) =>
paulson@1529
  1655
	       (case rewritec (prover,sign) mss trec1 of
paulson@1529
  1656
		  Some(trec2) => botc false mss trec2
paulson@1529
  1657
		| None => some)
paulson@1529
  1658
	   | None =>
paulson@1529
  1659
	       (case rewritec (prover,sign) mss trec of
paulson@1529
  1660
		  Some(trec2) => botc false mss trec2
paulson@1529
  1661
		| None => if fail then None else Some(trec)))
clasohm@0
  1662
paulson@1529
  1663
     and try_botc mss trec = (case botc true mss trec of
paulson@1529
  1664
				Some(trec1) => trec1
paulson@1529
  1665
			      | None => trec)
nipkow@405
  1666
paulson@1529
  1667
     and subc (mss as Mss{net,congs,bounds,prems,mk_rews})
paulson@1529
  1668
	      (trec as (shyps,hyps,maxidx,t0,ders)) =
paulson@1529
  1669
       (case t0 of
paulson@1529
  1670
	   Abs(a,T,t) =>
paulson@1529
  1671
	     let val b = variant bounds a
paulson@1529
  1672
		 val v = Free("." ^ b,T)
paulson@1529
  1673
		 val mss' = Mss{net=net, congs=congs, bounds=b::bounds,
paulson@1529
  1674
				prems=prems,mk_rews=mk_rews}
paulson@1529
  1675
	     in case botc true mss' 
paulson@1529
  1676
		       (shyps,hyps,maxidx,subst_bounds([v],t),ders) of
paulson@1529
  1677
		  Some(shyps',hyps',maxidx',t',ders') =>
paulson@1529
  1678
		    Some(shyps', hyps', maxidx',
paulson@1529
  1679
			 Abs(a, T, abstract_over(v,t')),
paulson@1529
  1680
			 ders')
paulson@1529
  1681
		| None => None
paulson@1529
  1682
	     end
paulson@1529
  1683
	 | t$u => (case t of
paulson@1529
  1684
	     Const("==>",_)$s  => Some(impc(shyps,hyps,maxidx,s,u,mss,ders))
paulson@1529
  1685
	   | Abs(_,_,body) =>
paulson@1529
  1686
	       let val trec = (shyps,hyps,maxidx,subst_bounds([u],body),ders)
paulson@1529
  1687
	       in case subc mss trec of
paulson@1529
  1688
		    None => Some(trec)
paulson@1529
  1689
		  | trec => trec
paulson@1529
  1690
	       end
paulson@1529
  1691
	   | _  =>
paulson@1529
  1692
	       let fun appc() =
paulson@1529
  1693
		     (case botc true mss (shyps,hyps,maxidx,t,ders) of
paulson@1529
  1694
			Some(shyps1,hyps1,maxidx1,t1,ders1) =>
paulson@1529
  1695
			  (case botc true mss (shyps1,hyps1,maxidx,u,ders1) of
paulson@1529
  1696
			     Some(shyps2,hyps2,maxidx2,u1,ders2) =>
paulson@1529
  1697
			       Some(shyps2, hyps2, max[maxidx1,maxidx2],
paulson@1529
  1698
				    t1$u1, ders2)
paulson@1529
  1699
			   | None =>
paulson@1529
  1700
			       Some(shyps1, hyps1, max[maxidx1,maxidx], t1$u,
paulson@1529
  1701
				    ders1))
paulson@1529
  1702
		      | None =>
paulson@1529
  1703
			  (case botc true mss (shyps,hyps,maxidx,u,ders) of
paulson@1529
  1704
			     Some(shyps1,hyps1,maxidx1,u1,ders1) =>
paulson@1529
  1705
			       Some(shyps1, hyps1, max[maxidx,maxidx1], 
paulson@1529
  1706
				    t$u1, ders1)
paulson@1529
  1707
			   | None => None))
paulson@1529
  1708
		   val (h,ts) = strip_comb t
paulson@1529
  1709
	       in case h of
paulson@1529
  1710
		    Const(a,_) =>
berghofe@1576
  1711
		      (case assoc_string(congs,a) of
paulson@1529
  1712
			 None => appc()
nipkow@1569
  1713
		       | Some(cong) => (congc (prover mss,sign) cong trec
nipkow@1569
  1714
                                        handle Pattern.MATCH => appc() ) )
paulson@1529
  1715
		  | _ => appc()
paulson@1529
  1716
	       end)
paulson@1529
  1717
	 | _ => None)
clasohm@0
  1718
paulson@1529
  1719
     and impc(shyps, hyps, maxidx, s, u, mss as Mss{mk_rews,...}, ders) =
paulson@1529
  1720
       let val (shyps1,hyps1,_,s1,ders1) =
paulson@1529
  1721
	     if simprem then try_botc mss (shyps,hyps,maxidx,s,ders)
paulson@1529
  1722
	                else (shyps,hyps,0,s,ders);
paulson@1529
  1723
	   val maxidx1 = maxidx_of_term s1
paulson@1529
  1724
	   val mss1 =
paulson@1529
  1725
	     if not useprem orelse maxidx1 <> ~1 then mss
paulson@1529
  1726
	     else let val thm = assume (Cterm{sign=sign, t=s1, 
paulson@1529
  1727
					      T=propT, maxidx=maxidx1})
paulson@1529
  1728
		  in add_simps(add_prems(mss,[thm]), mk_rews thm) end
paulson@1529
  1729
	   val (shyps2,hyps2,maxidx2,u1,ders2) = 
paulson@1529
  1730
	       try_botc mss1 (shyps1,hyps1,maxidx,u,ders1)
paulson@1529
  1731
	   val hyps3 = if s1 mem hyps1 then hyps2 else hyps2\s1
paulson@1529
  1732
       in (shyps2, hyps3, max[maxidx1,maxidx2], 
paulson@1529
  1733
	   Logic.mk_implies(s1,u1), ders2) 
paulson@1529
  1734
       end
clasohm@0
  1735
paulson@1529
  1736
 in try_botc end;
clasohm@0
  1737
clasohm@0
  1738
clasohm@0
  1739
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
clasohm@0
  1740
(* Parameters:
wenzelm@250
  1741
   mode = (simplify A, use A in simplifying B) when simplifying A ==> B
clasohm@0
  1742
   mss: contains equality theorems of the form [|p1,...|] ==> t==u
clasohm@0
  1743
   prover: how to solve premises in conditional rewrites and congruences
clasohm@0
  1744
*)
nipkow@405
  1745
(*** FIXME: check that #bounds(mss) does not "occur" in ct alread ***)
nipkow@214
  1746
fun rewrite_cterm mode mss prover ct =
lcp@229
  1747
  let val {sign, t, T, maxidx} = rep_cterm ct;
paulson@1529
  1748
      val (shyps,hyps,maxidxu,u,ders) =
paulson@1529
  1749
        bottomc (mode,prover,sign) mss 
paulson@1529
  1750
	        (add_term_sorts(t,[]), [], maxidx, t, []);
clasohm@0
  1751
      val prop = Logic.mk_equals(t,u)
wenzelm@1258
  1752
  in
paulson@1529
  1753
      Thm{sign = sign, 
paulson@1529
  1754
	  der = infer_derivs (Rewrite_cterm ct, ders),
paulson@1529
  1755
	  maxidx = max[maxidx,maxidxu],
paulson@1529
  1756
	  shyps = shyps, 
paulson@1529
  1757
	  hyps = hyps, 
paulson@1529
  1758
          prop = prop}
clasohm@0
  1759
  end
clasohm@0
  1760
paulson@1539
  1761
paulson@1539
  1762
fun invoke_oracle (thy, sign, exn) =
paulson@1539
  1763
    case #oraopt(rep_theory thy) of
paulson@1539
  1764
	None => raise THM ("No oracle in supplied theory", 0, [])
paulson@1539
  1765
      | Some oracle => 
paulson@1539
  1766
	    let val sign' = Sign.merge(sign_of thy, sign)
paulson@1539
  1767
		val (prop, T, maxidx) = 
paulson@1539
  1768
		    Sign.certify_term sign' (oracle (sign', exn))
paulson@1539
  1769
            in if T<>propT then
paulson@1539
  1770
                  raise THM("Oracle's result must have type prop", 0, [])
paulson@1539
  1771
	       else fix_shyps [] []
paulson@1539
  1772
		     (Thm {sign = sign', 
paulson@1597
  1773
			   der = Join (Oracle(thy,sign,exn), []),
paulson@1539
  1774
			   maxidx = maxidx,
paulson@1539
  1775
			   shyps = [], 
paulson@1539
  1776
			   hyps = [], 
paulson@1539
  1777
			   prop = prop})
paulson@1539
  1778
            end;
paulson@1539
  1779
clasohm@0
  1780
end;
paulson@1503
  1781
paulson@1503
  1782
open Thm;