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