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