src/Pure/thm.ML
author nipkow
Wed Jan 05 19:33:56 1994 +0100 (1994-01-05)
changeset 214 ed6a3e2b1a33
parent 209 feb8ff35810a
child 219 a2447b00517b
permissions -rw-r--r--
added new parameter to the simplification tactics which indicates if
assumptions are to be simplified and/or to be used when simplifying the
conclusion. This gets rid of METAHYPS and speeds up simplification of goals
with big assumptions.
clasohm@0
     1
(*  Title: 	thm
clasohm@0
     2
    ID:         $Id$
clasohm@0
     3
    Author: 	Lawrence C Paulson, Cambridge University Computer Laboratory
clasohm@0
     4
    Copyright   1991  University of Cambridge
clasohm@0
     5
clasohm@0
     6
The abstract types "theory" and "thm"
clasohm@0
     7
*)
clasohm@0
     8
clasohm@0
     9
signature THM = 
clasohm@0
    10
  sig
clasohm@0
    11
  structure Envir : ENVIR
clasohm@0
    12
  structure Sequence : SEQUENCE
clasohm@0
    13
  structure Sign : SIGN
clasohm@0
    14
  type meta_simpset
clasohm@0
    15
  type theory
clasohm@0
    16
  type thm
clasohm@0
    17
  exception THM of string * int * thm list
clasohm@0
    18
  exception THEORY of string * theory list
clasohm@0
    19
  exception SIMPLIFIER of string * thm
clasohm@0
    20
  val abstract_rule: string -> Sign.cterm -> thm -> thm
clasohm@0
    21
  val add_congs: meta_simpset * thm list -> meta_simpset
clasohm@0
    22
  val add_prems: meta_simpset * thm list -> meta_simpset
clasohm@0
    23
  val add_simps: meta_simpset * thm list -> meta_simpset
clasohm@0
    24
  val assume: Sign.cterm -> thm
clasohm@0
    25
  val assumption: int -> thm -> thm Sequence.seq   
clasohm@0
    26
  val axioms_of: theory -> (string * thm) list
clasohm@0
    27
  val beta_conversion: Sign.cterm -> thm   
clasohm@0
    28
  val bicompose: bool -> bool * thm * int -> int -> thm -> thm Sequence.seq   
clasohm@0
    29
  val biresolution: bool -> (bool*thm)list -> int -> thm -> thm Sequence.seq   
clasohm@0
    30
  val combination: thm -> thm -> thm   
clasohm@0
    31
  val concl_of: thm -> term   
nipkow@87
    32
  val del_simps: meta_simpset * thm list -> meta_simpset
clasohm@0
    33
  val dest_state: thm * int -> (term*term)list * term list * term * term
clasohm@0
    34
  val empty_mss: meta_simpset
clasohm@0
    35
  val eq_assumption: int -> thm -> thm   
clasohm@0
    36
  val equal_intr: thm -> thm -> thm
clasohm@0
    37
  val equal_elim: thm -> thm -> thm
clasohm@0
    38
  val extend_theory: theory -> string
clasohm@0
    39
	-> (class * class list) list * sort
clasohm@0
    40
	   * (string list * int)list
nipkow@200
    41
           * (string * indexname list * string) list
clasohm@0
    42
	   * (string list * (sort list * class))list
clasohm@0
    43
	   * (string list * string)list * Sign.Syntax.sext option
clasohm@0
    44
	-> (string*string)list -> theory
clasohm@0
    45
  val extensional: thm -> thm   
clasohm@0
    46
  val flexflex_rule: thm -> thm Sequence.seq  
clasohm@0
    47
  val flexpair_def: thm 
clasohm@0
    48
  val forall_elim: Sign.cterm -> thm -> thm
clasohm@0
    49
  val forall_intr: Sign.cterm -> thm -> thm
clasohm@0
    50
  val freezeT: thm -> thm
clasohm@0
    51
  val get_axiom: theory -> string -> thm
clasohm@0
    52
  val implies_elim: thm -> thm -> thm
clasohm@0
    53
  val implies_intr: Sign.cterm -> thm -> thm
clasohm@0
    54
  val implies_intr_hyps: thm -> thm
clasohm@0
    55
  val instantiate: (indexname*Sign.ctyp)list * (Sign.cterm*Sign.cterm)list 
clasohm@0
    56
                   -> thm -> thm
clasohm@0
    57
  val lift_rule: (thm * int) -> thm -> thm
clasohm@0
    58
  val merge_theories: theory * theory -> theory
clasohm@0
    59
  val mk_rews_of_mss: meta_simpset -> thm -> thm list
clasohm@0
    60
  val mss_of: thm list -> meta_simpset
clasohm@0
    61
  val nprems_of: thm -> int
clasohm@0
    62
  val parents_of: theory -> theory list
clasohm@0
    63
  val prems_of: thm -> term list
clasohm@0
    64
  val prems_of_mss: meta_simpset -> thm list
clasohm@0
    65
  val pure_thy: theory
clasohm@0
    66
  val reflexive: Sign.cterm -> thm 
clasohm@0
    67
  val rename_params_rule: string list * int -> thm -> thm
clasohm@0
    68
  val rep_thm: thm -> {prop: term, hyps: term list, maxidx: int, sign: Sign.sg}
nipkow@214
    69
  val rewrite_cterm:
nipkow@214
    70
         bool*bool -> meta_simpset -> (meta_simpset -> thm -> thm option)
nipkow@214
    71
           -> Sign.cterm -> thm
clasohm@0
    72
  val set_mk_rews: meta_simpset * (thm -> thm list) -> meta_simpset
clasohm@0
    73
  val sign_of: theory -> Sign.sg   
clasohm@0
    74
  val syn_of: theory -> Sign.Syntax.syntax
clasohm@0
    75
  val stamps_of_thm: thm -> string ref list
clasohm@0
    76
  val stamps_of_thy: theory -> string ref list
clasohm@0
    77
  val symmetric: thm -> thm   
clasohm@0
    78
  val tpairs_of: thm -> (term*term)list
clasohm@0
    79
  val trace_simp: bool ref
clasohm@0
    80
  val transitive: thm -> thm -> thm
clasohm@0
    81
  val trivial: Sign.cterm -> thm
clasohm@0
    82
  val varifyT: thm -> thm
clasohm@0
    83
  end;
clasohm@0
    84
clasohm@0
    85
clasohm@0
    86
clasohm@0
    87
functor ThmFun (structure Logic: LOGIC and Unify: UNIFY and Pattern:PATTERN
clasohm@0
    88
                      and Net:NET
clasohm@0
    89
                sharing type Pattern.type_sig = Unify.Sign.Type.type_sig)
clasohm@0
    90
        : THM = 
clasohm@0
    91
struct
clasohm@0
    92
structure Sequence = Unify.Sequence;
clasohm@0
    93
structure Envir = Unify.Envir;
clasohm@0
    94
structure Sign = Unify.Sign;
clasohm@0
    95
structure Type = Sign.Type;
clasohm@0
    96
structure Syntax = Sign.Syntax;
clasohm@0
    97
structure Symtab = Sign.Symtab;
clasohm@0
    98
clasohm@0
    99
clasohm@0
   100
(*Meta-theorems*)
clasohm@0
   101
datatype thm = Thm of
clasohm@0
   102
    {sign: Sign.sg,  maxidx: int,  hyps: term list,  prop: term};
clasohm@0
   103
clasohm@0
   104
fun rep_thm (Thm x) = x;
clasohm@0
   105
clasohm@0
   106
(*Errors involving theorems*)
clasohm@0
   107
exception THM of string * int * thm list;
clasohm@0
   108
clasohm@0
   109
(*maps object-rule to tpairs *)
clasohm@0
   110
fun tpairs_of (Thm{prop,...}) = #1 (Logic.strip_flexpairs prop);
clasohm@0
   111
clasohm@0
   112
(*maps object-rule to premises *)
clasohm@0
   113
fun prems_of (Thm{prop,...}) =
clasohm@0
   114
    Logic.strip_imp_prems (Logic.skip_flexpairs prop);
clasohm@0
   115
clasohm@0
   116
(*counts premises in a rule*)
clasohm@0
   117
fun nprems_of (Thm{prop,...}) =
clasohm@0
   118
    Logic.count_prems (Logic.skip_flexpairs prop, 0);
clasohm@0
   119
clasohm@0
   120
(*maps object-rule to conclusion *)
clasohm@0
   121
fun concl_of (Thm{prop,...}) = Logic.strip_imp_concl prop;
clasohm@0
   122
clasohm@0
   123
(*Stamps associated with a signature*)
clasohm@0
   124
val stamps_of_thm = #stamps o Sign.rep_sg o #sign o rep_thm;
clasohm@0
   125
