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