src/Provers/blast.ML
author paulson
Mon, 05 Oct 1998 10:30:57 +0200
changeset 5613 5cb6129566e7
parent 5481 c41956742c2e
child 5734 bebd10cb7a8d
permissions -rw-r--r--
MLWorks demands the "op" before $
wenzelm@4078
     1
(*  Title: 	Provers/blast.ML
paulson@2894
     2
    ID:         $Id$
paulson@2894
     3
    Author: 	Lawrence C Paulson, Cambridge University Computer Laboratory
paulson@3083
     4
    Copyright   1997  University of Cambridge
paulson@2894
     5
paulson@2894
     6
Generic tableau prover with proof reconstruction
paulson@2894
     7
paulson@2854
     8
  SKOLEMIZES ReplaceI WRONGLY: allow new vars in prems, or forbid such rules??
paulson@2894
     9
  Needs explicit instantiation of assumptions?
paulson@2894
    10
paulson@2894
    11
paulson@2924
    12
Blast_tac is often more powerful than fast_tac, but has some limitations.
paulson@2924
    13
Blast_tac...
oheimb@4651
    14
  * ignores wrappers (addss, addbefore, addafter, addWrapper, ...); 
oheimb@4651
    15
    this restriction is intrinsic
paulson@2894
    16
  * ignores elimination rules that don't have the correct format
paulson@2894
    17
	(conclusion must be a formula variable)
paulson@2894
    18
  * ignores types, which can make HOL proofs fail
paulson@2924
    19
  * rules must not require higher-order unification, e.g. apply_type in ZF
paulson@2924
    20
    + message "Function Var's argument not a bound variable" relates to this
paulson@2924
    21
  * its proof strategy is more general but can actually be slower
paulson@2894
    22
paulson@2894
    23
Known problems:
paulson@3092
    24
  "Recursive" chains of rules can sometimes exclude other unsafe formulae
paulson@3021
    25
	from expansion.  This happens because newly-created formulae always
paulson@3092
    26
	have priority over existing ones.  But obviously recursive rules 
paulson@5343
    27
	such as transitivity are treated specially to prevent this.  Sometimes
paulson@5343
    28
	the formulae get into the wrong order (see WRONG below).
paulson@3021
    29
paulson@2952
    30
  With overloading:
paulson@5343
    31
        Calls to Blast.overloaded (see HOL/Set.ML for examples) are needed
paulson@5343
    32
	to tell Blast_tac when to retain some type information.  Make sure
paulson@5343
    33
	you know the constant's internal name, which might be "op <=" or 
paulson@5343
    34
	"Relation.op ^^".
paulson@2952
    35
paulson@2924
    36
  With substition for equalities (hyp_subst_tac):
paulson@3092
    37
        When substitution affects a haz formula or literal, it is moved
paulson@2924
    38
        back to the list of safe formulae.
paulson@2924
    39
        But there's no way of putting it in the right place.  A "moved" or
paulson@2924
    40
        "no DETERM" flag would prevent proofs failing here.
paulson@2854
    41
*)
paulson@2854
    42
paulson@2854
    43
(*Should be a type abbreviation?*)
paulson@2854
    44