clasohm@0
   126
(*Theories.  There is one pure theory.
clasohm@0
   127
  A theory can be extended.  Two theories can be merged.*)
clasohm@0
   128
datatype theory =
clasohm@0
   129
    Pure of {sign: Sign.sg}
clasohm@0
   130
  | Extend of {sign: Sign.sg,  axioms: thm Symtab.table,  thy: theory}
clasohm@0
   131
  | Merge of {sign: Sign.sg,  thy1: theory,  thy2: theory};
clasohm@0
   132
clasohm@0
   133
(*Errors involving theories*)
clasohm@0
   134
exception THEORY of string * theory list;
clasohm@0
   135
clasohm@0
   136
fun sign_of (Pure {sign}) = sign
clasohm@0
   137
  | sign_of (Extend {sign,...}) = sign
clasohm@0
   138
  | sign_of (Merge {sign,...}) = sign;
clasohm@0
   139
clasohm@0
   140
val syn_of = #syn o Sign.rep_sg o sign_of;
clasohm@0
   141
clasohm@0
   142
(*return the axioms of a theory and its ancestors*)
clasohm@0
   143
fun axioms_of (Pure _) = []
clasohm@0
   144
  | axioms_of (Extend{axioms,thy,...}) = Symtab.alist_of axioms
clasohm@0
   145
  | axioms_of (Merge{thy1,thy2,...}) = axioms_of thy1  @  axioms_of thy2;
clasohm@0
   146
clasohm@0
   147
(*return the immediate ancestors -- also distinguishes the kinds of theories*)
clasohm@0
   148
fun parents_of (Pure _) = []
clasohm@0
   149
  | parents_of (Extend{thy,...}) = [thy]
clasohm@0
   150
  | parents_of (Merge{thy1,thy2,...}) = [thy1,thy2];
clasohm@0
   151
clasohm@0
   152
clasohm@0
   153
(*Merge theories of two theorems.  Raise exception if incompatible.
clasohm@0
   154
  Prefers (via Sign.merge) the signature of th1.  *)
clasohm@0
   155
fun merge_theories(th1,th2) =
clasohm@0
   156
  let val Thm{sign=sign1,...} = th1 and Thm{sign=sign2,...} = th2
clasohm@0
   157
  in  Sign.merge (sign1,sign2)  end
clasohm@0
   158
  handle TERM _ => raise THM("incompatible signatures", 0, [th1,th2]);
clasohm@0
   159
clasohm@0
   160
(*Stamps associated with a theory*)
clasohm@0
   161
val stamps_of_thy = #stamps o Sign.rep_sg o sign_of;
clasohm@0
   162
clasohm@0
   163
clasohm@0
   164
(**** Primitive rules ****)
clasohm@0
   165
clasohm@0
   166
(* discharge all assumptions t from ts *)
clasohm@0
   167
val disch = gen_rem (op aconv);
clasohm@0
   168
clasohm@0
   169
(*The assumption rule A|-A in a theory  *)
clasohm@0
   170
fun assume ct : thm = 
clasohm@0
   171
  let val {sign, t=prop, T, maxidx} = Sign.rep_cterm ct
clasohm@0
   172
  in  if T<>propT then  
clasohm@0
   173
	raise THM("assume: assumptions must have type prop", 0, [])
clasohm@0
   174
      else if maxidx <> ~1 then
clasohm@0
   175
	raise THM("assume: assumptions may not contain scheme variables", 
clasohm@0
   176
		  maxidx, [])
clasohm@0
   177
      else Thm{sign = sign, maxidx = ~1, hyps = [prop], prop = prop}
clasohm@0
   178
  end;
clasohm@0
   179
clasohm@0
   180
(* Implication introduction  
clasohm@0
   181
	      A |- B
clasohm@0
   182
	      -------
clasohm@0
   183
	      A ==> B    *)
clasohm@0
   184
fun implies_intr cA (thB as Thm{sign,maxidx,hyps,prop}) : thm =
clasohm@0
   185
  let val {sign=signA, t=A, T, maxidx=maxidxA} = Sign.rep_cterm cA
clasohm@0
   186
  in  if T<>propT then
clasohm@0
   187
	raise THM("implies_intr: assumptions must have type prop", 0, [thB])
clasohm@0
   188
      else Thm{sign= Sign.merge (sign,signA),  maxidx= max[maxidxA, maxidx], 
clasohm@0
   189
	     hyps= disch(hyps,A),  prop= implies$A$prop}
clasohm@0
   190
      handle TERM _ =>
clasohm@0
   191
        raise THM("implies_intr: incompatible signatures", 0, [thB])
clasohm@0
   192
  end;
clasohm@0
   193
clasohm@0
   194
(* Implication elimination
clasohm@0
   195
	A ==> B       A
clasohm@0
   196
	---------------
clasohm@0
   197
		B      *)
clasohm@0
   198
fun implies_elim thAB thA : thm =
clasohm@0
   199
    let val Thm{maxidx=maxA, hyps=hypsA, prop=propA,...} = thA
clasohm@0
   200
	and Thm{sign, maxidx, hyps, prop,...} = thAB;
clasohm@0
   201
	fun err(a) = raise THM("implies_elim: "^a, 0, [thAB,thA])
clasohm@0
   202
    in  case prop of
clasohm@0
   203
	    imp$A$B => 
clasohm@0
   204
		if imp=implies andalso  A aconv propA
clasohm@0
   205
		then  Thm{sign= merge_theories(thAB,thA),
clasohm@0
   206
			  maxidx= max[maxA,maxidx], 
clasohm@0
   207
			  hyps= hypsA union hyps,  (*dups suppressed*)
clasohm@0
   208
			  prop= B}
clasohm@0
   209
		else err("major premise")
clasohm@0
   210
	  | _ => err("major premise")
clasohm@0
   211
    end;
clasohm@0
   212
      
clasohm@0
   213
(* Forall introduction.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   214
     A
clasohm@0
   215
   ------
clasohm@0
   216
   !!x.A       *)
clasohm@0
   217
fun forall_intr cx (th as Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   218
  let val x = Sign.term_of cx;
clasohm@0
   219
      fun result(a,T) = Thm{sign= sign, maxidx= maxidx, hyps= hyps,
clasohm@0
   220
	                    prop= all(T) $ Abs(a, T, abstract_over (x,prop))}
clasohm@0
   221
  in  case x of
clasohm@0
   222
	Free(a,T) => 
clasohm@0
   223
	  if exists (apl(x, Logic.occs)) hyps 
clasohm@0
   224
	  then  raise THM("forall_intr: variable free in assumptions", 0, [th])
clasohm@0
   225
	  else  result(a,T)
clasohm@0
   226
      | Var((a,_),T) => result(a,T)
clasohm@0
   227
      | _ => raise THM("forall_intr: not a variable", 0, [th])
clasohm@0
   228
  end;
clasohm@0
   229
clasohm@0
   230
(* Forall elimination
clasohm@0
   231
	      !!x.A
clasohm@0
   232
	     --------
clasohm@0
   233
	      A[t/x]     *)
clasohm@0
   234
fun forall_elim ct (th as Thm{sign,maxidx,hyps,prop}) : thm =
clasohm@0
   235
  let val {sign=signt, t, T, maxidx=maxt} = Sign.rep_cterm ct
clasohm@0
   236
  in  case prop of
clasohm@0
   237
	  Const("all",Type("fun",[Type("fun",[qary,_]),_])) $ A =>
clasohm@0
   238
	    if T<>qary then
clasohm@0
   239
		raise THM("forall_elim: type mismatch", 0, [th])
clasohm@0
   240
	    else Thm{sign= Sign.merge(sign,signt), 
clasohm@0
   241
		     maxidx= max[maxidx, maxt],
clasohm@0
   242
		     hyps= hyps,  prop= betapply(A,t)}
clasohm@0
   243
	| _ => raise THM("forall_elim: not quantified", 0, [th])
clasohm@0
   244
  end
clasohm@0
   245
  handle TERM _ =>
clasohm@0
   246
	 raise THM("forall_elim: incompatible signatures", 0, [th]);
clasohm@0
   247
clasohm@0
   248
clasohm@0
   249
(*** Equality ***)
clasohm@0
   250
clasohm@0
   251
(*Definition of the relation =?= *)
clasohm@0
   252
val flexpair_def =
clasohm@0
   253
  Thm{sign= Sign.pure, hyps= [], maxidx= 0, 
clasohm@0
   254
      prop= Sign.term_of 
clasohm@0
   255
	      (Sign.read_cterm Sign.pure 
clasohm@0
   256
	         ("(?t =?= ?u) == (?t == ?u::?'a::{})", propT))};
clasohm@0
   257
clasohm@0
   258
(*The reflexivity rule: maps  t   to the theorem   t==t   *)
clasohm@0
   259
fun reflexive ct = 
clasohm@0
   260
  let val {sign, t, T, maxidx} = Sign.rep_cterm ct
clasohm@0
   261
  in  Thm{sign= sign, hyps= [], maxidx= maxidx, prop= Logic.mk_equals(t,t)}
clasohm@0
   262
  end;
clasohm@0
   263
clasohm@0
   264
(*The symmetry rule
clasohm@0
   265
    t==u
clasohm@0
   266
    ----
clasohm@0
   267
    u==t         *)
clasohm@0
   268
fun symmetric (th as Thm{sign,hyps,prop,maxidx}) =
clasohm@0
   269
  case prop of
clasohm@0
   270
      (eq as Const("==",_)) $ t $ u =>
clasohm@0
   271
	  Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop= eq$u$t} 
