src/Provers/blast.ML
author paulson
Thu Nov 20 10:54:04 1997 +0100 (1997-11-20)
changeset 4240 8ba60a4cd380
parent 4233 85d004a96b98
child 4271 3a82492e70c5
permissions -rw-r--r--
Renamed "overload" to "overloaded" for sml/nj compatibility
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...
paulson@2894
    14
  * ignores addss, addbefore, addafter; this restriction is intrinsic
paulson@2894
    15
  * ignores elimination rules that don't have the correct format
paulson@2894
    16
	(conclusion must be a formula variable)
paulson@2894
    17
  * ignores types, which can make HOL proofs fail
paulson@2924
    18
  * rules must not require higher-order unification, e.g. apply_type in ZF
paulson@2924
    19
    + message "Function Var's argument not a bound variable" relates to this
paulson@2924
    20
  * its proof strategy is more general but can actually be slower
paulson@2894
    21
paulson@2894
    22
Known problems:
paulson@3092
    23
  "Recursive" chains of rules can sometimes exclude other unsafe formulae
paulson@3021
    24
	from expansion.  This happens because newly-created formulae always
paulson@3092
    25
	have priority over existing ones.  But obviously recursive rules 
paulson@3092
    26
	such as transitivity are treated specially to prevent this.
paulson@3021
    27
paulson@2952
    28
  With overloading:
paulson@3021
    29
        Overloading can't follow all chains of type dependencies.  Cannot
paulson@2952
    30
        prove "In1 x ~: Part A In0" because PartE introducees the polymorphic
paulson@2952
    31
	equality In1 x = In0 y, when the corresponding rule uses the (distinct)
paulson@2952
    32
	set equality.  Workaround: supply a type instance of the rule that
paulson@2952
    33
	creates new equalities (e.g. PartE in HOL/ex/Simult)
paulson@2952
    34
	==> affects freeness reasoning about Sexp constants (since they have
paulson@2952
    35
		type ... set)
paulson@2952
    36
paulson@2924
    37
  With substition for equalities (hyp_subst_tac):
paulson@3092
    38
        When substitution affects a haz formula or literal, it is moved
paulson@2924
    39
        back to the list of safe formulae.
paulson@2924
    40
        But there's no way of putting it in the right place.  A "moved" or
paulson@2924
    41
        "no DETERM" flag would prevent proofs failing here.
paulson@2854
    42
*)
paulson@2854
    43
paulson@2854
    44
paulson@2854
    45
(*Should be a type abbreviation?*)
paulson@2854
    46
type netpair = (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net;
paulson@2854
    47
paulson@2854
    48
paulson@2854
    49
(*Assumptions about constants:
paulson@2854
    50
  --The negation symbol is "Not"
paulson@2854
    51
  --The equality symbol is "op ="
paulson@2854
    52
  --The is-true judgement symbol is "Trueprop"
paulson@2854
    53
  --There are no constants named "*Goal* or "*False*"
paulson@2854
    54
*)
paulson@2854
    55
signature BLAST_DATA =
paulson@2854
    56
  sig
paulson@2854
    57
  type claset
paulson@2854
    58
  val notE		: thm		(* [| ~P;  P |] ==> R *)
paulson@2854
    59
  val ccontr		: thm		
paulson@2854
    60
  val contr_tac 	: int -> tactic
paulson@2854
    61
  val dup_intr		: thm -> thm
paulson@2854
    62
  val vars_gen_hyp_subst_tac : bool -> int -> tactic
wenzelm@4078
    63
  val claset		: unit -> claset
paulson@2854
    64
  val rep_claset	: 
paulson@2854
    65
      claset -> {safeIs: thm list, safeEs: thm list, 
paulson@2854
    66
		 hazIs: thm list, hazEs: thm list,
paulson@2854
    67
		 uwrapper: (int -> tactic) -> (int -> tactic),
paulson@2854
    68
		 swrapper: (int -> tactic) -> (int -> tactic),
paulson@2854
    69
		 safe0_netpair: netpair, safep_netpair: netpair,
paulson@2854
    70
		 haz_netpair: netpair, dup_netpair: netpair}
paulson@2854
    71
  end;
paulson@2854
    72
paulson@2854
    73
paulson@2854
    74
signature BLAST =
paulson@2854
    75
  sig
paulson@2924
    76
  type claset 
paulson@4233
    77
  exception TRANS of string    (*reports translation errors*)
paulson@2924
    78
  datatype term = 
paulson@2924
    79
      Const of string
paulson@4065
    80
    | TConst of string * term
paulson@2924
    81
    | Skolem of string * term option ref list
paulson@2924
    82
    | Free  of string
paulson@2924
    83
    | Var   of term option ref
paulson@2924
    84
    | Bound of int
paulson@2924
    85
    | Abs   of string*term
paulson@3030
    86
    | $  of term*term;
paulson@2924
    87
  type branch
paulson@2883
    88
  val depth_tac 	: claset -> int -> int -> tactic
paulson@2883
    89
  val blast_tac 	: claset -> int -> tactic
paulson@2883
    90
  val Blast_tac 	: int -> tactic
paulson@4240
    91
  val overloaded 	: string * (Term.typ -> Term.typ) -> unit
paulson@2924
    92
  (*debugging tools*)
paulson@2924
    93
  val trace	        : bool ref
paulson@2924
    94
  val fullTrace	        : branch list list ref
paulson@4065
    95
  val fromType	        : (indexname * term) list ref -> Term.typ -> term
paulson@4065
    96
  val fromTerm	        : Term.term -> term
paulson@4065
    97
  val fromSubgoal       : Term.term -> term
paulson@4065
    98
  val instVars          : term -> (unit -> unit)
paulson@2924
    99
  val toTerm	        : int -> term -> Term.term
paulson@2924
   100
  val readGoal          : Sign.sg -> string -> term
paulson@2924
   101
  val tryInThy		: theory -> int -> string ->
paulson@3083
   102
		  (int->tactic) list * branch list list * (int*int*exn) list
paulson@2924
   103
  val trygl		: claset -> int -> int ->
paulson@3083
   104
		  (int->tactic) list * branch list list * (int*int*exn) list
paulson@3083
   105
  val Trygl		: int -> int -> 
paulson@3083
   106
                  (int->tactic) list * branch list list * (int*int*exn) list
paulson@2924
   107
  val normBr		: branch -> branch
paulson@2854
   108
  end;
paulson@2854
   109
paulson@2854
   110
paulson@3092
   111
functor BlastFun(Data: BLAST_DATA) : BLAST = 
paulson@2854
   112
struct
paulson@2854
   113
paulson@2854
   114
type claset = Data.claset;
paulson@2854
   115
paulson@2854
   116
val trace = ref false;
paulson@2854
   117
paulson@2854
   118
datatype term = 
paulson@2854
   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@2854
   122
  | Free  of string
paulson@2854
   123
  | Var   of term option ref
paulson@2854
   124
  | Bound of int
paulson@2854
   125
  | Abs   of string*term
paulson@2854
   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@4065
   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*)
paulson@2854
   462
fun rev_dup_elim th = th RSN (2, revcut_rl) |> assumption 2 |> Sequence.hd;
paulson@2854
   463
paulson@2854
   464
paulson@2854
   465
(*Count new hyps so that they can be rotated*)
paulson@2854
   466