type netpair = (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net;
paulson@2854
    45
paulson@2854
    46
paulson@2854
    47
(*Assumptions about constants:
paulson@2854
    48
  --The negation symbol is "Not"
paulson@2854
    49
  --The equality symbol is "op ="
paulson@2854
    50
  --The is-true judgement symbol is "Trueprop"
paulson@2854
    51
  --There are no constants named "*Goal* or "*False*"
paulson@2854
    52
*)
paulson@2854
    53
signature BLAST_DATA =
paulson@2854
    54
  sig
paulson@2854
    55
  type claset
paulson@2854
    56
  val notE		: thm		(* [| ~P;  P |] ==> R *)
paulson@2854
    57
  val ccontr		: thm		
paulson@2854
    58
  val contr_tac 	: int -> tactic
paulson@2854
    59
  val dup_intr		: thm -> thm
paulson@4466
    60
  val hyp_subst_tac     : bool ref -> int -> tactic
wenzelm@4078
    61
  val claset		: unit -> claset
oheimb@4653
    62
  val rep_cs	: (* dependent on classical.ML *)
paulson@2854
    63
      claset -> {safeIs: thm list, safeEs: thm list, 
paulson@2854
    64
		 hazIs: thm list, hazEs: thm list,
oheimb@4651
    65
		 swrappers: (string * wrapper) list, 
oheimb@4651
    66
		 uwrappers: (string * wrapper) list,
paulson@2854
    67
		 safe0_netpair: netpair, safep_netpair: netpair,
paulson@2854
    68
		 haz_netpair: netpair, dup_netpair: netpair}
paulson@2854
    69
  end;
paulson@2854
    70
paulson@2854
    71
paulson@2854
    72
signature BLAST =
paulson@2854
    73
  sig
paulson@2924
    74
  type claset 
paulson@4233
    75
  exception TRANS of string    (*reports translation errors*)
paulson@2924
    76
  datatype term = 
paulson@2924
    77
      Const of string
paulson@4065
    78
    | TConst of string * term
paulson@2924
    79
    | Skolem of string * term option ref list
paulson@2924
    80
    | Free  of string
paulson@2924
    81
    | Var   of term option ref
paulson@2924
    82
    | Bound of int
paulson@2924
    83
    | Abs   of string*term
paulson@3030
    84
    | $  of term*term;
paulson@2924
    85
  type branch
paulson@2883
    86
  val depth_tac 	: claset -> int -> int -> tactic
paulson@2883
    87
  val blast_tac 	: claset -> int -> tactic
paulson@2883
    88
  val Blast_tac 	: int -> tactic
paulson@4240
    89
  val overloaded 	: string * (Term.typ -> Term.typ) -> unit
paulson@2924
    90
  (*debugging tools*)
paulson@4323
    91
  val stats	        : bool ref
paulson@2924
    92
  val trace	        : bool ref
paulson@2924
    93
  val fullTrace	        : branch list list ref
paulson@4065
    94
  val fromType	        : (indexname * term) list ref -> Term.typ -> term
paulson@4065
    95
  val fromTerm	        : Term.term -> term
paulson@4065
    96
  val fromSubgoal       : Term.term -> term
paulson@4065
    97
  val instVars          : term -> (unit -> unit)
paulson@2924
    98
  val toTerm	        : int -> term -> Term.term
paulson@2924
    99
  val readGoal          : Sign.sg -> string -> term
paulson@2924
   100
  val tryInThy		: theory -> int -> string ->
paulson@3083
   101
		  (int->tactic) list * branch list list * (int*int*exn) list
paulson@2924
   102
  val trygl		: claset -> int -> int ->
paulson@3083
   103
		  (int->tactic) list * branch list list * (int*int*exn) list
paulson@3083
   104
  val Trygl		: int -> int -> 
paulson@3083
   105
                  (int->tactic) list * branch list list * (int*int*exn) list
paulson@2924
   106
  val normBr		: branch -> branch
paulson@2854
   107
  end;
paulson@2854
   108
paulson@2854
   109
paulson@3092
   110
functor BlastFun(Data: BLAST_DATA) : BLAST = 
paulson@2854
   111
struct
paulson@2854
   112
paulson@2854
   113
type claset = Data.claset;
paulson@2854
   114
paulson@4323
   115
val trace = ref false
paulson@4323
   116
and stats = ref false;   (*for runtime and search statistics*)
paulson@2854
   117
paulson@2854
   118
datatype term = 
paulson@5343
   119
    Const  of string
paulson@4065
   120
  | TConst of string * term    (*type of overloaded constant--as a term!*)
paulson@2854
   121
  | Skolem of string * term option ref list
paulson@5343
   122
  | Free   of string
paulson@5343
   123
  | Var    of term option ref
paulson@5343
   124
  | Bound  of int
paulson@5343
   125
  | Abs    of string*term
paulson@5613
   126
  | op $   of term*term;
paulson@2854
   127
paulson@2854
   128
paulson@2854
   129
(** Basic syntactic operations **)
paulson@2854
   130
paulson@2854
   131
fun is_Var (Var _) = true
paulson@2854
   132
  | is_Var _ = false;
paulson@2854
   133
paulson@2854
   134
fun dest_Var (Var x) =  x;
paulson@2854
   135
paulson@2854
   136
paulson@2854
   137
fun rand (f$x) = x;
paulson@2854
   138
paulson@2854
   139
(* maps   (f, [t1,...,tn])  to  f(t1,...,tn) *)
paulson@2854
   140
val list_comb : term * term list -> term = foldl (op $);
paulson@2854
   141
paulson@2854
   142
paulson@2854
   143
(* maps   f(t1,...,tn)  to  (f, [t1,...,tn]) ; naturally tail-recursive*)
paulson@2854
   144
fun strip_comb u : term * term list = 
paulson@2854
   145
    let fun stripc (f$t, ts) = stripc (f, t::ts)
paulson@2854
   146
        |   stripc  x =  x 
paulson@2854
   147
    in  stripc(u,[])  end;
paulson@2854
   148
paulson@2854
   149
paulson@2854
   150
(* maps   f(t1,...,tn)  to  f , which is never a combination *)
paulson@2854
   151
fun head_of (f$t) = head_of f
paulson@2854
   152
  | head_of u = u;
paulson@2854
   153
paulson@2854
   154
paulson@2854
   155
(** Particular constants **)
paulson@2854
   156
paulson@2854
   157
fun negate P = Const"Not" $ P;
paulson@2854
   158
paulson@2854
   159
fun mkGoal P = Const"*Goal*" $ P;
paulson@2854
   160
paulson@2854
   161
fun isGoal (Const"*Goal*" $ _) = true
paulson@2854
   162
  | isGoal _                   = false;
paulson@2854
   163
paulson@2854
   164
val Trueprop = Term.Const("Trueprop", Type("o",[])-->propT);
paulson@2854
   165
fun mk_tprop P = Term.$ (Trueprop, P);
paulson@2854
   166
paulson@2854
   167
fun isTrueprop (Term.Const("Trueprop",_)) = true
paulson@2854
   168
  | isTrueprop _                          = false;
paulson@2854
   169
paulson@2854
   170
paulson@4065
   171
(*** Dealing with overloaded constants ***)
paulson@2854
   172
paulson@4065
   173
(*alist is a map from TVar names to Vars.  We need to unify the TVars
paulson@4065
   174
  faithfully in order to track overloading*)
paulson@4065
   175
fun fromType alist (Term.Type(a,Ts)) = list_comb (Const a, 
paulson@4065
   176
						  map (fromType alist) Ts)
paulson@4065
   177
  | fromType alist (Term.TFree(a,_)) = Free a
paulson@4065
   178
  | fromType alist (Term.TVar (ixn,_)) =
paulson@4065
   179
	      (case (assoc_string_int(!alist,ixn)) of
paulson@4065
   180
		   None => let val t' = Var(ref None)
paulson@4065
   181
		           in  alist := (ixn, t') :: !alist;  t'
paulson@4065
   182
			   end
paulson@4065
   183
		 | Some v => v)
paulson@2854
   184
paulson@2854
   185
local
paulson@4065
   186
val overloads = ref ([]: (string * (Term.typ -> Term.typ)) list)
paulson@2854
   187
in
paulson@2854
   188
paulson@4240
   189
fun overloaded arg = (overloads := arg :: (!overloads));
paulson@2854
   190
paulson@4065
   191
(*Convert a possibly overloaded Term.Const to a Blast.Const or Blast.TConst,
paulson@4065
   192
  converting its type to a Blast.term in the latter case.*)
paulson@4065
   193
fun fromConst alist (a,T) =
paulson@4065
   194
  case assoc_string (!overloads, a) of
paulson@4065
   195
      None   => Const a		(*not overloaded*)
paulson@4065
   196
    | Some f => 
paulson@4065
   197
	let val T' = f T
paulson@4233
   198
		     handle Match => error
paulson@4233
   199
                ("Blast_tac: unexpected type for overloaded constant " ^ a)
paulson@4065
   200
        in  TConst(a, fromType alist T')  end;
paulson@2854
   201
paulson@2854
   202
end;
paulson@2854
   203
paulson@2854
   204
paulson@2854
   205
(*Tests whether 2 terms are alpha-convertible; chases instantiations*)
paulson@2854
   206
fun (Const a)      aconv (Const b)      = a=b
paulson@4065
   207
  | (TConst (a,ta)) aconv (TConst (b,tb)) = a=b andalso ta aconv tb
paulson@2854
   208
  | (Skolem (a,_)) aconv (Skolem (b,_)) = a=b  (*arglists must then be equal*)
paulson@2854
   209
  | (Free a)       aconv (Free b)       = a=b
paulson@2854
   210
  | (Var(ref(Some t))) aconv u          = t aconv u
paulson@4065
   211
  | t          aconv (Var(ref(Some u))) = t aconv u
paulson@2854
   212
  | (Var v)        aconv (Var w)        = v=w	(*both Vars are un-assigned*)
paulson@2854
   213
  | (Bound i)      aconv (Bound j)      = i=j
paulson@2854
   214
  | (Abs(_,t))     aconv (Abs(_,u))     = t aconv u
paulson@2854
   215
  | (f$t)          aconv (g$u)          = (f aconv g) andalso (t aconv u)
paulson@2854
   216
  | _ aconv _  =  false;
paulson@2854
   217
paulson@2854
   218
paulson@2854
   219
fun mem_term (_, [])     = false
paulson@2854
   220
  | mem_term (t, t'::ts) = t aconv t' orelse mem_term(t,ts);
paulson@2854
   221
paulson@2854
   222
fun ins_term(t,ts) = if mem_term(t,ts) then ts else t :: ts;
paulson@2854
   223
paulson@2854
   224
fun mem_var (v: term option ref, []) = false
paulson@2854
   225
  | mem_var (v, v'::vs)              = v=v' orelse mem_var(v,vs);
paulson@2854
   226
paulson@2854
   227
fun ins_var(v,vs) = if mem_var(v,vs) then vs else v :: vs;
paulson@2854
   228
paulson@2854
   229
paulson@2854
   230
(** Vars **)
paulson@2854
   231
paulson@2854
   232
(*Accumulates the Vars in the term, suppressing duplicates*)
paulson@2854
   233
fun add_term_vars (Skolem(a,args),	vars) = add_vars_vars(args,vars)
paulson@2854
   234
  | add_term_vars (Var (v as ref None),	vars) = ins_var (v, vars)
paulson@2854
   235
  | add_term_vars (Var (ref (Some u)), vars)  = add_term_vars(u,vars)
paulson@4065
   236
  | add_term_vars (TConst (_,t),	vars) = add_term_vars(t,vars)
paulson@2854
   237
  | add_term_vars (Abs (_,body),	vars) = add_term_vars(body,vars)
paulson@2854
   238
  | add_term_vars (f$t,	vars) =  add_term_vars (f, add_term_vars(t, vars))
paulson@2854
   239
  | add_term_vars (_,	vars) = vars
paulson@2854
   240
(*Term list version.  [The fold functionals are slow]*)
paulson@2854
   241
and add_terms_vars ([],    vars) = vars
paulson@2854
   242
  | add_terms_vars (t::ts, vars) = add_terms_vars (ts, add_term_vars(t,vars))
paulson@2854
   243
(*Var list version.*)
paulson@2854
   244
and add_vars_vars ([],    vars) = vars
paulson@2854
   245
  | add_vars_vars (ref (Some u) :: vs, vars) = 
paulson@2854
   246
	add_vars_vars (vs, add_term_vars(u,vars))
paulson@2854
   247
  | add_vars_vars (v::vs, vars) =   (*v must be a ref None*)
paulson@2854
   248
	add_vars_vars (vs, ins_var (v, vars));
paulson@2854
   249
paulson@2854
   250
paulson@2854
   251
(*Chase assignments in "vars"; return a list of unassigned variables*)
paulson@2854
   252
fun vars_in_vars vars = add_vars_vars(vars,[]);
paulson@2854
   253
paulson@2854
   254
paulson@2854
   255
paulson@2854
   256
(*increment a term's non-local bound variables
paulson@2854
   257
     inc is  increment for bound variables
paulson@2854
   258
     lev is  level at which a bound variable is considered 'loose'*)
paulson@2854
   259
fun incr_bv (inc, lev, u as Bound i) = if i>=lev then Bound(i+inc) else u 
paulson@2854
   260
  | incr_bv (inc, lev, Abs(a,body)) = Abs(a, incr_bv(inc,lev+1,body))
paulson@2854
   261
  | incr_bv (inc, lev, f$t) = incr_bv(inc,lev,f) $ incr_bv(inc,lev,t)
paulson@2854
   262
  | incr_bv (inc, lev, u) = u;
paulson@2854
   263
paulson@2854
   264
fun incr_boundvars  0  t = t
paulson@2854
   265
  | incr_boundvars inc t = incr_bv(inc,0,t);
paulson@2854
   266
paulson@2854
   267
paulson@2854
   268
(*Accumulate all 'loose' bound vars referring to level 'lev' or beyond.
paulson@2854
   269
   (Bound 0) is loose at level 0 *)
paulson@2854
   270
fun add_loose_bnos (Bound i, lev, js)   = if i<lev then js  
paulson@2854
   271
					  else  (i-lev) ins_int js
paulson@2854
   272
  | add_loose_bnos (Abs (_,t), lev, js) = add_loose_bnos (t, lev+1, js)
paulson@2854
   273
  | add_loose_bnos (f$t, lev, js)       =
paulson@2854
   274
	        add_loose_bnos (f, lev, add_loose_bnos (t, lev, js)) 
paulson@2854
   275
  | add_loose_bnos (_, _, js)           = js;
paulson@2854
   276
paulson@2854
   277
fun loose_bnos t = add_loose_bnos (t, 0, []);
paulson@2854
   278
paulson@2854
   279
fun subst_bound (arg, t) : term = 
paulson@2854
   280
  let fun subst (t as Bound i, lev) =
paulson@2854
   281
 	    if i<lev then  t    (*var is locally bound*)
paulson@2854
   282
	    else  if i=lev then incr_boundvars lev arg
paulson@2854
   283
		           else Bound(i-1)  (*loose: change it*)
paulson@2854
   284
	| subst (Abs(a,body), lev) = Abs(a, subst(body,lev+1))
paulson@2854
   285
	| subst (f$t, lev) =  subst(f,lev)  $  subst(t,lev)
paulson@2854
   286
	| subst (t,lev)    = t
paulson@2854
   287
  in  subst (t,0)  end;
paulson@2854
   288
paulson@2854
   289
paulson@3101
   290
(*Normalize...but not the bodies of ABSTRACTIONS*)
paulson@2854
   291
fun norm t = case t of
paulson@2952
   292
    Skolem (a,args)      => Skolem(a, vars_in_vars args)
paulson@4065
   293
  | TConst(a,aT)         => TConst(a, norm aT)
paulson@2854
   294
  | (Var (ref None))     => t
paulson@2854
   295
  | (Var (ref (Some u))) => norm u
paulson@2854
   296
  | (f $ u) => (case norm f of
paulson@3101
   297
                    Abs(_,body) => norm (subst_bound (u, body))
paulson@3101
   298
                  | nf => nf $ norm u)
paulson@2854
   299
  | _ => t;
paulson@2854
   300
paulson@2854
   301
paulson@2854
   302
(*Weak (one-level) normalize for use in unification*)
paulson@2854
   303
fun wkNormAux t = case t of
paulson@2854
   304
    (Var v) => (case !v of
paulson@2854
   305
		    Some u => wkNorm u
paulson@2854
   306
		  | None   => t)
paulson@2854
   307
  | (f $ u) => (case wkNormAux f of
paulson@2854
   308
		    Abs(_,body) => wkNorm (subst_bound (u, body))
paulson@2854
   309
		  | nf          => nf $ u)
paulson@2952
   310
  | Abs (a,body) =>	(*eta-contract if possible*)
paulson@2952
   311
	(case wkNormAux body of
paulson@2952
   312
	     nb as (f $ t) => 
paulson@2952
   313
		 if (0 mem_int loose_bnos f) orelse wkNorm t <> Bound 0
paulson@2952
   314
		 then Abs(a,nb)
paulson@2952
   315
		 else wkNorm (incr_boundvars ~1 f)
paulson@3092
   316
	   | nb => Abs (a,nb))
paulson@2854
   317
  | _ => t
paulson@2854
   318
and wkNorm t = case head_of t of
paulson@2854
   319
    Const _        => t
paulson@4065
   320
  | TConst _       => t
paulson@2854
   321
  | Skolem(a,args) => t
paulson@2854
   322
  | Free _         => t
paulson@2854
   323
  | _              => wkNormAux t;
paulson@2854
   324
paulson@2854
   325
paulson@2854
   326
(*Does variable v occur in u?  For unification.*)
paulson@2854
   327
fun varOccur v = 
paulson@2854
   328
  let fun occL [] = false	(*same as (exists occ), but faster*)
paulson@2854
   329
	| occL (u::us) = occ u orelse occL us
paulson@2854
   330
      and occ (Var w) = 
paulson@2854
   331
	      v=w orelse
paulson@2854
   332
              (case !w of None   => false
paulson@2854
   333
	                | Some u => occ u)
paulson@2854
   334
        | occ (Skolem(_,args)) = occL (map Var args)
paulson@4065
   335
        | occ (TConst(_,u)) = occ u
paulson@2854
   336
        | occ (Abs(_,u)) = occ u
paulson@2854
   337
        | occ (f$u)      = occ u  orelse  occ f
paulson@2854
   338
        | occ (_)        = false;
paulson@2854
   339
  in  occ  end;
paulson@2854
   340
paulson@2854
   341
exception UNIFY;
paulson@2854
   342
paulson@2854
   343
val trail = ref [] : term option ref list ref;
paulson@2854
   344
val ntrail = ref 0;
paulson@2854
   345
paulson@2854
   346
paulson@2854
   347
(*Restore the trail to some previous state: for backtracking*)
paulson@2854
   348
fun clearTo n =
paulson@3083
   349
    while !ntrail<>n do
paulson@2854
   350
	(hd(!trail) := None;
paulson@2854
   351
	 trail := tl (!trail);
paulson@2854
   352
	 ntrail := !ntrail - 1);
paulson@2854
   353
paulson@2854
   354
paulson@2854
   355
(*First-order unification with bound variables.  
paulson@2854
   356
  "vars" is a list of variables local to the rule and NOT to be put
paulson@2854
   357
	on the trail (no point in doing so)
paulson@2854
   358
*)
paulson@4065
   359
fun unify(vars,t,u) =
paulson@2854
   360
    let val n = !ntrail 
paulson@2854
   361
	fun update (t as Var v, u) =
paulson@2854
   362
	    if t aconv u then ()
paulson@2854
   363
	    else if varOccur v u then raise UNIFY 
paulson@2854
   364
	    else if mem_var(v, vars) then v := Some u
paulson@2854
   365
		 else (*avoid updating Vars in the branch if possible!*)
paulson@2854
   366
		      if is_Var u andalso mem_var(dest_Var u, vars)
paulson@2854
   367
		      then dest_Var u := Some t
paulson@2854
   368
		      else (v := Some u;
paulson@2854
   369
			    trail := v :: !trail;  ntrail := !ntrail + 1)
paulson@2854
   370
	fun unifyAux (t,u) = 
paulson@2854
   371
	    case (wkNorm t,  wkNorm u) of
paulson@2854
   372
		(nt as Var v,  nu) => update(nt,nu)
paulson@2854
   373
	      | (nu,  nt as Var v) => update(nt,nu)
paulson@4065
   374
	      | (TConst(a,at), TConst(b,bt)) => if a=b then unifyAux(at,bt)
paulson@4065
   375
		                                else raise UNIFY
paulson@2854
   376
	      | (Abs(_,t'),  Abs(_,u')) => unifyAux(t',u')
paulson@2854
   377
		    (*NB: can yield unifiers having dangling Bound vars!*)
paulson@2854
   378
	      | (f$t',  g$u') => (unifyAux(f,g); unifyAux(t',u'))
paulson@2854
   379
	      | (nt,  nu)    => if nt aconv nu then () else raise UNIFY
paulson@3083
   380
    in  (unifyAux(t,u); true) handle UNIFY => (clearTo n; false)
paulson@2854
   381
    end;
paulson@2854
   382
paulson@2854
   383
paulson@4065
   384
(*Convert from "real" terms to prototerms; eta-contract
paulson@4065
   385
  Code is duplicated with fromSubgoal.  Correct this?*)
paulson@4065
   386
fun fromTerm t =
paulson@4065
   387
  let val alistVar = ref []
paulson@4065
   388
      and alistTVar = ref []
paulson@4065
   389
      fun from (Term.Const aT) = fromConst alistTVar aT
paulson@2854
   390
	| from (Term.Free  (a,_)) = Free a
paulson@2854
   391
	| from (Term.Bound i)     = Bound i
paulson@2854
   392
	| from (Term.Var (ixn,T)) = 
paulson@4065
   393
	      (case (assoc_string_int(!alistVar,ixn)) of
paulson@2854
   394
		   None => let val t' = Var(ref None)
paulson@4065
   395
		           in  alistVar := (ixn, t') :: !alistVar;  t'
paulson@2854
   396
			   end
paulson@4065
   397
		 | Some v => v)
paulson@2854
   398
	| from (Term.Abs (a,_,u)) = 
paulson@2854
   399
	      (case  from u  of
paulson@2854
   400
		u' as (f $ Bound 0) => 
paulson@2854
   401
		  if (0 mem_int loose_bnos f) then Abs(a,u')
paulson@2854
   402
		  else incr_boundvars ~1 f 
paulson@2854
   403
	      | u' => Abs(a,u'))
paulson@2854
   404
	| from (Term.$ (f,u)) = from f $ from u
paulson@2854
   405
  in  from t  end;
paulson@2854
   406
paulson@4065
   407
(*A debugging function: replaces all Vars by dummy Frees for visual inspection
paulson@4065
   408
  of whether they are distinct.  Function revert undoes the assignments.*)
paulson@4065
   409
fun instVars t =
paulson@4065
   410
  let val name = ref "A"
paulson@4065
   411
      val updated = ref []
paulson@4065
   412
      fun inst (TConst(a,t)) = inst t
paulson@4065
   413
	| inst (Var(v as ref None)) = (updated := v :: (!updated);
paulson@4065
   414
				       v       := Some (Free ("?" ^ !name)); 
paulson@4065
   415
				       name    := bump_string (!name))
paulson@4065
   416
	| inst (Abs(a,t))    = inst t
paulson@4065
   417
	| inst (f $ u)       = (inst f; inst u)
paulson@4065
   418
	| inst _             = ()
paulson@4065
   419
      fun revert() = seq (fn v => v:=None) (!updated)
paulson@4065
   420
  in  inst t; revert  end;
paulson@4065
   421
paulson@4065
   422
paulson@2854
   423
(* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
paulson@2854
   424
fun strip_imp_prems (Const"==>" $ (Const"Trueprop" $ A) $ B) = 
paulson@2854
   425
           A :: strip_imp_prems B
paulson@2854
   426
  | strip_imp_prems (Const"==>" $ A $ B) = A :: strip_imp_prems B
paulson@2854
   427
  | strip_imp_prems _ = [];
paulson@2854
   428
paulson@2854
   429
(* A1==>...An==>B  goes to B, where B is not an implication *)
paulson@2854
   430
fun strip_imp_concl (Const"==>" $ A $ B) = strip_imp_concl B
paulson@2854
   431
  | strip_imp_concl (Const"Trueprop" $ A) = A
paulson@2854
   432
  | strip_imp_concl A = A : term;
paulson@2854
   433
paulson@2854
   434
paulson@2854
   435
(*** Conversion of Elimination Rules to Tableau Operations ***)
paulson@2854
   436
paulson@2854
   437
(*The conclusion becomes the goal/negated assumption *False*: delete it!*)
paulson@2854
   438
fun squash_nots [] = []
paulson@2854
   439
  | squash_nots (Const "*Goal*" $ (Var (ref (Some (Const"*False*")))) :: Ps) =
paulson@2854
   440
	squash_nots Ps
paulson@2854
   441
  | squash_nots (Const "Not" $ (Var (ref (Some (Const"*False*")))) :: Ps) =
paulson@2854
   442
	squash_nots Ps
paulson@2854
   443
  | squash_nots (P::Ps) = P :: squash_nots Ps;
paulson@2854
   444
paulson@2854
   445
fun skoPrem vars (Const "all" $ Abs (_, P)) =
paulson@2854
   446
        skoPrem vars (subst_bound (Skolem (gensym "S_", vars), P))
paulson@2854
   447
  | skoPrem vars P = P;
paulson@2854
   448
paulson@2854
   449
fun convertPrem t = 
paulson@2854
   450
    squash_nots (mkGoal (strip_imp_concl t) :: strip_imp_prems t);
paulson@2854
   451
paulson@2854
   452
(*Expects elimination rules to have a formula variable as conclusion*)
paulson@2854
   453
fun convertRule vars t =
paulson@2854
   454
  let val (P::Ps) = strip_imp_prems t
paulson@2854
   455
      val Var v   = strip_imp_concl t
paulson@2854
   456
  in  v := Some (Const"*False*");
paulson@2854
   457
      (P, map (convertPrem o skoPrem vars) Ps) 
paulson@2854
   458
  end;
paulson@2854
   459
paulson@2854
   460
paulson@2854
   461
(*Like dup_elim, but puts the duplicated major premise FIRST*)
wenzelm@4271
   462
fun rev_dup_elim th = th RSN (2, revcut_rl) |> assumption 2 |> Seq.hd;
paulson@2854
   463
paulson@2854
   464
paulson@4391
   465
(*Rotate the assumptions in all new subgoals for the LIFO discipline*)
paulson@4391
   466
local
paulson@4391
   467
  (*Count new hyps so that they can be rotated*)
paulson@4391
   468
  fun nNewHyps []                         = 0
paulson@4391
   469
    | nNewHyps (Const "*Goal*" $ _ :: Ps) = nNewHyps Ps
paulson@4391
   470
    | nNewHyps (P::Ps)                    = 1 + nNewHyps Ps;
paulson@2854
   471
paulson@5463
   472
  fun rot_tac [] i st      = Seq.single st
paulson@4391
   473
    | rot_tac (0::ks) i st = rot_tac ks (i+1) st
paulson@4391
   474
    | rot_tac (k::ks) i st = rot_tac ks (i+1) (rotate_rule (~k) i st);
paulson@4391
   475
in
paulson@4391
   476
fun rot_subgoals_tac (rot, rl) =
paulson@4391
   477
     rot_tac (if rot then map nNewHyps rl else []) 
paulson@4391
   478
end;
paulson@4391
   479
paulson@2854
   480
paulson@2999
   481
fun TRACE rl tac st i = if !trace then (prth rl; tac st i) else tac st i;
paulson@2854
   482
paulson@5343
   483
(*Resolution/matching tactics: if upd then the proof state may be updated.
paulson@5343
   484
  Matching makes the tactics more deterministic in the presence of Vars.*)
paulson@5343
   485
fun emtac upd rl = TRACE rl (if upd then etac rl else ematch_tac [rl]);
paulson@5343
   486
fun rmtac upd rl = TRACE rl (if upd then rtac rl else match_tac [rl]);
paulson@5343
   487
paulson@5343
   488
(*Tableau rule from elimination rule.  
paulson@5343
   489
  Flag "upd" says that the inference updated the branch.
paulson@5343
   490
  Flag "dup" requests duplication of the affected formula.*)
paulson@2854
   491
fun fromRule vars rl = 
paulson@4065
   492
  let val trl = rl |> rep_thm |> #prop |> fromTerm |> convertRule vars
paulson@5343
   493
      fun tac (upd, dup,rot) i = 
paulson@5343
   494
	emtac upd (if dup then rev_dup_elim rl else rl) i
paulson@4391
   495
	THEN
paulson@4391
   496
	rot_subgoals_tac (rot, #2 trl) i
paulson@3244
   497
  in Option.SOME (trl, tac) end
paulson@2924
   498
  handle Bind => (*reject: conclusion is not just a variable*)
wenzelm@3533
   499
   (if !trace then (warning ("ignoring ill-formed elimination rule\n" ^
wenzelm@3533
   500
		    string_of_thm rl))
paulson@2924
   501
    else ();
paulson@3244
   502
    Option.NONE);
paulson@2854
   503
paulson@2854
   504
paulson@3101
   505
(*** Conversion of Introduction Rules ***)
paulson@2854
   506
paulson@2854
   507
fun convertIntrPrem t = mkGoal (strip_imp_concl t) :: strip_imp_prems t;
paulson@2854
   508
paulson@2854
   509
fun convertIntrRule vars t =
paulson@2854
   510
  let val Ps = strip_imp_prems t
paulson@2854
   511
      val P  = strip_imp_concl t
paulson@2854
   512
  in  (mkGoal P, map (convertIntrPrem o skoPrem vars) Ps) 
paulson@2854
   513
  end;
paulson@2854
   514
paulson@5343
   515
(*Tableau rule from introduction rule.  
paulson@5343
   516
  Flag "upd" says that the inference updated the branch.
paulson@5343
   517
  Flag "dup" requests duplication of the affected formula.
paulson@5343
   518
  Since haz rules are now delayed, "dup" is always FALSE for
paulson@5343
   519
  introduction rules.*)
paulson@2854
   520
fun fromIntrRule vars rl = 
paulson@4065
   521
  let val trl = rl |> rep_thm |> #prop |> fromTerm |> convertIntrRule vars
paulson@5343
   522
      fun tac (upd,dup,rot) i = 
paulson@5343
   523
	 rmtac upd (if dup then Data.dup_intr rl else rl) i
paulson@4391
   524
	 THEN
paulson@4391
   525
	 rot_subgoals_tac (rot, #2 trl) i
paulson@2854
   526
  in (trl, tac) end;
paulson@2854
   527
paulson@2854
   528
paulson@3030
   529
val dummyVar = Term.Var (("etc",0), dummyT);
paulson@2854
   530
paulson@2854
   531
(*Convert from prototerms to ordinary terms with dummy types
paulson@2924
   532
  Ignore abstractions; identify all Vars; STOP at given depth*)
paulson@2924
   533
fun toTerm 0 _             = dummyVar
paulson@2924
   534
  | toTerm d (Const a)     = Term.Const (a,dummyT)
paulson@4065
   535
  | toTerm d (TConst(a,_)) = Term.Const (a,dummyT)  (*no need to convert type*)
paulson@2924
   536
  | toTerm d (Skolem(a,_)) = Term.Const (a,dummyT)
paulson@2924
   537
  | toTerm d (Free a)      = Term.Free  (a,dummyT)
paulson@2924
   538
  | toTerm d (Bound i)     = Term.Bound i
paulson@2924
   539
  | toTerm d (Var _)       = dummyVar
paulson@2924
   540
  | toTerm d (Abs(a,_))    = dummyVar
paulson@2924
   541
  | toTerm d (f $ u)       = Term.$ (toTerm d f, toTerm (d-1) u);
paulson@2854
   542
paulson@2854
   543
paulson@2854
   544
fun netMkRules P vars (nps: netpair list) =
paulson@2854
   545
  case P of
paulson@2854
   546
      (Const "*Goal*" $ G) =>
paulson@2924
   547
	let val pG = mk_tprop (toTerm 2 G)
paulson@2854
   548
	    val intrs = List.concat 
paulson@2854
   549
		             (map (fn (inet,_) => Net.unify_term inet pG) 
paulson@2854
   550
			      nps)
paulson@2854
   551
	in  map (fromIntrRule vars o #2) (orderlist intrs)  end
paulson@2854
   552
    | _ =>
paulson@2924
   553
	let val pP = mk_tprop (toTerm 3 P)
paulson@2854
   554
	    val elims = List.concat 
paulson@2854
   555
		             (map (fn (_,enet) => Net.unify_term enet pP) 
paulson@2854
   556
			      nps)
paulson@2854
   557
	in  List.mapPartial (fromRule vars o #2) (orderlist elims)  end;
paulson@2854
   558
paulson@2854
   559
(**
paulson@2854
   560
end;
paulson@2854
   561
**)
paulson@2854
   562
paulson@3092
   563
paulson@3092
   564
(*Pending formulae carry md (may duplicate) flags*)
paulson@5463
   565
type branch = 
paulson@5463
   566
    {pairs: ((term*bool) list *	(*safe formulae on this level*)
paulson@5463
   567
               (term*bool) list) list,  (*haz formulae  on this level*)
paulson@5463
   568
     lits:   term list,                 (*literals: irreducible formulae*)
paulson@5463
   569
     vars:   term option ref list,      (*variables occurring in branch*)
paulson@5463
   570
     lim:    int};                      (*resource limit*)
paulson@3092
   571
paulson@3092
   572
val fullTrace = ref[] : branch list list ref;
paulson@3092
   573
paulson@3092
   574
(*Normalize a branch--for tracing*)
paulson@3092
   575
fun norm2 (G,md) = (norm G, md);
paulson@3092
   576
paulson@3092
   577
fun normLev (Gs,Hs) = (map norm2 Gs, map norm2 Hs);
paulson@3092
   578
paulson@5463
   579
fun normBr {pairs, lits, vars, lim} =
paulson@5463
   580
     {pairs = map normLev pairs, 
paulson@5463
   581
      lits  = map norm lits, 
paulson@5463
   582
      vars  = vars, 
paulson@5463
   583
      lim   = lim};
paulson@3092
   584
paulson@3092
   585
paulson@4065
   586
val dummyTVar = Term.TVar(("a",0), []);
paulson@3092
   587
val dummyVar2 = Term.Var(("var",0), dummyT);
paulson@3092
   588
paulson@4065
   589
(*convert Blast_tac's type representation to real types for tracing*)
paulson@4065
   590
fun showType (Free a)  = Term.TFree (a,[])
paulson@4065
   591
  | showType (Var _)   = dummyTVar
paulson@4065
   592
  | showType t         =
paulson@4065
   593
      (case strip_comb t of
paulson@4065
   594
	   (Const a, us) => Term.Type(a, map showType us)
paulson@4065
   595
	 | _ => dummyT);
paulson@4065
   596
paulson@4065
   597
(*Display top-level overloading if any*)
paulson@4065
   598
fun topType (TConst(a,t)) = Some (showType t)
paulson@4065
   599
  | topType (Abs(a,t))    = topType t
paulson@4065
   600
  | topType (f $ u)       = (case topType f of
paulson@4065
   601
				 None => topType u
paulson@4065
   602
			       | some => some)
paulson@4065
   603
  | topType _             = None;
paulson@4065
   604
paulson@4065
   605
paulson@3092
   606
(*Convert from prototerms to ordinary terms with dummy types for tracing*)
paulson@3092
   607
fun showTerm d (Const a)     = Term.Const (a,dummyT)
paulson@4065
   608
  | showTerm d (TConst(a,_)) = Term.Const (a,dummyT)
paulson@3092
   609
  | showTerm d (Skolem(a,_)) = Term.Const (a,dummyT)
paulson@3092
   610
  | showTerm d (Free a)      = Term.Free  (a,dummyT)
paulson@3092
   611
  | showTerm d (Bound i)     = Term.Bound i
paulson@3101
   612
  | showTerm d (Var(ref(Some u))) = showTerm d u
paulson@3101
   613
  | showTerm d (Var(ref None))    = dummyVar2
paulson@3092
   614
  | showTerm d (Abs(a,t))    = if d=0 then dummyVar
paulson@3092
   615
			       else Term.Abs(a, dummyT, showTerm (d-1) t)
paulson@3092
   616
  | showTerm d (f $ u)       = if d=0 then dummyVar
paulson@3092
   617
			       else Term.$ (showTerm d f, showTerm (d-1) u);
paulson@3092
   618
paulson@4065
   619
fun string_of sign d t = Sign.string_of_term sign (showTerm d t);
paulson@3092
   620
paulson@4065
   621
fun traceTerm sign t = 
paulson@4065
   622
  let val t' = norm t
paulson@4065
   623
      val stm = string_of sign 8 t'
paulson@4065
   624
  in  
paulson@4065
   625
      case topType t' of
paulson@4065
   626
	  None   => stm   (*no type to attach*)
paulson@4065
   627
	| Some T => stm ^ "\t:: " ^ Sign.string_of_typ sign T
paulson@4065
   628
  end;
paulson@3092
   629
paulson@3092
   630
paulson@3092
   631
(*Print tracing information at each iteration of prover*)
paulson@3092
   632
fun tracing sign brs = 
paulson@3092
   633
  let fun printPairs (((G,_)::_,_)::_)  = prs(traceTerm sign G)
paulson@3092
   634
	| printPairs (([],(H,_)::_)::_) = prs(traceTerm sign H ^ "\t (Unsafe)")
paulson@3092
   635
	| printPairs _                 = ()
paulson@5463
   636
      fun printBrs (brs0 as {pairs, lits, lim, ...} :: brs) =
paulson@3092
   637
	    (fullTrace := brs0 :: !fullTrace;
paulson@3092
   638
	     seq (fn _ => prs "+") brs;
paulson@3092
   639
	     prs (" [" ^ Int.toString lim ^ "] ");
paulson@3092
   640
	     printPairs pairs;
paulson@3092
   641
	     writeln"")
paulson@3092
   642
  in if !trace then printBrs (map normBr brs) else ()
paulson@3092
   643
  end;
paulson@3092
   644
paulson@5343
   645
fun traceMsg s = if !trace then writeln s else ();
paulson@4065
   646
paulson@3092
   647
(*Tracing: variables updated in the last branch operation?*)
paulson@4065
   648
fun traceVars sign ntrl =
paulson@4065
   649
  if !trace then 
paulson@4065
   650
      (case !ntrail-ntrl of
paulson@4065
   651
	    0 => ()
paulson@4065
   652
	  | 1 => prs"\t1 variable UPDATED:"
paulson@4065
   653
	  | n => prs("\t" ^ Int.toString n ^ " variables UPDATED:");
paulson@4065
   654
       (*display the instantiations themselves, though no variable names*)
paulson@4065
   655
       seq (fn v => prs("   " ^ string_of sign 4 (the (!v))))
paulson@4065
   656
           (List.take(!trail, !ntrail-ntrl));
paulson@4065
   657
       writeln"")
paulson@3092
   658
    else ();
paulson@3092
   659
paulson@3092
   660
(*Tracing: how many new branches are created?*)
paulson@3092
   661
fun traceNew prems =
paulson@3092
   662
    if !trace then 
paulson@3092
   663
        case length prems of
paulson@3092
   664
	    0 => prs"branch closed by rule"
paulson@3092
   665
	  | 1 => prs"branch extended (1 new subgoal)"
paulson@3092
   666
	  | n => prs("branch split: "^ Int.toString n ^ " new subgoals")
paulson@3092
   667
    else ();
paulson@3092
   668
paulson@3092
   669
paulson@3092
   670
paulson@2854
   671
(*** Code for handling equality: naive substitution, like hyp_subst_tac ***)
paulson@2854
   672
paulson@2854
   673
(*Replace the ATOMIC term "old" by "new" in t*)  
paulson@2854
   674
fun subst_atomic (old,new) t =
paulson@2854
   675
    let fun subst (Var(ref(Some u))) = subst u
paulson@2854
   676
	  | subst (Abs(a,body))      = Abs(a, subst body)
paulson@2854
   677
	  | subst (f$t)              = subst f $ subst t
paulson@2854
   678
	  | subst t                  = if t aconv old then new else t
paulson@2854
   679
    in  subst t  end;
paulson@2854
   680
paulson@2854
   681
(*Eta-contract a term from outside: just enough to reduce it to an atom*)
paulson@2854
   682
fun eta_contract_atom (t0 as Abs(a, body)) = 
paulson@2854
   683
      (case  eta_contract2 body  of
paulson@2854
   684
        f $ Bound 0 => if (0 mem_int loose_bnos f) then t0
paulson@2854
   685
		       else eta_contract_atom (incr_boundvars ~1 f)
paulson@2854
   686
      | _ => t0)
paulson@2854
   687
  | eta_contract_atom t = t
paulson@2854
   688
and eta_contract2 (f$t) = f $ eta_contract_atom t
paulson@2854
   689
  | eta_contract2 t     = eta_contract_atom t;
paulson@2854
   690
paulson@2854
   691
paulson@2854
   692
(*When can we safely delete the equality?
paulson@2854
   693
    Not if it equates two constants; consider 0=1.
paulson@2854
   694
    Not if it resembles x=t[x], since substitution does not eliminate x.
paulson@2854
   695
    Not if it resembles ?x=0; another goal could instantiate ?x to Suc(i)
paulson@2854
   696
  Prefer to eliminate Bound variables if possible.
paulson@2854
   697
  Result:  true = use as is,  false = reorient first *)
paulson@2854
   698
paulson@4354
   699
(*Can t occur in u?  For substitution.  
paulson@4354
   700
  Does NOT examine the args of Skolem terms: substitution does not affect them.
paulson@4196
   701
  REFLEXIVE because hyp_subst_tac fails on x=x.*)
paulson@2854
   702
fun substOccur t = 
paulson@4354
   703
  let (*NO vars are permitted in u except the arguments of t, if it is 
paulson@4354
   704
        a Skolem term.  This ensures that no equations are deleted that could
paulson@4354
   705
        be instantiated to a cycle.  For example, x=?a is rejected because ?a
paulson@4354
   706
	could be instantiated to Suc(x).*)
paulson@4354
   707
      val vars = case t of
paulson@4354
   708
                     Skolem(_,vars) => vars
paulson@4354
   709
		   | _ => []
paulson@4354
   710
      fun occEq u = (t aconv u) orelse occ u
paulson@4354
   711
      and occ (Var(ref(Some u))) = occEq u
paulson@4354
   712
        | occ (Var v)            = not (mem_var (v, vars))
paulson@4354
   713
	| occ (Abs(_,u))         = occEq u
paulson@2854
   714
        | occ (f$u)              = occEq u  orelse  occEq f
paulson@2854
   715
        | occ (_)                = false;
paulson@2854
   716
  in  occEq  end;
paulson@2854
   717
paulson@3092
   718
exception DEST_EQ;
paulson@3092
   719
paulson@3092
   720
(*Take apart an equality (plain or overloaded).  NO constant Trueprop*)
paulson@3092
   721
fun dest_eq (Const  "op ="     $ t $ u) = 
paulson@3092
   722
		(eta_contract_atom t, eta_contract_atom u)
paulson@4065
   723
  | dest_eq (TConst("op =",_)  $ t $ u) = 
paulson@3092
   724
		(eta_contract_atom t, eta_contract_atom u)
paulson@3092
   725
  | dest_eq _                           = raise DEST_EQ;
paulson@3092
   726
paulson@4196
   727
(*Reject the equality if u occurs in (or equals!) t*)
paulson@2854
   728
fun check (t,u,v) = if substOccur t u then raise DEST_EQ else v;
paulson@2854
   729
paulson@2854
   730
(*IF the goal is an equality with a substitutable variable 
paulson@2854
   731
  THEN orient that equality ELSE raise exception DEST_EQ*)
paulson@3092
   732
fun orientGoal (t,u) = case (t,u) of
paulson@2854
   733
       (Skolem _, _) => check(t,u,(t,u))	(*eliminates t*)
paulson@2854
   734
     | (_, Skolem _) => check(u,t,(u,t))	(*eliminates u*)
paulson@2854
   735
     | (Free _, _)   => check(t,u,(t,u))	(*eliminates t*)
paulson@2854
   736
     | (_, Free _)   => check(u,t,(u,t))	(*eliminates u*)
paulson@2854
   737
     | _             => raise DEST_EQ;
paulson@2854
   738
paulson@2894
   739
(*Substitute through the branch if an equality goal (else raise DEST_EQ).
paulson@2894
   740
  Moves affected literals back into the branch, but it is not clear where
paulson@4391
   741
  they should go: this could make proofs fail.*)
paulson@5463
   742
fun equalSubst sign (G, {pairs, lits, vars, lim}) = 
paulson@3092
   743
  let val (t,u) = orientGoal(dest_eq G)
paulson@3092
   744
      val subst = subst_atomic (t,u)
paulson@2854
   745
      fun subst2(G,md) = (subst G, md)
paulson@4466
   746
      (*substitute throughout list; extract affected formulae*)
paulson@4466
   747
      fun subForm ((G,md), (changed, pairs)) =
paulson@4466
   748
	    let val nG = subst G
paulson@4466
   749
	    in  if nG aconv G then (changed, (G,md)::pairs)
paulson@4466
   750
		              else ((nG,md)::changed, pairs)
paulson@2924
   751
            end
paulson@4466
   752
      (*substitute throughout "stack frame"; extract affected formulae*)
paulson@4466
   753
      fun subFrame ((Gs,Hs), (changed, frames)) =
paulson@4466
   754
	    let val (changed', Gs') = foldr subForm (Gs, (changed, []))
paulson@4466
   755
                val (changed'', Hs') = foldr subForm (Hs, (changed', []))
paulson@4466
   756
            in  (changed'', (Gs',Hs')::frames)  end
paulson@4466
   757
      (*substitute throughout literals; extract affected ones*)
paulson@4466
   758
      fun subLit (lit, (changed, nlits)) =
paulson@2854
   759
	    let val nlit = subst lit
paulson@4466
   760
	    in  if nlit aconv lit then (changed, nlit::nlits)
paulson@4466
   761
		                  else ((nlit,true)::changed, nlits)
paulson@2854
   762
            end
paulson@4466
   763
      val (changed, lits') = foldr subLit (lits, ([], []))
paulson@4466
   764
      val (changed', pairs') = foldr subFrame (pairs, (changed, []))
paulson@3092
   765
  in  if !trace then writeln ("Substituting " ^ traceTerm sign u ^
paulson@3092
   766
			      " for " ^ traceTerm sign t ^ " in branch" )
paulson@3092
   767
      else ();
paulson@5463
   768
      {pairs = (changed',[])::pairs',	(*affected formulas, and others*)
paulson@5463
   769
       lits  = lits',			(*unaffected literals*)
paulson@5463
   770
       vars  = vars, 
paulson@5463
   771
       lim   = lim}
paulson@2854
   772
  end;
paulson@2854
   773
paulson@2854
   774
paulson@2854
   775
exception NEWBRANCHES and CLOSEF;
paulson@2854
   776
paulson@2854
   777
exception PROVE;
paulson@2854
   778
paulson@4391
   779
(*Trying eq_contr_tac first INCREASES the effort, slowing reconstruction*)
paulson@4391
   780
val contr_tac = ematch_tac [Data.notE] THEN' 
paulson@4391
   781
                (eq_assume_tac ORELSE' assume_tac);
paulson@2854
   782
paulson@4391
   783
val eContr_tac  = TRACE Data.notE contr_tac;
paulson@2854
   784
val eAssume_tac = TRACE asm_rl   (eq_assume_tac ORELSE' assume_tac);
paulson@2854
   785
paulson@2854
   786
(*Try to unify complementary literals and return the corresponding tactic. *) 
paulson@3083
   787
fun tryClose (Const"*Goal*" $ G,  L) = 
paulson@4065
   788
	if unify([],G,L) then Some eAssume_tac else None
paulson@3083
   789
  | tryClose (G,  Const"*Goal*" $ L) = 
paulson@4065
   790
	if unify([],G,L) then Some eAssume_tac else None
paulson@3083
   791
  | tryClose (Const"Not" $ G,  L)    = 
paulson@4065
   792
	if unify([],G,L) then Some eContr_tac else None
paulson@3083
   793
  | tryClose (G,  Const"Not" $ L)    = 
paulson@4065
   794
	if unify([],G,L) then Some eContr_tac else None
paulson@3083
   795
  | tryClose _                       = None;
paulson@2854
   796
paulson@2854
   797
paulson@2854
   798
(*Were there Skolem terms in the premise?  Must NOT chase Vars*)
paulson@2854
   799
fun hasSkolem (Skolem _)     = true
paulson@2854
   800
  | hasSkolem (Abs (_,body)) = hasSkolem body 
paulson@2854
   801
  | hasSkolem (f$t)          =  hasSkolem f orelse hasSkolem t
paulson@2854
   802
  | hasSkolem _              = false;
paulson@2854
   803
paulson@2854
   804
(*Attach the right "may duplicate" flag to new formulae: if they contain
paulson@2854
   805
  Skolem terms then allow duplication.*)
paulson@2854
   806
fun joinMd md [] = []
paulson@2854
   807
  | joinMd md (G::Gs) = (G, hasSkolem G orelse md) :: joinMd md Gs;
paulson@2854
   808
paulson@2894
   809
(*Convert a Goal to an ordinary Not.  Used also in dup_intr, where a goal like
paulson@2894
   810
  Ex(P) is duplicated as the assumption ~Ex(P). *)
paulson@2894
   811
fun negOfGoal (Const"*Goal*" $ G) = negate G
paulson@2894
   812
  | negOfGoal G                   = G;
paulson@2894
   813
paulson@2894
   814
fun negOfGoal2 (G,md) = (negOfGoal G, md);
paulson@2894
   815
paulson@2894
   816
(*Converts all Goals to Nots in the safe parts of a branch.  They could
paulson@2894
   817
  have been moved there from the literals list after substitution (equalSubst).
paulson@2894
   818
  There can be at most one--this function could be made more efficient.*)
paulson@2894
   819
fun negOfGoals pairs = map (fn (Gs,haz) => (map negOfGoal2 Gs, haz)) pairs;
paulson@2894
   820
paulson@2894
   821
(*Tactic.  Convert *Goal* to negated assumption in FIRST position*)
paulson@4391
   822
fun negOfGoal_tac i = TRACE Data.ccontr (rtac Data.ccontr) i THEN
paulson@4391
   823
                      rotate_tac ~1 i;
paulson@2894
   824
paulson@2854
   825
paulson@2854
   826
(** Backtracking and Pruning **)
paulson@2854
   827
paulson@2854
   828
(*clashVar vars (n,trail) determines whether any of the last n elements
paulson@2854
   829
  of "trail" occur in "vars" OR in their instantiations*)
paulson@2854
   830
fun clashVar [] = (fn _ => false)
paulson@2854
   831
  | clashVar vars =
paulson@2854
   832
      let fun clash (0, _)     = false
paulson@2854
   833
	    | clash (_, [])    = false
paulson@2854
   834
	    | clash (n, v::vs) = exists (varOccur v) vars orelse clash(n-1,vs)
paulson@2854
   835
      in  clash  end;
paulson@2854
   836
paulson@2854
   837
paulson@2854
   838
(*nbrs = # of branches just prior to closing this one.  Delete choice points
paulson@2854
   839
  for goals proved by the latest inference, provided NO variables in the
paulson@2854
   840
  next branch have been updated.*)
paulson@2854
   841
fun prune (1, nxtVars, choices) = choices  (*DON'T prune at very end: allow 
paulson@2854
   842
					     backtracking over bad proofs*)
paulson@2854
   843
  | prune (nbrs, nxtVars, choices) =
paulson@2854
   844
      let fun traceIt last =
paulson@2854
   845
		let val ll = length last
paulson@2854
   846
		    and lc = length choices
paulson@2854
   847
		in if !trace andalso ll<lc then
paulson@3083
   848
		    (writeln("Pruning " ^ Int.toString(lc-ll) ^ " levels"); 
paulson@2854
   849
		     last)
paulson@2854
   850
		   else last
paulson@2854
   851
		end
paulson@2854
   852
	  fun pruneAux (last, _, _, []) = last
paulson@3083
   853
	    | pruneAux (last, ntrl, trl, (ntrl',nbrs',exn) :: choices) =
paulson@2854
   854
		if nbrs' < nbrs 
paulson@2854
   855
		then last  (*don't backtrack beyond first solution of goal*)
paulson@2854
   856
		else if nbrs' > nbrs then pruneAux (last, ntrl, trl, choices)
paulson@2854
   857
		else (* nbrs'=nbrs *)
paulson@2854
   858
		     if clashVar nxtVars (ntrl-ntrl', trl) then last
paulson@2854
   859
		     else (*no clashes: can go back at least this far!*)
paulson@2854
   860
			  pruneAux(choices, ntrl', List.drop(trl, ntrl-ntrl'), 
paulson@2854
   861
				   choices)
paulson@2854
   862
  in  traceIt (pruneAux (choices, !ntrail, !trail, choices))  end;
paulson@2854
   863
paulson@5463
   864
fun nextVars ({pairs, lits, vars, lim} :: _) = map Var vars
paulson@5463
   865
  | nextVars []                              = [];
paulson@2854
   866
paulson@3083
   867
fun backtrack (choices as (ntrl, nbrs, exn)::_) = 
paulson@3083
   868
      (if !trace then (writeln ("Backtracking; now there are " ^ 
paulson@3083
   869
				Int.toString nbrs ^ " branches"))
paulson@3083
   870
                 else (); 
paulson@3083
   871
       raise exn)
paulson@3083
   872
  | backtrack _ = raise PROVE;
paulson@2854
   873
paulson@2894
   874
(*Add the literal G, handling *Goal* and detecting duplicates.*)
paulson@2894
   875
fun addLit (Const "*Goal*" $ G, lits) = 
paulson@2894
   876
      (*New literal is a *Goal*, so change all other Goals to Nots*)
paulson@2854
   877
      let fun bad (Const"*Goal*" $ _) = true
paulson@2854
   878
	    | bad (Const"Not" $ G')   = G aconv G'
paulson@2854
   879
	    | bad _                   = false;
paulson@2854
   880
	  fun change [] = []
paulson@2854
   881
	    | change (Const"*Goal*" $ G' :: lits) = 
paulson@2854
   882
		  if G aconv G' then change lits
paulson@2854
   883
		  else Const"Not" $ G' :: change lits
paulson@2854
   884
	    | change (Const"Not" $ G' :: lits)    = 
paulson@2854
   885
		  if G aconv G' then change lits
paulson@2854
   886
		  else Const"Not" $ G' :: change lits
paulson@2854
   887
	    | change (lit::lits) = lit :: change lits
paulson@2854
   888
      in
paulson@2854
   889
	Const "*Goal*" $ G :: (if exists bad lits then change lits else lits)
paulson@2854
   890
      end
paulson@2854
   891
  | addLit (G,lits) = ins_term(G, lits)
paulson@2854
   892
paulson@2854
   893
paulson@2952
   894
(*For calculating the "penalty" to assess on a branching factor of n
paulson@2952
   895
  log2 seems a little too severe*)
paulson@3083
   896
fun log n = if n<4 then 0 else 1 + log(n div 4);
paulson@2924
   897
paulson@2924
   898
paulson@3021
   899
(*match(t,u) says whether the term u might be an instance of the pattern t
paulson@3021
   900
  Used to detect "recursive" rules such as transitivity*)
paulson@3021
   901
fun match (Var _) u   = true
paulson@4065
   902
  | match (Const"*Goal*") (Const"Not")    = true
paulson@4065
   903
  | match (Const"Not")    (Const"*Goal*") = true
paulson@4065
   904
  | match (Const a)       (Const b)       = (a=b)
paulson@4065
   905
  | match (TConst (a,ta)) (TConst (b,tb)) = a=b andalso match ta tb
paulson@4065
   906
  | match (Free a)        (Free b)        = (a=b)
paulson@4065
   907
  | match (Bound i)       (Bound j)       = (i=j)
paulson@4065
   908
  | match (Abs(_,t))      (Abs(_,u))      = match t u
paulson@4065
   909
  | match (f$t)           (g$u)           = match f g andalso match t u
paulson@4065
   910
  | match t               u   = false;
paulson@3021
   911
paulson@3021
   912
paulson@4300
   913
(*Branches closed: number of branches closed during the search
paulson@4300
   914
  Branches tried:  number of branches created by splitting (counting from 1)*)
paulson@4300
   915
val nclosed = ref 0
paulson@4300
   916
and ntried  = ref 1;
paulson@4300
   917
paulson@4391
   918
fun printStats (b, start, tacs) =
paulson@4323
   919
  if b then
paulson@4323
   920
    writeln (endTiming start ^ " for search.  Closed: " 
paulson@4323
   921
	     ^ Int.toString (!nclosed) ^
paulson@4391
   922
             " tried: " ^ Int.toString (!ntried) ^
paulson@4391
   923
             " tactics: " ^ Int.toString (length tacs))
paulson@4323
   924
  else ();
paulson@4323
   925
paulson@4323
   926
paulson@2854
   927
(*Tableau prover based on leanTaP.  Argument is a list of branches.  Each 
paulson@2854
   928
  branch contains a list of unexpanded formulae, a list of literals, and a 
paulson@4391
   929
  bound on unsafe expansions.
paulson@4391
   930
 "start" is CPU time at start, for printing search time
paulson@4391
   931
*)
paulson@4391
   932
fun prove (sign, start, cs, brs, cont) =
oheimb@4653
   933
 let val {safe0_netpair, safep_netpair, haz_netpair, ...} = Data.rep_cs cs
paulson@2854
   934
     val safeList = [safe0_netpair, safep_netpair]
paulson@2854
   935
     and hazList  = [haz_netpair]
paulson@4065
   936
     fun prv (tacs, trs, choices, []) = 
paulson@4391
   937
	        (printStats (!trace orelse !stats, start, tacs); 
paulson@4323
   938
		 cont (tacs, trs, choices))   (*all branches closed!*)
paulson@2854
   939
       | prv (tacs, trs, choices, 
paulson@5463
   940
	      brs0 as {pairs = ((G,md)::br, haz)::pairs, 
paulson@5463
   941
		       lits, vars, lim} :: brs) =
paulson@3917
   942
   	     (*apply a safe rule only (possibly allowing instantiation);
paulson@3917
   943
               defer any haz formulae*)
paulson@2854
   944
	  let exception PRV (*backtrack to precisely this recursion!*)
paulson@2854
   945
	      val ntrl = !ntrail 
paulson@2854
   946
	      val nbrs = length brs0
paulson@2854
   947
              val nxtVars = nextVars brs
paulson@2854
   948
	      val G = norm G
paulson@2924
   949
	      val rules = netMkRules G vars safeList
paulson@2854
   950
	      (*Make a new branch, decrementing "lim" if instantiations occur*)
paulson@2894
   951
	      fun newBr (vars',lim') prems =
paulson@2894
   952
		  map (fn prem => 
paulson@2894
   953
		       if (exists isGoal prem) 
paulson@5463
   954
		       then {pairs = ((joinMd md prem, []) :: 
paulson@5463
   955
				      negOfGoals ((br, haz)::pairs)),
paulson@5463
   956
			     lits  = map negOfGoal lits, 
paulson@5463
   957
			     vars  = vars', 
paulson@5463
   958
			     lim   = lim'}
paulson@5463
   959
		       else {pairs = ((joinMd md prem, []) :: 
paulson@5463
   960
				      (br, haz) :: pairs),
paulson@5463
   961
			     lits = lits, 
paulson@5463
   962
			     vars = vars', 
paulson@5463
   963
			     lim  = lim'})
paulson@2854
   964
		  prems @
paulson@2854
   965
		  brs		  
paulson@2854
   966
	      (*Seek a matching rule.  If unifiable then add new premises
paulson@2854
   967
                to branch.*)
paulson@2854
   968
	      fun deeper [] = raise NEWBRANCHES
paulson@2854
   969
		| deeper (((P,prems),tac)::grls) =
paulson@4065
   970
		    if unify(add_term_vars(P,[]), P, G) 
paulson@3083
   971
		    then  (*P comes from the rule; G comes from the branch.*)
paulson@5343
   972
		     let val updated = ntrl < !ntrail (*branch updated*)
paulson@5343
   973
			 val lim' = if updated
paulson@3083
   974
				    then lim - (1+log(length rules))
paulson@3083
   975
				    else lim   (*discourage branching updates*)
paulson@3083
   976
			 val vars  = vars_in_vars vars
paulson@3083
   977
			 val vars' = foldr add_terms_vars (prems, vars)
paulson@3083
   978
			 val choices' = (ntrl, nbrs, PRV) :: choices
paulson@5463
   979
			 val tacs' = (tac(updated,false,true)) 
paulson@5343
   980
                                     :: tacs  (*no duplication; rotate*)
paulson@3083
   981
		     in
paulson@4065
   982
			 traceNew prems;  traceVars sign ntrl;
paulson@3083
   983
			 (if null prems then (*closed the branch: prune!*)
paulson@4300
   984
			    (nclosed := !nclosed + 1;
paulson@4300
   985
			     prv(tacs',  brs0::trs, 
paulson@4300
   986
				 prune (nbrs, nxtVars, choices'),
paulson@4300
   987
				 brs))
paulson@4300
   988
			  else (*prems non-null*)
paulson@3083
   989
			  if lim'<0 (*faster to kill ALL the alternatives*)
paulson@5343
   990
			  then (traceMsg"Excessive branching: KILLED";
paulson@4065
   991
			        clearTo ntrl;  raise NEWBRANCHES)
paulson@3083
   992
			  else
paulson@4300
   993
			    (ntried := !ntried + length prems - 1;
paulson@4300
   994
			     prv(tacs',  brs0::trs, choices',
paulson@4300
   995
				 newBr (vars',lim') prems)))
paulson@3083
   996
                         handle PRV => 
paulson@5343
   997
			   if updated then
paulson@3083
   998
				(*Backtrack at this level.
paulson@3083
   999
				  Reset Vars and try another rule*)
paulson@3083
  1000
				(clearTo ntrl;  deeper grls)
paulson@3083
  1001
			   else (*backtrack to previous level*)
paulson@3083
  1002
				backtrack choices
paulson@3083
  1003
		     end
paulson@3083
  1004
		    else deeper grls
paulson@2854
  1005
	      (*Try to close branch by unifying with head goal*)
paulson@2854
  1006
	      fun closeF [] = raise CLOSEF
paulson@2854
  1007
		| closeF (L::Ls) = 
paulson@3083
  1008
		    case tryClose(G,L) of
paulson@3083
  1009
			None     => closeF Ls
paulson@3083
  1010
		      | Some tac => 
paulson@3083
  1011
			    let val choices' = 
paulson@3092
  1012
				    (if !trace then (prs"branch closed";
paulson@4065
  1013
						     traceVars sign ntrl)
paulson@3083
  1014
				               else ();
paulson@3083
  1015
				     prune (nbrs, nxtVars, 
paulson@3083
  1016
					    (ntrl, nbrs, PRV) :: choices))
paulson@4300
  1017
			    in  nclosed := !nclosed + 1;
paulson@4300
  1018
				prv (tac::tacs, brs0::trs, choices', brs)  
paulson@3083
  1019
				handle PRV => 
paulson@3083
  1020
				    (*reset Vars and try another literal
paulson@3083
  1021
				      [this handler is pruned if possible!]*)
paulson@3083
  1022
				 (clearTo ntrl;  closeF Ls)
paulson@3083
  1023
			    end
paulson@2894
  1024
	      fun closeFl [] = raise CLOSEF
paulson@2894
  1025
		| closeFl ((br, haz)::pairs) =
paulson@2894
  1026
		    closeF (map fst br)
paulson@2894
  1027
		      handle CLOSEF => closeF (map fst haz)
paulson@2894
  1028
			handle CLOSEF => closeFl pairs
paulson@3083
  1029
	  in tracing sign brs0; 
paulson@4065
  1030
	     if lim<0 then (traceMsg "Limit reached.  "; backtrack choices)
paulson@2854
  1031
	     else
paulson@4466
  1032
	     prv (Data.hyp_subst_tac trace :: tacs, 
paulson@2854
  1033
		  brs0::trs,  choices,
paulson@5463
  1034
		  equalSubst sign
paulson@5463
  1035
		    (G, {pairs = (br,haz)::pairs, 
paulson@5463
  1036
			 lits  = lits, vars  = vars, lim   = lim}) 
paulson@5463
  1037
		    :: brs)
paulson@4065
  1038
	     handle DEST_EQ =>   closeF lits
paulson@4065
  1039
	      handle CLOSEF =>   closeFl ((br,haz)::pairs)
paulson@4065
  1040
	        handle CLOSEF => deeper rules
paulson@2894
  1041
		  handle NEWBRANCHES => 
paulson@2894
  1042
		   (case netMkRules G vars hazList of
paulson@4466
  1043
		       [] => (*there are no plausible haz rules*)
paulson@5463
  1044
			     (traceMsg "moving formula to literals";
paulson@5463
  1045
			      prv (tacs, brs0::trs, choices,
paulson@5463
  1046
				   {pairs = (br,haz)::pairs, 
paulson@5463
  1047
				    lits  = addLit(G,lits), 
paulson@5463
  1048
				    vars  = vars, 
paulson@5463
  1049
				    lim   = lim}  :: brs))
paulson@2894
  1050
		    | _ => (*G admits some haz rules: try later*)
paulson@5463
  1051
			   (traceMsg "moving formula to haz list";
paulson@4466
  1052
			    prv (if isGoal G then negOfGoal_tac :: tacs
paulson@5463
  1053
				             else tacs, 
paulson@5463
  1054
				 brs0::trs,  
paulson@5463
  1055
				 choices,
paulson@5463
  1056
				 {pairs = (br, haz@[(negOfGoal G, md)])::pairs,
paulson@5463
  1057
				  lits  = lits,
paulson@5463
  1058
				  vars  = vars, 
paulson@5463
  1059
				  lim   = lim}  :: brs)))
paulson@2854
  1060
	  end
paulson@2924
  1061
       | prv (tacs, trs, choices, 
paulson@5463
  1062
	      {pairs = ([],haz)::(Gs,haz')::pairs, lits, vars, lim} :: brs) =
paulson@2894
  1063
	     (*no more "safe" formulae: transfer haz down a level*)
paulson@2924
  1064
	   prv (tacs, trs, choices, 
paulson@5463
  1065
		{pairs = (Gs,haz@haz')::pairs, 
paulson@5463
  1066
		 lits  = lits, 
paulson@5463
  1067
		 vars  = vars, 
paulson@5463
  1068
		 lim    = lim} :: brs)
paulson@2854
  1069
       | prv (tacs, trs, choices, 
paulson@5463
  1070
	      brs0 as {pairs = [([], (H,md)::Hs)],
paulson@5463
  1071
		       lits, vars, lim} :: brs) =
paulson@2894
  1072
   	     (*no safe steps possible at any level: apply a haz rule*)
paulson@2854
  1073
	  let exception PRV (*backtrack to precisely this recursion!*)
paulson@2894
  1074
	      val H = norm H
paulson@2854
  1075
	      val ntrl = !ntrail
paulson@2924
  1076
	      val rules = netMkRules H vars hazList
paulson@3021
  1077
	      (*new premises of haz rules may NOT be duplicated*)
paulson@4391
  1078
	      fun newPrem (vars,P,dup,lim') prem = 
paulson@4391
  1079
		  let val Gs' = map (fn Q => (Q,false)) prem
paulson@3021
  1080
		      and Hs' = if dup then Hs @ [(negOfGoal H, md)] else Hs
paulson@4196
  1081
		      and lits' = if (exists isGoal prem) 
paulson@4196
  1082
			          then map negOfGoal lits
paulson@4196
  1083
				  else lits
paulson@5463
  1084
                  in  {pairs = if exists (match P) prem then [(Gs',Hs')] 
paulson@5463
  1085
			       (*Recursive in this premise.  Don't make new
paulson@5463
  1086
				 "stack frame".  New haz premises will end up
paulson@5463
  1087
				 at the BACK of the queue, preventing
paulson@5463
  1088
				 exclusion of others*)
paulson@5463
  1089
			    else [(Gs',[]), ([],Hs')], 
paulson@5463
  1090
		       lits = lits', 
paulson@5463
  1091
		       vars = vars, 
paulson@5463
  1092
		       lim  = lim'}
paulson@3021
  1093
		  end
paulson@2854
  1094
	      fun newBr x prems = map (newPrem x) prems  @  brs
paulson@2854
  1095
	      (*Seek a matching rule.  If unifiable then add new premises
paulson@2854
  1096
                to branch.*)
paulson@2854
  1097
	      fun deeper [] = raise NEWBRANCHES
paulson@2854
  1098
		| deeper (((P,prems),tac)::grls) =
paulson@4065
  1099
		    if unify(add_term_vars(P,[]), P, H)
paulson@3083
  1100
		    then
paulson@5343
  1101
		     let val updated = ntrl < !ntrail (*branch updated*)
paulson@3083
  1102
			 val vars  = vars_in_vars vars
paulson@3083
  1103
			 val vars' = foldr add_terms_vars (prems, vars)
paulson@3083
  1104
			    (*duplicate H if md and the subgoal has new vars*)
paulson@3083
  1105
			 val dup = md andalso vars' <> vars
paulson@5463
  1106
			     (*any instances of P in the subgoals?
paulson@5463
  1107
			       NB: this boolean affects tracing only!*)
paulson@3083
  1108
			 and recur = exists (exists (match P)) prems
paulson@3083
  1109
			 val lim' = (*Decrement "lim" extra if updates occur*)
paulson@5343
  1110
			     if updated then lim - (1+log(length rules))
paulson@3083
  1111
			     else lim-1 
paulson@3083
  1112
				 (*It is tempting to leave "lim" UNCHANGED if
paulson@3083
  1113
				   both dup and recur are false.  Proofs are
paulson@3083
  1114
				   found at shallower depths, but looping
paulson@3083
  1115
				   occurs too often...*)
paulson@3917
  1116
			 val mayUndo = 
paulson@3917
  1117
			     (*Allowing backtracking from a rule application
paulson@3917
  1118
			       if other matching rules exist, if the rule
paulson@3917
  1119
			       updated variables, or if the rule did not
paulson@3917
  1120
			       introduce new variables.  This latter condition
paulson@3917
  1121
			       means it is not a standard "gamma-rule" but
paulson@3917
  1122
			       some other form of unsafe rule.  Aim is to
paulson@3917
  1123
			       emulate Fast_tac, which allows all unsafe steps
paulson@3917
  1124
			       to be undone.*)
paulson@3917
  1125
			     not(null grls)   (*other rules to try?*)
paulson@5343
  1126
			     orelse updated
paulson@3917
  1127
			     orelse vars=vars'   (*no new Vars?*)
paulson@5481
  1128
			 val tac' = tac(updated, dup, true)
paulson@5463
  1129
		       (*if recur then perhaps shouldn't call rotate_tac: new
paulson@5463
  1130
                         formulae should be last, but that's WRONG if the new
paulson@5463
  1131
                         formulae are Goals, since they remain in the first
paulson@5463
  1132
                         position*)
paulson@5463
  1133
paulson@3083
  1134
		     in
paulson@3083
  1135
		       if lim'<0 andalso not (null prems)
paulson@3083
  1136
		       then (*it's faster to kill ALL the alternatives*)
paulson@5343
  1137
			   (traceMsg"Excessive branching: KILLED";
paulson@4065
  1138
			    clearTo ntrl;  raise NEWBRANCHES)
paulson@3083
  1139
		       else 
paulson@4391
  1140
			 traceNew prems;  
paulson@4391
  1141
			 if !trace andalso recur then prs" (recursive)"
paulson@4391
  1142
					         else ();
paulson@4391
  1143
			 traceVars sign ntrl;
paulson@4300
  1144
			 if null prems then nclosed := !nclosed + 1
paulson@4300
  1145
			 else ntried := !ntried + length prems - 1;
paulson@4391
  1146
			 prv(tac' :: tacs, 
paulson@3083
  1147
			     brs0::trs, 
paulson@3083
  1148
			     (ntrl, length brs0, PRV) :: choices, 
paulson@4391
  1149
			     newBr (vars', P, dup, lim') prems)
paulson@3083
  1150
			  handle PRV => 
paulson@3083
  1151
			      if mayUndo
paulson@3083
  1152
			      then (*reset Vars and try another rule*)
paulson@3083
  1153
				   (clearTo ntrl;  deeper grls)
paulson@3083
  1154
			      else (*backtrack to previous level*)
paulson@3083
  1155
				   backtrack choices
paulson@3083
  1156
		     end
paulson@3083
  1157
		    else deeper grls
paulson@3083
  1158
	  in tracing sign brs0; 
paulson@4065
  1159
	     if lim<1 then (traceMsg "Limit reached.  "; backtrack choices)
paulson@2924
  1160
	     else deeper rules
paulson@2854
  1161
	     handle NEWBRANCHES => 
paulson@2894
  1162
		 (*cannot close branch: move H to literals*)
paulson@2854
  1163
		 prv (tacs,  brs0::trs,  choices,
paulson@5463
  1164
		      {pairs = [([], Hs)], 
paulson@5463
  1165
		       lits  = H::lits, 
paulson@5463
  1166
		       vars  = vars, 
paulson@5463
  1167
		       lim   = lim}  :: brs)
paulson@2854
  1168
	  end
paulson@2854
  1169
       | prv (tacs, trs, choices, _ :: brs) = backtrack choices
paulson@4065
  1170
 in init_gensym();
paulson@4065
  1171
    prv ([], [], [(!ntrail, length brs, PROVE)], brs) 
paulson@4065
  1172
 end;
paulson@2854
  1173
paulson@2854
  1174
paulson@2883
  1175
(*Construct an initial branch.*)
paulson@2854
  1176
fun initBranch (ts,lim) = 
paulson@5463
  1177
    {pairs = [(map (fn t => (t,true)) ts, [])],
paulson@5463
  1178
     lits  = [], 
paulson@5463
  1179
     vars  = add_terms_vars (ts,[]), 
paulson@5463
  1180
     lim   = lim};
paulson@2854
  1181
paulson@2854
  1182
paulson@2854
  1183
(*** Conversion & Skolemization of the Isabelle proof state ***)
paulson@2854
  1184
paulson@2854
  1185
(*Make a list of all the parameters in a subgoal, even if nested*)
paulson@2854
  1186
local open Term 
paulson@2854
  1187
in
paulson@2854
  1188
fun discard_foralls (Const("all",_)$Abs(a,T,t)) = discard_foralls t
paulson@2854
  1189
  | discard_foralls t = t;
paulson@2854
  1190
end;
paulson@2854
  1191
paulson@2854
  1192
paulson@2854
  1193
(*List of variables not appearing as arguments to the given parameter*)
paulson@2854
  1194
fun getVars []                  i = []
paulson@2854
  1195
  | getVars ((_,(v,is))::alist) i =
paulson@2854
  1196
	if i mem is then getVars alist i
paulson@2854
  1197
	else v :: getVars alist i;
paulson@2854
  1198
paulson@4233
  1199
exception TRANS of string;
paulson@2854
  1200
paulson@4233
  1201
(*Translation of a subgoal: Skolemize all parameters*)
paulson@4065
  1202
fun fromSubgoal t =
paulson@4065
  1203
  let val alistVar = ref []
paulson@4065
  1204
      and alistTVar = ref []
paulson@2854
  1205
      fun hdvar ((ix,(v,is))::_) = v
paulson@2854
  1206
      fun from lev t =
paulson@2854
  1207
	let val (ht,ts) = Term.strip_comb t
paulson@2854
  1208
	    fun apply u = list_comb (u, map (from lev) ts)
paulson@2854
  1209
	    fun bounds [] = []
paulson@2854
  1210
	      | bounds (Term.Bound i::ts) = 
paulson@4233
  1211
		  if i<lev then raise TRANS
paulson@4233
  1212
		      "Function unknown's argument not a parameter"
paulson@2854
  1213
		  else i-lev :: bounds ts
paulson@4233
  1214
	      | bounds ts = raise TRANS
paulson@4233
  1215
		      "Function unknown's argument not a bound variable"
paulson@2854
  1216
        in
paulson@2854
  1217
	  case ht of 
paulson@4065
  1218
	      Term.Const aT    => apply (fromConst alistTVar aT)
paulson@2854
  1219
	    | Term.Free  (a,_) => apply (Free a)
paulson@2854
  1220
	    | Term.Bound i     => apply (Bound i)
paulson@2854
  1221
	    | Term.Var (ix,_) => 
paulson@4065
  1222
		  (case (assoc_string_int(!alistVar,ix)) of
paulson@4065
  1223
		       None => (alistVar := (ix, (ref None, bounds ts))
paulson@4065
  1224
					  :: !alistVar;
paulson@4065
  1225
				Var (hdvar(!alistVar)))
paulson@2854
  1226
		     | Some(v,is) => if is=bounds ts then Var v
paulson@4233
  1227
			    else raise TRANS
paulson@5411
  1228
				("Discrepancy among occurrences of "
paulson@4233
  1229
				 ^ Syntax.string_of_vname ix))
paulson@2854
  1230
	    | Term.Abs (a,_,body) => 
paulson@2854
  1231
		  if null ts then Abs(a, from (lev+1) body)
paulson@4233
  1232
		  else raise TRANS "argument not in normal form"
paulson@2854
  1233
        end
paulson@2854
  1234
paulson@2854
  1235
      val npars = length (Logic.strip_params t)
paulson@2854
  1236
paulson@2854
  1237
      (*Skolemize a subgoal from a proof state*)
paulson@2854
  1238
      fun skoSubgoal i t =
paulson@2854
  1239
	  if i<npars then 
paulson@2854
  1240
	      skoSubgoal (i+1)
paulson@4065
  1241
		(subst_bound (Skolem (gensym "T_", getVars (!alistVar) i), 
paulson@2854
  1242
			      t))
paulson@2854
  1243
	  else t
paulson@2854
  1244
paulson@2854
  1245
  in  skoSubgoal 0 (from 0 (discard_foralls t))  end;
paulson@2854
  1246
paulson@2854
  1247
paulson@4300
  1248
fun initialize() = 
paulson@4300
  1249
    (fullTrace:=[];  trail := [];  ntrail := 0;
paulson@4300
  1250
     nclosed := 0;  ntried := 1);
paulson@4300
  1251
paulson@4300
  1252
paulson@2854
  1253
(*Tactic using tableau engine and proof reconstruction.  
paulson@4391
  1254
 "start" is CPU time at start, for printing SEARCH time
paulson@4391
  1255
	(also prints reconstruction time)
paulson@2854
  1256
 "lim" is depth limit.*)
paulson@4391
  1257
fun timing_depth_tac start cs lim i st = 
paulson@4323
  1258
 (initialize();
paulson@4323
  1259
  let val {sign,...} = rep_thm st
paulson@4323
  1260
      val skoprem = fromSubgoal (List.nth(prems_of st, i-1))
paulson@4323
  1261
      val hyps  = strip_imp_prems skoprem
paulson@4323
  1262
      and concl = strip_imp_concl skoprem
paulson@4323
  1263
      fun cont (tacs,_,choices) = 
paulson@4323
  1264
	  let val start = startTiming()
paulson@4323
  1265
	  in
paulson@4323
  1266
	  case Seq.pull(EVERY' (rev tacs) i st) of
paulson@4323
  1267
	      None => (writeln ("PROOF FAILED for depth " ^
paulson@4323
  1268
				Int.toString lim);
paulson@5463
  1269
		       if !trace then writeln "************************\n"
paulson@5463
  1270
		       else ();
paulson@4323
  1271
		       backtrack choices)
paulson@4323
  1272
	    | cell => (if (!trace orelse !stats)
paulson@4323
  1273
		       then writeln (endTiming start ^ " for reconstruction")
paulson@4323
  1274
		       else ();
paulson@4323
  1275
		       Seq.make(fn()=> cell))
paulson@4323
  1276
          end
paulson@4391
  1277
  in prove (sign, start, cs, [initBranch (mkGoal concl :: hyps, lim)], cont) 
paulson@4323
  1278
  end
paulson@4323
  1279
  handle PROVE     => Seq.empty);
paulson@2854
  1280
paulson@4391
  1281
(*Public version with fixed depth*)
paulson@4391
  1282
fun depth_tac cs lim i st = timing_depth_tac (startTiming()) cs lim i st;
paulson@4391
  1283
paulson@4391
  1284
fun blast_tac cs i st = 
paulson@5463
  1285
    ((DEEPEN (1,20) (timing_depth_tac (startTiming()) cs) 0) i 
paulson@5463
  1286
     THEN flexflex_tac) st
paulson@4391
  1287
    handle TRANS s => (warning ("Blast_tac: " ^ s); Seq.empty);
paulson@2854
  1288
wenzelm@4078
  1289
fun Blast_tac i = blast_tac (Data.claset()) i;
paulson@2854
  1290
paulson@2924
  1291
paulson@2924
  1292
(*** For debugging: these apply the prover to a subgoal and return 
paulson@2924
  1293
     the resulting tactics, trace, etc.                            ***)
paulson@2924
  1294
paulson@2924
  1295
(*Translate subgoal i from a proof state*)
paulson@2924
  1296
fun trygl cs lim i = 
paulson@4300
  1297
    (initialize();
paulson@2924
  1298
     let val st = topthm()
paulson@3030
  1299
         val {sign,...} = rep_thm st
paulson@4065
  1300
	 val skoprem = fromSubgoal (List.nth(prems_of st, i-1))
paulson@2924
  1301
         val hyps  = strip_imp_prems skoprem
paulson@2924
  1302
         and concl = strip_imp_concl skoprem
paulson@4391
  1303
     in timeap prove (sign, startTiming(), cs, 
paulson@4391
  1304
		      [initBranch (mkGoal concl :: hyps, lim)], I)
paulson@2924
  1305
     end
paulson@2924
  1306
     handle Subscript => error("There is no subgoal " ^ Int.toString i));
paulson@2924
  1307
wenzelm@4078
  1308
fun Trygl lim i = trygl (Data.claset()) lim i;
paulson@2924
  1309
paulson@2924
  1310
(*Read a string to make an initial, singleton branch*)
paulson@2924
  1311
fun readGoal sign s = read_cterm sign (s,propT) |>
paulson@4065
  1312
                      term_of |> fromTerm |> rand |> mkGoal;
paulson@2924
  1313
paulson@2924
  1314
fun tryInThy thy lim s = 
paulson@4300
  1315
    (initialize();
paulson@4323
  1316
     timeap prove (sign_of thy, 
paulson@4391
  1317
		   startTiming(), 
paulson@4323
  1318
		   Data.claset(), 
paulson@4323
  1319
		   [initBranch ([readGoal (sign_of thy) s], lim)], 
paulson@4323
  1320
		   I));
paulson@2924
  1321
paulson@2924
  1322
paulson@2854
  1323
end;