clasohm@0
   272
    | _ => raise THM("symmetric", 0, [th]);
clasohm@0
   273
clasohm@0
   274
(*The transitive rule
clasohm@0
   275
    t1==u    u==t2
clasohm@0
   276
    ------------
clasohm@0
   277
        t1==t2      *)
clasohm@0
   278
fun transitive th1 th2 =
clasohm@0
   279
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   280
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   281
      fun err(msg) = raise THM("transitive: "^msg, 0, [th1,th2])
clasohm@0
   282
  in case (prop1,prop2) of
clasohm@0
   283
       ((eq as Const("==",_)) $ t1 $ u, Const("==",_) $ u' $ t2) =>
clasohm@0
   284
	  if not (u aconv u') then err"middle term"  else
clasohm@0
   285
	      Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2, 
clasohm@0
   286
		  maxidx= max[max1,max2], prop= eq$t1$t2}
clasohm@0
   287
     | _ =>  err"premises"
clasohm@0
   288
  end;
clasohm@0
   289
clasohm@0
   290
(*Beta-conversion: maps (%(x)t)(u) to the theorem  (%(x)t)(u) == t[u/x]   *)
clasohm@0
   291
fun beta_conversion ct = 
clasohm@0
   292
  let val {sign, t, T, maxidx} = Sign.rep_cterm ct
clasohm@0
   293
  in  case t of
clasohm@0
   294
	  Abs(_,_,bodt) $ u => 
clasohm@0
   295
	    Thm{sign= sign,  hyps= [],  
clasohm@0
   296
		maxidx= maxidx_of_term t, 
clasohm@0
   297
		prop= Logic.mk_equals(t, subst_bounds([u],bodt))}
clasohm@0
   298
	| _ =>  raise THM("beta_conversion: not a redex", 0, [])
clasohm@0
   299
  end;
clasohm@0
   300
clasohm@0
   301
(*The extensionality rule   (proviso: x not free in f, g, or hypotheses)
clasohm@0
   302
    f(x) == g(x)
clasohm@0
   303
    ------------
clasohm@0
   304
       f == g    *)
clasohm@0
   305
fun extensional (th as Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   306
  case prop of
clasohm@0
   307
    (Const("==",_)) $ (f$x) $ (g$y) =>
clasohm@0
   308
      let fun err(msg) = raise THM("extensional: "^msg, 0, [th]) 
clasohm@0
   309
      in (if x<>y then err"different variables" else
clasohm@0
   310
          case y of
clasohm@0
   311
		Free _ => 
clasohm@0
   312
		  if exists (apl(y, Logic.occs)) (f::g::hyps) 
clasohm@0
   313
		  then err"variable free in hyps or functions"    else  ()
clasohm@0
   314
	      | Var _ => 
clasohm@0
   315
		  if Logic.occs(y,f)  orelse  Logic.occs(y,g) 
clasohm@0
   316
		  then err"variable free in functions"   else  ()
clasohm@0
   317
	      | _ => err"not a variable");
clasohm@0
   318
	  Thm{sign=sign, hyps=hyps, maxidx=maxidx, 
clasohm@0
   319
	      prop= Logic.mk_equals(f,g)} 
clasohm@0
   320
      end
clasohm@0
   321
 | _ =>  raise THM("extensional: premise", 0, [th]);
clasohm@0
   322
clasohm@0
   323
(*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   324
  The bound variable will be named "a" (since x will be something like x320)
clasohm@0
   325
          t == u
clasohm@0
   326
    ----------------
clasohm@0
   327
      %(x)t == %(x)u     *)
clasohm@0
   328
fun abstract_rule a cx (th as Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   329
  let val x = Sign.term_of cx;
clasohm@0
   330
      val (t,u) = Logic.dest_equals prop  
clasohm@0
   331
	    handle TERM _ =>
clasohm@0
   332
		raise THM("abstract_rule: premise not an equality", 0, [th])
clasohm@0
   333
      fun result T =
clasohm@0
   334
            Thm{sign= sign, maxidx= maxidx, hyps= hyps,
clasohm@0
   335
	        prop= Logic.mk_equals(Abs(a, T, abstract_over (x,t)),
clasohm@0
   336
		  	              Abs(a, T, abstract_over (x,u)))}
clasohm@0
   337
  in  case x of
clasohm@0
   338
	Free(_,T) => 
clasohm@0
   339
	 if exists (apl(x, Logic.occs)) hyps 
clasohm@0
   340
	 then raise THM("abstract_rule: variable free in assumptions", 0, [th])
clasohm@0
   341
	 else result T
clasohm@0
   342
      | Var(_,T) => result T
clasohm@0
   343
      | _ => raise THM("abstract_rule: not a variable", 0, [th])
clasohm@0
   344
  end;
clasohm@0
   345
clasohm@0
   346
(*The combination rule
clasohm@0
   347
    f==g    t==u
clasohm@0
   348
    ------------
clasohm@0
   349
     f(t)==g(u)      *)
clasohm@0
   350
fun combination th1 th2 =
clasohm@0
   351
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   352
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2
clasohm@0
   353
  in  case (prop1,prop2)  of
clasohm@0
   354
       (Const("==",_) $ f $ g, Const("==",_) $ t $ u) =>
clasohm@0
   355
	      Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2, 
clasohm@0
   356
		  maxidx= max[max1,max2], prop= Logic.mk_equals(f$t, g$u)}
clasohm@0
   357
     | _ =>  raise THM("combination: premises", 0, [th1,th2])
clasohm@0
   358
  end;
clasohm@0
   359
clasohm@0
   360
clasohm@0
   361
(*The equal propositions rule
clasohm@0
   362
    A==B    A
clasohm@0
   363
    ---------
clasohm@0
   364
        B          *)
clasohm@0
   365
fun equal_elim th1 th2 =
clasohm@0
   366
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   367
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   368
      fun err(msg) = raise THM("equal_elim: "^msg, 0, [th1,th2])
clasohm@0
   369
  in  case prop1  of
clasohm@0
   370
       Const("==",_) $ A $ B =>
clasohm@0
   371
	  if not (prop2 aconv A) then err"not equal"  else
clasohm@0
   372
	      Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2, 
clasohm@0
   373
		  maxidx= max[max1,max2], prop= B}
clasohm@0
   374
     | _ =>  err"major premise"
clasohm@0
   375
  end;
clasohm@0
   376
clasohm@0
   377
clasohm@0
   378
(* Equality introduction
clasohm@0
   379
    A==>B    B==>A
clasohm@0
   380
    -------------
clasohm@0
   381
         A==B            *)
clasohm@0
   382
fun equal_intr th1 th2 =
clasohm@0
   383
let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   384
    and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   385
    fun err(msg) = raise THM("equal_intr: "^msg, 0, [th1,th2])
clasohm@0
   386
in case (prop1,prop2) of
clasohm@0
   387
     (Const("==>",_) $ A $ B, Const("==>",_) $ B' $ A')  =>
clasohm@0
   388
	if A aconv A' andalso B aconv B'
clasohm@0
   389
	then Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2, 
clasohm@0
   390
		 maxidx= max[max1,max2], prop= Logic.mk_equals(A,B)}
clasohm@0
   391
	else err"not equal"
clasohm@0
   392
   | _ =>  err"premises"
clasohm@0
   393
end;
clasohm@0
   394
clasohm@0
   395
(**** Derived rules ****)
clasohm@0
   396
clasohm@0
   397
(*Discharge all hypotheses (need not verify cterms)
clasohm@0
   398
  Repeated hypotheses are discharged only once;  fold cannot do this*)
clasohm@0
   399
fun implies_intr_hyps (Thm{sign, maxidx, hyps=A::As, prop}) =
clasohm@0
   400
      implies_intr_hyps