fun nNewHyps []                         = 0
paulson@2854
   467
  | nNewHyps (Const "*Goal*" $ _ :: Ps) = nNewHyps Ps
paulson@2854
   468
  | nNewHyps (P::Ps)                    = 1 + nNewHyps Ps;
paulson@2854
   469
paulson@2854
   470
fun rot_subgoals_tac [] i st      = Sequence.single st
paulson@2854
   471
  | rot_subgoals_tac (k::ks) i st =
paulson@2854
   472
      rot_subgoals_tac ks (i+1) (Sequence.hd (rotate_tac (~k) i st))
wenzelm@4149
   473
      handle OPTION => Sequence.null;
paulson@2854
   474
paulson@2999
   475
fun TRACE rl tac st i = if !trace then (prth rl; tac st i) else tac st i;
paulson@2854
   476
paulson@2854
   477
(*Tableau rule from elimination rule.  Flag "dup" requests duplication of the
paulson@2854
   478
  affected formula.*)
paulson@2854
   479
fun fromRule vars rl = 
paulson@4065
   480
  let val trl = rl |> rep_thm |> #prop |> fromTerm |> convertRule vars
paulson@2854
   481
      fun tac dup i = 
paulson@2999
   482
	  TRACE rl (etac (if dup then rev_dup_elim rl else rl)) i
