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