clasohm@0
   401
	    (Thm{sign=sign,  maxidx=maxidx, 
clasohm@0
   402
	         hyps= disch(As,A),  prop= implies$A$prop})
clasohm@0
   403
  | implies_intr_hyps th = th;
clasohm@0
   404
clasohm@0
   405
(*Smash" unifies the list of term pairs leaving no flex-flex pairs.
clasohm@0
   406
  Instantiates the theorem and deletes trivial tpairs. 
clasohm@0
   407
  Resulting sequence may contain multiple elements if the tpairs are
clasohm@0
   408
    not all flex-flex. *)
clasohm@0
   409
fun flexflex_rule (Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   410
  let fun newthm env = 
clasohm@0
   411
	  let val (tpairs,horn) = 
clasohm@0
   412
			Logic.strip_flexpairs (Envir.norm_term env prop)
clasohm@0
   413
	        (*Remove trivial tpairs, of the form t=t*)
clasohm@0
   414
	      val distpairs = filter (not o op aconv) tpairs
clasohm@0
   415
	      val newprop = Logic.list_flexpairs(distpairs, horn)
clasohm@0
   416
	  in  Thm{sign= sign, hyps= hyps, 
clasohm@0
   417
		  maxidx= maxidx_of_term newprop, prop= newprop}
clasohm@0
   418
	  end;
clasohm@0
   419
      val (tpairs,_) = Logic.strip_flexpairs prop
clasohm@0
   420
  in Sequence.maps newthm
clasohm@0
   421
	    (Unify.smash_unifiers(sign, Envir.empty maxidx, tpairs))
clasohm@0
   422
  end;
clasohm@0
   423
clasohm@0
   424
(*Instantiation of Vars
clasohm@0
   425
		      A
clasohm@0
   426
	     --------------------
clasohm@0
   427
	      A[t1/v1,....,tn/vn]     *)
clasohm@0
   428
clasohm@0
   429
(*Check that all the terms are Vars and are distinct*)
clasohm@0
   430
fun instl_ok ts = forall is_Var ts andalso null(findrep ts);
clasohm@0
   431
clasohm@0
   432
(*For instantiate: process pair of cterms, merge theories*)
clasohm@0
   433
fun add_ctpair ((ct,cu), (sign,tpairs)) =
clasohm@0
   434
  let val {sign=signt, t=t, T= T, ...} = Sign.rep_cterm ct
clasohm@0
   435
      and {sign=signu, t=u, T= U, ...} = Sign.rep_cterm cu
clasohm@0
   436
  in  if T=U  then (Sign.merge(sign, Sign.merge(signt, signu)), (t,u)::tpairs)
clasohm@0
   437
      else raise TYPE("add_ctpair", [T,U], [t,u])
clasohm@0
   438
  end;
clasohm@0
   439
clasohm@0
   440
fun add_ctyp ((v,ctyp), (sign',vTs)) =
clasohm@0
   441
  let val {T,sign} = Sign.rep_ctyp ctyp
clasohm@0
   442
  in (Sign.merge(sign,sign'), (v,T)::vTs) end;
clasohm@0
   443
clasohm@0
   444
(*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
   445
  Instantiates distinct Vars by terms of same type.
clasohm@0
   446
  Normalizes the new theorem! *)
clasohm@0
   447
fun instantiate (vcTs,ctpairs)  (th as Thm{sign,maxidx,hyps,prop}) = 
clasohm@0
   448
  let val (newsign,tpairs) = foldr add_ctpair (ctpairs, (sign,[]));
clasohm@0
   449
      val (newsign,vTs) = foldr add_ctyp (vcTs, (newsign,[]));
nipkow@193
   450
      val newprop = 
nipkow@193
   451
	    Envir.norm_term (Envir.empty 0) 
nipkow@193
   452
	      (subst_atomic tpairs 
nipkow@193
   453
	       (Type.inst_term_tvars(#tsig(Sign.rep_sg newsign),vTs) prop))
clasohm@0
   454
      val newth = Thm{sign= newsign, hyps= hyps,
clasohm@0
   455
		      maxidx= maxidx_of_term newprop, prop= newprop}
nipkow@193
   456
  in  if not(instl_ok(map #1 tpairs)) 
nipkow@193
   457
      then raise THM("instantiate: variables not distinct", 0, [th])
nipkow@193
   458
      else if not(null(findrep(map #1 vTs)))
nipkow@193
   459
      then raise THM("instantiate: type variables not distinct", 0, [th])
nipkow@193
   460
      else (*Check types of Vars for agreement*)
nipkow@193
   461
      case findrep (map (#1 o dest_Var) (term_vars newprop)) of
nipkow@193
   462
	  ix::_ => raise THM("instantiate: conflicting types for variable " ^
nipkow@193
   463
			     Syntax.string_of_vname ix ^ "\n", 0, [newth])
nipkow@193
   464
	| [] => 
nipkow@193
   465
	     case findrep (map #1 (term_tvars newprop)) of
nipkow@193
   466
	     ix::_ => raise THM
nipkow@193
   467
		    ("instantiate: conflicting sorts for type variable " ^
nipkow@193
   468
		     Syntax.string_of_vname ix ^ "\n", 0, [newth])
nipkow@193
   469
        | [] => newth
clasohm@0
   470
  end
clasohm@0
   471
  handle TERM _ => 
clasohm@0
   472
           raise THM("instantiate: incompatible signatures",0,[th])
nipkow@193
   473
       | TYPE _ => raise THM("instantiate: type conflict", 0, [th]);
clasohm@0
   474
clasohm@0
   475
(*The trivial implication A==>A, justified by assume and forall rules.
clasohm@0
   476
  A can contain Vars, not so for assume!   *)
clasohm@0
   477
fun trivial ct : thm = 
clasohm@0
   478
  let val {sign, t=A, T, maxidx} = Sign.rep_cterm ct
clasohm@0
   479
  in  if T<>propT then  
clasohm@0
   480
	    raise THM("trivial: the term must have type prop", 0, [])
clasohm@0
   481
      else Thm{sign= sign, maxidx= maxidx, hyps= [], prop= implies$A$A}
clasohm@0
   482
  end;
clasohm@0
   483
clasohm@0
   484
(* Replace all TFrees not in the hyps by new TVars *)
clasohm@0
   485
fun varifyT(Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   486
  let val tfrees = foldr add_term_tfree_names (hyps,[])
clasohm@0
   487
  in Thm{sign=sign, maxidx=max[0,maxidx], hyps=hyps,
clasohm@0
   488
	 prop= Type.varify(prop,tfrees)}
clasohm@0
   489
  end;
clasohm@0
   490
clasohm@0
   491
(* Replace all TVars by new TFrees *)
clasohm@0
   492
fun freezeT(Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   493
  let val prop' = Type.freeze (K true) prop
clasohm@0
   494
  in Thm{sign=sign, maxidx=maxidx_of_term prop', hyps=hyps, prop=prop'} end;
clasohm@0
   495
clasohm@0
   496
clasohm@0
   497
(*** Inference rules for tactics ***)
clasohm@0
   498
clasohm@0
   499
(*Destruct proof state into constraints, other goals, goal(i), rest *)
clasohm@0
   500
fun dest_state (state as Thm{prop,...}, i) =
clasohm@0
   501
  let val (tpairs,horn) = Logic.strip_flexpairs prop
clasohm@0
   502
  in  case  Logic.strip_prems(i, [], horn) of
clasohm@0
   503
          (B::rBs, C) => (tpairs, rev rBs, B, C)
clasohm@0
   504
        | _ => raise THM("dest_state", i, [state])
clasohm@0
   505
  end
clasohm@0
   506
  handle TERM _ => raise THM("dest_state", i, [state]);
clasohm@0
   507
clasohm@0
   508
(*Increment variables and parameters of rule as required for
clasohm@0
   509
  resolution with goal i of state. *)
clasohm@0
   510
fun lift_rule (state, i) orule =
clasohm@0
   511
  let val Thm{prop=sprop,maxidx=smax,...} = state;
clasohm@0
   512
      val (Bi::_, _) = Logic.strip_prems(i, [], Logic.skip_flexpairs sprop)
clasohm@0
   513
	handle TERM _ => raise THM("lift_rule", i, [orule,state]);
clasohm@0
   514
      val (lift_abs,lift_all) = Logic.lift_fns(Bi,smax+1);
clasohm@0
   515
      val (Thm{sign,maxidx,hyps,prop}) = orule
clasohm@0
   516
      val (tpairs,As,B) = Logic.strip_horn prop
clasohm@0
   517
  in  Thm{hyps=hyps, sign= merge_theories(state,orule),
clasohm@0
   518
	  maxidx= maxidx+smax+1,
clasohm@0
   519
	  prop= Logic.rule_of(map (pairself lift_abs) tpairs,
clasohm@0
   520
			      map lift_all As,    lift_all B)}
clasohm@0
   521
  end;
clasohm@0
   522
clasohm@0
   523
(*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
clasohm@0
   524
fun assumption i state =
clasohm@0
   525
  let val Thm{sign,maxidx,hyps,prop} = state;
clasohm@0
   526
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   527
      fun newth (env as Envir.Envir{maxidx,asol,iTs}, tpairs) =
clasohm@0
   528
	  Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop=
clasohm@0
   529
	    case (Envir.alist_of_olist asol, iTs) of
clasohm@0
   530
		(*avoid wasted normalizations*)
clasohm@0
   531
	        ([],[]) => Logic.rule_of(tpairs, Bs, C)
clasohm@0
   532
	      | _ => (*normalize the new rule fully*)
clasohm@0
   533
		      Envir.norm_term env (Logic.rule_of(tpairs, Bs, C))};
clasohm@0
   534
      fun addprfs [] = Sequence.null
clasohm@0
   535
        | addprfs ((t,u)::apairs) = Sequence.seqof (fn()=> Sequence.pull
clasohm@0
   536
             (Sequence.mapp newth
clasohm@0
   537
	        (Unify.unifiers(sign,Envir.empty maxidx, (t,u)::tpairs)) 
clasohm@0
   538
	        (addprfs apairs)))
clasohm@0
   539
  in  addprfs (Logic.assum_pairs Bi)  end;
clasohm@0
   540
clasohm@0
   541
(*Solve subgoal Bi of proof state B1...Bn/C by assumption. 
clasohm@0
   542
  Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
clasohm@0
   543
fun eq_assumption i state =
clasohm@0
   544
  let val Thm{sign,maxidx,hyps,prop} = state;
clasohm@0
   545
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   546
  in  if exists (op aconv) (Logic.assum_pairs Bi)
clasohm@0
   547
      then Thm{sign=sign, hyps=hyps, maxidx=maxidx, 
clasohm@0
   548
	       prop=Logic.rule_of(tpairs, Bs, C)}
clasohm@0
   549
      else  raise THM("eq_assumption", 0, [state])
clasohm@0
   550
  end;
clasohm@0
   551
clasohm@0
   552
clasohm@0
   553
(** User renaming of parameters in a subgoal **)
clasohm@0
   554
clasohm@0
   555
(*Calls error rather than raising an exception because it is intended
clasohm@0
   556
  for top-level use -- exception handling would not make sense here.
clasohm@0
   557
  The names in cs, if distinct, are used for the innermost parameters;
clasohm@0
   558
   preceding parameters may be renamed to make all params distinct.*)
clasohm@0
   559
fun rename_params_rule (cs, i) state =
clasohm@0
   560
  let val Thm{sign,maxidx,hyps,prop} = state
clasohm@0
   561
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   562
      val iparams = map #1 (Logic.strip_params Bi)
clasohm@0
   563
      val short = length iparams - length cs
clasohm@0
   564
      val newnames = 
clasohm@0
   565
	    if short<0 then error"More names than abstractions!"
clasohm@0
   566
	    else variantlist(take (short,iparams), cs) @ cs
clasohm@0
   567
      val freenames = map (#1 o dest_Free) (term_frees prop)
clasohm@0
   568
      val newBi = Logic.list_rename_params (newnames, Bi)
clasohm@0
   569
  in  
clasohm@0
   570
  case findrep cs of
clasohm@0
   571
     c::_ => error ("Bound variables not distinct: " ^ c)
clasohm@0
   572
   | [] => (case cs inter freenames of
clasohm@0
   573
       a::_ => error ("Bound/Free variable clash: " ^ a)
clasohm@0
   574
     | [] => Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop=
clasohm@0
   575
		    Logic.rule_of(tpairs, Bs@[newBi], C)})
clasohm@0
   576
  end;
clasohm@0
   577
clasohm@0
   578
(*** Preservation of bound variable names ***)
clasohm@0
   579
clasohm@0
   580
(*Scan a pair of terms; while they are similar, 
clasohm@0
   581
  accumulate corresponding bound vars in "al"*)
clasohm@0
   582
fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) = match_bvs(s,t,(x,y)::al)
clasohm@0
   583
  | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
clasohm@0
   584
  | match_bvs(_,_,al) = al;
clasohm@0
   585
clasohm@0
   586
(* strip abstractions created by parameters *)
clasohm@0
   587
fun match_bvars((s,t),al) = match_bvs(strip_abs_body s, strip_abs_body t, al);
clasohm@0
   588
clasohm@0
   589
clasohm@0
   590
(* strip_apply f A(,B) strips off all assumptions/parameters from A 
clasohm@0
   591
   introduced by lifting over B, and applies f to remaining part of A*)
clasohm@0
   592
fun strip_apply f =
clasohm@0
   593
  let fun strip(Const("==>",_)$ A1 $ B1,
clasohm@0
   594
		Const("==>",_)$ _  $ B2) = implies $ A1 $ strip(B1,B2)
clasohm@0
   595
	| strip((c as Const("all",_)) $ Abs(a,T,t1),
clasohm@0
   596
		      Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
clasohm@0
   597
	| strip(A,_) = f A
clasohm@0
   598
  in strip end;
clasohm@0
   599
clasohm@0
   600
(*Use the alist to rename all bound variables and some unknowns in a term
clasohm@0
   601
  dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
clasohm@0
   602
  Preserves unknowns in tpairs and on lhs of dpairs. *)
clasohm@0
   603
fun rename_bvs([],_,_,_) = I
clasohm@0
   604
  | rename_bvs(al,dpairs,tpairs,B) =
clasohm@0
   605
    let val vars = foldr add_term_vars 
clasohm@0
   606
			(map fst dpairs @ map fst tpairs @ map snd tpairs, [])
clasohm@0
   607
	(*unknowns appearing elsewhere be preserved!*)
clasohm@0
   608
	val vids = map (#1 o #1 o dest_Var) vars;
clasohm@0
   609
	fun rename(t as Var((x,i),T)) =
clasohm@0
   610
		(case assoc(al,x) of
clasohm@0
   611
		   Some(y) => if x mem vids orelse y mem vids then t
clasohm@0
   612
			      else Var((y,i),T)
clasohm@0
   613
		 | None=> t)
clasohm@0
   614
          | rename(Abs(x,T,t)) =
clasohm@0
   615
	      Abs(case assoc(al,x) of Some(y) => y | None => x,
clasohm@0
   616
		  T, rename t)
clasohm@0
   617
          | rename(f$t) = rename f $ rename t
clasohm@0
   618
          | rename(t) = t;
clasohm@0
   619
	fun strip_ren Ai = strip_apply rename (Ai,B)
clasohm@0
   620
    in strip_ren end;
clasohm@0
   621
clasohm@0
   622
(*Function to rename bounds/unknowns in the argument, lifted over B*)
clasohm@0
   623
fun rename_bvars(dpairs, tpairs, B) =
clasohm@0
   624
	rename_bvs(foldr match_bvars (dpairs,[]), dpairs, tpairs, B);
clasohm@0
   625
clasohm@0
   626
clasohm@0
   627
(*** RESOLUTION ***)
clasohm@0
   628
clasohm@0
   629
(*strip off pairs of assumptions/parameters in parallel -- they are
clasohm@0
   630
  identical because of lifting*)
clasohm@0
   631
fun strip_assums2 (Const("==>", _) $ _ $ B1, 
clasohm@0
   632
		   Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
clasohm@0
   633
  | strip_assums2 (Const("all",_)$Abs(a,T,t1),
clasohm@0
   634
		   Const("all",_)$Abs(_,_,t2)) = 
clasohm@0
   635
      let val (B1,B2) = strip_assums2 (t1,t2)
clasohm@0
   636
      in  (Abs(a,T,B1), Abs(a,T,B2))  end
clasohm@0
   637
  | strip_assums2 BB = BB;
clasohm@0
   638
clasohm@0
   639
clasohm@0
   640
(*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
clasohm@0
   641
  Unifies B with Bi, replacing subgoal i    (1 <= i <= n)  
clasohm@0
   642
  If match then forbid instantiations in proof state
clasohm@0
   643
  If lifted then shorten the dpair using strip_assums2.
clasohm@0
   644
  If eres_flg then simultaneously proves A1 by assumption.
clasohm@0
   645
  nsubgoal is the number of new subgoals (written m above). 
clasohm@0
   646
  Curried so that resolution calls dest_state only once.
clasohm@0
   647
*)
clasohm@0
   648
local open Sequence; exception Bicompose
clasohm@0
   649
in
clasohm@0
   650
fun bicompose_aux match (state, (stpairs, Bs, Bi, C), lifted) 
clasohm@0
   651
                        (eres_flg, orule, nsubgoal) =
clasohm@0
   652
 let val Thm{maxidx=smax, hyps=shyps, ...} = state
clasohm@0
   653
     and Thm{maxidx=rmax, hyps=rhyps, prop=rprop,...} = orule;
clasohm@0
   654
     val sign = merge_theories(state,orule);
clasohm@0
   655
     (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
clasohm@0
   656
     fun addth As ((env as Envir.Envir{maxidx,asol,iTs}, tpairs), thq) =
clasohm@0
   657
       let val minenv = case Envir.alist_of_olist asol of
clasohm@0
   658
			  [] => ~1  |  ((_,i),_) :: _ => i;
clasohm@0
   659
	   val minx = min (minenv :: map (fn ((_,i),_) => i) iTs);
clasohm@0
   660
	   val normt = Envir.norm_term env;
clasohm@0
   661
	   (*Perform minimal copying here by examining env*)
clasohm@0
   662
	   val normp = if minx = ~1 then (tpairs, Bs@As, C) 
clasohm@0
   663
		       else 
clasohm@0
   664
		       let val ntps = map (pairself normt) tpairs
clasohm@0
   665
		       in if minx>smax then (*no assignments in state*)
clasohm@0
   666
			    (ntps, Bs @ map normt As, C)
clasohm@0
   667
			  else if match then raise Bicompose
clasohm@0
   668
			  else (*normalize the new rule fully*)
clasohm@0
   669
			    (ntps, map normt (Bs @ As), normt C)
clasohm@0
   670
		       end
clasohm@0
   671
	   val th = Thm{sign=sign, hyps=rhyps union shyps, maxidx=maxidx,
clasohm@0
   672
			prop= Logic.rule_of normp}
clasohm@0
   673
        in  cons(th, thq)  end  handle Bicompose => thq
clasohm@0
   674
     val (rtpairs,rhorn) = Logic.strip_flexpairs(rprop);
clasohm@0
   675
     val (rAs,B) = Logic.strip_prems(nsubgoal, [], rhorn)
clasohm@0
   676
       handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
clasohm@0
   677
     (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
clasohm@0
   678
     fun newAs(As0, n, dpairs, tpairs) =
clasohm@0
   679
       let val As1 = if !Logic.auto_rename orelse not lifted then As0
clasohm@0
   680
		     else map (rename_bvars(dpairs,tpairs,B)) As0
clasohm@0
   681
       in (map (Logic.flatten_params n) As1)
clasohm@0
   682
	  handle TERM _ =>
clasohm@0
   683
	  raise THM("bicompose: 1st premise", 0, [orule])
clasohm@0
   684
       end;
clasohm@0
   685
     val env = Envir.empty(max[rmax,smax]);
clasohm@0
   686
     val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
clasohm@0
   687
     val dpairs = BBi :: (rtpairs@stpairs);
clasohm@0
   688
     (*elim-resolution: try each assumption in turn.  Initially n=1*)
clasohm@0
   689
     fun tryasms (_, _, []) = null
clasohm@0
   690
       | tryasms (As, n, (t,u)::apairs) =
clasohm@0
   691
	  (case pull(Unify.unifiers(sign, env, (t,u)::dpairs))  of
clasohm@0
   692
	       None                   => tryasms (As, n+1, apairs)
clasohm@0
   693
	     | cell as Some((_,tpairs),_) => 
clasohm@0
   694
		   its_right (addth (newAs(As, n, [BBi,(u,t)], tpairs)))
clasohm@0
   695
		       (seqof (fn()=> cell),
clasohm@0
   696
		        seqof (fn()=> pull (tryasms (As, n+1, apairs)))));
clasohm@0
   697
     fun eres [] = raise THM("bicompose: no premises", 0, [orule,state])
clasohm@0
   698
       | eres (A1::As) = tryasms (As, 1, Logic.assum_pairs A1);
clasohm@0
   699
     (*ordinary resolution*)
clasohm@0
   700
     fun res(None) = null
clasohm@0
   701
       | res(cell as Some((_,tpairs),_)) = 
clasohm@0
   702
	     its_right (addth(newAs(rev rAs, 0, [BBi], tpairs)))
clasohm@0
   703
	 	       (seqof (fn()=> cell), null)
clasohm@0
   704
 in  if eres_flg then eres(rev rAs)
clasohm@0
   705
     else res(pull(Unify.unifiers(sign, env, dpairs)))
clasohm@0
   706
 end;
clasohm@0
   707
end;  (*open Sequence*)
clasohm@0
   708
clasohm@0
   709
clasohm@0
   710
fun bicompose match arg i state =
clasohm@0
   711
    bicompose_aux match (state, dest_state(state,i), false) arg;
clasohm@0
   712
clasohm@0
   713
(*Quick test whether rule is resolvable with the subgoal with hyps Hs
clasohm@0
   714
  and conclusion B.  If eres_flg then checks 1st premise of rule also*)
clasohm@0
   715
fun could_bires (Hs, B, eres_flg, rule) =
clasohm@0
   716
    let fun could_reshyp (A1::_) = exists (apl(A1,could_unify)) Hs
clasohm@0
   717
	  | could_reshyp [] = false;  (*no premise -- illegal*)
clasohm@0
   718
    in  could_unify(concl_of rule, B) andalso 
clasohm@0
   719
	(not eres_flg  orelse  could_reshyp (prems_of rule))
clasohm@0
   720
    end;
clasohm@0
   721
clasohm@0
   722
(*Bi-resolution of a state with a list of (flag,rule) pairs.
clasohm@0
   723
  Puts the rule above:  rule/state.  Renames vars in the rules. *)
clasohm@0
   724
fun biresolution match brules i state = 
clasohm@0
   725
    let val lift = lift_rule(state, i);
clasohm@0
   726
	val (stpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   727
	val B = Logic.strip_assums_concl Bi;
clasohm@0
   728
	val Hs = Logic.strip_assums_hyp Bi;
clasohm@0
   729
	val comp = bicompose_aux match (state, (stpairs, Bs, Bi, C), true);
clasohm@0
   730
	fun res [] = Sequence.null
clasohm@0
   731
	  | res ((eres_flg, rule)::brules) = 
clasohm@0
   732
	      if could_bires (Hs, B, eres_flg, rule)
clasohm@0
   733
	      then Sequence.seqof (*delay processing remainder til needed*)
clasohm@0
   734
	          (fn()=> Some(comp (eres_flg, lift rule, nprems_of rule),
clasohm@0
   735
			       res brules))
clasohm@0
   736
	      else res brules
clasohm@0
   737
    in  Sequence.flats (res brules)  end;
clasohm@0
   738
clasohm@0
   739
clasohm@0
   740
(**** THEORIES ****)
clasohm@0
   741
clasohm@0
   742
val pure_thy = Pure{sign = Sign.pure};
clasohm@0
   743
clasohm@0
   744
(*Look up the named axiom in the theory*)
clasohm@0
   745
fun get_axiom thy axname =
clasohm@0
   746
    let fun get (Pure _) = raise Match
clasohm@0
   747
	  | get (Extend{axioms,thy,...}) =
clasohm@0
   748
	     (case Symtab.lookup(axioms,axname) of
clasohm@0
   749
		  Some th => th
clasohm@0
   750
		| None => get thy)
clasohm@0
   751
 	 | get (Merge{thy1,thy2,...}) = 
clasohm@0
   752
		get thy1  handle Match => get thy2
clasohm@0
   753
    in  get thy
clasohm@0
   754
	handle Match => raise THEORY("get_axiom: No axiom "^axname, [thy])
clasohm@0
   755
    end;
clasohm@0
   756
clasohm@0
   757
(*Converts Frees to Vars: axioms can be written without question marks*)
clasohm@0
   758
fun prepare_axiom sign sP =
clasohm@0
   759
    Logic.varify (Sign.term_of (Sign.read_cterm sign (sP,propT)));
clasohm@0
   760
clasohm@0
   761
(*Read an axiom for a new theory*)
clasohm@0
   762
fun read_ax sign (a, sP) : string*thm =
clasohm@0
   763
  let val prop = prepare_axiom sign sP
clasohm@0
   764
  in  (a, Thm{sign=sign, hyps=[], maxidx= maxidx_of_term prop, prop= prop}) 
clasohm@0
   765
  end
clasohm@0
   766
  handle ERROR =>
clasohm@0
   767
	error("extend_theory: The error above occurred in axiom " ^ a);
clasohm@0
   768
clasohm@0
   769
fun mk_axioms sign axpairs =
clasohm@0
   770
	Symtab.st_of_alist(map (read_ax sign) axpairs, Symtab.null)
clasohm@0
   771
	handle Symtab.DUPLICATE(a) => error("Two axioms named " ^ a);
clasohm@0
   772
clasohm@0
   773
(*Extension of a theory with given classes, types, constants and syntax.
clasohm@0
   774
  Reads the axioms from strings: axpairs have the form (axname, axiom). *)
clasohm@0
   775
fun extend_theory thy thyname ext axpairs =
clasohm@0
   776
  let val sign = Sign.extend (sign_of thy) thyname ext;
clasohm@0
   777
      val axioms= mk_axioms sign axpairs
clasohm@0
   778
  in  Extend{sign=sign, axioms= axioms, thy = thy}  end;
clasohm@0
   779
clasohm@0
   780
(*The union of two theories*)
clasohm@0
   781
fun merge_theories (thy1,thy2) =
clasohm@0
   782
    Merge{sign = Sign.merge(sign_of thy1, sign_of thy2),
clasohm@0
   783
	  thy1 = thy1, thy2 = thy2};
clasohm@0
   784
clasohm@0
   785
clasohm@0
   786
(*** Meta simp sets ***)
clasohm@0
   787
clasohm@0
   788
type rrule = {thm:thm, lhs:term};
clasohm@0
   789
datatype meta_simpset =
clasohm@0
   790
  Mss of {net:rrule Net.net, congs:(string * rrule)list, primes:string,
clasohm@0
   791
          prems: thm list, mk_rews: thm -> thm list};
clasohm@0
   792
clasohm@0
   793
(*A "mss" contains data needed during conversion:
clasohm@0
   794
  net: discrimination net of rewrite rules
clasohm@0
   795
  congs: association list of congruence rules
clasohm@0
   796
  primes: offset for generating unique new names
clasohm@0
   797
          for rewriting under lambda abstractions
clasohm@0
   798
  mk_rews: used when local assumptions are added
clasohm@0
   799
*)
clasohm@0
   800
clasohm@0
   801
val empty_mss = Mss{net= Net.empty, congs= [], primes="", prems= [],
clasohm@0
   802
                    mk_rews = K[]};
clasohm@0
   803
clasohm@0
   804
exception SIMPLIFIER of string * thm;
clasohm@0
   805
clasohm@0
   806
fun prtm a sg t = (writeln a; writeln(Sign.string_of_term sg t));
clasohm@0
   807
nipkow@209
   808
val trace_simp = ref false;
nipkow@209
   809
nipkow@209
   810
fun trace_term a sg t = if !trace_simp then prtm a sg t else ();
nipkow@209
   811
nipkow@209
   812
fun trace_thm a (Thm{sign,prop,...}) = trace_term a sign prop;
nipkow@209
   813
clasohm@0
   814
(*simple test for looping rewrite*)
clasohm@0
   815
fun loops sign prems (lhs,rhs) =
clasohm@0
   816
  null(prems) andalso
clasohm@0
   817
  Pattern.eta_matches (#tsig(Sign.rep_sg sign)) (lhs,rhs);
clasohm@0
   818
clasohm@0
   819
fun mk_rrule (thm as Thm{hyps,sign,prop,maxidx,...}) =
clasohm@0
   820
  let val prems = Logic.strip_imp_prems prop
clasohm@0
   821
      val concl = Pattern.eta_contract (Logic.strip_imp_concl prop)
clasohm@0
   822
      val (lhs,rhs) = Logic.dest_equals concl handle TERM _ =>
clasohm@0
   823
                      raise SIMPLIFIER("Rewrite rule not a meta-equality",thm)
clasohm@0
   824
  in if loops sign prems (lhs,rhs)
clasohm@0
   825
     then (prtm "Warning: ignoring looping rewrite rule" sign prop; None)
clasohm@0
   826
     else Some{thm=thm,lhs=lhs}
clasohm@0
   827
  end;
clasohm@0
   828
nipkow@87
   829
local
nipkow@87
   830
 fun eq({thm=Thm{prop=p1,...},...}:rrule,
nipkow@87
   831
        {thm=Thm{prop=p2,...},...}:rrule) = p1 aconv p2
nipkow@87
   832
in
nipkow@87
   833
clasohm@0
   834
fun add_simp(mss as Mss{net,congs,primes,prems,mk_rews},
clasohm@0
   835
             thm as Thm{sign,prop,...}) =
nipkow@87
   836
  case mk_rrule thm of
nipkow@87
   837
    None => mss
nipkow@87
   838
  | Some(rrule as {lhs,...}) =>
nipkow@209
   839
      (trace_thm "Adding rewrite rule:" thm;
nipkow@209
   840
       Mss{net= (Net.insert_term((lhs,rrule),net,eq)
nipkow@209
   841
                 handle Net.INSERT =>
nipkow@87
   842
                  (prtm "Warning: ignoring duplicate rewrite rule" sign prop;
nipkow@87
   843
                   net)),
nipkow@209
   844
           congs=congs, primes=primes, prems=prems,mk_rews=mk_rews});
nipkow@87
   845
nipkow@87
   846
fun del_simp(mss as Mss{net,congs,primes,prems,mk_rews},
nipkow@87
   847
             thm as Thm{sign,prop,...}) =
nipkow@87
   848
  case mk_rrule thm of
nipkow@87
   849
    None => mss
nipkow@87
   850
  | Some(rrule as {lhs,...}) =>
nipkow@87
   851
      Mss{net= (Net.delete_term((lhs,rrule),net,eq)
nipkow@87
   852
                handle Net.INSERT =>
nipkow@87
   853
                 (prtm "Warning: rewrite rule not in simpset" sign prop;
nipkow@87
   854
                  net)),
clasohm@0
   855
             congs=congs, primes=primes, prems=prems,mk_rews=mk_rews}
nipkow@87
   856
nipkow@87
   857
end;
clasohm@0
   858
clasohm@0
   859
val add_simps = foldl add_simp;
nipkow@87
   860
val del_simps = foldl del_simp;
clasohm@0
   861
clasohm@0
   862
fun mss_of thms = add_simps(empty_mss,thms);
clasohm@0
   863
clasohm@0
   864
fun add_cong(Mss{net,congs,primes,prems,mk_rews},thm) =
clasohm@0
   865
  let val (lhs,_) = Logic.dest_equals(concl_of thm) handle TERM _ =>
clasohm@0
   866
                    raise SIMPLIFIER("Congruence not a meta-equality",thm)
clasohm@0
   867
      val lhs = Pattern.eta_contract lhs
clasohm@0
   868
      val (a,_) = dest_Const (head_of lhs) handle TERM _ =>
clasohm@0
   869
                  raise SIMPLIFIER("Congruence must start with a constant",thm)
clasohm@0
   870
  in Mss{net=net, congs=(a,{lhs=lhs,thm=thm})::congs, primes=primes,
clasohm@0
   871
         prems=prems, mk_rews=mk_rews}
clasohm@0
   872
  end;
clasohm@0
   873
clasohm@0
   874
val (op add_congs) = foldl add_cong;
clasohm@0
   875
clasohm@0
   876
fun add_prems(Mss{net,congs,primes,prems,mk_rews},thms) =
clasohm@0
   877
  Mss{net=net, congs=congs, primes=primes, prems=thms@prems, mk_rews=mk_rews};
clasohm@0
   878
clasohm@0
   879
fun prems_of_mss(Mss{prems,...}) = prems;
clasohm@0
   880
clasohm@0
   881
fun set_mk_rews(Mss{net,congs,primes,prems,...},mk_rews) =
clasohm@0
   882
  Mss{net=net, congs=congs, primes=primes, prems=prems, mk_rews=mk_rews};
clasohm@0
   883
fun mk_rews_of_mss(Mss{mk_rews,...}) = mk_rews;
clasohm@0
   884
clasohm@0
   885
clasohm@0
   886
(*** Meta-level rewriting 
clasohm@0
   887
     uses conversions, omitting proofs for efficiency.  See
clasohm@0
   888
	L C Paulson, A higher-order implementation of rewriting,
clasohm@0
   889
	Science of Computer Programming 3 (1983), pages 119-149. ***)
clasohm@0
   890
clasohm@0
   891
type prover = meta_simpset -> thm -> thm option;
clasohm@0
   892
type termrec = (Sign.sg * term list) * term;
clasohm@0
   893
type conv = meta_simpset -> termrec -> termrec;
clasohm@0
   894
nipkow@208
   895
fun check_conv(thm as Thm{hyps,prop,...}, prop0) =
nipkow@112
   896
  let fun err() = (trace_thm "Proved wrong thm (Check subgoaler?)" thm; None)
clasohm@0
   897
      val (lhs0,_) = Logic.dest_equals(Logic.strip_imp_concl prop0)
clasohm@0
   898
  in case prop of
clasohm@0
   899
       Const("==",_) $ lhs $ rhs =>
clasohm@0
   900
         if (lhs = lhs0) orelse
clasohm@0
   901
            (lhs aconv (Envir.norm_term (Envir.empty 0) lhs0))
nipkow@208
   902
         then (trace_thm "SUCCEEDED" thm; Some(hyps,rhs))
clasohm@0
   903
         else err()
clasohm@0
   904
     | _ => err()
clasohm@0
   905
  end;
clasohm@0
   906
clasohm@0
   907
(*Conversion to apply the meta simpset to a term*)
nipkow@208
   908
fun rewritec (prover,signt) (mss as Mss{net,...}) (hypst,t) =
clasohm@0
   909
  let val t = Pattern.eta_contract t
clasohm@0
   910
      fun rew {thm as Thm{sign,hyps,maxidx,prop,...}, lhs} =
nipkow@208
   911
	let val unit = if Sign.subsig(sign,signt) then ()
nipkow@208
   912
                  else (writeln"Warning: rewrite rule from different theory";
nipkow@208
   913
                        raise Pattern.MATCH)
nipkow@208
   914
            val insts = Pattern.match (#tsig(Sign.rep_sg signt)) (lhs,t)
clasohm@0
   915
            val prop' = subst_vars insts prop;
clasohm@0
   916
            val hyps' = hyps union hypst;
nipkow@208
   917
            val thm' = Thm{sign=signt, hyps=hyps', prop=prop', maxidx=maxidx}
clasohm@0
   918
        in if nprems_of thm' = 0
clasohm@0
   919
           then let val (_,rhs) = Logic.dest_equals prop'
nipkow@208
   920
                in trace_thm "Rewriting:" thm'; Some(hyps',rhs) end
clasohm@0
   921
           else (trace_thm "Trying to rewrite:" thm';
clasohm@0
   922
                 case prover mss thm' of
clasohm@0
   923
                   None       => (trace_thm "FAILED" thm'; None)
nipkow@112
   924
                 | Some(thm2) => check_conv(thm2,prop'))
clasohm@0
   925
        end
clasohm@0
   926
clasohm@0
   927
      fun rewl [] = None
clasohm@0
   928
	| rewl (rrule::rrules) =
clasohm@0
   929
            let val opt = rew rrule handle Pattern.MATCH => None
clasohm@0
   930
            in case opt of None => rewl rrules | some => some end;
clasohm@0
   931
clasohm@0
   932
  in case t of
nipkow@208
   933
       Abs(_,_,body) $ u => Some(hypst,subst_bounds([u], body))
clasohm@0
   934
     | _                 => rewl (Net.match_term net t)
clasohm@0
   935
  end;
clasohm@0
   936
clasohm@0
   937
(*Conversion to apply a congruence rule to a term*)
nipkow@208
   938
fun congc (prover,signt) {thm=cong,lhs=lhs} (hypst,t) =
clasohm@0
   939
  let val Thm{sign,hyps,maxidx,prop,...} = cong
nipkow@208
   940
      val unit = if Sign.subsig(sign,signt) then ()
nipkow@208
   941
                 else error("Congruence rule from different theory")
nipkow@208
   942
      val tsig = #tsig(Sign.rep_sg signt)
clasohm@0
   943
      val insts = Pattern.match tsig (lhs,t) handle Pattern.MATCH =>
clasohm@0
   944
                  error("Congruence rule did not match")
clasohm@0
   945
      val prop' = subst_vars insts prop;
nipkow@208
   946
      val thm' = Thm{sign=signt, hyps=hyps union hypst,
clasohm@0
   947
                     prop=prop', maxidx=maxidx}
clasohm@0
   948
      val unit = trace_thm "Applying congruence rule" thm';
nipkow@112
   949
      fun err() = error("Failed congruence proof!")
clasohm@0
   950
clasohm@0
   951
  in case prover thm' of
nipkow@112
   952
       None => err()
nipkow@112
   953
     | Some(thm2) => (case check_conv(thm2,prop') of
nipkow@112
   954
                        None => err() | Some(x) => x)
clasohm@0
   955
  end;
clasohm@0
   956
clasohm@0
   957
nipkow@214
   958
fun bottomc ((simprem,useprem),prover,sign) =
clasohm@0
   959
  let fun botc mss trec = let val trec1 = subc mss trec
nipkow@208
   960
                          in case rewritec (prover,sign) mss trec1 of
clasohm@0
   961
                               None => trec1
clasohm@0
   962
                             | Some(trec2) => botc mss trec2
clasohm@0
   963
                          end
clasohm@0
   964
clasohm@0
   965
      and subc (mss as Mss{net,congs,primes,prems,mk_rews})
nipkow@208
   966
               (trec as (hyps,t)) =
clasohm@0
   967
        (case t of
clasohm@0
   968
            Abs(a,T,t) =>
clasohm@0
   969
              let val v = Free(".subc." ^ primes,T)
clasohm@0
   970
                  val mss' = Mss{net=net, congs=congs, primes=primes^"'",
clasohm@0
   971
                                 prems=prems,mk_rews=mk_rews}
nipkow@208
   972
                  val (hyps',t') = botc mss' (hyps,subst_bounds([v],t))
nipkow@208
   973
              in  (hyps', Abs(a, T, abstract_over(v,t')))  end
clasohm@0
   974
          | t$u => (case t of
nipkow@208
   975
              Const("==>",_)$s  => impc(hyps,s,u,mss)
nipkow@208
   976
            | Abs(_,_,body)     => subc mss (hyps,subst_bounds([u], body))
clasohm@0
   977
            | _                 =>
nipkow@208
   978
                let fun appc() = let val (hyps1,t1) = botc mss (hyps,t)
nipkow@208
   979
                                     val (hyps2,u1) = botc mss (hyps1,u)
nipkow@208
   980
                                 in (hyps2,t1$u1) end
clasohm@0
   981
                    val (h,ts) = strip_comb t
clasohm@0
   982
                in case h of
clasohm@0
   983
                     Const(a,_) =>
clasohm@0
   984
                       (case assoc(congs,a) of
clasohm@0
   985
                          None => appc()
nipkow@208
   986
                        | Some(cong) => congc (prover mss,sign) cong trec)
clasohm@0
   987
                   | _ => appc()
clasohm@0
   988
                end)
clasohm@0
   989
          | _ => trec)
clasohm@0
   990
nipkow@208
   991
      and impc(hyps,s,u,mss as Mss{mk_rews,...}) =
nipkow@214
   992
        let val (hyps1,s') = if simprem then botc mss (hyps,s) else (hyps,s)
nipkow@214
   993
            val mss' =
nipkow@214
   994
              if not useprem orelse maxidx_of_term s' <> ~1 then mss
nipkow@208
   995
              else let val thm = Thm{sign=sign,hyps=[s'],prop=s',maxidx= ~1}
nipkow@214
   996
                   in add_simps(add_prems(mss,[thm]), mk_rews thm) end
nipkow@208
   997
            val (hyps2,u') = botc mss' (hyps1,u)
nipkow@134
   998
            val hyps2' = if s' mem hyps1 then hyps2 else hyps2\s'
nipkow@208
   999
        in (hyps2', Logic.mk_implies(s',u')) end
clasohm@0
  1000
clasohm@0
  1001
  in botc end;
clasohm@0
  1002
clasohm@0
  1003
clasohm@0
  1004
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
clasohm@0
  1005
(* Parameters:
nipkow@214
  1006
   mode = (simplify A, use A in simplifying B) when simplifying A ==> B 
clasohm@0
  1007
   mss: contains equality theorems of the form [|p1,...|] ==> t==u
clasohm@0
  1008
   prover: how to solve premises in conditional rewrites and congruences
clasohm@0
  1009
*)
clasohm@0
  1010
clasohm@0
  1011
(*** FIXME: check that #primes(mss) does not "occur" in ct alread ***)
nipkow@214
  1012
fun rewrite_cterm mode mss prover ct =
clasohm@0
  1013
  let val {sign, t, T, maxidx} = Sign.rep_cterm ct;
nipkow@214
  1014
      val (hyps,u) = bottomc (mode,prover,sign) mss ([],t);
clasohm@0
  1015
      val prop = Logic.mk_equals(t,u)
nipkow@208
  1016
  in  Thm{sign= sign, hyps= hyps, maxidx= maxidx_of_term prop, prop= prop}
clasohm@0
  1017
  end
clasohm@0
  1018
clasohm@0
  1019
end;