paulson@2854
   483
	  THEN rot_subgoals_tac (map nNewHyps (#2 trl)) i
paulson@2854
   484
	  
paulson@3244
   485
  in Option.SOME (trl, tac) end
paulson@2924
   486
  handle Bind => (*reject: conclusion is not just a variable*)
wenzelm@3533
   487
   (if !trace then (warning ("ignoring ill-formed elimination rule\n" ^
wenzelm@3533
   488
		    string_of_thm rl))
paulson@2924
   489
    else ();
paulson@3244
   490
    Option.NONE);
paulson@2854
   491
paulson@2854
   492
paulson@3101
   493
(*** Conversion of Introduction Rules ***)
paulson@2854
   494
paulson@2854
   495
fun convertIntrPrem t = mkGoal (strip_imp_concl t) :: strip_imp_prems t;
paulson@2854
   496
paulson@2854
   497
fun convertIntrRule vars t =
paulson@2854
   498
  let val Ps = strip_imp_prems t
paulson@2854
   499
      val P  = strip_imp_concl t
paulson@2854
   500
  in  (mkGoal P, map (convertIntrPrem o skoPrem vars) Ps) 
paulson@2854
   501
  end;
paulson@2854
   502
paulson@2854
   503
(*Tableau rule from introduction rule.  Since haz rules are now delayed, 
paulson@2854
   504
  "dup" is always FALSE for introduction rules.*)
paulson@2854
   505
fun fromIntrRule vars rl = 
paulson@4065
   506
  let val trl = rl |> rep_thm |> #prop |> fromTerm |> convertIntrRule vars
paulson@2854
   507
      fun tac dup i = 
paulson@2999
   508
	  TRACE rl (DETERM o (rtac (if dup then Data.dup_intr rl else rl))) i
paulson@2854
   509
	  THEN rot_subgoals_tac (map nNewHyps (#2 trl)) i
paulson@2854
   510
  in (trl, tac) end;
paulson@2854
   511
paulson@2854
   512
paulson@3030
   513
val dummyVar = Term.Var (("etc",0), dummyT);
paulson@2854
   514
paulson@2854
   515
(*Convert from prototerms to ordinary terms with dummy types
paulson@2924
   516
  Ignore abstractions; identify all Vars; STOP at given depth*)
paulson@2924
   517
fun toTerm 0 _             = dummyVar
paulson@2924
   518
  | toTerm d (Const a)     = Term.Const (a,dummyT)
paulson@4065
   519
  | toTerm d (TConst(a,_)) = Term.Const (a,dummyT)  (*no need to convert type*)
paulson@2924
   520
  | toTerm d (Skolem(a,_)) = Term.Const (a,dummyT)
paulson@2924
   521
  | toTerm d (Free a)      = Term.Free  (a,dummyT)
paulson@2924
   522
  | toTerm d (Bound i)     = Term.Bound i
paulson@2924
   523
  | toTerm d (Var _)       = dummyVar
paulson@2924
   524
  | toTerm d (Abs(a,_))    = dummyVar
paulson@2924
   525
  | toTerm d (f $ u)       = Term.$ (toTerm d f, toTerm (d-1) u);
paulson@2854
   526
paulson@2854
   527
paulson@2854
   528
fun netMkRules P vars (nps: netpair list) =
paulson@2854
   529
  case P of
paulson@2854
   530
      (Const "*Goal*" $ G) =>
paulson@2924
   531
	let val pG = mk_tprop (toTerm 2 G)
paulson@2854
   532
	    val intrs = List.concat 
paulson@2854
   533
		             (map (fn (inet,_) => Net.unify_term inet pG) 
paulson@2854
   534
			      nps)
paulson@2854
   535
	in  map (fromIntrRule vars o #2) (orderlist intrs)  end
paulson@2854
   536
    | _ =>
paulson@2924
   537
	let val pP = mk_tprop (toTerm 3 P)
paulson@2854
   538
	    val elims = List.concat 
paulson@2854
   539
		             (map (fn (_,enet) => Net.unify_term enet pP) 
paulson@2854
   540
			      nps)
paulson@2854
   541
	in  List.mapPartial (fromRule vars o #2) (orderlist elims)  end;
paulson@2854
   542
paulson@2854
   543
(**
paulson@2854
   544
end;
paulson@2854
   545
**)
paulson@2854
   546
paulson@3092
   547
paulson@3092
   548
(*Pending formulae carry md (may duplicate) flags*)
paulson@3092
   549
type branch = ((term*bool) list *	(*safe formulae on this level*)
paulson@3092
   550
               (term*bool) list) list * (*haz formulae  on this level*)
paulson@3092
   551
	      term list *               (*literals: irreducible formulae*)
paulson@3092
   552
	      term option ref list *    (*variables occurring in branch*)
paulson@3092
   553
	      int;                      (*resource limit*)
paulson@3092
   554
paulson@3092
   555
val fullTrace = ref[] : branch list list ref;
paulson@3092
   556
paulson@3092
   557
(*Normalize a branch--for tracing*)
paulson@3092
   558
fun norm2 (G,md) = (norm G, md);
paulson@3092
   559
paulson@3092
   560
fun normLev (Gs,Hs) = (map norm2 Gs, map norm2 Hs);
paulson@3092
   561
paulson@3092
   562
fun normBr (br, lits, vars, lim) =
paulson@3092
   563
     (map normLev br, map norm lits, vars, lim);
paulson@3092
   564
paulson@3092
   565
paulson@4065
   566
val dummyTVar = Term.TVar(("a",0), []);
paulson@3092
   567
val dummyVar2 = Term.Var(("var",0), dummyT);
paulson@3092
   568
paulson@4065
   569
(*convert Blast_tac's type representation to real types for tracing*)
paulson@4065
   570
fun showType (Free a)  = Term.TFree (a,[])
paulson@4065
   571
  | showType (Var _)   = dummyTVar
paulson@4065
   572
  | showType t         =
paulson@4065
   573
      (case strip_comb t of
paulson@4065
   574
	   (Const a, us) => Term.Type(a, map showType us)
paulson@4065
   575
	 | _ => dummyT);
paulson@4065
   576
paulson@4065
   577
(*Display top-level overloading if any*)
paulson@4065
   578
fun topType (TConst(a,t)) = Some (showType t)
paulson@4065
   579
  | topType (Abs(a,t))    = topType t
paulson@4065
   580
  | topType (f $ u)       = (case topType f of
paulson@4065
   581
				 None => topType u
paulson@4065
   582
			       | some => some)
paulson@4065
   583
  | topType _             = None;
paulson@4065
   584
paulson@4065
   585
paulson@3092
   586
(*Convert from prototerms to ordinary terms with dummy types for tracing*)
paulson@3092
   587
fun showTerm d (Const a)     = Term.Const (a,dummyT)
paulson@4065
   588
  | showTerm d (TConst(a,_)) = Term.Const (a,dummyT)
paulson@3092
   589
  | showTerm d (Skolem(a,_)) = Term.Const (a,dummyT)
paulson@3092
   590
  | showTerm d (Free a)      = Term.Free  (a,dummyT)
paulson@3092
   591
  | showTerm d (Bound i)     = Term.Bound i
paulson@3101
   592
  | showTerm d (Var(ref(Some u))) = showTerm d u
paulson@3101
   593
  | showTerm d (Var(ref None))    = dummyVar2
paulson@3092
   594
  | showTerm d (Abs(a,t))    = if d=0 then dummyVar
paulson@3092
   595
			       else Term.Abs(a, dummyT, showTerm (d-1) t)
paulson@3092
   596
  | showTerm d (f $ u)       = if d=0 then dummyVar
paulson@3092
   597
			       else Term.$ (showTerm d f, showTerm (d-1) u);
paulson@3092
   598
paulson@4065
   599
fun string_of sign d t = Sign.string_of_term sign (showTerm d t);
paulson@3092
   600
paulson@4065
   601
fun traceTerm sign t = 
paulson@4065
   602
  let val t' = norm t
paulson@4065
   603
      val stm = string_of sign 8 t'
paulson@4065
   604
  in  
paulson@4065
   605
      case topType t' of
paulson@4065
   606
	  None   => stm   (*no type to attach*)
paulson@4065
   607
	| Some T => stm ^ "\t:: " ^ Sign.string_of_typ sign T
paulson@4065
   608
  end;
paulson@3092
   609
paulson@3092
   610
paulson@3092
   611
(*Print tracing information at each iteration of prover*)
paulson@3092
   612
fun tracing sign brs = 
paulson@3092
   613
  let fun printPairs (((G,_)::_,_)::_)  = prs(traceTerm sign G)
paulson@3092
   614
	| printPairs (([],(H,_)::_)::_) = prs(traceTerm sign H ^ "\t (Unsafe)")
paulson@3092
   615
	| printPairs _                 = ()
paulson@3092
   616
      fun printBrs (brs0 as (pairs, lits, _, lim) :: brs) =
paulson@3092
   617
	    (fullTrace := brs0 :: !fullTrace;
paulson@3092
   618
	     seq (fn _ => prs "+") brs;
paulson@3092
   619
	     prs (" [" ^ Int.toString lim ^ "] ");
paulson@3092
   620
	     printPairs pairs;
paulson@3092
   621
	     writeln"")
paulson@3092
   622
  in if !trace then printBrs (map normBr brs) else ()
paulson@3092
   623
  end;
paulson@3092
   624
paulson@4065
   625
fun traceMsg s = if !trace then prs s else ();
paulson@4065
   626
paulson@3092
   627
(*Tracing: variables updated in the last branch operation?*)
paulson@4065
   628
fun traceVars sign ntrl =
paulson@4065
   629
  if !trace then 
paulson@4065
   630
      (case !ntrail-ntrl of
paulson@4065
   631
	    0 => ()
paulson@4065
   632
	  | 1 => prs"\t1 variable UPDATED:"
paulson@4065
   633
	  | n => prs("\t" ^ Int.toString n ^ " variables UPDATED:");
paulson@4065
   634
       (*display the instantiations themselves, though no variable names*)
paulson@4065
   635
       seq (fn v => prs("   " ^ string_of sign 4 (the (!v))))
paulson@4065
   636
           (List.take(!trail, !ntrail-ntrl));
paulson@4065
   637
       writeln"")
paulson@3092
   638
    else ();
paulson@3092
   639
paulson@3092
   640
(*Tracing: how many new branches are created?*)
paulson@3092
   641
fun traceNew prems =
paulson@3092
   642
    if !trace then 
paulson@3092
   643
        case length prems of
paulson@3092
   644
	    0 => prs"branch closed by rule"
paulson@3092
   645
	  | 1 => prs"branch extended (1 new subgoal)"
paulson@3092
   646
	  | n => prs("branch split: "^ Int.toString n ^ " new subgoals")
paulson@3092
   647
    else ();
paulson@3092
   648
paulson@3092
   649
paulson@3092
   650
paulson@2854
   651
(*** Code for handling equality: naive substitution, like hyp_subst_tac ***)
paulson@2854
   652
paulson@2854
   653
(*Replace the ATOMIC term "old" by "new" in t*)  
paulson@2854
   654
fun subst_atomic (old,new) t =
paulson@2854
   655
    let fun subst (Var(ref(Some u))) = subst u
paulson@2854
   656
	  | subst (Abs(a,body))      = Abs(a, subst body)
paulson@2854
   657
	  | subst (f$t)              = subst f $ subst t
paulson@2854
   658
	  | subst t                  = if t aconv old then new else t
paulson@2854
   659
    in  subst t  end;
paulson@2854
   660
paulson@2854
   661
(*Eta-contract a term from outside: just enough to reduce it to an atom*)
paulson@2854
   662
fun eta_contract_atom (t0 as Abs(a, body)) = 
paulson@2854
   663
      (case  eta_contract2 body  of
paulson@2854
   664
        f $ Bound 0 => if (0 mem_int loose_bnos f) then t0
paulson@2854
   665
		       else eta_contract_atom (incr_boundvars ~1 f)
paulson@2854
   666
      | _ => t0)
paulson@2854
   667
  | eta_contract_atom t = t
paulson@2854
   668
and eta_contract2 (f$t) = f $ eta_contract_atom t
paulson@2854
   669
  | eta_contract2 t     = eta_contract_atom t;
paulson@2854
   670
paulson@2854
   671
paulson@2854
   672
(*When can we safely delete the equality?
paulson@2854
   673
    Not if it equates two constants; consider 0=1.
paulson@2854
   674
    Not if it resembles x=t[x], since substitution does not eliminate x.
paulson@2854
   675
    Not if it resembles ?x=0; another goal could instantiate ?x to Suc(i)
paulson@2854
   676
  Prefer to eliminate Bound variables if possible.
paulson@2854
   677
  Result:  true = use as is,  false = reorient first *)
paulson@2854
   678
paulson@2854
   679
(*Does t occur in u?  For substitution.  
paulson@2854
   680
  Does NOT check args of Skolem terms: substitution does not affect them.
paulson@4196
   681
  REFLEXIVE because hyp_subst_tac fails on x=x.*)
paulson@2854
   682
fun substOccur t = 
paulson@2854
   683
  let fun occEq u = (t aconv u) orelse occ u
paulson@2854
   684
      and occ (Var(ref None))    = false
paulson@2854
   685
	| occ (Var(ref(Some u))) = occEq u
paulson@2854
   686
        | occ (Abs(_,u))         = occEq u
paulson@2854
   687
        | occ (f$u)              = occEq u  orelse  occEq f
paulson@2854
   688
        | occ (_)                = false;
paulson@2854
   689
  in  occEq  end;
paulson@2854
   690
paulson@3092
   691
exception DEST_EQ;
paulson@3092
   692
paulson@3092
   693
(*Take apart an equality (plain or overloaded).  NO constant Trueprop*)
paulson@3092
   694
fun dest_eq (Const  "op ="     $ t $ u) = 
paulson@3092
   695
		(eta_contract_atom t, eta_contract_atom u)
paulson@4065
   696
  | dest_eq (TConst("op =",_)  $ t $ u) = 
paulson@3092
   697
		(eta_contract_atom t, eta_contract_atom u)
paulson@3092
   698
  | dest_eq _                           = raise DEST_EQ;
paulson@3092
   699
paulson@4196
   700
(*Reject the equality if u occurs in (or equals!) t*)
paulson@2854
   701
fun check (t,u,v) = if substOccur t u then raise DEST_EQ else v;
paulson@2854
   702
paulson@2854
   703
(*IF the goal is an equality with a substitutable variable 
paulson@2854
   704
  THEN orient that equality ELSE raise exception DEST_EQ*)
paulson@3092
   705
fun orientGoal (t,u) = case (t,u) of
paulson@2854
   706
       (Skolem _, _) => check(t,u,(t,u))	(*eliminates t*)
paulson@2854
   707
     | (_, Skolem _) => check(u,t,(u,t))	(*eliminates u*)
paulson@2854
   708
     | (Free _, _)   => check(t,u,(t,u))	(*eliminates t*)
paulson@2854
   709
     | (_, Free _)   => check(u,t,(u,t))	(*eliminates u*)
paulson@2854
   710
     | _             => raise DEST_EQ;
paulson@2854
   711
paulson@2894
   712
(*Substitute through the branch if an equality goal (else raise DEST_EQ).
paulson@2894
   713
  Moves affected literals back into the branch, but it is not clear where
paulson@2894
   714
  they should go: this could make proofs fail.  ??? *)
paulson@3092
   715
fun equalSubst sign (G, pairs, lits, vars, lim) = 
paulson@3092
   716
  let val (t,u) = orientGoal(dest_eq G)
paulson@3092
   717
      val subst = subst_atomic (t,u)
paulson@2854
   718
      fun subst2(G,md) = (subst G, md)
paulson@2924
   719
      (*substitute throughout Haz list; move affected ones to Safe part*)
paulson@2924
   720
      fun subHazs ([], Gs, nHs)         = (Gs,nHs)
paulson@2924
   721
	| subHazs ((H,md)::Hs, Gs, nHs) =
paulson@2924
   722
	    let val nH = subst H
paulson@2924
   723
	    in  if nH aconv H then subHazs (Hs, Gs, (H,md)::nHs)
paulson@2924
   724
		              else subHazs (Hs, (nH,md)::Gs, nHs)
paulson@2924
   725
            end
paulson@2924
   726
      val pairs' = map (fn(Gs,Hs) => subHazs(rev Hs, map subst2 Gs, [])) pairs
paulson@2924
   727
      (*substitute throughout literals; move affected ones to Safe part*)
paulson@2894
   728
      fun subLits ([], [], nlits) =          (pairs', nlits, vars, lim)
paulson@2894
   729
	| subLits ([], Gs, nlits) = ((Gs,[])::pairs', nlits, vars, lim)
paulson@2894
   730
	| subLits (lit::lits, Gs, nlits) =
paulson@2854
   731
	    let val nlit = subst lit
paulson@2894
   732
	    in  if nlit aconv lit then subLits (lits, Gs, nlit::nlits)
paulson@2894
   733
		                  else subLits (lits, (nlit,true)::Gs, nlits)
paulson@2854
   734
            end
paulson@3092
   735
  in  if !trace then writeln ("Substituting " ^ traceTerm sign u ^
paulson@3092
   736
			      " for " ^ traceTerm sign t ^ " in branch" )
paulson@3092
   737
      else ();
paulson@3083
   738
      subLits (rev lits, [], [])  
paulson@2854
   739
  end;
paulson@2854
   740
paulson@2854
   741
paulson@2854
   742
exception NEWBRANCHES and CLOSEF;
paulson@2854
   743
paulson@2854
   744
exception PROVE;
paulson@2854
   745
paulson@2854
   746
val eq_contr_tac = eresolve_tac [Data.notE]  THEN'  eq_assume_tac;
paulson@2854
   747
paulson@2854
   748
val eContr_tac  = TRACE Data.notE (eq_contr_tac ORELSE' Data.contr_tac);
paulson@2854
   749
val eAssume_tac = TRACE asm_rl   (eq_assume_tac ORELSE' assume_tac);
paulson@2854
   750
paulson@2854
   751
(*Try to unify complementary literals and return the corresponding tactic. *) 
paulson@3083
   752
fun tryClose (Const"*Goal*" $ G,  L) = 
paulson@4065
   753
	if unify([],G,L) then Some eAssume_tac else None
paulson@3083
   754
  | tryClose (G,  Const"*Goal*" $ L) = 
paulson@4065
   755
	if unify([],G,L) then Some eAssume_tac else None
paulson@3083
   756
  | tryClose (Const"Not" $ G,  L)    = 
paulson@4065
   757
	if unify([],G,L) then Some eContr_tac else None
paulson@3083
   758
  | tryClose (G,  Const"Not" $ L)    = 
paulson@4065
   759
	if unify([],G,L) then Some eContr_tac else None
paulson@3083
   760
  | tryClose _                       = None;
paulson@2854
   761
paulson@2854
   762
paulson@2854
   763
(*Were there Skolem terms in the premise?  Must NOT chase Vars*)
paulson@2854
   764
fun hasSkolem (Skolem _)     = true
paulson@2854
   765
  | hasSkolem (Abs (_,body)) = hasSkolem body 
paulson@2854
   766
  | hasSkolem (f$t)          =  hasSkolem f orelse hasSkolem t
paulson@2854
   767
  | hasSkolem _              = false;
paulson@2854
   768
paulson@2854
   769
(*Attach the right "may duplicate" flag to new formulae: if they contain
paulson@2854
   770
  Skolem terms then allow duplication.*)
paulson@2854
   771
fun joinMd md [] = []
paulson@2854
   772
  | joinMd md (G::Gs) = (G, hasSkolem G orelse md) :: joinMd md Gs;
paulson@2854
   773
paulson@2894
   774
(*Convert a Goal to an ordinary Not.  Used also in dup_intr, where a goal like
paulson@2894
   775
  Ex(P) is duplicated as the assumption ~Ex(P). *)
paulson@2894
   776
fun negOfGoal (Const"*Goal*" $ G) = negate G
paulson@2894
   777
  | negOfGoal G                   = G;
paulson@2894
   778
paulson@2894
   779
fun negOfGoal2 (G,md) = (negOfGoal G, md);
paulson@2894
   780
paulson@2894
   781
(*Converts all Goals to Nots in the safe parts of a branch.  They could
paulson@2894
   782
  have been moved there from the literals list after substitution (equalSubst).
paulson@2894
   783
  There can be at most one--this function could be made more efficient.*)
paulson@2894
   784
fun negOfGoals pairs = map (fn (Gs,haz) => (map negOfGoal2 Gs, haz)) pairs;
paulson@2894
   785
paulson@2894
   786
(*Tactic.  Convert *Goal* to negated assumption in FIRST position*)
paulson@2894
   787
val negOfGoal_tac = rtac Data.ccontr THEN' rotate_tac ~1;
paulson@2894
   788
paulson@2854
   789
paulson@2854
   790
(** Backtracking and Pruning **)
paulson@2854
   791
paulson@2854
   792
(*clashVar vars (n,trail) determines whether any of the last n elements
paulson@2854
   793
  of "trail" occur in "vars" OR in their instantiations*)
paulson@2854
   794
fun clashVar [] = (fn _ => false)
paulson@2854
   795
  | clashVar vars =
paulson@2854
   796
      let fun clash (0, _)     = false
paulson@2854
   797
	    | clash (_, [])    = false
paulson@2854
   798
	    | clash (n, v::vs) = exists (varOccur v) vars orelse clash(n-1,vs)
paulson@2854
   799
      in  clash  end;
paulson@2854
   800
paulson@2854
   801
paulson@2854
   802
(*nbrs = # of branches just prior to closing this one.  Delete choice points
paulson@2854
   803
  for goals proved by the latest inference, provided NO variables in the
paulson@2854
   804
  next branch have been updated.*)
paulson@2854
   805
fun prune (1, nxtVars, choices) = choices  (*DON'T prune at very end: allow 
paulson@2854
   806
					     backtracking over bad proofs*)
paulson@2854
   807
  | prune (nbrs, nxtVars, choices) =
paulson@2854
   808
      let fun traceIt last =
paulson@2854
   809
		let val ll = length last
paulson@2854
   810
		    and lc = length choices
paulson@2854
   811
		in if !trace andalso ll<lc then
paulson@3083
   812
		    (writeln("Pruning " ^ Int.toString(lc-ll) ^ " levels"); 
paulson@2854
   813
		     last)
paulson@2854
   814
		   else last
paulson@2854
   815
		end
paulson@2854
   816
	  fun pruneAux (last, _, _, []) = last
paulson@3083
   817
	    | pruneAux (last, ntrl, trl, (ntrl',nbrs',exn) :: choices) =
paulson@2854
   818
		if nbrs' < nbrs 
paulson@2854
   819
		then last  (*don't backtrack beyond first solution of goal*)
paulson@2854
   820
		else if nbrs' > nbrs then pruneAux (last, ntrl, trl, choices)
paulson@2854
   821
		else (* nbrs'=nbrs *)
paulson@2854
   822
		     if clashVar nxtVars (ntrl-ntrl', trl) then last
paulson@2854
   823
		     else (*no clashes: can go back at least this far!*)
paulson@2854
   824
			  pruneAux(choices, ntrl', List.drop(trl, ntrl-ntrl'), 
paulson@2854
   825
				   choices)
paulson@2854
   826
  in  traceIt (pruneAux (choices, !ntrail, !trail, choices))  end;
paulson@2854
   827
paulson@2894
   828
fun nextVars ((br, lits, vars, lim) :: _) = map Var vars
paulson@3083
   829
  | nextVars []                           = [];
paulson@2854
   830
paulson@3083
   831
fun backtrack (choices as (ntrl, nbrs, exn)::_) = 
paulson@3083
   832
      (if !trace then (writeln ("Backtracking; now there are " ^ 
paulson@3083
   833
				Int.toString nbrs ^ " branches"))
paulson@3083
   834
                 else (); 
paulson@3083
   835
       raise exn)
paulson@3083
   836
  | backtrack _ = raise PROVE;
paulson@2854
   837
paulson@2894
   838
(*Add the literal G, handling *Goal* and detecting duplicates.*)
paulson@2894
   839
fun addLit (Const "*Goal*" $ G, lits) = 
paulson@2894
   840
      (*New literal is a *Goal*, so change all other Goals to Nots*)
paulson@2854
   841
      let fun bad (Const"*Goal*" $ _) = true
paulson@2854
   842
	    | bad (Const"Not" $ G')   = G aconv G'
paulson@2854
   843
	    | bad _                   = false;
paulson@2854
   844
	  fun change [] = []
paulson@2854
   845
	    | change (Const"*Goal*" $ G' :: lits) = 
paulson@2854
   846
		  if G aconv G' then change lits
paulson@2854
   847
		  else Const"Not" $ G' :: change lits
paulson@2854
   848
	    | change (Const"Not" $ G' :: lits)    = 
paulson@2854
   849
		  if G aconv G' then change lits
paulson@2854
   850
		  else Const"Not" $ G' :: change lits
paulson@2854
   851
	    | change (lit::lits) = lit :: change lits
paulson@2854
   852
      in
paulson@2854
   853
	Const "*Goal*" $ G :: (if exists bad lits then change lits else lits)
paulson@2854
   854
      end
paulson@2854
   855
  | addLit (G,lits) = ins_term(G, lits)
paulson@2854
   856
paulson@2854
   857
paulson@2952
   858
(*For calculating the "penalty" to assess on a branching factor of n
paulson@2952
   859
  log2 seems a little too severe*)
paulson@3083
   860
fun log n = if n<4 then 0 else 1 + log(n div 4);
paulson@2924
   861
paulson@2924
   862
paulson@3021
   863
(*match(t,u) says whether the term u might be an instance of the pattern t
paulson@3021
   864
  Used to detect "recursive" rules such as transitivity*)
paulson@3021
   865
fun match (Var _) u   = true
paulson@4065
   866
  | match (Const"*Goal*") (Const"Not")    = true
paulson@4065
   867
  | match (Const"Not")    (Const"*Goal*") = true
paulson@4065
   868
  | match (Const a)       (Const b)       = (a=b)
paulson@4065
   869
  | match (TConst (a,ta)) (TConst (b,tb)) = a=b andalso match ta tb
paulson@4065
   870
  | match (Free a)        (Free b)        = (a=b)
paulson@4065
   871
  | match (Bound i)       (Bound j)       = (i=j)
paulson@4065
   872
  | match (Abs(_,t))      (Abs(_,u))      = match t u
paulson@4065
   873
  | match (f$t)           (g$u)           = match f g andalso match t u
paulson@4065
   874
  | match t               u   = false;
paulson@3021
   875
paulson@3021
   876
paulson@2854
   877
(*Tableau prover based on leanTaP.  Argument is a list of branches.  Each 
paulson@2854
   878
  branch contains a list of unexpanded formulae, a list of literals, and a 
paulson@2854
   879
  bound on unsafe expansions.*)
paulson@3030
   880
fun prove (sign, cs, brs, cont) =
paulson@2854
   881
 let val {safe0_netpair, safep_netpair, haz_netpair, ...} = Data.rep_claset cs
paulson@2854
   882
     val safeList = [safe0_netpair, safep_netpair]
paulson@2854
   883
     and hazList  = [haz_netpair]
paulson@4065
   884
     fun prv (tacs, trs, choices, []) = 
paulson@4065
   885
	         cont (tacs, trs, choices)   (*all branches closed!*)
paulson@2854
   886
       | prv (tacs, trs, choices, 
paulson@2894
   887
	      brs0 as (((G,md)::br, haz)::pairs, lits, vars, lim) :: brs) =
paulson@3917
   888
   	     (*apply a safe rule only (possibly allowing instantiation);
paulson@3917
   889
               defer any haz formulae*)
paulson@2854
   890
	  let exception PRV (*backtrack to precisely this recursion!*)
paulson@2854
   891
	      val ntrl = !ntrail 
paulson@2854
   892
	      val nbrs = length brs0
paulson@2854
   893
              val nxtVars = nextVars brs
paulson@2854
   894
	      val G = norm G
paulson@2924
   895
	      val rules = netMkRules G vars safeList
paulson@2854
   896
	      (*Make a new branch, decrementing "lim" if instantiations occur*)
paulson@2894
   897
	      fun newBr (vars',lim') prems =
paulson@2894
   898
		  map (fn prem => 
paulson@2894
   899
		       if (exists isGoal prem) 
paulson@2894
   900
		       then (((joinMd md prem, []) :: 
paulson@2894
   901
			      negOfGoals ((br, haz)::pairs)),
paulson@2894
   902
			     map negOfGoal lits, 
paulson@2894
   903
			     vars', lim') 
paulson@2894
   904
		       else (((joinMd md prem, []) :: (br, haz) :: pairs),
paulson@2894
   905
			     lits, vars', lim'))
paulson@2854
   906
		  prems @
paulson@2854
   907
		  brs		  
paulson@2854
   908
	      (*Seek a matching rule.  If unifiable then add new premises
paulson@2854
   909
                to branch.*)
paulson@2854
   910
	      fun deeper [] = raise NEWBRANCHES
paulson@2854
   911
		| deeper (((P,prems),tac)::grls) =
paulson@4065
   912
		    if unify(add_term_vars(P,[]), P, G) 
paulson@3083
   913
		    then  (*P comes from the rule; G comes from the branch.*)
paulson@3083
   914
		     let val ntrl' = !ntrail
paulson@3083
   915
			 val lim' = if ntrl < !ntrail 
paulson@3083
   916
				    then lim - (1+log(length rules))
paulson@3083
   917
				    else lim   (*discourage branching updates*)
paulson@3083
   918
			 val vars  = vars_in_vars vars
paulson@3083
   919
			 val vars' = foldr add_terms_vars (prems, vars)
paulson@3083
   920
			 val choices' = (ntrl, nbrs, PRV) :: choices
paulson@3083
   921
			 val tacs' = (DETERM o (tac false)) :: tacs 
paulson@3083
   922
					 (*no duplication*)
paulson@3083
   923
		     in
paulson@4065
   924
			 traceNew prems;  traceVars sign ntrl;
paulson@3083
   925
			 (if null prems then (*closed the branch: prune!*)
paulson@3083
   926
			    prv(tacs',  brs0::trs, 
paulson@3083
   927
				prune (nbrs, nxtVars, choices'),
paulson@3083
   928
				brs)
paulson@3083
   929
			  else
paulson@3083
   930
			  if lim'<0 (*faster to kill ALL the alternatives*)
paulson@4065
   931
			  then (traceMsg"Excessive branching: KILLED\n";
paulson@4065
   932
			        clearTo ntrl;  raise NEWBRANCHES)
paulson@3083
   933
			  else
paulson@3083
   934
			    prv(tacs',  brs0::trs, choices',
paulson@3083
   935
				newBr (vars',lim') prems))
paulson@3083
   936
                         handle PRV => 
paulson@3083
   937
			   if ntrl < ntrl' (*Vars have been updated*)
paulson@4065
   938
			   then
paulson@3083
   939
				(*Backtrack at this level.
paulson@3083
   940
				  Reset Vars and try another rule*)
paulson@3083
   941
				(clearTo ntrl;  deeper grls)
paulson@3083
   942
			   else (*backtrack to previous level*)
paulson@3083
   943
				backtrack choices
paulson@3083
   944
		     end
paulson@3083
   945
		    else deeper grls
paulson@2854
   946
	      (*Try to close branch by unifying with head goal*)
paulson@2854
   947
	      fun closeF [] = raise CLOSEF
paulson@2854
   948
		| closeF (L::Ls) = 
paulson@3083
   949
		    case tryClose(G,L) of
paulson@3083
   950
			None     => closeF Ls
paulson@3083
   951
		      | Some tac => 
paulson@3083
   952
			    let val choices' = 
paulson@3092
   953
				    (if !trace then (prs"branch closed";
paulson@4065
   954
						     traceVars sign ntrl)
paulson@3083
   955
				               else ();
paulson@3083
   956
				     prune (nbrs, nxtVars, 
paulson@3083
   957
					    (ntrl, nbrs, PRV) :: choices))
paulson@3083
   958
			    in  prv (tac::tacs, brs0::trs, choices', brs)  
paulson@3083
   959
				handle PRV => 
paulson@3083
   960
				    (*reset Vars and try another literal
paulson@3083
   961
				      [this handler is pruned if possible!]*)
paulson@3083
   962
				 (clearTo ntrl;  closeF Ls)
paulson@3083
   963
			    end
paulson@2894
   964
	      fun closeFl [] = raise CLOSEF
paulson@2894
   965
		| closeFl ((br, haz)::pairs) =
paulson@2894
   966
		    closeF (map fst br)
paulson@2894
   967
		      handle CLOSEF => closeF (map fst haz)
paulson@2894
   968
			handle CLOSEF => closeFl pairs
paulson@3083
   969
	  in tracing sign brs0; 
paulson@4065
   970
	     if lim<0 then (traceMsg "Limit reached.  "; backtrack choices)
paulson@2854
   971
	     else
paulson@3092
   972
	     prv ((TRY  o  Data.vars_gen_hyp_subst_tac false)  ::  tacs, 
paulson@3092
   973
		  (*The TRY above allows the substitution to fail, e.g. if
paulson@3092
   974
		    the real version is z = f(?x z).  Rest of proof might
paulson@3092
   975
		    still succeed!*)
paulson@2854
   976
		  brs0::trs,  choices,
paulson@3092
   977
		  equalSubst sign (G, (br,haz)::pairs, lits, vars, lim) :: brs)
paulson@4065
   978
	     handle DEST_EQ =>   closeF lits
paulson@4065
   979
	      handle CLOSEF =>   closeFl ((br,haz)::pairs)
paulson@4065
   980
	        handle CLOSEF => deeper rules
paulson@2894
   981
		  handle NEWBRANCHES => 
paulson@2894
   982
		   (case netMkRules G vars hazList of
paulson@3917
   983
		       [] => (*no plausible haz rules: move G to literals*)
paulson@2894
   984
			   prv (tacs, brs0::trs, choices,
paulson@2894
   985
				((br,haz)::pairs, addLit(G,lits), vars, lim)
paulson@2894
   986
				::brs)
paulson@2894
   987
		    | _ => (*G admits some haz rules: try later*)
paulson@2894
   988
			   prv (if isGoal G then negOfGoal_tac :: tacs
paulson@2894
   989
				else tacs, 
paulson@2894
   990
				brs0::trs,  choices,
paulson@2894
   991
				((br, haz@[(negOfGoal G, md)])::pairs,
paulson@2894
   992
				 lits, vars, lim)  ::  brs))
paulson@2854
   993
	  end
paulson@2924
   994
       | prv (tacs, trs, choices, 
paulson@2924
   995
	      (([],haz)::(Gs,haz')::pairs, lits, vars, lim) :: brs) =
paulson@2894
   996
	     (*no more "safe" formulae: transfer haz down a level*)
paulson@2924
   997
	   prv (tacs, trs, choices, 
paulson@2924
   998
		((Gs,haz@haz')::pairs, lits, vars, lim) :: brs)
paulson@2854
   999
       | prv (tacs, trs, choices, 
paulson@2894
  1000
	      brs0 as ([([], (H,md)::Hs)], lits, vars, lim) :: brs) =
paulson@2894
  1001
   	     (*no safe steps possible at any level: apply a haz rule*)
paulson@2854
  1002
	  let exception PRV (*backtrack to precisely this recursion!*)
paulson@2894
  1003
	      val H = norm H
paulson@2854
  1004
	      val ntrl = !ntrail
paulson@2924
  1005
	      val rules = netMkRules H vars hazList
paulson@3021
  1006
	      (*new premises of haz rules may NOT be duplicated*)
paulson@3021
  1007
	      fun newPrem (vars,recur,dup,lim') prem = 
paulson@3021
  1008
		  let val Gs' = map (fn P => (P,false)) prem
paulson@3021
  1009
		      and Hs' = if dup then Hs @ [(negOfGoal H, md)] else Hs
paulson@4196
  1010
		      and lits' = if (exists isGoal prem) 
paulson@4196
  1011
			          then map negOfGoal lits
paulson@4196
  1012
				  else lits
paulson@4196
  1013
                  in  (if recur (*send new haz premises to the BACK of the
paulson@4196
  1014
				  queue to prevent exclusion of others*)
paulson@4196
  1015
		       then [(Gs',Hs')] 
paulson@4196
  1016
		       else [(Gs',[]), ([],Hs')], 
paulson@4196
  1017
		       lits', vars, lim')
paulson@3021
  1018
		  end
paulson@2854
  1019
	      fun newBr x prems = map (newPrem x) prems  @  brs
paulson@2854
  1020
	      (*Seek a matching rule.  If unifiable then add new premises
paulson@2854
  1021
                to branch.*)
paulson@2854
  1022
	      fun deeper [] = raise NEWBRANCHES
paulson@2854
  1023
		| deeper (((P,prems),tac)::grls) =
paulson@4065
  1024
		    if unify(add_term_vars(P,[]), P, H)
paulson@3083
  1025
		    then
paulson@3083
  1026
		     let val ntrl' = !ntrail
paulson@3083
  1027
			 val vars  = vars_in_vars vars
paulson@3083
  1028
			 val vars' = foldr add_terms_vars (prems, vars)
paulson@3083
  1029
			    (*duplicate H if md and the subgoal has new vars*)
paulson@3083
  1030
			 val dup = md andalso vars' <> vars
paulson@3083
  1031
			     (*any instances of P in the subgoals?*)
paulson@3083
  1032
			 and recur = exists (exists (match P)) prems
paulson@3083
  1033
			 val lim' = (*Decrement "lim" extra if updates occur*)
paulson@3083
  1034
			     if ntrl < !ntrail then lim - (1+log(length rules))
paulson@3083
  1035
			     else lim-1 
paulson@3083
  1036
				 (*It is tempting to leave "lim" UNCHANGED if
paulson@3083
  1037
				   both dup and recur are false.  Proofs are
paulson@3083
  1038
				   found at shallower depths, but looping
paulson@3083
  1039
				   occurs too often...*)
paulson@3917
  1040
			 val mayUndo = 
paulson@3917
  1041
			     (*Allowing backtracking from a rule application
paulson@3917
  1042
			       if other matching rules exist, if the rule
paulson@3917
  1043
			       updated variables, or if the rule did not
paulson@3917
  1044
			       introduce new variables.  This latter condition
paulson@3917
  1045
			       means it is not a standard "gamma-rule" but
paulson@3917
  1046
			       some other form of unsafe rule.  Aim is to
paulson@3917
  1047
			       emulate Fast_tac, which allows all unsafe steps
paulson@3917
  1048
			       to be undone.*)
paulson@3917
  1049
			     not(null grls)   (*other rules to try?*)
paulson@3917
  1050
			     orelse ntrl < ntrl' (*variables updated?*)
paulson@3917
  1051
			     orelse vars=vars'   (*no new Vars?*)
paulson@3083
  1052
			 val tac' = if mayUndo then tac dup
paulson@3083
  1053
				    else DETERM o (tac dup) 
paulson@3083
  1054
		     in
paulson@3083
  1055
		       if lim'<0 andalso not (null prems)
paulson@3083
  1056
		       then (*it's faster to kill ALL the alternatives*)
paulson@4065
  1057
			   (traceMsg"Excessive branching: KILLED\n";
paulson@4065
  1058
			    clearTo ntrl;  raise NEWBRANCHES)
paulson@3083
  1059
		       else 
paulson@4065
  1060
			 traceNew prems;  traceVars sign ntrl;
paulson@3083
  1061
			 prv(tac dup :: tacs, 
paulson@3101
  1062
			       (*FIXME: if recur then the tactic should not
paulson@3101
  1063
				 call rotate_tac: new formulae should be last*)
paulson@3083
  1064
			     brs0::trs, 
paulson@3083
  1065
			     (ntrl, length brs0, PRV) :: choices, 
paulson@3083
  1066
			     newBr (vars', recur, dup, lim') prems)
paulson@3083
  1067
			  handle PRV => 
paulson@3083
  1068
			      if mayUndo
paulson@3083
  1069
			      then (*reset Vars and try another rule*)
paulson@3083
  1070
				   (clearTo ntrl;  deeper grls)
paulson@3083
  1071
			      else (*backtrack to previous level*)
paulson@3083
  1072
				   backtrack choices
paulson@3083
  1073
		     end
paulson@3083
  1074
		    else deeper grls
paulson@3083
  1075
	  in tracing sign brs0; 
paulson@4065
  1076
	     if lim<1 then (traceMsg "Limit reached.  "; backtrack choices)
paulson@2924
  1077
	     else deeper rules
paulson@2854
  1078
	     handle NEWBRANCHES => 
paulson@2894
  1079
		 (*cannot close branch: move H to literals*)
paulson@2854
  1080
		 prv (tacs,  brs0::trs,  choices,
paulson@2894
  1081
		      ([([], Hs)], H::lits, vars, lim)::brs)
paulson@2854
  1082
	  end
paulson@2854
  1083
       | prv (tacs, trs, choices, _ :: brs) = backtrack choices
paulson@4065
  1084
 in init_gensym();
paulson@4065
  1085
    prv ([], [], [(!ntrail, length brs, PROVE)], brs) 
paulson@4065
  1086
 end;
paulson@2854
  1087
paulson@2854
  1088
paulson@2883
  1089
(*Construct an initial branch.*)
paulson@2854
  1090
fun initBranch (ts,lim) = 
paulson@2894
  1091
    ([(map (fn t => (t,true)) ts, [])],
paulson@2894
  1092
     [], add_terms_vars (ts,[]), lim);
paulson@2854
  1093
paulson@2854
  1094
paulson@2854
  1095
(*** Conversion & Skolemization of the Isabelle proof state ***)
paulson@2854
  1096
paulson@2854
  1097
(*Make a list of all the parameters in a subgoal, even if nested*)
paulson@2854
  1098
local open Term 
paulson@2854
  1099
in
paulson@2854
  1100
fun discard_foralls (Const("all",_)$Abs(a,T,t)) = discard_foralls t
paulson@2854
  1101
  | discard_foralls t = t;
paulson@2854
  1102
end;
paulson@2854
  1103
paulson@2854
  1104
paulson@2854
  1105
(*List of variables not appearing as arguments to the given parameter*)
paulson@2854
  1106
fun getVars []                  i = []
paulson@2854
  1107
  | getVars ((_,(v,is))::alist) i =
paulson@2854
  1108
	if i mem is then getVars alist i
paulson@2854
  1109
	else v :: getVars alist i;
paulson@2854
  1110
paulson@4233
  1111
exception TRANS of string;
paulson@2854
  1112
paulson@4233
  1113
(*Translation of a subgoal: Skolemize all parameters*)
paulson@4065
  1114
fun fromSubgoal t =
paulson@4065
  1115
  let val alistVar = ref []
paulson@4065
  1116
      and alistTVar = ref []
paulson@2854
  1117
      fun hdvar ((ix,(v,is))::_) = v
paulson@2854
  1118
      fun from lev t =
paulson@2854
  1119
	let val (ht,ts) = Term.strip_comb t
paulson@2854
  1120
	    fun apply u = list_comb (u, map (from lev) ts)
paulson@2854
  1121
	    fun bounds [] = []
paulson@2854
  1122
	      | bounds (Term.Bound i::ts) = 
paulson@4233
  1123
		  if i<lev then raise TRANS
paulson@4233
  1124
		      "Function unknown's argument not a parameter"
paulson@2854
  1125
		  else i-lev :: bounds ts
paulson@4233
  1126
	      | bounds ts = raise TRANS
paulson@4233
  1127
		      "Function unknown's argument not a bound variable"
paulson@2854
  1128
        in
paulson@2854
  1129
	  case ht of 
paulson@4065
  1130
	      Term.Const aT    => apply (fromConst alistTVar aT)
paulson@2854
  1131
	    | Term.Free  (a,_) => apply (Free a)
paulson@2854
  1132
	    | Term.Bound i     => apply (Bound i)
paulson@2854
  1133
	    | Term.Var (ix,_) => 
paulson@4065
  1134
		  (case (assoc_string_int(!alistVar,ix)) of
paulson@4065
  1135
		       None => (alistVar := (ix, (ref None, bounds ts))
paulson@4065
  1136
					  :: !alistVar;
paulson@4065
  1137
				Var (hdvar(!alistVar)))
paulson@2854
  1138
		     | Some(v,is) => if is=bounds ts then Var v
paulson@4233
  1139
			    else raise TRANS
paulson@4233
  1140
				("Discrepancy among occurrences of ?"
paulson@4233
  1141
				 ^ Syntax.string_of_vname ix))
paulson@2854
  1142
	    | Term.Abs (a,_,body) => 
paulson@2854
  1143
		  if null ts then Abs(a, from (lev+1) body)
paulson@4233
  1144
		  else raise TRANS "argument not in normal form"
paulson@2854
  1145
        end
paulson@2854
  1146
paulson@2854
  1147
      val npars = length (Logic.strip_params t)
paulson@2854
  1148
paulson@2854
  1149
      (*Skolemize a subgoal from a proof state*)
paulson@2854
  1150
      fun skoSubgoal i t =
paulson@2854
  1151
	  if i<npars then 
paulson@2854
  1152
	      skoSubgoal (i+1)
paulson@4065
  1153
		(subst_bound (Skolem (gensym "T_", getVars (!alistVar) i), 
paulson@2854
  1154
			      t))
paulson@2854
  1155
	  else t
paulson@2854
  1156
paulson@2854
  1157
  in  skoSubgoal 0 (from 0 (discard_foralls t))  end;
paulson@2854
  1158
paulson@2854
  1159
paulson@2854
  1160
(*Tactic using tableau engine and proof reconstruction.  
paulson@2854
  1161
 "lim" is depth limit.*)
paulson@2854
  1162
fun depth_tac cs lim i st = 
paulson@2854
  1163
    (fullTrace:=[];  trail := [];  ntrail := 0;
paulson@3030
  1164
     let val {sign,...} = rep_thm st
paulson@4065
  1165
	 val skoprem = fromSubgoal (List.nth(prems_of st, i-1))
paulson@2854
  1166
         val hyps  = strip_imp_prems skoprem
paulson@2854
  1167
         and concl = strip_imp_concl skoprem
paulson@3083
  1168
         fun cont (tacs,_,choices) = 
paulson@2854
  1169
	     (case Sequence.pull(EVERY' (rev tacs) i st) of
paulson@2854
  1170
		  None => (writeln ("PROOF FAILED for depth " ^
paulson@2854
  1171
				    Int.toString lim);
paulson@2854
  1172
			   backtrack choices)
paulson@2854
  1173
		| cell => Sequence.seqof(fn()=> cell))
paulson@3030
  1174
     in prove (sign, cs, [initBranch (mkGoal concl :: hyps, lim)], cont)
paulson@2854
  1175
     end
paulson@3451
  1176
     handle PROVE     => Sequence.null);
paulson@2854
  1177
paulson@4233
  1178
fun blast_tac cs i st = (DEEPEN (1,20) (depth_tac cs) 0) i st
paulson@4233
  1179
     handle TRANS s => (warning ("Blast_tac: " ^ s); Sequence.null);
paulson@2854
  1180
wenzelm@4078
  1181
fun Blast_tac i = blast_tac (Data.claset()) i;
paulson@2854
  1182
paulson@2924
  1183
paulson@2924
  1184
(*** For debugging: these apply the prover to a subgoal and return 
paulson@2924
  1185
     the resulting tactics, trace, etc.                            ***)
paulson@2924
  1186
paulson@2924
  1187
(*Translate subgoal i from a proof state*)
paulson@2924
  1188
fun trygl cs lim i = 
paulson@2924
  1189
    (fullTrace:=[];  trail := [];  ntrail := 0;
paulson@2924
  1190
     let val st = topthm()
paulson@3030
  1191
         val {sign,...} = rep_thm st
paulson@4065
  1192
	 val skoprem = fromSubgoal (List.nth(prems_of st, i-1))
paulson@2924
  1193
         val hyps  = strip_imp_prems skoprem
paulson@2924
  1194
         and concl = strip_imp_concl skoprem
paulson@2924
  1195
     in timeap prove
paulson@3030
  1196
	 (sign, cs, [initBranch (mkGoal concl :: hyps, lim)], I)
paulson@2924
  1197
     end
paulson@2924
  1198
     handle Subscript => error("There is no subgoal " ^ Int.toString i));
paulson@2924
  1199
wenzelm@4078
  1200
fun Trygl lim i = trygl (Data.claset()) lim i;
paulson@2924
  1201
paulson@2924
  1202
(*Read a string to make an initial, singleton branch*)
paulson@2924
  1203
fun readGoal sign s = read_cterm sign (s,propT) |>
paulson@4065
  1204
                      term_of |> fromTerm |> rand |> mkGoal;
paulson@2924
  1205
paulson@2924
  1206
fun tryInThy thy lim s = 
paulson@2924
  1207
    (fullTrace:=[];  trail := [];  ntrail := 0;
paulson@3030
  1208
     timeap prove (sign_of thy, 
wenzelm@4078
  1209
		   Data.claset(), 
paulson@2924
  1210
		   [initBranch ([readGoal (sign_of thy) s], lim)], 
paulson@2924
  1211
		   I));
paulson@2924
  1212
paulson@2924
  1213
paulson@2854
  1214
end;
paulson@2854
  1215