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