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