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