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