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