1 /********************* */
2 /*! \file theory_engine.cpp
4 ** Top contributors (to current version):
5 ** Dejan Jovanovic, Morgan Deters, Andrew Reynolds
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2019 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
12 ** \brief The theory engine
17 #include "theory/theory_engine.h"
22 #include "base/map_util.h"
23 #include "decision/decision_engine.h"
24 #include "expr/attribute.h"
25 #include "expr/node.h"
26 #include "expr/node_algorithm.h"
27 #include "expr/node_builder.h"
28 #include "expr/node_visitor.h"
29 #include "options/bv_options.h"
30 #include "options/options.h"
31 #include "options/proof_options.h"
32 #include "options/quantifiers_options.h"
33 #include "options/theory_options.h"
34 #include "preprocessing/assertion_pipeline.h"
35 #include "proof/cnf_proof.h"
36 #include "proof/lemma_proof.h"
37 #include "proof/proof_manager.h"
38 #include "proof/theory_proof.h"
39 #include "smt/logic_exception.h"
40 #include "smt/term_formula_removal.h"
41 #include "theory/arith/arith_ite_utils.h"
42 #include "theory/bv/theory_bv_utils.h"
43 #include "theory/care_graph.h"
44 #include "theory/quantifiers/first_order_model.h"
45 #include "theory/quantifiers/fmf/model_engine.h"
46 #include "theory/quantifiers/theory_quantifiers.h"
47 #include "theory/quantifiers_engine.h"
48 #include "theory/rewriter.h"
49 #include "theory/theory.h"
50 #include "theory/theory_model.h"
51 #include "theory/theory_traits.h"
52 #include "theory/uf/equality_engine.h"
53 #include "util/resource_manager.h"
57 using namespace CVC4::preprocessing
;
58 using namespace CVC4::theory
;
62 /* -------------------------------------------------------------------------- */
67 * IMPORTANT: The order of the theories is important. For example, strings
68 * depends on arith, quantifiers needs to come as the very last.
69 * Do not change this order.
72 #define CVC4_FOR_EACH_THEORY \
73 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BUILTIN) \
74 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BOOL) \
75 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_UF) \
76 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_ARITH) \
77 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BV) \
78 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_FP) \
79 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_ARRAYS) \
80 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_DATATYPES) \
81 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_SEP) \
82 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_SETS) \
83 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_STRINGS) \
84 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_QUANTIFIERS)
88 /* -------------------------------------------------------------------------- */
90 inline void flattenAnd(Node n
, std::vector
<TNode
>& out
){
91 Assert(n
.getKind() == kind::AND
);
92 for(Node::iterator i
=n
.begin(), i_end
=n
.end(); i
!= i_end
; ++i
){
94 if(curr
.getKind() == kind::AND
){
95 flattenAnd(curr
, out
);
102 inline Node
flattenAnd(Node n
){
103 std::vector
<TNode
> out
;
105 return NodeManager::currentNM()->mkNode(kind::AND
, out
);
109 * Compute the string for a given theory id. In this module, we use
110 * THEORY_SAT_SOLVER as an id, which is not a normal id but maps to
111 * THEORY_LAST. Thus, we need our own string conversion here.
113 * @param id The theory id
114 * @return The string corresponding to the theory id
116 std::string
getTheoryString(theory::TheoryId id
)
118 if (id
== theory::THEORY_SAT_SOLVER
)
120 return "THEORY_SAT_SOLVER";
124 std::stringstream ss
;
130 theory::LemmaStatus
TheoryEngine::EngineOutputChannel::lemma(TNode lemma
,
135 Debug("theory::lemma") << "EngineOutputChannel<" << d_theory
<< ">::lemma("
137 << ", preprocess = " << preprocess
<< std::endl
;
138 ++d_statistics
.lemmas
;
139 d_engine
->d_outputChannelUsed
= true;
141 PROOF({ registerLemmaRecipe(lemma
, lemma
, preprocess
, d_theory
); });
143 theory::LemmaStatus result
=
144 d_engine
->lemma(lemma
, rule
, false, removable
, preprocess
,
145 sendAtoms
? d_theory
: theory::THEORY_LAST
);
149 void TheoryEngine::EngineOutputChannel::registerLemmaRecipe(Node lemma
, Node originalLemma
, bool preprocess
, theory::TheoryId theoryId
) {
150 // During CNF conversion, conjunctions will be broken down into
151 // multiple lemmas. In order for the recipes to match, we have to do
153 NodeManager
* nm
= NodeManager::currentNM();
156 lemma
= d_engine
->preprocess(lemma
);
158 bool negated
= (lemma
.getKind() == kind::NOT
);
159 Node nnLemma
= negated
? lemma
[0] : lemma
;
161 switch (nnLemma
.getKind()) {
165 for (unsigned i
= 0; i
< nnLemma
.getNumChildren(); ++i
)
166 registerLemmaRecipe(nnLemma
[i
], originalLemma
, false, theoryId
);
168 NodeBuilder
<> builder(kind::OR
);
169 for (unsigned i
= 0; i
< nnLemma
.getNumChildren(); ++i
)
170 builder
<< nnLemma
[i
].negate();
172 Node disjunction
= (builder
.getNumChildren() == 1) ? builder
[0] : builder
;
173 registerLemmaRecipe(disjunction
, originalLemma
, false, theoryId
);
178 if( nnLemma
[0].getType().isBoolean() ){
180 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0], nnLemma
[1].negate()), originalLemma
, false, theoryId
);
181 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0].negate(), nnLemma
[1]), originalLemma
, false, theoryId
);
183 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0], nnLemma
[1]), originalLemma
, false, theoryId
);
184 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0].negate(), nnLemma
[1].negate()), originalLemma
, false, theoryId
);
191 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0].negate(), nnLemma
[1]), originalLemma
, false, theoryId
);
192 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0], nnLemma
[2]), originalLemma
, false, theoryId
);
194 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0].negate(), nnLemma
[1].negate()), originalLemma
, false, theoryId
);
195 registerLemmaRecipe(nm
->mkNode(kind::OR
, nnLemma
[0], nnLemma
[2].negate()), originalLemma
, false, theoryId
);
203 // Theory lemmas have one step that proves the empty clause
204 LemmaProofRecipe proofRecipe
;
206 LemmaProofRecipe::ProofStep
proofStep(theoryId
, emptyNode
);
208 // Remember the original lemma, so we can report this later when asked to
209 proofRecipe
.setOriginalLemma(originalLemma
);
211 // Record the assertions and rewrites
213 if (lemma
.getKind() == kind::OR
) {
214 for (unsigned i
= 0; i
< lemma
.getNumChildren(); ++i
) {
215 rewritten
= theory::Rewriter::rewrite(lemma
[i
]);
216 if (rewritten
!= lemma
[i
]) {
217 proofRecipe
.addRewriteRule(lemma
[i
].negate(), rewritten
.negate());
219 proofStep
.addAssertion(lemma
[i
]);
220 proofRecipe
.addBaseAssertion(rewritten
);
223 rewritten
= theory::Rewriter::rewrite(lemma
);
224 if (rewritten
!= lemma
) {
225 proofRecipe
.addRewriteRule(lemma
.negate(), rewritten
.negate());
227 proofStep
.addAssertion(lemma
);
228 proofRecipe
.addBaseAssertion(rewritten
);
230 proofRecipe
.addStep(proofStep
);
231 ProofManager::getCnfProof()->setProofRecipe(&proofRecipe
);
234 theory::LemmaStatus
TheoryEngine::EngineOutputChannel::splitLemma(
235 TNode lemma
, bool removable
) {
236 Debug("theory::lemma") << "EngineOutputChannel<" << d_theory
<< ">::lemma("
237 << lemma
<< ")" << std::endl
;
238 ++d_statistics
.lemmas
;
239 d_engine
->d_outputChannelUsed
= true;
241 Debug("pf::explain") << "TheoryEngine::EngineOutputChannel::splitLemma( "
242 << lemma
<< " )" << std::endl
;
243 theory::LemmaStatus result
=
244 d_engine
->lemma(lemma
, RULE_SPLIT
, false, removable
, false, d_theory
);
248 bool TheoryEngine::EngineOutputChannel::propagate(TNode literal
) {
249 Debug("theory::propagate") << "EngineOutputChannel<" << d_theory
250 << ">::propagate(" << literal
<< ")" << std::endl
;
251 ++d_statistics
.propagations
;
252 d_engine
->d_outputChannelUsed
= true;
253 return d_engine
->propagate(literal
, d_theory
);
256 void TheoryEngine::EngineOutputChannel::conflict(TNode conflictNode
,
257 std::unique_ptr
<Proof
> proof
)
259 Trace("theory::conflict")
260 << "EngineOutputChannel<" << d_theory
<< ">::conflict(" << conflictNode
262 Assert(!proof
); // Theory shouldn't be producing proofs yet
263 ++d_statistics
.conflicts
;
264 d_engine
->d_outputChannelUsed
= true;
265 d_engine
->conflict(conflictNode
, d_theory
);
268 void TheoryEngine::finishInit() {
270 //initialize the quantifiers engine, master equality engine, model, model builder
271 if( d_logicInfo
.isQuantified() ) {
272 // initialize the quantifiers engine
273 d_quantEngine
= new QuantifiersEngine(d_context
, d_userContext
, this);
274 Assert(d_masterEqualityEngine
== 0);
275 d_masterEqualityEngine
= new eq::EqualityEngine(d_masterEENotify
,getSatContext(), "theory::master", false);
277 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
278 if (d_theoryTable
[theoryId
]) {
279 d_theoryTable
[theoryId
]->setQuantifiersEngine(d_quantEngine
);
280 d_theoryTable
[theoryId
]->setMasterEqualityEngine(d_masterEqualityEngine
);
284 d_curr_model_builder
= d_quantEngine
->getModelBuilder();
285 d_curr_model
= d_quantEngine
->getModel();
287 d_curr_model
= new theory::TheoryModel(
288 d_userContext
, "DefaultModel", options::assignFunctionValues());
289 d_aloc_curr_model
= true;
291 //make the default builder, e.g. in the case that the quantifiers engine does not have a model builder
292 if( d_curr_model_builder
==NULL
){
293 d_curr_model_builder
= new theory::TheoryEngineModelBuilder(this);
294 d_aloc_curr_model_builder
= true;
297 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
298 if (d_theoryTable
[theoryId
]) {
299 // set the decision manager for the theory
300 d_theoryTable
[theoryId
]->setDecisionManager(d_decManager
.get());
301 // finish initializing the theory
302 d_theoryTable
[theoryId
]->finishInit();
307 void TheoryEngine::eqNotifyNewClass(TNode t
){
308 if (d_logicInfo
.isQuantified()) {
309 d_quantEngine
->eqNotifyNewClass( t
);
313 TheoryEngine::TheoryEngine(context::Context
* context
,
314 context::UserContext
* userContext
,
315 RemoveTermFormulas
& iteRemover
,
316 const LogicInfo
& logicInfo
)
317 : d_propEngine(nullptr),
319 d_userContext(userContext
),
320 d_logicInfo(logicInfo
),
321 d_sharedTerms(this, context
),
322 d_masterEqualityEngine(nullptr),
323 d_masterEENotify(*this),
324 d_quantEngine(nullptr),
325 d_decManager(new DecisionManager(userContext
)),
326 d_curr_model(nullptr),
327 d_aloc_curr_model(false),
328 d_curr_model_builder(nullptr),
329 d_aloc_curr_model_builder(false),
330 d_eager_model_building(false),
332 d_possiblePropagations(context
),
333 d_hasPropagated(context
),
334 d_inConflict(context
, false),
336 d_hasShutDown(false),
337 d_incomplete(context
, false),
338 d_propagationMap(context
),
339 d_propagationMapTimestamp(context
, 0),
340 d_propagatedLiterals(context
),
341 d_propagatedLiteralsIndex(context
, 0),
342 d_atomRequests(context
),
343 d_tform_remover(iteRemover
),
344 d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
347 d_interrupted(false),
348 d_resourceManager(NodeManager::currentResourceManager()),
349 d_inPreregister(false),
350 d_factsAsserted(context
, false),
351 d_preRegistrationVisitor(this, context
),
352 d_sharedTermsVisitor(d_sharedTerms
),
354 d_arithSubstitutionsAdded("theory::arith::zzz::arith::substitutions", 0)
356 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
;
359 d_theoryTable
[theoryId
] = NULL
;
360 d_theoryOut
[theoryId
] = NULL
;
363 smtStatisticsRegistry()->registerStat(&d_combineTheoriesTime
);
364 d_true
= NodeManager::currentNM()->mkConst
<bool>(true);
365 d_false
= NodeManager::currentNM()->mkConst
<bool>(false);
368 ProofManager::currentPM()->initTheoryProofEngine();
371 smtStatisticsRegistry()->registerStat(&d_arithSubstitutionsAdded
);
374 TheoryEngine::~TheoryEngine() {
375 Assert(d_hasShutDown
);
377 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
378 if(d_theoryTable
[theoryId
] != NULL
) {
379 delete d_theoryTable
[theoryId
];
380 delete d_theoryOut
[theoryId
];
384 if( d_aloc_curr_model_builder
){
385 delete d_curr_model_builder
;
387 if( d_aloc_curr_model
){
391 delete d_quantEngine
;
393 delete d_masterEqualityEngine
;
395 smtStatisticsRegistry()->unregisterStat(&d_combineTheoriesTime
);
396 smtStatisticsRegistry()->unregisterStat(&d_arithSubstitutionsAdded
);
399 void TheoryEngine::interrupt() { d_interrupted
= true; }
400 void TheoryEngine::preRegister(TNode preprocessed
) {
402 Debug("theory") << "TheoryEngine::preRegister( " << preprocessed
<< ")" << std::endl
;
403 if(Dump
.isOn("missed-t-propagations")) {
404 d_possiblePropagations
.push_back(preprocessed
);
406 d_preregisterQueue
.push(preprocessed
);
408 if (!d_inPreregister
) {
409 // We're in pre-register
410 d_inPreregister
= true;
412 // Process the pre-registration queue
413 while (!d_preregisterQueue
.empty()) {
414 // Get the next atom to pre-register
415 preprocessed
= d_preregisterQueue
.front();
416 d_preregisterQueue
.pop();
418 if (d_logicInfo
.isSharingEnabled() && preprocessed
.getKind() == kind::EQUAL
) {
419 // When sharing is enabled, we propagate from the shared terms manager also
420 d_sharedTerms
.addEqualityToPropagate(preprocessed
);
423 // the atom should not have free variables
424 Debug("theory") << "TheoryEngine::preRegister: " << preprocessed
426 Assert(!expr::hasFreeVar(preprocessed
));
427 // Pre-register the terms in the atom
428 Theory::Set theories
= NodeVisitor
<PreRegisterVisitor
>::run(d_preRegistrationVisitor
, preprocessed
);
429 theories
= Theory::setRemove(THEORY_BOOL
, theories
);
430 // Remove the top theory, if any more that means multiple theories were involved
431 bool multipleTheories
= Theory::setRemove(Theory::theoryOf(preprocessed
), theories
);
433 // These checks don't work with finite model finding, because it
434 // uses Rational constants to represent cardinality constraints,
435 // even though arithmetic isn't actually involved.
436 if(!options::finiteModelFind()) {
437 while((i
= Theory::setPop(theories
)) != THEORY_LAST
) {
438 if(!d_logicInfo
.isTheoryEnabled(i
)) {
439 LogicInfo newLogicInfo
= d_logicInfo
.getUnlockedCopy();
440 newLogicInfo
.enableTheory(i
);
443 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
444 << ", which doesn't include " << i
445 << ", but found a term in that theory." << endl
446 << "You might want to extend your logic to "
447 << newLogicInfo
.getLogicString() << endl
;
448 throw LogicException(ss
.str());
452 if (multipleTheories
) {
453 // Collect the shared terms if there are multiple theories
454 NodeVisitor
<SharedTermsVisitor
>::run(d_sharedTermsVisitor
, preprocessed
);
458 // Leaving pre-register
459 d_inPreregister
= false;
463 void TheoryEngine::printAssertions(const char* tag
) {
464 if (Trace
.isOn(tag
)) {
466 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
467 Theory
* theory
= d_theoryTable
[theoryId
];
468 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
469 Trace(tag
) << "--------------------------------------------" << endl
;
470 Trace(tag
) << "Assertions of " << theory
->getId() << ": " << endl
;
472 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
475 for (unsigned i
= 0; it
!= it_end
; ++it
, ++i
)
477 if ((*it
).d_isPreregistered
)
479 Trace(tag
) << "[" << i
<< "]: ";
483 Trace(tag
) << "(" << i
<< "): ";
485 Trace(tag
) << (*it
).d_assertion
<< endl
;
489 if (d_logicInfo
.isSharingEnabled()) {
490 Trace(tag
) << "Shared terms of " << theory
->getId() << ": " << endl
;
491 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
492 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
493 Trace(tag
) << "[" << i
<< "]: " << (*it
) << endl
;
501 void TheoryEngine::dumpAssertions(const char* tag
) {
502 if (Dump
.isOn(tag
)) {
503 Dump(tag
) << CommentCommand("Starting completeness check");
504 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
505 Theory
* theory
= d_theoryTable
[theoryId
];
506 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
507 Dump(tag
) << CommentCommand("Completeness check");
508 Dump(tag
) << PushCommand();
510 // Dump the shared terms
511 if (d_logicInfo
.isSharingEnabled()) {
512 Dump(tag
) << CommentCommand("Shared terms");
513 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
514 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
517 Dump(tag
) << CommentCommand(ss
.str());
521 // Dump the assertions
522 Dump(tag
) << CommentCommand("Assertions");
523 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(), it_end
= theory
->facts_end();
524 for (; it
!= it_end
; ++ it
) {
526 Node assertionNode
= (*it
).d_assertion
;
527 // Purify all the terms
529 if ((*it
).d_isPreregistered
)
531 Dump(tag
) << CommentCommand("Preregistered");
535 Dump(tag
) << CommentCommand("Shared assertion");
537 Dump(tag
) << AssertCommand(assertionNode
.toExpr());
539 Dump(tag
) << CheckSatCommand();
541 Dump(tag
) << PopCommand();
548 * Check all (currently-active) theories for conflicts.
549 * @param effort the effort level to use
551 void TheoryEngine::check(Theory::Effort effort
) {
554 // Reset the interrupt flag
555 d_interrupted
= false;
557 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
558 #undef CVC4_FOR_EACH_THEORY_STATEMENT
560 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
561 if (theory::TheoryTraits<THEORY>::hasCheck && d_logicInfo.isTheoryEnabled(THEORY)) { \
562 theoryOf(THEORY)->check(effort); \
563 if (d_inConflict) { \
564 Debug("conflict") << THEORY << " in conflict. " << std::endl; \
572 // Mark the output channel unused (if this is FULL_EFFORT, and nothing
573 // is done by the theories, no additional check will be needed)
574 d_outputChannelUsed
= false;
576 // Mark the lemmas flag (no lemmas added)
577 d_lemmasAdded
= false;
579 Debug("theory") << "TheoryEngine::check(" << effort
<< "): d_factsAsserted = " << (d_factsAsserted
? "true" : "false") << endl
;
581 // If in full effort, we have a fake new assertion just to jumpstart the checking
582 if (Theory::fullEffort(effort
)) {
583 d_factsAsserted
= true;
587 while (d_factsAsserted
&& !d_inConflict
&& !d_lemmasAdded
) {
589 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running check" << endl
;
591 Trace("theory::assertions") << endl
;
592 if (Trace
.isOn("theory::assertions")) {
593 printAssertions("theory::assertions");
596 if(Theory::fullEffort(effort
)) {
597 Trace("theory::assertions::fulleffort") << endl
;
598 if (Trace
.isOn("theory::assertions::fulleffort")) {
599 printAssertions("theory::assertions::fulleffort");
603 // Note that we've discharged all the facts
604 d_factsAsserted
= false;
607 CVC4_FOR_EACH_THEORY
;
609 if(Dump
.isOn("missed-t-conflicts")) {
610 Dump("missed-t-conflicts")
611 << CommentCommand("Completeness check for T-conflicts; expect sat")
612 << CheckSatCommand();
615 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running propagation after the initial check" << endl
;
617 // We are still satisfiable, propagate as much as possible
620 // We do combination if all has been processed and we are in fullcheck
621 if (Theory::fullEffort(effort
) && d_logicInfo
.isSharingEnabled() && !d_factsAsserted
&& !d_lemmasAdded
&& !d_inConflict
) {
622 // Do the combination
623 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running combination" << endl
;
625 if(d_logicInfo
.isQuantified()){
626 d_quantEngine
->notifyCombineTheories();
631 // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
632 if( Theory::fullEffort(effort
) && ! d_inConflict
&& ! needCheck() ) {
633 Trace("theory::assertions-model") << endl
;
634 if (Trace
.isOn("theory::assertions-model")) {
635 printAssertions("theory::assertions-model");
637 //checks for theories requiring the model go at last call
638 d_curr_model
->reset();
639 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
640 if( theoryId
!=THEORY_QUANTIFIERS
){
641 Theory
* theory
= d_theoryTable
[theoryId
];
642 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
643 if( theory
->needsCheckLastEffort() ){
644 if( !d_curr_model
->isBuilt() ){
645 if( !d_curr_model_builder
->buildModel(d_curr_model
) ){
649 theory
->check(Theory::EFFORT_LAST_CALL
);
656 if(d_logicInfo
.isQuantified()) {
657 // quantifiers engine must check at last call effort
658 d_quantEngine
->check(Theory::EFFORT_LAST_CALL
);
661 if (!d_inConflict
&& !needCheck())
663 // If d_eager_model_building is false, then we only mark that we
664 // are in "SAT mode". We build the model later only if the user asks
665 // for it via getBuiltModel.
667 if (d_eager_model_building
&& !d_curr_model
->isBuilt())
669 d_curr_model_builder
->buildModel(d_curr_model
);
674 Debug("theory") << "TheoryEngine::check(" << effort
<< "): done, we are " << (d_inConflict
? "unsat" : "sat") << (d_lemmasAdded
? " with new lemmas" : " with no new lemmas");
675 Debug("theory") << ", need check = " << (needCheck() ? "YES" : "NO") << endl
;
677 if( Theory::fullEffort(effort
) && !d_inConflict
&& !needCheck()) {
678 // case where we are about to answer SAT
679 if( d_masterEqualityEngine
!= NULL
){
680 AlwaysAssert(d_masterEqualityEngine
->consistent());
682 if (d_curr_model
->isBuilt())
684 // model construction should always succeed unless lemmas were added
685 AlwaysAssert(d_curr_model
->isBuiltSuccess());
686 if (options::produceModels())
688 // Do post-processing of model from the theories (used for THEORY_SEP
689 // to construct heap model)
690 postProcessModel(d_curr_model
);
691 // also call the model builder's post-process model
692 d_curr_model_builder
->postProcessModel(d_incomplete
.get(),
697 } catch(const theory::Interrupted
&) {
698 Trace("theory") << "TheoryEngine::check() => interrupted" << endl
;
700 // If fulleffort, check all theories
701 if(Dump
.isOn("theory::fullcheck") && Theory::fullEffort(effort
)) {
702 if (!d_inConflict
&& !needCheck()) {
703 dumpAssertions("theory::fullcheck");
708 void TheoryEngine::combineTheories() {
710 Trace("combineTheories") << "TheoryEngine::combineTheories()" << endl
;
712 TimerStat::CodeTimer
combineTheoriesTimer(d_combineTheoriesTime
);
714 // Care graph we'll be building
717 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
718 #undef CVC4_FOR_EACH_THEORY_STATEMENT
720 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
721 if (theory::TheoryTraits<THEORY>::isParametric && d_logicInfo.isTheoryEnabled(THEORY)) { \
722 theoryOf(THEORY)->getCareGraph(&careGraph); \
725 // Call on each parametric theory to give us its care graph
726 CVC4_FOR_EACH_THEORY
;
728 Trace("combineTheories") << "TheoryEngine::combineTheories(): care graph size = " << careGraph
.size() << endl
;
730 // Now add splitters for the ones we are interested in
731 CareGraph::const_iterator care_it
= careGraph
.begin();
732 CareGraph::const_iterator care_it_end
= careGraph
.end();
734 for (; care_it
!= care_it_end
; ++ care_it
) {
735 const CarePair
& carePair
= *care_it
;
737 Debug("combineTheories")
738 << "TheoryEngine::combineTheories(): checking " << carePair
.d_a
<< " = "
739 << carePair
.d_b
<< " from " << carePair
.d_theory
<< endl
;
741 Assert(d_sharedTerms
.isShared(carePair
.d_a
) || carePair
.d_a
.isConst());
742 Assert(d_sharedTerms
.isShared(carePair
.d_b
) || carePair
.d_b
.isConst());
744 // The equality in question (order for no repetition)
745 Node equality
= carePair
.d_a
.eqNode(carePair
.d_b
);
746 // EqualityStatus es = getEqualityStatus(carePair.d_a, carePair.d_b);
747 // Debug("combineTheories") << "TheoryEngine::combineTheories(): " <<
748 // (es == EQUALITY_TRUE_AND_PROPAGATED ? "EQUALITY_TRUE_AND_PROPAGATED" :
749 // es == EQUALITY_FALSE_AND_PROPAGATED ? "EQUALITY_FALSE_AND_PROPAGATED" :
750 // es == EQUALITY_TRUE ? "EQUALITY_TRUE" :
751 // es == EQUALITY_FALSE ? "EQUALITY_FALSE" :
752 // es == EQUALITY_TRUE_IN_MODEL ? "EQUALITY_TRUE_IN_MODEL" :
753 // es == EQUALITY_FALSE_IN_MODEL ? "EQUALITY_FALSE_IN_MODEL" :
754 // es == EQUALITY_UNKNOWN ? "EQUALITY_UNKNOWN" :
755 // "Unexpected case") << endl;
757 // We need to split on it
758 Debug("combineTheories") << "TheoryEngine::combineTheories(): requesting a split " << endl
;
760 lemma(equality
.orNode(equality
.notNode()),
767 // This code is supposed to force preference to follow what the theory models already have
768 // but it doesn't seem to make a big difference - need to explore more -Clark
770 // if (es == EQUALITY_TRUE || es == EQUALITY_TRUE_IN_MODEL) {
771 Node e
= ensureLiteral(equality
);
772 d_propEngine
->requirePhase(e
, true);
774 // else if (es == EQUALITY_FALSE_IN_MODEL) {
775 // Node e = ensureLiteral(equality);
776 // d_propEngine->requirePhase(e, false);
782 void TheoryEngine::propagate(Theory::Effort effort
) {
783 // Reset the interrupt flag
784 d_interrupted
= false;
786 // Definition of the statement that is to be run by every theory
787 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
788 #undef CVC4_FOR_EACH_THEORY_STATEMENT
790 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
791 if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
792 theoryOf(THEORY)->propagate(effort); \
795 // Reset the interrupt flag
796 d_interrupted
= false;
798 // Propagate for each theory using the statement above
799 CVC4_FOR_EACH_THEORY
;
801 if(Dump
.isOn("missed-t-propagations")) {
802 for(unsigned i
= 0; i
< d_possiblePropagations
.size(); ++i
) {
803 Node atom
= d_possiblePropagations
[i
];
805 if(d_propEngine
->hasValue(atom
, value
)) {
808 // Doesn't have a value, check it (and the negation)
809 if(d_hasPropagated
.find(atom
) == d_hasPropagated
.end()) {
810 Dump("missed-t-propagations")
811 << CommentCommand("Completeness check for T-propagations; expect invalid")
812 << EchoCommand(atom
.toString())
813 << QueryCommand(atom
.toExpr())
814 << EchoCommand(atom
.notNode().toString())
815 << QueryCommand(atom
.notNode().toExpr());
821 Node
TheoryEngine::getNextDecisionRequest()
823 return d_decManager
->getNextDecisionRequest();
826 bool TheoryEngine::properConflict(TNode conflict
) const {
828 if (conflict
.getKind() == kind::AND
) {
829 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++ i
) {
830 if (! getPropEngine()->hasValue(conflict
[i
], value
)) {
831 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
832 << conflict
[i
] << endl
;
836 Debug("properConflict") << "Bad conflict is due to false atom: "
837 << conflict
[i
] << endl
;
840 if (conflict
[i
] != Rewriter::rewrite(conflict
[i
])) {
841 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
842 << conflict
[i
] << " vs " << Rewriter::rewrite(conflict
[i
]) << endl
;
847 if (! getPropEngine()->hasValue(conflict
, value
)) {
848 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
853 Debug("properConflict") << "Bad conflict is due to false atom: "
857 if (conflict
!= Rewriter::rewrite(conflict
)) {
858 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
859 << conflict
<< " vs " << Rewriter::rewrite(conflict
) << endl
;
866 bool TheoryEngine::properPropagation(TNode lit
) const {
867 if(!getPropEngine()->isSatLiteral(lit
)) {
871 return !getPropEngine()->hasValue(lit
, b
);
874 bool TheoryEngine::properExplanation(TNode node
, TNode expl
) const {
875 // Explanation must be either a conjunction of true literals that have true SAT values already
876 // or a singled literal that has a true SAT value already.
877 if (expl
.getKind() == kind::AND
) {
878 for (unsigned i
= 0; i
< expl
.getNumChildren(); ++ i
) {
880 if (!d_propEngine
->hasValue(expl
[i
], value
) || !value
) {
886 return d_propEngine
->hasValue(expl
, value
) && value
;
891 bool TheoryEngine::collectModelInfo(theory::TheoryModel
* m
)
893 //have shared term engine collectModelInfo
894 // d_sharedTerms.collectModelInfo( m );
895 // Consult each active theory to get all relevant information
896 // concerning the model.
897 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
898 if(d_logicInfo
.isTheoryEnabled(theoryId
)) {
899 Trace("model-builder") << " CollectModelInfo on theory: " << theoryId
<< endl
;
900 if (!d_theoryTable
[theoryId
]->collectModelInfo(m
))
906 Trace("model-builder") << " CollectModelInfo boolean variables" << std::endl
;
907 // Get the Boolean variables
908 vector
<TNode
> boolVars
;
909 d_propEngine
->getBooleanVariables(boolVars
);
910 vector
<TNode
>::iterator it
, iend
= boolVars
.end();
911 bool hasValue
, value
;
912 for (it
= boolVars
.begin(); it
!= iend
; ++it
) {
914 hasValue
= d_propEngine
->hasValue(var
, value
);
915 // TODO: Assert that hasValue is true?
917 Trace("model-builder-assertions")
918 << " has no value : " << var
<< std::endl
;
921 Trace("model-builder-assertions") << "(assert" << (value
? " " : " (not ") << var
<< (value
? ");" : "));") << endl
;
922 if (!m
->assertPredicate(var
, value
))
930 void TheoryEngine::postProcessModel( theory::TheoryModel
* m
){
931 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
932 if(d_logicInfo
.isTheoryEnabled(theoryId
)) {
933 Trace("model-builder-debug") << " PostProcessModel on theory: " << theoryId
<< endl
;
934 d_theoryTable
[theoryId
]->postProcessModel( m
);
939 TheoryModel
* TheoryEngine::getModel() {
943 TheoryModel
* TheoryEngine::getBuiltModel()
945 if (!d_curr_model
->isBuilt())
947 // If this method was called, we should be in SAT mode, and produceModels
949 AlwaysAssert(options::produceModels());
952 // not available, perhaps due to interuption.
955 // must build model at this point
956 d_curr_model_builder
->buildModel(d_curr_model
);
961 bool TheoryEngine::getSynthSolutions(
962 std::map
<Node
, std::map
<Node
, Node
>>& sol_map
)
966 return d_quantEngine
->getSynthSolutions(sol_map
);
968 // we are not in a quantified logic, there is no synthesis solution
972 bool TheoryEngine::presolve() {
973 // Reset the interrupt flag
974 d_interrupted
= false;
976 // Reset the decision manager. This clears its decision strategies that are
977 // no longer valid in this user context.
978 d_decManager
->presolve();
981 // Definition of the statement that is to be run by every theory
982 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
983 #undef CVC4_FOR_EACH_THEORY_STATEMENT
985 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
986 if (theory::TheoryTraits<THEORY>::hasPresolve) { \
987 theoryOf(THEORY)->presolve(); \
993 // Presolve for each theory using the statement above
994 CVC4_FOR_EACH_THEORY
;
995 } catch(const theory::Interrupted
&) {
996 Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl
;
998 // return whether we have a conflict
1000 }/* TheoryEngine::presolve() */
1002 void TheoryEngine::postsolve() {
1003 // no longer in SAT mode
1004 d_inSatMode
= false;
1005 // Reset the interrupt flag
1006 d_interrupted
= false;
1007 bool CVC4_UNUSED wasInConflict
= d_inConflict
;
1010 // Definition of the statement that is to be run by every theory
1011 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
1012 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1014 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1015 if (theory::TheoryTraits<THEORY>::hasPostsolve) \
1017 theoryOf(THEORY)->postsolve(); \
1018 Assert(!d_inConflict || wasInConflict) \
1019 << "conflict raised during postsolve()"; \
1022 // Postsolve for each theory using the statement above
1023 CVC4_FOR_EACH_THEORY
;
1024 } catch(const theory::Interrupted
&) {
1025 Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl
;
1027 }/* TheoryEngine::postsolve() */
1030 void TheoryEngine::notifyRestart() {
1031 // Reset the interrupt flag
1032 d_interrupted
= false;
1034 // Definition of the statement that is to be run by every theory
1035 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
1036 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1038 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1039 if (theory::TheoryTraits<THEORY>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
1040 theoryOf(THEORY)->notifyRestart(); \
1043 // notify each theory using the statement above
1044 CVC4_FOR_EACH_THEORY
;
1047 void TheoryEngine::ppStaticLearn(TNode in
, NodeBuilder
<>& learned
) {
1048 // Reset the interrupt flag
1049 d_interrupted
= false;
1051 // Definition of the statement that is to be run by every theory
1052 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
1053 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1055 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1056 if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) { \
1057 theoryOf(THEORY)->ppStaticLearn(in, learned); \
1060 // static learning for each theory using the statement above
1061 CVC4_FOR_EACH_THEORY
;
1064 void TheoryEngine::shutdown() {
1065 // Set this first; if a Theory shutdown() throws an exception,
1066 // at least the destruction of the TheoryEngine won't confound
1068 d_hasShutDown
= true;
1070 // Shutdown all the theories
1071 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
1072 if(d_theoryTable
[theoryId
]) {
1073 theoryOf(theoryId
)->shutdown();
1080 theory::Theory::PPAssertStatus
TheoryEngine::solve(TNode literal
, SubstitutionMap
& substitutionOut
) {
1081 // Reset the interrupt flag
1082 d_interrupted
= false;
1084 TNode atom
= literal
.getKind() == kind::NOT
? literal
[0] : literal
;
1085 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< "): solving with " << theoryOf(atom
)->getId() << endl
;
1087 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(atom
)) &&
1088 Theory::theoryOf(atom
) != THEORY_SAT_SOLVER
) {
1090 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1091 << ", which doesn't include " << Theory::theoryOf(atom
)
1092 << ", but got a preprocessing-time fact for that theory." << endl
1093 << "The fact:" << endl
1095 throw LogicException(ss
.str());
1098 Theory::PPAssertStatus solveStatus
= theoryOf(atom
)->ppAssert(literal
, substitutionOut
);
1099 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< ") => " << solveStatus
<< endl
;
1103 // Recursively traverse a term and call the theory rewriter on its sub-terms
1104 Node
TheoryEngine::ppTheoryRewrite(TNode term
) {
1105 NodeMap::iterator find
= d_ppCache
.find(term
);
1106 if (find
!= d_ppCache
.end()) {
1107 return (*find
).second
;
1109 unsigned nc
= term
.getNumChildren();
1111 return theoryOf(term
)->ppRewrite(term
);
1113 Trace("theory-pp") << "ppTheoryRewrite { " << term
<< endl
;
1116 // do not rewrite inside quantifiers
1117 if (term
.isClosure())
1119 newTerm
= Rewriter::rewrite(term
);
1123 NodeBuilder
<> newNode(term
.getKind());
1124 if (term
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
1125 newNode
<< term
.getOperator();
1128 for (i
= 0; i
< nc
; ++i
) {
1129 newNode
<< ppTheoryRewrite(term
[i
]);
1131 newTerm
= Rewriter::rewrite(Node(newNode
));
1133 Node newTerm2
= theoryOf(newTerm
)->ppRewrite(newTerm
);
1134 if (newTerm
!= newTerm2
) {
1135 newTerm
= ppTheoryRewrite(Rewriter::rewrite(newTerm2
));
1137 d_ppCache
[term
] = newTerm
;
1138 Trace("theory-pp")<< "ppTheoryRewrite returning " << newTerm
<< "}" << endl
;
1143 void TheoryEngine::preprocessStart()
1149 struct preprocess_stack_element
{
1151 bool children_added
;
1152 preprocess_stack_element(TNode n
) : node(n
), children_added(false) {}
1153 };/* struct preprocess_stack_element */
1156 Node
TheoryEngine::preprocess(TNode assertion
) {
1158 Trace("theory::preprocess") << "TheoryEngine::preprocess(" << assertion
<< ")" << endl
;
1161 // Do a topological sort of the subexpressions and substitute them
1162 vector
<preprocess_stack_element
> toVisit
;
1163 toVisit
.push_back(assertion
);
1165 while (!toVisit
.empty())
1167 // The current node we are processing
1168 preprocess_stack_element
& stackHead
= toVisit
.back();
1169 TNode current
= stackHead
.node
;
1171 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion
<< "): processing " << current
<< endl
;
1173 // If node already in the cache we're done, pop from the stack
1174 NodeMap::iterator find
= d_ppCache
.find(current
);
1175 if (find
!= d_ppCache
.end()) {
1180 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(current
)) &&
1181 Theory::theoryOf(current
) != THEORY_SAT_SOLVER
) {
1183 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1184 << ", which doesn't include " << Theory::theoryOf(current
)
1185 << ", but got a preprocessing-time fact for that theory." << endl
1186 << "The fact:" << endl
1188 throw LogicException(ss
.str());
1191 // If this is an atom, we preprocess its terms with the theory ppRewriter
1192 if (Theory::theoryOf(current
) != THEORY_BOOL
) {
1193 Node ppRewritten
= ppTheoryRewrite(current
);
1194 d_ppCache
[current
] = ppRewritten
;
1195 Assert(Rewriter::rewrite(d_ppCache
[current
]) == d_ppCache
[current
]);
1199 // Not yet substituted, so process
1200 if (stackHead
.children_added
) {
1201 // Children have been processed, so substitute
1202 NodeBuilder
<> builder(current
.getKind());
1203 if (current
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
1204 builder
<< current
.getOperator();
1206 for (unsigned i
= 0; i
< current
.getNumChildren(); ++ i
) {
1207 Assert(d_ppCache
.find(current
[i
]) != d_ppCache
.end());
1208 builder
<< d_ppCache
[current
[i
]];
1210 // Mark the substitution and continue
1211 Node result
= builder
;
1212 if (result
!= current
) {
1213 result
= Rewriter::rewrite(result
);
1215 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion
<< "): setting " << current
<< " -> " << result
<< endl
;
1216 d_ppCache
[current
] = result
;
1219 // Mark that we have added the children if any
1220 if (current
.getNumChildren() > 0) {
1221 stackHead
.children_added
= true;
1222 // We need to add the children
1223 for(TNode::iterator child_it
= current
.begin(); child_it
!= current
.end(); ++ child_it
) {
1224 TNode childNode
= *child_it
;
1225 NodeMap::iterator childFind
= d_ppCache
.find(childNode
);
1226 if (childFind
== d_ppCache
.end()) {
1227 toVisit
.push_back(childNode
);
1231 // No children, so we're done
1232 Debug("substitution::internal") << "SubstitutionMap::internalSubstitute(" << assertion
<< "): setting " << current
<< " -> " << current
<< endl
;
1233 d_ppCache
[current
] = current
;
1239 // Return the substituted version
1240 return d_ppCache
[assertion
];
1243 void TheoryEngine::notifyPreprocessedAssertions(
1244 const std::vector
<Node
>& assertions
) {
1245 // call all the theories
1246 for (TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
;
1248 if (d_theoryTable
[theoryId
]) {
1249 theoryOf(theoryId
)->ppNotifyAssertions(assertions
);
1254 bool TheoryEngine::markPropagation(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
1256 // What and where we are asserting
1257 NodeTheoryPair
toAssert(assertion
, toTheoryId
, d_propagationMapTimestamp
);
1258 // What and where it came from
1259 NodeTheoryPair
toExplain(originalAssertion
, fromTheoryId
, d_propagationMapTimestamp
);
1261 // See if the theory already got this literal
1262 PropagationMap::const_iterator find
= d_propagationMap
.find(toAssert
);
1263 if (find
!= d_propagationMap
.end()) {
1264 // The theory already knows this
1265 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl
;
1269 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp
<< "] " << assertion
<< ", " << toTheoryId
<< " from " << originalAssertion
<< ", " << fromTheoryId
<< endl
;
1271 // Mark the propagation
1272 d_propagationMap
[toAssert
] = toExplain
;
1273 d_propagationMapTimestamp
= d_propagationMapTimestamp
+ 1;
1279 void TheoryEngine::assertToTheory(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
1281 Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << originalAssertion
<< "," << toTheoryId
<< ", " << fromTheoryId
<< ")" << endl
;
1283 Assert(toTheoryId
!= fromTheoryId
);
1284 if(toTheoryId
!= THEORY_SAT_SOLVER
&&
1285 ! d_logicInfo
.isTheoryEnabled(toTheoryId
)) {
1287 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1288 << ", which doesn't include " << toTheoryId
1289 << ", but got an asserted fact to that theory." << endl
1290 << "The fact:" << endl
1292 throw LogicException(ss
.str());
1299 // If sharing is disabled, things are easy
1300 if (!d_logicInfo
.isSharingEnabled()) {
1301 Assert(assertion
== originalAssertion
);
1302 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
1303 // Send to the apropriate theory
1304 theory::Theory
* toTheory
= theoryOf(toTheoryId
);
1305 // We assert it, and we know it's preregistereed
1306 toTheory
->assertFact(assertion
, true);
1307 // Mark that we have more information
1308 d_factsAsserted
= true;
1310 Assert(toTheoryId
== THEORY_SAT_SOLVER
);
1311 // Check for propositional conflict
1313 if (d_propEngine
->hasValue(assertion
, value
)) {
1315 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (no sharing)" << endl
;
1316 Trace("dtview::conflict")
1317 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
1318 d_inConflict
= true;
1323 d_propagatedLiterals
.push_back(assertion
);
1328 // Polarity of the assertion
1329 bool polarity
= assertion
.getKind() != kind::NOT
;
1331 // Atom of the assertion
1332 TNode atom
= polarity
? assertion
: assertion
[0];
1334 // If sending to the shared terms database, it's also simple
1335 if (toTheoryId
== THEORY_BUILTIN
) {
1336 Assert(atom
.getKind() == kind::EQUAL
)
1337 << "atom should be an EQUALity, not `" << atom
<< "'";
1338 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1339 d_sharedTerms
.assertEquality(atom
, polarity
, assertion
);
1344 // Things from the SAT solver are already normalized, so they go
1345 // directly to the apropriate theory
1346 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
1347 // We know that this is normalized, so just send it off to the theory
1348 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1349 // Is it preregistered
1350 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1352 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1353 // Mark that we have more information
1354 d_factsAsserted
= true;
1359 // Propagations to the SAT solver are just enqueued for pickup by
1360 // the SAT solver later
1361 if (toTheoryId
== THEORY_SAT_SOLVER
) {
1362 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1363 // Enqueue for propagation to the SAT solver
1364 d_propagatedLiterals
.push_back(assertion
);
1365 // Check for propositional conflicts
1367 if (d_propEngine
->hasValue(assertion
, value
) && !value
) {
1368 Trace("theory::propagate")
1369 << "TheoryEngine::assertToTheory(" << assertion
<< ", "
1370 << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (sharing)"
1372 Trace("dtview::conflict")
1373 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
1374 d_inConflict
= true;
1380 Assert(atom
.getKind() == kind::EQUAL
);
1383 Node normalizedLiteral
= Rewriter::rewrite(assertion
);
1385 // See if it rewrites false directly -> conflict
1386 if (normalizedLiteral
.isConst()) {
1387 if (!normalizedLiteral
.getConst
<bool>()) {
1388 // Mark the propagation for explanations
1389 if (markPropagation(normalizedLiteral
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1390 // Get the explanation (conflict will figure out where it came from)
1391 conflict(normalizedLiteral
, toTheoryId
);
1399 // Try and assert (note that we assert the non-normalized one)
1400 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1401 // Check if has been pre-registered with the theory
1402 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1404 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1405 d_factsAsserted
= true;
1411 void TheoryEngine::assertFact(TNode literal
)
1413 Trace("theory") << "TheoryEngine::assertFact(" << literal
<< ")" << endl
;
1417 // If we're in conflict, nothing to do
1423 bool polarity
= literal
.getKind() != kind::NOT
;
1424 TNode atom
= polarity
? literal
: literal
[0];
1426 if (d_logicInfo
.isSharingEnabled()) {
1428 // If any shared terms, it's time to do sharing work
1429 if (d_sharedTerms
.hasSharedTerms(atom
)) {
1430 // Notify the theories the shared terms
1431 SharedTermsDatabase::shared_terms_iterator it
= d_sharedTerms
.begin(atom
);
1432 SharedTermsDatabase::shared_terms_iterator it_end
= d_sharedTerms
.end(atom
);
1433 for (; it
!= it_end
; ++ it
) {
1435 Theory::Set theories
= d_sharedTerms
.getTheoriesToNotify(atom
, term
);
1436 for (TheoryId id
= THEORY_FIRST
; id
!= THEORY_LAST
; ++ id
) {
1437 if (Theory::setContains(id
, theories
)) {
1438 theoryOf(id
)->addSharedTermInternal(term
);
1441 d_sharedTerms
.markNotified(term
, theories
);
1445 // If it's an equality, assert it to the shared term manager, even though the terms are not
1446 // yet shared. As the terms become shared later, the shared terms manager will then add them
1447 // to the assert the equality to the interested theories
1448 if (atom
.getKind() == kind::EQUAL
) {
1449 // Assert it to the the owning theory
1450 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1451 // Shared terms manager will assert to interested theories directly, as the terms become shared
1452 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ THEORY_SAT_SOLVER
);
1454 // Now, let's check for any atom triggers from lemmas
1455 AtomRequests::atom_iterator it
= d_atomRequests
.getAtomIterator(atom
);
1456 while (!it
.done()) {
1457 const AtomRequests::Request
& request
= it
.get();
1459 polarity
? (Node
)request
.d_atom
: request
.d_atom
.notNode();
1460 Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal
<< "): sending requested " << toAssert
<< endl
;
1462 toAssert
, literal
, request
.d_toTheory
, THEORY_SAT_SOLVER
);
1467 // Not an equality, just assert to the appropriate theory
1468 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1471 // Assert the fact to the appropriate theory directly
1472 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1476 bool TheoryEngine::propagate(TNode literal
, theory::TheoryId theory
) {
1478 Debug("theory::propagate") << "TheoryEngine::propagate(" << literal
<< ", " << theory
<< ")" << endl
;
1480 Trace("dtview::prop") << std::string(d_context
->getLevel(), ' ')
1481 << ":THEORY-PROP: " << literal
<< endl
;
1485 if(Dump
.isOn("t-propagations")) {
1486 Dump("t-propagations") << CommentCommand("negation of theory propagation: expect valid")
1487 << QueryCommand(literal
.toExpr());
1489 if(Dump
.isOn("missed-t-propagations")) {
1490 d_hasPropagated
.insert(literal
);
1494 bool polarity
= literal
.getKind() != kind::NOT
;
1495 TNode atom
= polarity
? literal
: literal
[0];
1497 if (d_logicInfo
.isSharingEnabled() && atom
.getKind() == kind::EQUAL
) {
1498 if (d_propEngine
->isSatLiteral(literal
)) {
1499 // We propagate SAT literals to SAT
1500 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1502 if (theory
!= THEORY_BUILTIN
) {
1503 // Assert to the shared terms database
1504 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ theory
);
1507 // We could be propagating a unit-clause lemma. In this case, we need to provide a
1509 // TODO: Consider putting this someplace else? This is the only refence to the proof
1510 // manager in this class.
1513 LemmaProofRecipe proofRecipe
;
1514 proofRecipe
.addBaseAssertion(literal
);
1517 LemmaProofRecipe::ProofStep
proofStep(theory
, emptyNode
);
1518 proofStep
.addAssertion(literal
);
1519 proofRecipe
.addStep(proofStep
);
1521 ProofManager::getCnfProof()->setProofRecipe(&proofRecipe
);
1524 // Just send off to the SAT solver
1525 Assert(d_propEngine
->isSatLiteral(literal
));
1526 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1529 return !d_inConflict
;
1532 const LogicInfo
& TheoryEngine::getLogicInfo() const { return d_logicInfo
; }
1534 theory::EqualityStatus
TheoryEngine::getEqualityStatus(TNode a
, TNode b
) {
1535 Assert(a
.getType().isComparableTo(b
.getType()));
1536 if (d_sharedTerms
.isShared(a
) && d_sharedTerms
.isShared(b
)) {
1537 if (d_sharedTerms
.areEqual(a
,b
)) {
1538 return EQUALITY_TRUE_AND_PROPAGATED
;
1540 else if (d_sharedTerms
.areDisequal(a
,b
)) {
1541 return EQUALITY_FALSE_AND_PROPAGATED
;
1544 return theoryOf(Theory::theoryOf(a
.getType()))->getEqualityStatus(a
, b
);
1547 Node
TheoryEngine::getModelValue(TNode var
) {
1550 // the model value of a constant must be itself
1553 Assert(d_sharedTerms
.isShared(var
));
1554 return theoryOf(Theory::theoryOf(var
.getType()))->getModelValue(var
);
1558 Node
TheoryEngine::ensureLiteral(TNode n
) {
1559 Debug("ensureLiteral") << "rewriting: " << n
<< std::endl
;
1560 Node rewritten
= Rewriter::rewrite(n
);
1561 Debug("ensureLiteral") << " got: " << rewritten
<< std::endl
;
1562 Node preprocessed
= preprocess(rewritten
);
1563 Debug("ensureLiteral") << "preprocessed: " << preprocessed
<< std::endl
;
1564 d_propEngine
->ensureLiteral(preprocessed
);
1565 return preprocessed
;
1569 void TheoryEngine::printInstantiations( std::ostream
& out
) {
1570 if( d_quantEngine
){
1571 d_quantEngine
->printInstantiations( out
);
1573 out
<< "Internal error : instantiations not available when quantifiers are not present." << std::endl
;
1578 void TheoryEngine::printSynthSolution( std::ostream
& out
) {
1579 if( d_quantEngine
){
1580 d_quantEngine
->printSynthSolution( out
);
1582 out
<< "Internal error : synth solution not available when quantifiers are not present." << std::endl
;
1587 void TheoryEngine::getInstantiatedQuantifiedFormulas( std::vector
< Node
>& qs
) {
1588 if( d_quantEngine
){
1589 d_quantEngine
->getInstantiatedQuantifiedFormulas( qs
);
1595 void TheoryEngine::getInstantiations( Node q
, std::vector
< Node
>& insts
) {
1596 if( d_quantEngine
){
1597 d_quantEngine
->getInstantiations( q
, insts
);
1603 void TheoryEngine::getInstantiationTermVectors( Node q
, std::vector
< std::vector
< Node
> >& tvecs
) {
1604 if( d_quantEngine
){
1605 d_quantEngine
->getInstantiationTermVectors( q
, tvecs
);
1611 void TheoryEngine::getInstantiations( std::map
< Node
, std::vector
< Node
> >& insts
) {
1612 if( d_quantEngine
){
1613 d_quantEngine
->getInstantiations( insts
);
1619 void TheoryEngine::getInstantiationTermVectors( std::map
< Node
, std::vector
< std::vector
< Node
> > >& insts
) {
1620 if( d_quantEngine
){
1621 d_quantEngine
->getInstantiationTermVectors( insts
);
1627 Node
TheoryEngine::getInstantiatedConjunction( Node q
) {
1628 if( d_quantEngine
){
1629 return d_quantEngine
->getInstantiatedConjunction( q
);
1632 return Node::null();
1637 static Node
mkExplanation(const std::vector
<NodeTheoryPair
>& explanation
) {
1639 std::set
<TNode
> all
;
1640 for (unsigned i
= 0; i
< explanation
.size(); ++ i
) {
1641 Assert(explanation
[i
].d_theory
== THEORY_SAT_SOLVER
);
1642 all
.insert(explanation
[i
].d_node
);
1645 if (all
.size() == 0) {
1646 // Normalize to true
1647 return NodeManager::currentNM()->mkConst
<bool>(true);
1650 if (all
.size() == 1) {
1651 // All the same, or just one
1652 return explanation
[0].d_node
;
1655 NodeBuilder
<> conjunction(kind::AND
);
1656 std::set
<TNode
>::const_iterator it
= all
.begin();
1657 std::set
<TNode
>::const_iterator it_end
= all
.end();
1658 while (it
!= it_end
) {
1666 Node
TheoryEngine::getExplanationAndRecipe(TNode node
, LemmaProofRecipe
* proofRecipe
) {
1667 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< "): current propagation index = " << d_propagationMapTimestamp
<< endl
;
1669 bool polarity
= node
.getKind() != kind::NOT
;
1670 TNode atom
= polarity
? node
: node
[0];
1672 // If we're not in shared mode, explanations are simple
1673 if (!d_logicInfo
.isSharingEnabled()) {
1674 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing is NOT enabled. "
1675 << " Responsible theory is: "
1676 << theoryOf(atom
)->getId() << std::endl
;
1678 Node explanation
= theoryOf(atom
)->explain(node
);
1679 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => " << explanation
<< endl
;
1683 LemmaProofRecipe::ProofStep
proofStep(theoryOf(atom
)->getId(), emptyNode
);
1684 proofStep
.addAssertion(node
);
1685 proofRecipe
->addBaseAssertion(node
);
1687 if (explanation
.getKind() == kind::AND
) {
1688 // If the explanation is a conjunction, the recipe for the corresponding lemma is
1689 // the negation of its conjuncts.
1690 Node flat
= flattenAnd(explanation
);
1691 for (unsigned i
= 0; i
< flat
.getNumChildren(); ++i
) {
1692 if (flat
[i
].isConst() && flat
[i
].getConst
<bool>()) {
1696 if (flat
[i
].getKind() == kind::NOT
&&
1697 flat
[i
][0].isConst() && !flat
[i
][0].getConst
<bool>()) {
1701 Debug("theory::explain") << "TheoryEngine::getExplanationAndRecipe: adding recipe assertion: "
1702 << flat
[i
].negate() << std::endl
;
1703 proofStep
.addAssertion(flat
[i
].negate());
1704 proofRecipe
->addBaseAssertion(flat
[i
].negate());
1707 // The recipe for proving it is by negating it. "True" is not an acceptable reason.
1708 if (!((explanation
.isConst() && explanation
.getConst
<bool>()) ||
1709 (explanation
.getKind() == kind::NOT
&&
1710 explanation
[0].isConst() && !explanation
[0].getConst
<bool>()))) {
1711 proofStep
.addAssertion(explanation
.negate());
1712 proofRecipe
->addBaseAssertion(explanation
.negate());
1716 proofRecipe
->addStep(proofStep
);
1723 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing IS enabled" << std::endl
;
1725 // Initial thing to explain
1726 NodeTheoryPair
toExplain(node
, THEORY_SAT_SOLVER
, d_propagationMapTimestamp
);
1727 Assert(d_propagationMap
.find(toExplain
) != d_propagationMap
.end());
1729 NodeTheoryPair nodeExplainerPair
= d_propagationMap
[toExplain
];
1730 Debug("theory::explain")
1731 << "TheoryEngine::getExplanation: explainer for node "
1732 << nodeExplainerPair
.d_node
1733 << " is theory: " << nodeExplainerPair
.d_theory
<< std::endl
;
1734 TheoryId explainer
= nodeExplainerPair
.d_theory
;
1736 // Create the workplace for explanations
1737 std::vector
<NodeTheoryPair
> explanationVector
;
1738 explanationVector
.push_back(d_propagationMap
[toExplain
]);
1739 // Process the explanation
1742 LemmaProofRecipe::ProofStep
proofStep(explainer
, emptyNode
);
1743 proofStep
.addAssertion(node
);
1744 proofRecipe
->addStep(proofStep
);
1745 proofRecipe
->addBaseAssertion(node
);
1748 getExplanation(explanationVector
, proofRecipe
);
1749 Node explanation
= mkExplanation(explanationVector
);
1751 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => " << explanation
<< endl
;
1756 Node
TheoryEngine::getExplanation(TNode node
) {
1757 LemmaProofRecipe
*dontCareRecipe
= NULL
;
1758 return getExplanationAndRecipe(node
, dontCareRecipe
);
1761 struct AtomsCollect
{
1763 std::vector
<TNode
> d_atoms
;
1764 std::unordered_set
<TNode
, TNodeHashFunction
> d_visited
;
1768 typedef void return_type
;
1770 bool alreadyVisited(TNode current
, TNode parent
) {
1771 // Check if already visited
1772 if (d_visited
.find(current
) != d_visited
.end()) return true;
1773 // Don't visit non-boolean
1774 if (!current
.getType().isBoolean()) return true;
1779 void visit(TNode current
, TNode parent
) {
1780 if (Theory::theoryOf(current
) != theory::THEORY_BOOL
) {
1781 d_atoms
.push_back(current
);
1783 d_visited
.insert(current
);
1786 void start(TNode node
) {}
1787 void done(TNode node
) {}
1789 std::vector
<TNode
> getAtoms() const {
1794 void TheoryEngine::ensureLemmaAtoms(const std::vector
<TNode
>& atoms
, theory::TheoryId atomsTo
) {
1795 for (unsigned i
= 0; i
< atoms
.size(); ++ i
) {
1797 // Non-equality atoms are either owned by theory or they don't make sense
1798 if (atoms
[i
].getKind() != kind::EQUAL
) {
1804 // Simple normalization to not repeat stuff
1805 if (eq
[0] > eq
[1]) {
1806 eq
= eq
[1].eqNode(eq
[0]);
1809 // Rewrite the equality
1810 Node eqNormalized
= Rewriter::rewrite(atoms
[i
]);
1812 Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq
<< " with nf " << eqNormalized
<< endl
;
1814 // If the equality is a boolean constant, we send immediately
1815 if (eqNormalized
.isConst()) {
1816 if (eqNormalized
.getConst
<bool>()) {
1817 assertToTheory(eq
, eqNormalized
, /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1819 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1822 }else if( eqNormalized
.getKind() != kind::EQUAL
){
1823 Assert(eqNormalized
.getKind() == kind::BOOLEAN_TERM_VARIABLE
1824 || (eqNormalized
.getKind() == kind::NOT
1825 && eqNormalized
[0].getKind() == kind::BOOLEAN_TERM_VARIABLE
));
1826 // this happens for Boolean term equalities V = true that are rewritten to V, we should skip
1827 // TODO : revisit this
1831 // If the normalization did the just flips, keep the flip
1832 if (eqNormalized
[0] == eq
[1] && eqNormalized
[1] == eq
[0]) {
1836 // Check if the equality is already known by the sat solver
1837 if (d_propEngine
->isSatLiteral(eqNormalized
)) {
1839 if (d_propEngine
->hasValue(eqNormalized
, value
)) {
1841 assertToTheory(eq
, eqNormalized
, atomsTo
, theory::THEORY_SAT_SOLVER
);
1844 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), atomsTo
, theory::THEORY_SAT_SOLVER
);
1850 // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1851 // then we must figure it out
1852 if (eqNormalized
!= eq
|| Theory::theoryOf(eq
) != atomsTo
) {
1853 // If you get eqNormalized, send atoms[i] to atomsTo
1854 d_atomRequests
.add(eqNormalized
, eq
, atomsTo
);
1859 theory::LemmaStatus
TheoryEngine::lemma(TNode node
,
1864 theory::TheoryId atomsTo
) {
1865 // For resource-limiting (also does a time check).
1868 // Do we need to check atoms
1869 if (atomsTo
!= theory::THEORY_LAST
) {
1870 Debug("theory::atoms") << "TheoryEngine::lemma(" << node
<< ", " << atomsTo
<< ")" << endl
;
1871 AtomsCollect collectAtoms
;
1872 NodeVisitor
<AtomsCollect
>::run(collectAtoms
, node
);
1873 ensureLemmaAtoms(collectAtoms
.getAtoms(), atomsTo
);
1876 if(Dump
.isOn("t-lemmas")) {
1881 Dump("t-lemmas") << CommentCommand("theory lemma: expect valid")
1882 << CheckSatCommand(n
.toExpr());
1885 AssertionPipeline additionalLemmas
;
1887 // Run theory preprocessing, maybe
1888 Node ppNode
= preprocess
? this->preprocess(node
) : Node(node
);
1891 Debug("ite") << "Remove ITE from " << ppNode
<< std::endl
;
1892 additionalLemmas
.push_back(ppNode
);
1893 additionalLemmas
.updateRealAssertionsEnd();
1894 d_tform_remover
.run(additionalLemmas
.ref(),
1895 additionalLemmas
.getIteSkolemMap());
1896 Debug("ite") << "..done " << additionalLemmas
[0] << std::endl
;
1897 additionalLemmas
.replace(0, theory::Rewriter::rewrite(additionalLemmas
[0]));
1899 if(Debug
.isOn("lemma-ites")) {
1900 Debug("lemma-ites") << "removed ITEs from lemma: " << ppNode
<< endl
;
1901 Debug("lemma-ites") << " + now have the following "
1902 << additionalLemmas
.size() << " lemma(s):" << endl
;
1903 for(std::vector
<Node
>::const_iterator i
= additionalLemmas
.begin();
1904 i
!= additionalLemmas
.end();
1906 Debug("lemma-ites") << " + " << *i
<< endl
;
1908 Debug("lemma-ites") << endl
;
1911 // assert to prop engine
1912 d_propEngine
->assertLemma(additionalLemmas
[0], negated
, removable
, rule
, node
);
1913 for (unsigned i
= 1; i
< additionalLemmas
.size(); ++ i
) {
1914 additionalLemmas
.replace(i
, theory::Rewriter::rewrite(additionalLemmas
[i
]));
1915 d_propEngine
->assertLemma(additionalLemmas
[i
], false, removable
, rule
, node
);
1918 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1920 additionalLemmas
.replace(0, additionalLemmas
[0].notNode());
1924 // assert to decision engine
1927 d_propEngine
->addAssertionsToDecisionEngine(additionalLemmas
);
1930 // Mark that we added some lemmas
1931 d_lemmasAdded
= true;
1933 // Lemma analysis isn't online yet; this lemma may only live for this
1935 return theory::LemmaStatus(additionalLemmas
[0], d_userContext
->getLevel());
1938 void TheoryEngine::conflict(TNode conflict
, TheoryId theoryId
) {
1940 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< ")" << endl
;
1942 Trace("dtview::conflict") << ":THEORY-CONFLICT: " << conflict
<< std::endl
;
1944 // Mark that we are in conflict
1945 d_inConflict
= true;
1947 if(Dump
.isOn("t-conflicts")) {
1948 Dump("t-conflicts") << CommentCommand("theory conflict: expect unsat")
1949 << CheckSatCommand(conflict
.toExpr());
1952 LemmaProofRecipe
* proofRecipe
= NULL
;
1954 proofRecipe
= new LemmaProofRecipe
;
1956 LemmaProofRecipe::ProofStep
proofStep(theoryId
, emptyNode
);
1958 if (conflict
.getKind() == kind::AND
) {
1959 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++i
) {
1960 proofStep
.addAssertion(conflict
[i
].negate());
1963 proofStep
.addAssertion(conflict
.negate());
1966 proofRecipe
->addStep(proofStep
);
1969 // In the multiple-theories case, we need to reconstruct the conflict
1970 if (d_logicInfo
.isSharingEnabled()) {
1971 // Create the workplace for explanations
1972 std::vector
<NodeTheoryPair
> explanationVector
;
1973 explanationVector
.push_back(NodeTheoryPair(conflict
, theoryId
, d_propagationMapTimestamp
));
1975 // Process the explanation
1976 getExplanation(explanationVector
, proofRecipe
);
1977 PROOF(ProofManager::getCnfProof()->setProofRecipe(proofRecipe
));
1978 Node fullConflict
= mkExplanation(explanationVector
);
1979 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< "): full = " << fullConflict
<< endl
;
1980 Assert(properConflict(fullConflict
));
1981 lemma(fullConflict
, RULE_CONFLICT
, true, true, false, THEORY_LAST
);
1984 // When only one theory, the conflict should need no processing
1985 Assert(properConflict(conflict
));
1987 if (conflict
.getKind() == kind::AND
) {
1988 // If the conflict is a conjunction, the corresponding lemma is derived by negating
1990 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++i
) {
1991 if (conflict
[i
].isConst() && conflict
[i
].getConst
<bool>()) {
1995 if (conflict
[i
].getKind() == kind::NOT
&&
1996 conflict
[i
][0].isConst() && !conflict
[i
][0].getConst
<bool>()) {
2000 proofRecipe
->getStep(0)->addAssertion(conflict
[i
].negate());
2001 proofRecipe
->addBaseAssertion(conflict
[i
].negate());
2004 proofRecipe
->getStep(0)->addAssertion(conflict
.negate());
2005 proofRecipe
->addBaseAssertion(conflict
.negate());
2008 ProofManager::getCnfProof()->setProofRecipe(proofRecipe
);
2011 lemma(conflict
, RULE_CONFLICT
, true, true, false, THEORY_LAST
);
2020 void TheoryEngine::staticInitializeBVOptions(
2021 const std::vector
<Node
>& assertions
)
2023 bool useSlicer
= true;
2024 if (options::bitvectorEqualitySlicer() == options::BvSlicerMode::ON
)
2026 if (!d_logicInfo
.isPure(theory::THEORY_BV
) || d_logicInfo
.isQuantified())
2027 throw ModalException(
2028 "Slicer currently only supports pure QF_BV formulas. Use "
2029 "--bv-eq-slicer=off");
2030 if (options::incrementalSolving())
2031 throw ModalException(
2032 "Slicer does not currently support incremental mode. Use "
2033 "--bv-eq-slicer=off");
2034 if (options::produceModels())
2035 throw ModalException(
2036 "Slicer does not currently support model generation. Use "
2037 "--bv-eq-slicer=off");
2039 else if (options::bitvectorEqualitySlicer() == options::BvSlicerMode::OFF
)
2043 else if (options::bitvectorEqualitySlicer() == options::BvSlicerMode::AUTO
)
2045 if ((!d_logicInfo
.isPure(theory::THEORY_BV
) || d_logicInfo
.isQuantified())
2046 || options::incrementalSolving()
2047 || options::produceModels())
2050 bv::utils::TNodeBoolMap cache
;
2051 for (unsigned i
= 0; i
< assertions
.size(); ++i
)
2053 useSlicer
= useSlicer
&& bv::utils::isCoreTerm(assertions
[i
], cache
);
2059 bv::TheoryBV
* bv_theory
= (bv::TheoryBV
*)d_theoryTable
[THEORY_BV
];
2060 bv_theory
->enableCoreTheorySlicer();
2064 void TheoryEngine::getExplanation(std::vector
<NodeTheoryPair
>& explanationVector
, LemmaProofRecipe
* proofRecipe
) {
2065 Assert(explanationVector
.size() > 0);
2067 unsigned i
= 0; // Index of the current literal we are processing
2068 unsigned j
= 0; // Index of the last literal we are keeping
2070 std::unique_ptr
<std::set
<Node
>> inputAssertions
= nullptr;
2074 inputAssertions
.reset(
2075 new std::set
<Node
>(proofRecipe
->getStep(0)->getAssertions()));
2079 while (i
< explanationVector
.size()) {
2080 // Get the current literal to explain
2081 NodeTheoryPair toExplain
= explanationVector
[i
];
2083 Debug("theory::explain")
2084 << "[i=" << i
<< "] TheoryEngine::explain(): processing ["
2085 << toExplain
.d_timestamp
<< "] " << toExplain
.d_node
<< " sent from "
2086 << toExplain
.d_theory
<< endl
;
2088 // If a true constant or a negation of a false constant we can ignore it
2089 if (toExplain
.d_node
.isConst() && toExplain
.d_node
.getConst
<bool>())
2094 if (toExplain
.d_node
.getKind() == kind::NOT
&& toExplain
.d_node
[0].isConst()
2095 && !toExplain
.d_node
[0].getConst
<bool>())
2101 // If from the SAT solver, keep it
2102 if (toExplain
.d_theory
== THEORY_SAT_SOLVER
)
2104 Debug("theory::explain") << "\tLiteral came from THEORY_SAT_SOLVER. Kepping it." << endl
;
2105 explanationVector
[j
++] = explanationVector
[i
++];
2109 // If an and, expand it
2110 if (toExplain
.d_node
.getKind() == kind::AND
)
2112 Debug("theory::explain")
2113 << "TheoryEngine::explain(): expanding " << toExplain
.d_node
2114 << " got from " << toExplain
.d_theory
<< endl
;
2115 for (unsigned k
= 0; k
< toExplain
.d_node
.getNumChildren(); ++k
)
2117 NodeTheoryPair
newExplain(
2118 toExplain
.d_node
[k
], toExplain
.d_theory
, toExplain
.d_timestamp
);
2119 explanationVector
.push_back(newExplain
);
2125 // See if it was sent to the theory by another theory
2126 PropagationMap::const_iterator find
= d_propagationMap
.find(toExplain
);
2127 if (find
!= d_propagationMap
.end()) {
2128 Debug("theory::explain")
2129 << "\tTerm was propagated by another theory (theory = "
2130 << getTheoryString((*find
).second
.d_theory
) << ")" << std::endl
;
2131 // There is some propagation, check if its a timely one
2132 if ((*find
).second
.d_timestamp
< toExplain
.d_timestamp
)
2134 Debug("theory::explain")
2135 << "\tRelevant timetsamp, pushing " << (*find
).second
.d_node
2136 << "to index = " << explanationVector
.size() << std::endl
;
2137 explanationVector
.push_back((*find
).second
);
2141 if (toExplain
.d_node
!= (*find
).second
.d_node
)
2143 Debug("pf::explain")
2144 << "TheoryEngine::getExplanation: Rewrite alert! toAssert = "
2145 << toExplain
.d_node
<< ", toExplain = " << (*find
).second
.d_node
2150 proofRecipe
->addRewriteRule(toExplain
.d_node
,
2151 (*find
).second
.d_node
);
2160 // It was produced by the theory, so ask for an explanation
2162 if (toExplain
.d_theory
== THEORY_BUILTIN
)
2164 explanation
= d_sharedTerms
.explain(toExplain
.d_node
);
2165 Debug("theory::explain") << "\tTerm was propagated by THEORY_BUILTIN. Explanation: " << explanation
<< std::endl
;
2169 explanation
= theoryOf(toExplain
.d_theory
)->explain(toExplain
.d_node
);
2170 Debug("theory::explain") << "\tTerm was propagated by owner theory: "
2171 << theoryOf(toExplain
.d_theory
)->getId()
2172 << ". Explanation: " << explanation
<< std::endl
;
2175 Debug("theory::explain")
2176 << "TheoryEngine::explain(): got explanation " << explanation
2177 << " got from " << toExplain
.d_theory
<< endl
;
2178 Assert(explanation
!= toExplain
.d_node
)
2179 << "wasn't sent to you, so why are you explaining it trivially";
2180 // Mark the explanation
2181 NodeTheoryPair
newExplain(
2182 explanation
, toExplain
.d_theory
, toExplain
.d_timestamp
);
2183 explanationVector
.push_back(newExplain
);
2188 if (proofRecipe
&& inputAssertions
)
2190 // If we're expanding the target node of the explanation (this is the
2191 // first expansion...), we don't want to add it as a separate proof
2192 // step. It is already part of the assertions.
2193 if (!ContainsKey(*inputAssertions
, toExplain
.d_node
))
2195 LemmaProofRecipe::ProofStep
proofStep(toExplain
.d_theory
,
2197 if (explanation
.getKind() == kind::AND
)
2199 Node flat
= flattenAnd(explanation
);
2200 for (unsigned k
= 0; k
< flat
.getNumChildren(); ++k
)
2202 // If a true constant or a negation of a false constant we can
2204 if (!((flat
[k
].isConst() && flat
[k
].getConst
<bool>())
2205 || (flat
[k
].getKind() == kind::NOT
&& flat
[k
][0].isConst()
2206 && !flat
[k
][0].getConst
<bool>())))
2208 proofStep
.addAssertion(flat
[k
].negate());
2214 if (!((explanation
.isConst() && explanation
.getConst
<bool>())
2215 || (explanation
.getKind() == kind::NOT
2216 && explanation
[0].isConst()
2217 && !explanation
[0].getConst
<bool>())))
2219 proofStep
.addAssertion(explanation
.negate());
2222 proofRecipe
->addStep(proofStep
);
2228 // Keep only the relevant literals
2229 explanationVector
.resize(j
);
2233 // The remaining literals are the base of the proof
2234 for (unsigned k
= 0; k
< explanationVector
.size(); ++k
) {
2235 proofRecipe
->addBaseAssertion(explanationVector
[k
].d_node
.negate());
2241 void TheoryEngine::setUserAttribute(const std::string
& attr
,
2243 const std::vector
<Node
>& node_values
,
2244 const std::string
& str_value
)
2246 Trace("te-attr") << "set user attribute " << attr
<< " " << n
<< endl
;
2247 if( d_attr_handle
.find( attr
)!=d_attr_handle
.end() ){
2248 for( size_t i
=0; i
<d_attr_handle
[attr
].size(); i
++ ){
2249 d_attr_handle
[attr
][i
]->setUserAttribute(attr
, n
, node_values
, str_value
);
2252 //unhandled exception?
2256 void TheoryEngine::handleUserAttribute(const char* attr
, Theory
* t
) {
2257 Trace("te-attr") << "Handle user attribute " << attr
<< " " << t
<< endl
;
2258 std::string
str( attr
);
2259 d_attr_handle
[ str
].push_back( t
);
2262 void TheoryEngine::checkTheoryAssertionsWithModel(bool hardFailure
) {
2263 for(TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
2264 Theory
* theory
= d_theoryTable
[theoryId
];
2265 if(theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
2266 for(context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
2267 it_end
= theory
->facts_end();
2270 Node assertion
= (*it
).d_assertion
;
2271 Node val
= getModel()->getValue(assertion
);
2274 std::stringstream ss
;
2276 << " has an asserted fact that the model doesn't satisfy." << endl
2277 << "The fact: " << assertion
<< endl
2278 << "Model value: " << val
<< endl
;
2283 // Always an error if it is false
2284 InternalError() << ss
.str();
2288 // Otherwise just a warning. Notice this case may happen for
2289 // assertions with unevaluable operators, e.g. transcendental
2290 // functions. It also may happen for separation logic, where
2291 // check-model support is limited.
2292 Warning() << ss
.str();
2301 std::pair
<bool, Node
> TheoryEngine::entailmentCheck(
2302 options::TheoryOfMode mode
,
2304 const EntailmentCheckParameters
* params
,
2305 EntailmentCheckSideEffects
* seffects
)
2307 TNode atom
= (lit
.getKind() == kind::NOT
) ? lit
[0] : lit
;
2308 if( atom
.getKind()==kind::AND
|| atom
.getKind()==kind::OR
|| atom
.getKind()==kind::IMPLIES
){
2309 //Boolean connective, recurse
2310 std::vector
< Node
> children
;
2311 bool pol
= (lit
.getKind()!=kind::NOT
);
2312 bool is_conjunction
= pol
==(lit
.getKind()==kind::AND
);
2313 for( unsigned i
=0; i
<atom
.getNumChildren(); i
++ ){
2315 if( pol
==( lit
.getKind()==kind::IMPLIES
&& i
==0 ) ){
2316 ch
= atom
[i
].negate();
2318 std::pair
<bool, Node
> chres
= entailmentCheck( mode
, ch
, params
, seffects
);
2320 if( !is_conjunction
){
2323 children
.push_back( chres
.second
);
2325 }else if( !chres
.first
&& is_conjunction
){
2326 return std::pair
<bool, Node
>(false, Node::null());
2329 if( is_conjunction
){
2330 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, children
));
2332 return std::pair
<bool, Node
>(false, Node::null());
2334 }else if( atom
.getKind()==kind::ITE
|| ( atom
.getKind()==kind::EQUAL
&& atom
[0].getType().isBoolean() ) ){
2335 bool pol
= (lit
.getKind()!=kind::NOT
);
2336 for( unsigned r
=0; r
<2; r
++ ){
2341 std::pair
<bool, Node
> chres
= entailmentCheck( mode
, ch
, params
, seffects
);
2343 Node ch2
= atom
[ atom
.getKind()==kind::ITE
? r
+1 : 1 ];
2344 if( pol
==( atom
.getKind()==kind::ITE
? true : r
==1 ) ){
2347 std::pair
<bool, Node
> chres2
= entailmentCheck( mode
, ch2
, params
, seffects
);
2349 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, chres
.second
, chres2
.second
));
2355 return std::pair
<bool, Node
>(false, Node::null());
2357 //it is a theory atom
2358 theory::TheoryId tid
= theory::Theory::theoryOf(mode
, atom
);
2359 theory::Theory
* th
= theoryOf(tid
);
2362 Assert(params
== NULL
|| tid
== params
->getTheoryId());
2363 Assert(seffects
== NULL
|| tid
== seffects
->getTheoryId());
2364 Trace("theory-engine-entc") << "Entailment check : " << lit
<< std::endl
;
2366 std::pair
<bool, Node
> chres
= th
->entailmentCheck(lit
, params
, seffects
);
2371 void TheoryEngine::spendResource(ResourceManager::Resource r
)
2373 d_resourceManager
->spendResource(r
);
2376 TheoryEngine::Statistics::Statistics(theory::TheoryId theory
):
2377 conflicts(getStatsPrefix(theory
) + "::conflicts", 0),
2378 propagations(getStatsPrefix(theory
) + "::propagations", 0),
2379 lemmas(getStatsPrefix(theory
) + "::lemmas", 0),
2380 requirePhase(getStatsPrefix(theory
) + "::requirePhase", 0),
2381 restartDemands(getStatsPrefix(theory
) + "::restartDemands", 0)
2383 smtStatisticsRegistry()->registerStat(&conflicts
);
2384 smtStatisticsRegistry()->registerStat(&propagations
);
2385 smtStatisticsRegistry()->registerStat(&lemmas
);
2386 smtStatisticsRegistry()->registerStat(&requirePhase
);
2387 smtStatisticsRegistry()->registerStat(&restartDemands
);
2390 TheoryEngine::Statistics::~Statistics() {
2391 smtStatisticsRegistry()->unregisterStat(&conflicts
);
2392 smtStatisticsRegistry()->unregisterStat(&propagations
);
2393 smtStatisticsRegistry()->unregisterStat(&lemmas
);
2394 smtStatisticsRegistry()->unregisterStat(&requirePhase
);
2395 smtStatisticsRegistry()->unregisterStat(&restartDemands
);
2398 }/* CVC4 namespace */