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 "options/bv_options.h"
29 #include "options/options.h"
30 #include "options/proof_options.h"
31 #include "options/quantifiers_options.h"
32 #include "preprocessing/assertion_pipeline.h"
33 #include "proof/cnf_proof.h"
34 #include "proof/lemma_proof.h"
35 #include "proof/proof_manager.h"
36 #include "proof/theory_proof.h"
37 #include "smt/logic_exception.h"
38 #include "smt/term_formula_removal.h"
39 #include "smt_util/lemma_output_channel.h"
40 #include "smt_util/node_visitor.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 LemmaChannels
* channels
)
318 : d_propEngine(nullptr),
319 d_decisionEngine(nullptr),
321 d_userContext(userContext
),
322 d_logicInfo(logicInfo
),
323 d_sharedTerms(this, context
),
324 d_masterEqualityEngine(nullptr),
325 d_masterEENotify(*this),
326 d_quantEngine(nullptr),
327 d_decManager(new DecisionManager(userContext
)),
328 d_curr_model(nullptr),
329 d_aloc_curr_model(false),
330 d_curr_model_builder(nullptr),
331 d_aloc_curr_model_builder(false),
332 d_eager_model_building(false),
334 d_possiblePropagations(context
),
335 d_hasPropagated(context
),
336 d_inConflict(context
, false),
338 d_hasShutDown(false),
339 d_incomplete(context
, false),
340 d_propagationMap(context
),
341 d_propagationMapTimestamp(context
, 0),
342 d_propagatedLiterals(context
),
343 d_propagatedLiteralsIndex(context
, 0),
344 d_atomRequests(context
),
345 d_tform_remover(iteRemover
),
346 d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
349 d_interrupted(false),
350 d_resourceManager(NodeManager::currentResourceManager()),
351 d_channels(channels
),
352 d_inPreregister(false),
353 d_factsAsserted(context
, false),
354 d_preRegistrationVisitor(this, context
),
355 d_sharedTermsVisitor(d_sharedTerms
),
356 d_theoryAlternatives(),
358 d_arithSubstitutionsAdded("theory::arith::zzz::arith::substitutions", 0)
360 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
;
363 d_theoryTable
[theoryId
] = NULL
;
364 d_theoryOut
[theoryId
] = NULL
;
367 smtStatisticsRegistry()->registerStat(&d_combineTheoriesTime
);
368 d_true
= NodeManager::currentNM()->mkConst
<bool>(true);
369 d_false
= NodeManager::currentNM()->mkConst
<bool>(false);
372 ProofManager::currentPM()->initTheoryProofEngine();
375 smtStatisticsRegistry()->registerStat(&d_arithSubstitutionsAdded
);
378 TheoryEngine::~TheoryEngine() {
379 Assert(d_hasShutDown
);
381 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
382 if(d_theoryTable
[theoryId
] != NULL
) {
383 delete d_theoryTable
[theoryId
];
384 delete d_theoryOut
[theoryId
];
388 if( d_aloc_curr_model_builder
){
389 delete d_curr_model_builder
;
391 if( d_aloc_curr_model
){
395 delete d_quantEngine
;
397 delete d_masterEqualityEngine
;
399 smtStatisticsRegistry()->unregisterStat(&d_combineTheoriesTime
);
400 smtStatisticsRegistry()->unregisterStat(&d_arithSubstitutionsAdded
);
403 void TheoryEngine::interrupt() { d_interrupted
= true; }
404 void TheoryEngine::preRegister(TNode preprocessed
) {
406 Debug("theory") << "TheoryEngine::preRegister( " << preprocessed
<< ")" << std::endl
;
407 if(Dump
.isOn("missed-t-propagations")) {
408 d_possiblePropagations
.push_back(preprocessed
);
410 d_preregisterQueue
.push(preprocessed
);
412 if (!d_inPreregister
) {
413 // We're in pre-register
414 d_inPreregister
= true;
416 // Process the pre-registration queue
417 while (!d_preregisterQueue
.empty()) {
418 // Get the next atom to pre-register
419 preprocessed
= d_preregisterQueue
.front();
420 d_preregisterQueue
.pop();
422 if (d_logicInfo
.isSharingEnabled() && preprocessed
.getKind() == kind::EQUAL
) {
423 // When sharing is enabled, we propagate from the shared terms manager also
424 d_sharedTerms
.addEqualityToPropagate(preprocessed
);
427 // the atom should not have free variables
428 Debug("theory") << "TheoryEngine::preRegister: " << preprocessed
430 Assert(!expr::hasFreeVar(preprocessed
));
431 // Pre-register the terms in the atom
432 Theory::Set theories
= NodeVisitor
<PreRegisterVisitor
>::run(d_preRegistrationVisitor
, preprocessed
);
433 theories
= Theory::setRemove(THEORY_BOOL
, theories
);
434 // Remove the top theory, if any more that means multiple theories were involved
435 bool multipleTheories
= Theory::setRemove(Theory::theoryOf(preprocessed
), theories
);
437 // These checks don't work with finite model finding, because it
438 // uses Rational constants to represent cardinality constraints,
439 // even though arithmetic isn't actually involved.
440 if(!options::finiteModelFind()) {
441 while((i
= Theory::setPop(theories
)) != THEORY_LAST
) {
442 if(!d_logicInfo
.isTheoryEnabled(i
)) {
443 LogicInfo newLogicInfo
= d_logicInfo
.getUnlockedCopy();
444 newLogicInfo
.enableTheory(i
);
447 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
448 << ", which doesn't include " << i
449 << ", but found a term in that theory." << endl
450 << "You might want to extend your logic to "
451 << newLogicInfo
.getLogicString() << endl
;
452 throw LogicException(ss
.str());
456 if (multipleTheories
) {
457 // Collect the shared terms if there are multiple theories
458 NodeVisitor
<SharedTermsVisitor
>::run(d_sharedTermsVisitor
, preprocessed
);
462 // Leaving pre-register
463 d_inPreregister
= false;
467 void TheoryEngine::printAssertions(const char* tag
) {
468 if (Trace
.isOn(tag
)) {
470 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
471 Theory
* theory
= d_theoryTable
[theoryId
];
472 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
473 Trace(tag
) << "--------------------------------------------" << endl
;
474 Trace(tag
) << "Assertions of " << theory
->getId() << ": " << endl
;
475 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(), it_end
= theory
->facts_end();
476 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
477 if ((*it
).isPreregistered
) {
478 Trace(tag
) << "[" << i
<< "]: ";
480 Trace(tag
) << "(" << i
<< "): ";
482 Trace(tag
) << (*it
).assertion
<< endl
;
485 if (d_logicInfo
.isSharingEnabled()) {
486 Trace(tag
) << "Shared terms of " << theory
->getId() << ": " << endl
;
487 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
488 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
489 Trace(tag
) << "[" << i
<< "]: " << (*it
) << endl
;
497 void TheoryEngine::dumpAssertions(const char* tag
) {
498 if (Dump
.isOn(tag
)) {
499 Dump(tag
) << CommentCommand("Starting completeness check");
500 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
501 Theory
* theory
= d_theoryTable
[theoryId
];
502 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
503 Dump(tag
) << CommentCommand("Completeness check");
504 Dump(tag
) << PushCommand();
506 // Dump the shared terms
507 if (d_logicInfo
.isSharingEnabled()) {
508 Dump(tag
) << CommentCommand("Shared terms");
509 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
510 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
513 Dump(tag
) << CommentCommand(ss
.str());
517 // Dump the assertions
518 Dump(tag
) << CommentCommand("Assertions");
519 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(), it_end
= theory
->facts_end();
520 for (; it
!= it_end
; ++ it
) {
522 Node assertionNode
= (*it
).assertion
;
523 // Purify all the terms
525 if ((*it
).isPreregistered
) {
526 Dump(tag
) << CommentCommand("Preregistered");
528 Dump(tag
) << CommentCommand("Shared assertion");
530 Dump(tag
) << AssertCommand(assertionNode
.toExpr());
532 Dump(tag
) << CheckSatCommand();
534 Dump(tag
) << PopCommand();
541 * Check all (currently-active) theories for conflicts.
542 * @param effort the effort level to use
544 void TheoryEngine::check(Theory::Effort effort
) {
547 // Reset the interrupt flag
548 d_interrupted
= false;
550 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
551 #undef CVC4_FOR_EACH_THEORY_STATEMENT
553 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
554 if (theory::TheoryTraits<THEORY>::hasCheck && d_logicInfo.isTheoryEnabled(THEORY)) { \
555 theoryOf(THEORY)->check(effort); \
556 if (d_inConflict) { \
557 Debug("conflict") << THEORY << " in conflict. " << std::endl; \
565 // Mark the output channel unused (if this is FULL_EFFORT, and nothing
566 // is done by the theories, no additional check will be needed)
567 d_outputChannelUsed
= false;
569 // Mark the lemmas flag (no lemmas added)
570 d_lemmasAdded
= false;
572 Debug("theory") << "TheoryEngine::check(" << effort
<< "): d_factsAsserted = " << (d_factsAsserted
? "true" : "false") << endl
;
574 // If in full effort, we have a fake new assertion just to jumpstart the checking
575 if (Theory::fullEffort(effort
)) {
576 d_factsAsserted
= true;
580 while (d_factsAsserted
&& !d_inConflict
&& !d_lemmasAdded
) {
582 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running check" << endl
;
584 Trace("theory::assertions") << endl
;
585 if (Trace
.isOn("theory::assertions")) {
586 printAssertions("theory::assertions");
589 if(Theory::fullEffort(effort
)) {
590 Trace("theory::assertions::fulleffort") << endl
;
591 if (Trace
.isOn("theory::assertions::fulleffort")) {
592 printAssertions("theory::assertions::fulleffort");
596 // Note that we've discharged all the facts
597 d_factsAsserted
= false;
600 CVC4_FOR_EACH_THEORY
;
602 if(Dump
.isOn("missed-t-conflicts")) {
603 Dump("missed-t-conflicts")
604 << CommentCommand("Completeness check for T-conflicts; expect sat")
605 << CheckSatCommand();
608 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running propagation after the initial check" << endl
;
610 // We are still satisfiable, propagate as much as possible
613 // We do combination if all has been processed and we are in fullcheck
614 if (Theory::fullEffort(effort
) && d_logicInfo
.isSharingEnabled() && !d_factsAsserted
&& !d_lemmasAdded
&& !d_inConflict
) {
615 // Do the combination
616 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running combination" << endl
;
618 if(d_logicInfo
.isQuantified()){
619 d_quantEngine
->notifyCombineTheories();
624 // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
625 if( Theory::fullEffort(effort
) && ! d_inConflict
&& ! needCheck() ) {
626 Trace("theory::assertions-model") << endl
;
627 if (Trace
.isOn("theory::assertions-model")) {
628 printAssertions("theory::assertions-model");
630 //checks for theories requiring the model go at last call
631 d_curr_model
->reset();
632 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
633 if( theoryId
!=THEORY_QUANTIFIERS
){
634 Theory
* theory
= d_theoryTable
[theoryId
];
635 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
636 if( theory
->needsCheckLastEffort() ){
637 if( !d_curr_model
->isBuilt() ){
638 if( !d_curr_model_builder
->buildModel(d_curr_model
) ){
642 theory
->check(Theory::EFFORT_LAST_CALL
);
649 if(d_logicInfo
.isQuantified()) {
650 // quantifiers engine must check at last call effort
651 d_quantEngine
->check(Theory::EFFORT_LAST_CALL
);
654 if (!d_inConflict
&& !needCheck())
656 // If d_eager_model_building is false, then we only mark that we
657 // are in "SAT mode". We build the model later only if the user asks
658 // for it via getBuiltModel.
660 if (d_eager_model_building
&& !d_curr_model
->isBuilt())
662 d_curr_model_builder
->buildModel(d_curr_model
);
667 Debug("theory") << "TheoryEngine::check(" << effort
<< "): done, we are " << (d_inConflict
? "unsat" : "sat") << (d_lemmasAdded
? " with new lemmas" : " with no new lemmas");
668 Debug("theory") << ", need check = " << (needCheck() ? "YES" : "NO") << endl
;
670 if( Theory::fullEffort(effort
) && !d_inConflict
&& !needCheck()) {
671 // case where we are about to answer SAT
672 if( d_masterEqualityEngine
!= NULL
){
673 AlwaysAssert(d_masterEqualityEngine
->consistent());
675 if (d_curr_model
->isBuilt())
677 // model construction should always succeed unless lemmas were added
678 AlwaysAssert(d_curr_model
->isBuiltSuccess());
679 if (options::produceModels())
681 // Do post-processing of model from the theories (used for THEORY_SEP
682 // to construct heap model)
683 postProcessModel(d_curr_model
);
684 // also call the model builder's post-process model
685 d_curr_model_builder
->postProcessModel(d_incomplete
.get(),
690 } catch(const theory::Interrupted
&) {
691 Trace("theory") << "TheoryEngine::check() => interrupted" << endl
;
693 // If fulleffort, check all theories
694 if(Dump
.isOn("theory::fullcheck") && Theory::fullEffort(effort
)) {
695 if (!d_inConflict
&& !needCheck()) {
696 dumpAssertions("theory::fullcheck");
701 void TheoryEngine::combineTheories() {
703 Trace("combineTheories") << "TheoryEngine::combineTheories()" << endl
;
705 TimerStat::CodeTimer
combineTheoriesTimer(d_combineTheoriesTime
);
707 // Care graph we'll be building
710 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
711 #undef CVC4_FOR_EACH_THEORY_STATEMENT
713 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
714 if (theory::TheoryTraits<THEORY>::isParametric && d_logicInfo.isTheoryEnabled(THEORY)) { \
715 theoryOf(THEORY)->getCareGraph(&careGraph); \
718 // Call on each parametric theory to give us its care graph
719 CVC4_FOR_EACH_THEORY
;
721 Trace("combineTheories") << "TheoryEngine::combineTheories(): care graph size = " << careGraph
.size() << endl
;
723 // Now add splitters for the ones we are interested in
724 CareGraph::const_iterator care_it
= careGraph
.begin();
725 CareGraph::const_iterator care_it_end
= careGraph
.end();
727 for (; care_it
!= care_it_end
; ++ care_it
) {
728 const CarePair
& carePair
= *care_it
;
730 Debug("combineTheories") << "TheoryEngine::combineTheories(): checking " << carePair
.a
<< " = " << carePair
.b
<< " from " << carePair
.theory
<< endl
;
732 Assert(d_sharedTerms
.isShared(carePair
.a
) || carePair
.a
.isConst());
733 Assert(d_sharedTerms
.isShared(carePair
.b
) || carePair
.b
.isConst());
735 // The equality in question (order for no repetition)
736 Node equality
= carePair
.a
.eqNode(carePair
.b
);
737 // EqualityStatus es = getEqualityStatus(carePair.a, carePair.b);
738 // Debug("combineTheories") << "TheoryEngine::combineTheories(): " <<
739 // (es == EQUALITY_TRUE_AND_PROPAGATED ? "EQUALITY_TRUE_AND_PROPAGATED" :
740 // es == EQUALITY_FALSE_AND_PROPAGATED ? "EQUALITY_FALSE_AND_PROPAGATED" :
741 // es == EQUALITY_TRUE ? "EQUALITY_TRUE" :
742 // es == EQUALITY_FALSE ? "EQUALITY_FALSE" :
743 // es == EQUALITY_TRUE_IN_MODEL ? "EQUALITY_TRUE_IN_MODEL" :
744 // es == EQUALITY_FALSE_IN_MODEL ? "EQUALITY_FALSE_IN_MODEL" :
745 // es == EQUALITY_UNKNOWN ? "EQUALITY_UNKNOWN" :
746 // "Unexpected case") << endl;
748 // We need to split on it
749 Debug("combineTheories") << "TheoryEngine::combineTheories(): requesting a split " << endl
;
751 lemma(equality
.orNode(equality
.notNode()), RULE_INVALID
, false, false, false, carePair
.theory
);
753 // This code is supposed to force preference to follow what the theory models already have
754 // but it doesn't seem to make a big difference - need to explore more -Clark
756 // if (es == EQUALITY_TRUE || es == EQUALITY_TRUE_IN_MODEL) {
757 Node e
= ensureLiteral(equality
);
758 d_propEngine
->requirePhase(e
, true);
760 // else if (es == EQUALITY_FALSE_IN_MODEL) {
761 // Node e = ensureLiteral(equality);
762 // d_propEngine->requirePhase(e, false);
768 void TheoryEngine::propagate(Theory::Effort effort
) {
769 // Reset the interrupt flag
770 d_interrupted
= false;
772 // Definition of the statement that is to be run by every theory
773 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
774 #undef CVC4_FOR_EACH_THEORY_STATEMENT
776 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
777 if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
778 theoryOf(THEORY)->propagate(effort); \
781 // Reset the interrupt flag
782 d_interrupted
= false;
784 // Propagate for each theory using the statement above
785 CVC4_FOR_EACH_THEORY
;
787 if(Dump
.isOn("missed-t-propagations")) {
788 for(unsigned i
= 0; i
< d_possiblePropagations
.size(); ++i
) {
789 Node atom
= d_possiblePropagations
[i
];
791 if(d_propEngine
->hasValue(atom
, value
)) {
794 // Doesn't have a value, check it (and the negation)
795 if(d_hasPropagated
.find(atom
) == d_hasPropagated
.end()) {
796 Dump("missed-t-propagations")
797 << CommentCommand("Completeness check for T-propagations; expect invalid")
798 << EchoCommand(atom
.toString())
799 << QueryCommand(atom
.toExpr())
800 << EchoCommand(atom
.notNode().toString())
801 << QueryCommand(atom
.notNode().toExpr());
807 Node
TheoryEngine::getNextDecisionRequest()
809 return d_decManager
->getNextDecisionRequest();
812 bool TheoryEngine::properConflict(TNode conflict
) const {
814 if (conflict
.getKind() == kind::AND
) {
815 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++ i
) {
816 if (! getPropEngine()->hasValue(conflict
[i
], value
)) {
817 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
818 << conflict
[i
] << endl
;
822 Debug("properConflict") << "Bad conflict is due to false atom: "
823 << conflict
[i
] << endl
;
826 if (conflict
[i
] != Rewriter::rewrite(conflict
[i
])) {
827 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
828 << conflict
[i
] << " vs " << Rewriter::rewrite(conflict
[i
]) << endl
;
833 if (! getPropEngine()->hasValue(conflict
, value
)) {
834 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
839 Debug("properConflict") << "Bad conflict is due to false atom: "
843 if (conflict
!= Rewriter::rewrite(conflict
)) {
844 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
845 << conflict
<< " vs " << Rewriter::rewrite(conflict
) << endl
;
852 bool TheoryEngine::properPropagation(TNode lit
) const {
853 if(!getPropEngine()->isSatLiteral(lit
)) {
857 return !getPropEngine()->hasValue(lit
, b
);
860 bool TheoryEngine::properExplanation(TNode node
, TNode expl
) const {
861 // Explanation must be either a conjunction of true literals that have true SAT values already
862 // or a singled literal that has a true SAT value already.
863 if (expl
.getKind() == kind::AND
) {
864 for (unsigned i
= 0; i
< expl
.getNumChildren(); ++ i
) {
866 if (!d_propEngine
->hasValue(expl
[i
], value
) || !value
) {
872 return d_propEngine
->hasValue(expl
, value
) && value
;
877 bool TheoryEngine::collectModelInfo(theory::TheoryModel
* m
)
879 //have shared term engine collectModelInfo
880 // d_sharedTerms.collectModelInfo( m );
881 // Consult each active theory to get all relevant information
882 // concerning the model.
883 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
884 if(d_logicInfo
.isTheoryEnabled(theoryId
)) {
885 Trace("model-builder") << " CollectModelInfo on theory: " << theoryId
<< endl
;
886 if (!d_theoryTable
[theoryId
]->collectModelInfo(m
))
892 Trace("model-builder") << " CollectModelInfo boolean variables" << std::endl
;
893 // Get the Boolean variables
894 vector
<TNode
> boolVars
;
895 d_propEngine
->getBooleanVariables(boolVars
);
896 vector
<TNode
>::iterator it
, iend
= boolVars
.end();
897 bool hasValue
, value
;
898 for (it
= boolVars
.begin(); it
!= iend
; ++it
) {
900 hasValue
= d_propEngine
->hasValue(var
, value
);
901 // TODO: Assert that hasValue is true?
903 Trace("model-builder-assertions")
904 << " has no value : " << var
<< std::endl
;
907 Trace("model-builder-assertions") << "(assert" << (value
? " " : " (not ") << var
<< (value
? ");" : "));") << endl
;
908 if (!m
->assertPredicate(var
, value
))
916 void TheoryEngine::postProcessModel( theory::TheoryModel
* m
){
917 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
918 if(d_logicInfo
.isTheoryEnabled(theoryId
)) {
919 Trace("model-builder-debug") << " PostProcessModel on theory: " << theoryId
<< endl
;
920 d_theoryTable
[theoryId
]->postProcessModel( m
);
925 TheoryModel
* TheoryEngine::getModel() {
929 TheoryModel
* TheoryEngine::getBuiltModel()
931 if (!d_curr_model
->isBuilt())
933 // If this method was called, we should be in SAT mode, and produceModels
935 AlwaysAssert(options::produceModels());
938 // not available, perhaps due to interuption.
941 // must build model at this point
942 d_curr_model_builder
->buildModel(d_curr_model
);
947 void TheoryEngine::getSynthSolutions(std::map
<Node
, Node
>& sol_map
)
951 d_quantEngine
->getSynthSolutions(sol_map
);
959 bool TheoryEngine::presolve() {
960 // Reset the interrupt flag
961 d_interrupted
= false;
963 // Reset the decision manager. This clears its decision strategies that are
964 // no longer valid in this user context.
965 d_decManager
->presolve();
968 // Definition of the statement that is to be run by every theory
969 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
970 #undef CVC4_FOR_EACH_THEORY_STATEMENT
972 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
973 if (theory::TheoryTraits<THEORY>::hasPresolve) { \
974 theoryOf(THEORY)->presolve(); \
980 // Presolve for each theory using the statement above
981 CVC4_FOR_EACH_THEORY
;
982 } catch(const theory::Interrupted
&) {
983 Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl
;
985 // return whether we have a conflict
987 }/* TheoryEngine::presolve() */
989 void TheoryEngine::postsolve() {
990 // no longer in SAT mode
992 // Reset the interrupt flag
993 d_interrupted
= false;
994 bool CVC4_UNUSED wasInConflict
= d_inConflict
;
997 // Definition of the statement that is to be run by every theory
998 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
999 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1001 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1002 if (theory::TheoryTraits<THEORY>::hasPostsolve) \
1004 theoryOf(THEORY)->postsolve(); \
1005 Assert(!d_inConflict || wasInConflict) \
1006 << "conflict raised during postsolve()"; \
1009 // Postsolve for each theory using the statement above
1010 CVC4_FOR_EACH_THEORY
;
1011 } catch(const theory::Interrupted
&) {
1012 Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl
;
1014 }/* TheoryEngine::postsolve() */
1017 void TheoryEngine::notifyRestart() {
1018 // Reset the interrupt flag
1019 d_interrupted
= false;
1021 // Definition of the statement that is to be run by every theory
1022 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
1023 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1025 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1026 if (theory::TheoryTraits<THEORY>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
1027 theoryOf(THEORY)->notifyRestart(); \
1030 // notify each theory using the statement above
1031 CVC4_FOR_EACH_THEORY
;
1034 void TheoryEngine::ppStaticLearn(TNode in
, NodeBuilder
<>& learned
) {
1035 // Reset the interrupt flag
1036 d_interrupted
= false;
1038 // Definition of the statement that is to be run by every theory
1039 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
1040 #undef CVC4_FOR_EACH_THEORY_STATEMENT
1042 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
1043 if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) { \
1044 theoryOf(THEORY)->ppStaticLearn(in, learned); \
1047 // static learning for each theory using the statement above
1048 CVC4_FOR_EACH_THEORY
;
1051 void TheoryEngine::shutdown() {
1052 // Set this first; if a Theory shutdown() throws an exception,
1053 // at least the destruction of the TheoryEngine won't confound
1055 d_hasShutDown
= true;
1057 // Shutdown all the theories
1058 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
1059 if(d_theoryTable
[theoryId
]) {
1060 theoryOf(theoryId
)->shutdown();
1067 theory::Theory::PPAssertStatus
TheoryEngine::solve(TNode literal
, SubstitutionMap
& substitutionOut
) {
1068 // Reset the interrupt flag
1069 d_interrupted
= false;
1071 TNode atom
= literal
.getKind() == kind::NOT
? literal
[0] : literal
;
1072 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< "): solving with " << theoryOf(atom
)->getId() << endl
;
1074 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(atom
)) &&
1075 Theory::theoryOf(atom
) != THEORY_SAT_SOLVER
) {
1077 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1078 << ", which doesn't include " << Theory::theoryOf(atom
)
1079 << ", but got a preprocessing-time fact for that theory." << endl
1080 << "The fact:" << endl
1082 throw LogicException(ss
.str());
1085 Theory::PPAssertStatus solveStatus
= theoryOf(atom
)->ppAssert(literal
, substitutionOut
);
1086 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< ") => " << solveStatus
<< endl
;
1090 // Recursively traverse a term and call the theory rewriter on its sub-terms
1091 Node
TheoryEngine::ppTheoryRewrite(TNode term
) {
1092 NodeMap::iterator find
= d_ppCache
.find(term
);
1093 if (find
!= d_ppCache
.end()) {
1094 return (*find
).second
;
1096 unsigned nc
= term
.getNumChildren();
1098 return theoryOf(term
)->ppRewrite(term
);
1100 Trace("theory-pp") << "ppTheoryRewrite { " << term
<< endl
;
1103 // do not rewrite inside quantifiers
1104 if (term
.isClosure())
1106 newTerm
= Rewriter::rewrite(term
);
1110 NodeBuilder
<> newNode(term
.getKind());
1111 if (term
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
1112 newNode
<< term
.getOperator();
1115 for (i
= 0; i
< nc
; ++i
) {
1116 newNode
<< ppTheoryRewrite(term
[i
]);
1118 newTerm
= Rewriter::rewrite(Node(newNode
));
1120 Node newTerm2
= theoryOf(newTerm
)->ppRewrite(newTerm
);
1121 if (newTerm
!= newTerm2
) {
1122 newTerm
= ppTheoryRewrite(Rewriter::rewrite(newTerm2
));
1124 d_ppCache
[term
] = newTerm
;
1125 Trace("theory-pp")<< "ppTheoryRewrite returning " << newTerm
<< "}" << endl
;
1130 void TheoryEngine::preprocessStart()
1136 struct preprocess_stack_element
{
1138 bool children_added
;
1139 preprocess_stack_element(TNode node
)
1140 : node(node
), children_added(false) {}
1141 };/* struct preprocess_stack_element */
1144 Node
TheoryEngine::preprocess(TNode assertion
) {
1146 Trace("theory::preprocess") << "TheoryEngine::preprocess(" << assertion
<< ")" << endl
;
1149 // Do a topological sort of the subexpressions and substitute them
1150 vector
<preprocess_stack_element
> toVisit
;
1151 toVisit
.push_back(assertion
);
1153 while (!toVisit
.empty())
1155 // The current node we are processing
1156 preprocess_stack_element
& stackHead
= toVisit
.back();
1157 TNode current
= stackHead
.node
;
1159 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion
<< "): processing " << current
<< endl
;
1161 // If node already in the cache we're done, pop from the stack
1162 NodeMap::iterator find
= d_ppCache
.find(current
);
1163 if (find
!= d_ppCache
.end()) {
1168 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(current
)) &&
1169 Theory::theoryOf(current
) != THEORY_SAT_SOLVER
) {
1171 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1172 << ", which doesn't include " << Theory::theoryOf(current
)
1173 << ", but got a preprocessing-time fact for that theory." << endl
1174 << "The fact:" << endl
1176 throw LogicException(ss
.str());
1179 // If this is an atom, we preprocess its terms with the theory ppRewriter
1180 if (Theory::theoryOf(current
) != THEORY_BOOL
) {
1181 Node ppRewritten
= ppTheoryRewrite(current
);
1182 d_ppCache
[current
] = ppRewritten
;
1183 Assert(Rewriter::rewrite(d_ppCache
[current
]) == d_ppCache
[current
]);
1187 // Not yet substituted, so process
1188 if (stackHead
.children_added
) {
1189 // Children have been processed, so substitute
1190 NodeBuilder
<> builder(current
.getKind());
1191 if (current
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
1192 builder
<< current
.getOperator();
1194 for (unsigned i
= 0; i
< current
.getNumChildren(); ++ i
) {
1195 Assert(d_ppCache
.find(current
[i
]) != d_ppCache
.end());
1196 builder
<< d_ppCache
[current
[i
]];
1198 // Mark the substitution and continue
1199 Node result
= builder
;
1200 if (result
!= current
) {
1201 result
= Rewriter::rewrite(result
);
1203 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion
<< "): setting " << current
<< " -> " << result
<< endl
;
1204 d_ppCache
[current
] = result
;
1207 // Mark that we have added the children if any
1208 if (current
.getNumChildren() > 0) {
1209 stackHead
.children_added
= true;
1210 // We need to add the children
1211 for(TNode::iterator child_it
= current
.begin(); child_it
!= current
.end(); ++ child_it
) {
1212 TNode childNode
= *child_it
;
1213 NodeMap::iterator childFind
= d_ppCache
.find(childNode
);
1214 if (childFind
== d_ppCache
.end()) {
1215 toVisit
.push_back(childNode
);
1219 // No children, so we're done
1220 Debug("substitution::internal") << "SubstitutionMap::internalSubstitute(" << assertion
<< "): setting " << current
<< " -> " << current
<< endl
;
1221 d_ppCache
[current
] = current
;
1227 // Return the substituted version
1228 return d_ppCache
[assertion
];
1231 void TheoryEngine::notifyPreprocessedAssertions(
1232 const std::vector
<Node
>& assertions
) {
1233 // call all the theories
1234 for (TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
;
1236 if (d_theoryTable
[theoryId
]) {
1237 theoryOf(theoryId
)->ppNotifyAssertions(assertions
);
1242 bool TheoryEngine::markPropagation(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
1244 // What and where we are asserting
1245 NodeTheoryPair
toAssert(assertion
, toTheoryId
, d_propagationMapTimestamp
);
1246 // What and where it came from
1247 NodeTheoryPair
toExplain(originalAssertion
, fromTheoryId
, d_propagationMapTimestamp
);
1249 // See if the theory already got this literal
1250 PropagationMap::const_iterator find
= d_propagationMap
.find(toAssert
);
1251 if (find
!= d_propagationMap
.end()) {
1252 // The theory already knows this
1253 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl
;
1257 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp
<< "] " << assertion
<< ", " << toTheoryId
<< " from " << originalAssertion
<< ", " << fromTheoryId
<< endl
;
1259 // Mark the propagation
1260 d_propagationMap
[toAssert
] = toExplain
;
1261 d_propagationMapTimestamp
= d_propagationMapTimestamp
+ 1;
1267 void TheoryEngine::assertToTheory(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
1269 Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << originalAssertion
<< "," << toTheoryId
<< ", " << fromTheoryId
<< ")" << endl
;
1271 Assert(toTheoryId
!= fromTheoryId
);
1272 if(toTheoryId
!= THEORY_SAT_SOLVER
&&
1273 ! d_logicInfo
.isTheoryEnabled(toTheoryId
)) {
1275 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
1276 << ", which doesn't include " << toTheoryId
1277 << ", but got an asserted fact to that theory." << endl
1278 << "The fact:" << endl
1280 throw LogicException(ss
.str());
1287 // If sharing is disabled, things are easy
1288 if (!d_logicInfo
.isSharingEnabled()) {
1289 Assert(assertion
== originalAssertion
);
1290 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
1291 // Send to the apropriate theory
1292 theory::Theory
* toTheory
= theoryOf(toTheoryId
);
1293 // We assert it, and we know it's preregistereed
1294 toTheory
->assertFact(assertion
, true);
1295 // Mark that we have more information
1296 d_factsAsserted
= true;
1298 Assert(toTheoryId
== THEORY_SAT_SOLVER
);
1299 // Check for propositional conflict
1301 if (d_propEngine
->hasValue(assertion
, value
)) {
1303 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (no sharing)" << endl
;
1304 d_inConflict
= true;
1309 d_propagatedLiterals
.push_back(assertion
);
1314 // Polarity of the assertion
1315 bool polarity
= assertion
.getKind() != kind::NOT
;
1317 // Atom of the assertion
1318 TNode atom
= polarity
? assertion
: assertion
[0];
1320 // If sending to the shared terms database, it's also simple
1321 if (toTheoryId
== THEORY_BUILTIN
) {
1322 Assert(atom
.getKind() == kind::EQUAL
)
1323 << "atom should be an EQUALity, not `" << atom
<< "'";
1324 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1325 d_sharedTerms
.assertEquality(atom
, polarity
, assertion
);
1330 // Things from the SAT solver are already normalized, so they go
1331 // directly to the apropriate theory
1332 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
1333 // We know that this is normalized, so just send it off to the theory
1334 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1335 // Is it preregistered
1336 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1338 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1339 // Mark that we have more information
1340 d_factsAsserted
= true;
1345 // Propagations to the SAT solver are just enqueued for pickup by
1346 // the SAT solver later
1347 if (toTheoryId
== THEORY_SAT_SOLVER
) {
1348 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1349 // Enqueue for propagation to the SAT solver
1350 d_propagatedLiterals
.push_back(assertion
);
1351 // Check for propositional conflicts
1353 if (d_propEngine
->hasValue(assertion
, value
) && !value
) {
1354 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (sharing)" << endl
;
1355 d_inConflict
= true;
1361 Assert(atom
.getKind() == kind::EQUAL
);
1364 Node normalizedLiteral
= Rewriter::rewrite(assertion
);
1366 // See if it rewrites false directly -> conflict
1367 if (normalizedLiteral
.isConst()) {
1368 if (!normalizedLiteral
.getConst
<bool>()) {
1369 // Mark the propagation for explanations
1370 if (markPropagation(normalizedLiteral
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1371 // Get the explanation (conflict will figure out where it came from)
1372 conflict(normalizedLiteral
, toTheoryId
);
1380 // Try and assert (note that we assert the non-normalized one)
1381 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1382 // Check if has been pre-registered with the theory
1383 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1385 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1386 d_factsAsserted
= true;
1392 void TheoryEngine::assertFact(TNode literal
)
1394 Trace("theory") << "TheoryEngine::assertFact(" << literal
<< ")" << endl
;
1398 // If we're in conflict, nothing to do
1404 bool polarity
= literal
.getKind() != kind::NOT
;
1405 TNode atom
= polarity
? literal
: literal
[0];
1407 if (d_logicInfo
.isSharingEnabled()) {
1409 // If any shared terms, it's time to do sharing work
1410 if (d_sharedTerms
.hasSharedTerms(atom
)) {
1411 // Notify the theories the shared terms
1412 SharedTermsDatabase::shared_terms_iterator it
= d_sharedTerms
.begin(atom
);
1413 SharedTermsDatabase::shared_terms_iterator it_end
= d_sharedTerms
.end(atom
);
1414 for (; it
!= it_end
; ++ it
) {
1416 Theory::Set theories
= d_sharedTerms
.getTheoriesToNotify(atom
, term
);
1417 for (TheoryId id
= THEORY_FIRST
; id
!= THEORY_LAST
; ++ id
) {
1418 if (Theory::setContains(id
, theories
)) {
1419 theoryOf(id
)->addSharedTermInternal(term
);
1422 d_sharedTerms
.markNotified(term
, theories
);
1426 // If it's an equality, assert it to the shared term manager, even though the terms are not
1427 // yet shared. As the terms become shared later, the shared terms manager will then add them
1428 // to the assert the equality to the interested theories
1429 if (atom
.getKind() == kind::EQUAL
) {
1430 // Assert it to the the owning theory
1431 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1432 // Shared terms manager will assert to interested theories directly, as the terms become shared
1433 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ THEORY_SAT_SOLVER
);
1435 // Now, let's check for any atom triggers from lemmas
1436 AtomRequests::atom_iterator it
= d_atomRequests
.getAtomIterator(atom
);
1437 while (!it
.done()) {
1438 const AtomRequests::Request
& request
= it
.get();
1439 Node toAssert
= polarity
? (Node
) request
.atom
: request
.atom
.notNode();
1440 Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal
<< "): sending requested " << toAssert
<< endl
;
1441 assertToTheory(toAssert
, literal
, request
.toTheory
, THEORY_SAT_SOLVER
);
1446 // Not an equality, just assert to the appropriate theory
1447 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1450 // Assert the fact to the appropriate theory directly
1451 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1455 bool TheoryEngine::propagate(TNode literal
, theory::TheoryId theory
) {
1457 Debug("theory::propagate") << "TheoryEngine::propagate(" << literal
<< ", " << theory
<< ")" << endl
;
1461 if(Dump
.isOn("t-propagations")) {
1462 Dump("t-propagations") << CommentCommand("negation of theory propagation: expect valid")
1463 << QueryCommand(literal
.toExpr());
1465 if(Dump
.isOn("missed-t-propagations")) {
1466 d_hasPropagated
.insert(literal
);
1470 bool polarity
= literal
.getKind() != kind::NOT
;
1471 TNode atom
= polarity
? literal
: literal
[0];
1473 if (d_logicInfo
.isSharingEnabled() && atom
.getKind() == kind::EQUAL
) {
1474 if (d_propEngine
->isSatLiteral(literal
)) {
1475 // We propagate SAT literals to SAT
1476 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1478 if (theory
!= THEORY_BUILTIN
) {
1479 // Assert to the shared terms database
1480 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ theory
);
1483 // We could be propagating a unit-clause lemma. In this case, we need to provide a
1485 // TODO: Consider putting this someplace else? This is the only refence to the proof
1486 // manager in this class.
1489 LemmaProofRecipe proofRecipe
;
1490 proofRecipe
.addBaseAssertion(literal
);
1493 LemmaProofRecipe::ProofStep
proofStep(theory
, emptyNode
);
1494 proofStep
.addAssertion(literal
);
1495 proofRecipe
.addStep(proofStep
);
1497 ProofManager::getCnfProof()->setProofRecipe(&proofRecipe
);
1500 // Just send off to the SAT solver
1501 Assert(d_propEngine
->isSatLiteral(literal
));
1502 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1505 return !d_inConflict
;
1508 const LogicInfo
& TheoryEngine::getLogicInfo() const { return d_logicInfo
; }
1510 theory::EqualityStatus
TheoryEngine::getEqualityStatus(TNode a
, TNode b
) {
1511 Assert(a
.getType().isComparableTo(b
.getType()));
1512 if (d_sharedTerms
.isShared(a
) && d_sharedTerms
.isShared(b
)) {
1513 if (d_sharedTerms
.areEqual(a
,b
)) {
1514 return EQUALITY_TRUE_AND_PROPAGATED
;
1516 else if (d_sharedTerms
.areDisequal(a
,b
)) {
1517 return EQUALITY_FALSE_AND_PROPAGATED
;
1520 return theoryOf(Theory::theoryOf(a
.getType()))->getEqualityStatus(a
, b
);
1523 Node
TheoryEngine::getModelValue(TNode var
) {
1526 // the model value of a constant must be itself
1529 Assert(d_sharedTerms
.isShared(var
));
1530 return theoryOf(Theory::theoryOf(var
.getType()))->getModelValue(var
);
1534 Node
TheoryEngine::ensureLiteral(TNode n
) {
1535 Debug("ensureLiteral") << "rewriting: " << n
<< std::endl
;
1536 Node rewritten
= Rewriter::rewrite(n
);
1537 Debug("ensureLiteral") << " got: " << rewritten
<< std::endl
;
1538 Node preprocessed
= preprocess(rewritten
);
1539 Debug("ensureLiteral") << "preprocessed: " << preprocessed
<< std::endl
;
1540 d_propEngine
->ensureLiteral(preprocessed
);
1541 return preprocessed
;
1545 void TheoryEngine::printInstantiations( std::ostream
& out
) {
1546 if( d_quantEngine
){
1547 d_quantEngine
->printInstantiations( out
);
1549 out
<< "Internal error : instantiations not available when quantifiers are not present." << std::endl
;
1554 void TheoryEngine::printSynthSolution( std::ostream
& out
) {
1555 if( d_quantEngine
){
1556 d_quantEngine
->printSynthSolution( out
);
1558 out
<< "Internal error : synth solution not available when quantifiers are not present." << std::endl
;
1563 void TheoryEngine::getInstantiatedQuantifiedFormulas( std::vector
< Node
>& qs
) {
1564 if( d_quantEngine
){
1565 d_quantEngine
->getInstantiatedQuantifiedFormulas( qs
);
1571 void TheoryEngine::getInstantiations( Node q
, std::vector
< Node
>& insts
) {
1572 if( d_quantEngine
){
1573 d_quantEngine
->getInstantiations( q
, insts
);
1579 void TheoryEngine::getInstantiationTermVectors( Node q
, std::vector
< std::vector
< Node
> >& tvecs
) {
1580 if( d_quantEngine
){
1581 d_quantEngine
->getInstantiationTermVectors( q
, tvecs
);
1587 void TheoryEngine::getInstantiations( std::map
< Node
, std::vector
< Node
> >& insts
) {
1588 if( d_quantEngine
){
1589 d_quantEngine
->getInstantiations( insts
);
1595 void TheoryEngine::getInstantiationTermVectors( std::map
< Node
, std::vector
< std::vector
< Node
> > >& insts
) {
1596 if( d_quantEngine
){
1597 d_quantEngine
->getInstantiationTermVectors( insts
);
1603 Node
TheoryEngine::getInstantiatedConjunction( Node q
) {
1604 if( d_quantEngine
){
1605 return d_quantEngine
->getInstantiatedConjunction( q
);
1608 return Node::null();
1613 static Node
mkExplanation(const std::vector
<NodeTheoryPair
>& explanation
) {
1615 std::set
<TNode
> all
;
1616 for (unsigned i
= 0; i
< explanation
.size(); ++ i
) {
1617 Assert(explanation
[i
].theory
== THEORY_SAT_SOLVER
);
1618 all
.insert(explanation
[i
].node
);
1621 if (all
.size() == 0) {
1622 // Normalize to true
1623 return NodeManager::currentNM()->mkConst
<bool>(true);
1626 if (all
.size() == 1) {
1627 // All the same, or just one
1628 return explanation
[0].node
;
1631 NodeBuilder
<> conjunction(kind::AND
);
1632 std::set
<TNode
>::const_iterator it
= all
.begin();
1633 std::set
<TNode
>::const_iterator it_end
= all
.end();
1634 while (it
!= it_end
) {
1642 Node
TheoryEngine::getExplanationAndRecipe(TNode node
, LemmaProofRecipe
* proofRecipe
) {
1643 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< "): current propagation index = " << d_propagationMapTimestamp
<< endl
;
1645 bool polarity
= node
.getKind() != kind::NOT
;
1646 TNode atom
= polarity
? node
: node
[0];
1648 // If we're not in shared mode, explanations are simple
1649 if (!d_logicInfo
.isSharingEnabled()) {
1650 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing is NOT enabled. "
1651 << " Responsible theory is: "
1652 << theoryOf(atom
)->getId() << std::endl
;
1654 Node explanation
= theoryOf(atom
)->explain(node
);
1655 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => " << explanation
<< endl
;
1659 LemmaProofRecipe::ProofStep
proofStep(theoryOf(atom
)->getId(), emptyNode
);
1660 proofStep
.addAssertion(node
);
1661 proofRecipe
->addBaseAssertion(node
);
1663 if (explanation
.getKind() == kind::AND
) {
1664 // If the explanation is a conjunction, the recipe for the corresponding lemma is
1665 // the negation of its conjuncts.
1666 Node flat
= flattenAnd(explanation
);
1667 for (unsigned i
= 0; i
< flat
.getNumChildren(); ++i
) {
1668 if (flat
[i
].isConst() && flat
[i
].getConst
<bool>()) {
1672 if (flat
[i
].getKind() == kind::NOT
&&
1673 flat
[i
][0].isConst() && !flat
[i
][0].getConst
<bool>()) {
1677 Debug("theory::explain") << "TheoryEngine::getExplanationAndRecipe: adding recipe assertion: "
1678 << flat
[i
].negate() << std::endl
;
1679 proofStep
.addAssertion(flat
[i
].negate());
1680 proofRecipe
->addBaseAssertion(flat
[i
].negate());
1683 // The recipe for proving it is by negating it. "True" is not an acceptable reason.
1684 if (!((explanation
.isConst() && explanation
.getConst
<bool>()) ||
1685 (explanation
.getKind() == kind::NOT
&&
1686 explanation
[0].isConst() && !explanation
[0].getConst
<bool>()))) {
1687 proofStep
.addAssertion(explanation
.negate());
1688 proofRecipe
->addBaseAssertion(explanation
.negate());
1692 proofRecipe
->addStep(proofStep
);
1699 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing IS enabled" << std::endl
;
1701 // Initial thing to explain
1702 NodeTheoryPair
toExplain(node
, THEORY_SAT_SOLVER
, d_propagationMapTimestamp
);
1703 Assert(d_propagationMap
.find(toExplain
) != d_propagationMap
.end());
1705 NodeTheoryPair nodeExplainerPair
= d_propagationMap
[toExplain
];
1706 Debug("theory::explain") << "TheoryEngine::getExplanation: explainer for node "
1707 << nodeExplainerPair
.node
1708 << " is theory: " << nodeExplainerPair
.theory
<< std::endl
;
1709 TheoryId explainer
= nodeExplainerPair
.theory
;
1711 // Create the workplace for explanations
1712 std::vector
<NodeTheoryPair
> explanationVector
;
1713 explanationVector
.push_back(d_propagationMap
[toExplain
]);
1714 // Process the explanation
1717 LemmaProofRecipe::ProofStep
proofStep(explainer
, emptyNode
);
1718 proofStep
.addAssertion(node
);
1719 proofRecipe
->addStep(proofStep
);
1720 proofRecipe
->addBaseAssertion(node
);
1723 getExplanation(explanationVector
, proofRecipe
);
1724 Node explanation
= mkExplanation(explanationVector
);
1726 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => " << explanation
<< endl
;
1731 Node
TheoryEngine::getExplanation(TNode node
) {
1732 LemmaProofRecipe
*dontCareRecipe
= NULL
;
1733 return getExplanationAndRecipe(node
, dontCareRecipe
);
1736 struct AtomsCollect
{
1738 std::vector
<TNode
> d_atoms
;
1739 std::unordered_set
<TNode
, TNodeHashFunction
> d_visited
;
1743 typedef void return_type
;
1745 bool alreadyVisited(TNode current
, TNode parent
) {
1746 // Check if already visited
1747 if (d_visited
.find(current
) != d_visited
.end()) return true;
1748 // Don't visit non-boolean
1749 if (!current
.getType().isBoolean()) return true;
1754 void visit(TNode current
, TNode parent
) {
1755 if (Theory::theoryOf(current
) != theory::THEORY_BOOL
) {
1756 d_atoms
.push_back(current
);
1758 d_visited
.insert(current
);
1761 void start(TNode node
) {}
1762 void done(TNode node
) {}
1764 std::vector
<TNode
> getAtoms() const {
1769 void TheoryEngine::ensureLemmaAtoms(const std::vector
<TNode
>& atoms
, theory::TheoryId atomsTo
) {
1770 for (unsigned i
= 0; i
< atoms
.size(); ++ i
) {
1772 // Non-equality atoms are either owned by theory or they don't make sense
1773 if (atoms
[i
].getKind() != kind::EQUAL
) {
1779 // Simple normalization to not repeat stuff
1780 if (eq
[0] > eq
[1]) {
1781 eq
= eq
[1].eqNode(eq
[0]);
1784 // Rewrite the equality
1785 Node eqNormalized
= Rewriter::rewrite(atoms
[i
]);
1787 Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq
<< " with nf " << eqNormalized
<< endl
;
1789 // If the equality is a boolean constant, we send immediately
1790 if (eqNormalized
.isConst()) {
1791 if (eqNormalized
.getConst
<bool>()) {
1792 assertToTheory(eq
, eqNormalized
, /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1794 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1797 }else if( eqNormalized
.getKind() != kind::EQUAL
){
1798 Assert(eqNormalized
.getKind() == kind::BOOLEAN_TERM_VARIABLE
1799 || (eqNormalized
.getKind() == kind::NOT
1800 && eqNormalized
[0].getKind() == kind::BOOLEAN_TERM_VARIABLE
));
1801 // this happens for Boolean term equalities V = true that are rewritten to V, we should skip
1802 // TODO : revisit this
1806 // If the normalization did the just flips, keep the flip
1807 if (eqNormalized
[0] == eq
[1] && eqNormalized
[1] == eq
[0]) {
1811 // Check if the equality is already known by the sat solver
1812 if (d_propEngine
->isSatLiteral(eqNormalized
)) {
1814 if (d_propEngine
->hasValue(eqNormalized
, value
)) {
1816 assertToTheory(eq
, eqNormalized
, atomsTo
, theory::THEORY_SAT_SOLVER
);
1819 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), atomsTo
, theory::THEORY_SAT_SOLVER
);
1825 // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1826 // then we must figure it out
1827 if (eqNormalized
!= eq
|| Theory::theoryOf(eq
) != atomsTo
) {
1828 // If you get eqNormalized, send atoms[i] to atomsTo
1829 d_atomRequests
.add(eqNormalized
, eq
, atomsTo
);
1834 theory::LemmaStatus
TheoryEngine::lemma(TNode node
,
1839 theory::TheoryId atomsTo
) {
1840 // For resource-limiting (also does a time check).
1843 // Do we need to check atoms
1844 if (atomsTo
!= theory::THEORY_LAST
) {
1845 Debug("theory::atoms") << "TheoryEngine::lemma(" << node
<< ", " << atomsTo
<< ")" << endl
;
1846 AtomsCollect collectAtoms
;
1847 NodeVisitor
<AtomsCollect
>::run(collectAtoms
, node
);
1848 ensureLemmaAtoms(collectAtoms
.getAtoms(), atomsTo
);
1851 if(Dump
.isOn("t-lemmas")) {
1856 Dump("t-lemmas") << CommentCommand("theory lemma: expect valid")
1857 << QueryCommand(n
.toExpr());
1860 // Share with other portfolio threads
1861 if(d_channels
->getLemmaOutputChannel() != NULL
) {
1862 d_channels
->getLemmaOutputChannel()->notifyNewLemma(node
.toExpr());
1865 AssertionPipeline additionalLemmas
;
1867 // Run theory preprocessing, maybe
1868 Node ppNode
= preprocess
? this->preprocess(node
) : Node(node
);
1871 Debug("ite") << "Remove ITE from " << ppNode
<< std::endl
;
1872 additionalLemmas
.push_back(ppNode
);
1873 additionalLemmas
.updateRealAssertionsEnd();
1874 d_tform_remover
.run(additionalLemmas
.ref(),
1875 additionalLemmas
.getIteSkolemMap());
1876 Debug("ite") << "..done " << additionalLemmas
[0] << std::endl
;
1877 additionalLemmas
.replace(0, theory::Rewriter::rewrite(additionalLemmas
[0]));
1879 if(Debug
.isOn("lemma-ites")) {
1880 Debug("lemma-ites") << "removed ITEs from lemma: " << ppNode
<< endl
;
1881 Debug("lemma-ites") << " + now have the following "
1882 << additionalLemmas
.size() << " lemma(s):" << endl
;
1883 for(std::vector
<Node
>::const_iterator i
= additionalLemmas
.begin();
1884 i
!= additionalLemmas
.end();
1886 Debug("lemma-ites") << " + " << *i
<< endl
;
1888 Debug("lemma-ites") << endl
;
1891 // assert to prop engine
1892 d_propEngine
->assertLemma(additionalLemmas
[0], negated
, removable
, rule
, node
);
1893 for (unsigned i
= 1; i
< additionalLemmas
.size(); ++ i
) {
1894 additionalLemmas
.replace(i
, theory::Rewriter::rewrite(additionalLemmas
[i
]));
1895 d_propEngine
->assertLemma(additionalLemmas
[i
], false, removable
, rule
, node
);
1898 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1900 additionalLemmas
.replace(0, additionalLemmas
[0].notNode());
1904 // assert to decision engine
1906 d_decisionEngine
->addAssertions(additionalLemmas
);
1909 // Mark that we added some lemmas
1910 d_lemmasAdded
= true;
1912 // Lemma analysis isn't online yet; this lemma may only live for this
1914 return theory::LemmaStatus(additionalLemmas
[0], d_userContext
->getLevel());
1917 void TheoryEngine::conflict(TNode conflict
, TheoryId theoryId
) {
1919 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< ")" << endl
;
1921 // Mark that we are in conflict
1922 d_inConflict
= true;
1924 if(Dump
.isOn("t-conflicts")) {
1925 Dump("t-conflicts") << CommentCommand("theory conflict: expect unsat")
1926 << CheckSatCommand(conflict
.toExpr());
1929 LemmaProofRecipe
* proofRecipe
= NULL
;
1931 proofRecipe
= new LemmaProofRecipe
;
1933 LemmaProofRecipe::ProofStep
proofStep(theoryId
, emptyNode
);
1935 if (conflict
.getKind() == kind::AND
) {
1936 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++i
) {
1937 proofStep
.addAssertion(conflict
[i
].negate());
1940 proofStep
.addAssertion(conflict
.negate());
1943 proofRecipe
->addStep(proofStep
);
1946 // In the multiple-theories case, we need to reconstruct the conflict
1947 if (d_logicInfo
.isSharingEnabled()) {
1948 // Create the workplace for explanations
1949 std::vector
<NodeTheoryPair
> explanationVector
;
1950 explanationVector
.push_back(NodeTheoryPair(conflict
, theoryId
, d_propagationMapTimestamp
));
1952 // Process the explanation
1953 getExplanation(explanationVector
, proofRecipe
);
1954 PROOF(ProofManager::getCnfProof()->setProofRecipe(proofRecipe
));
1955 Node fullConflict
= mkExplanation(explanationVector
);
1956 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< "): full = " << fullConflict
<< endl
;
1957 Assert(properConflict(fullConflict
));
1958 lemma(fullConflict
, RULE_CONFLICT
, true, true, false, THEORY_LAST
);
1961 // When only one theory, the conflict should need no processing
1962 Assert(properConflict(conflict
));
1964 if (conflict
.getKind() == kind::AND
) {
1965 // If the conflict is a conjunction, the corresponding lemma is derived by negating
1967 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++i
) {
1968 if (conflict
[i
].isConst() && conflict
[i
].getConst
<bool>()) {
1972 if (conflict
[i
].getKind() == kind::NOT
&&
1973 conflict
[i
][0].isConst() && !conflict
[i
][0].getConst
<bool>()) {
1977 proofRecipe
->getStep(0)->addAssertion(conflict
[i
].negate());
1978 proofRecipe
->addBaseAssertion(conflict
[i
].negate());
1981 proofRecipe
->getStep(0)->addAssertion(conflict
.negate());
1982 proofRecipe
->addBaseAssertion(conflict
.negate());
1985 ProofManager::getCnfProof()->setProofRecipe(proofRecipe
);
1988 lemma(conflict
, RULE_CONFLICT
, true, true, false, THEORY_LAST
);
1997 void TheoryEngine::staticInitializeBVOptions(
1998 const std::vector
<Node
>& assertions
)
2000 bool useSlicer
= true;
2001 if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_ON
)
2003 if (!d_logicInfo
.isPure(theory::THEORY_BV
) || d_logicInfo
.isQuantified())
2004 throw ModalException(
2005 "Slicer currently only supports pure QF_BV formulas. Use "
2006 "--bv-eq-slicer=off");
2007 if (options::incrementalSolving())
2008 throw ModalException(
2009 "Slicer does not currently support incremental mode. Use "
2010 "--bv-eq-slicer=off");
2011 if (options::produceModels())
2012 throw ModalException(
2013 "Slicer does not currently support model generation. Use "
2014 "--bv-eq-slicer=off");
2016 else if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_OFF
)
2020 else if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_AUTO
)
2022 if ((!d_logicInfo
.isPure(theory::THEORY_BV
) || d_logicInfo
.isQuantified())
2023 || options::incrementalSolving()
2024 || options::produceModels())
2027 bv::utils::TNodeBoolMap cache
;
2028 for (unsigned i
= 0; i
< assertions
.size(); ++i
)
2030 useSlicer
= useSlicer
&& bv::utils::isCoreTerm(assertions
[i
], cache
);
2036 bv::TheoryBV
* bv_theory
= (bv::TheoryBV
*)d_theoryTable
[THEORY_BV
];
2037 bv_theory
->enableCoreTheorySlicer();
2041 void TheoryEngine::getExplanation(std::vector
<NodeTheoryPair
>& explanationVector
, LemmaProofRecipe
* proofRecipe
) {
2042 Assert(explanationVector
.size() > 0);
2044 unsigned i
= 0; // Index of the current literal we are processing
2045 unsigned j
= 0; // Index of the last literal we are keeping
2047 std::unique_ptr
<std::set
<Node
>> inputAssertions
= nullptr;
2051 inputAssertions
.reset(
2052 new std::set
<Node
>(proofRecipe
->getStep(0)->getAssertions()));
2056 while (i
< explanationVector
.size()) {
2057 // Get the current literal to explain
2058 NodeTheoryPair toExplain
= explanationVector
[i
];
2060 Debug("theory::explain") << "[i=" << i
<< "] TheoryEngine::explain(): processing [" << toExplain
.timestamp
<< "] " << toExplain
.node
<< " sent from " << toExplain
.theory
<< endl
;
2063 // If a true constant or a negation of a false constant we can ignore it
2064 if (toExplain
.node
.isConst() && toExplain
.node
.getConst
<bool>()) {
2068 if (toExplain
.node
.getKind() == kind::NOT
&& toExplain
.node
[0].isConst() && !toExplain
.node
[0].getConst
<bool>()) {
2073 // If from the SAT solver, keep it
2074 if (toExplain
.theory
== THEORY_SAT_SOLVER
) {
2075 Debug("theory::explain") << "\tLiteral came from THEORY_SAT_SOLVER. Kepping it." << endl
;
2076 explanationVector
[j
++] = explanationVector
[i
++];
2080 // If an and, expand it
2081 if (toExplain
.node
.getKind() == kind::AND
) {
2082 Debug("theory::explain") << "TheoryEngine::explain(): expanding " << toExplain
.node
<< " got from " << toExplain
.theory
<< endl
;
2083 for (unsigned k
= 0; k
< toExplain
.node
.getNumChildren(); ++ k
) {
2084 NodeTheoryPair
newExplain(toExplain
.node
[k
], toExplain
.theory
, toExplain
.timestamp
);
2085 explanationVector
.push_back(newExplain
);
2091 // See if it was sent to the theory by another theory
2092 PropagationMap::const_iterator find
= d_propagationMap
.find(toExplain
);
2093 if (find
!= d_propagationMap
.end()) {
2094 Debug("theory::explain")
2095 << "\tTerm was propagated by another theory (theory = "
2096 << getTheoryString((*find
).second
.theory
) << ")" << std::endl
;
2097 // There is some propagation, check if its a timely one
2098 if ((*find
).second
.timestamp
< toExplain
.timestamp
) {
2099 Debug("theory::explain") << "\tRelevant timetsamp, pushing "
2100 << (*find
).second
.node
<< "to index = " << explanationVector
.size() << std::endl
;
2101 explanationVector
.push_back((*find
).second
);
2105 if (toExplain
.node
!= (*find
).second
.node
) {
2106 Debug("pf::explain") << "TheoryEngine::getExplanation: Rewrite alert! toAssert = " << toExplain
.node
2107 << ", toExplain = " << (*find
).second
.node
<< std::endl
;
2110 proofRecipe
->addRewriteRule(toExplain
.node
, (*find
).second
.node
);
2119 // It was produced by the theory, so ask for an explanation
2121 if (toExplain
.theory
== THEORY_BUILTIN
) {
2122 explanation
= d_sharedTerms
.explain(toExplain
.node
);
2123 Debug("theory::explain") << "\tTerm was propagated by THEORY_BUILTIN. Explanation: " << explanation
<< std::endl
;
2125 explanation
= theoryOf(toExplain
.theory
)->explain(toExplain
.node
);
2126 Debug("theory::explain") << "\tTerm was propagated by owner theory: "
2127 << theoryOf(toExplain
.theory
)->getId()
2128 << ". Explanation: " << explanation
<< std::endl
;
2131 Debug("theory::explain") << "TheoryEngine::explain(): got explanation " << explanation
<< " got from " << toExplain
.theory
<< endl
;
2132 Assert(explanation
!= toExplain
.node
)
2133 << "wasn't sent to you, so why are you explaining it trivially";
2134 // Mark the explanation
2135 NodeTheoryPair
newExplain(explanation
, toExplain
.theory
, toExplain
.timestamp
);
2136 explanationVector
.push_back(newExplain
);
2141 if (proofRecipe
&& inputAssertions
)
2143 // If we're expanding the target node of the explanation (this is the
2144 // first expansion...), we don't want to add it as a separate proof
2145 // step. It is already part of the assertions.
2146 if (!ContainsKey(*inputAssertions
, toExplain
.node
))
2148 LemmaProofRecipe::ProofStep
proofStep(toExplain
.theory
,
2150 if (explanation
.getKind() == kind::AND
)
2152 Node flat
= flattenAnd(explanation
);
2153 for (unsigned k
= 0; k
< flat
.getNumChildren(); ++k
)
2155 // If a true constant or a negation of a false constant we can
2157 if (!((flat
[k
].isConst() && flat
[k
].getConst
<bool>())
2158 || (flat
[k
].getKind() == kind::NOT
&& flat
[k
][0].isConst()
2159 && !flat
[k
][0].getConst
<bool>())))
2161 proofStep
.addAssertion(flat
[k
].negate());
2167 if (!((explanation
.isConst() && explanation
.getConst
<bool>())
2168 || (explanation
.getKind() == kind::NOT
2169 && explanation
[0].isConst()
2170 && !explanation
[0].getConst
<bool>())))
2172 proofStep
.addAssertion(explanation
.negate());
2175 proofRecipe
->addStep(proofStep
);
2181 // Keep only the relevant literals
2182 explanationVector
.resize(j
);
2186 // The remaining literals are the base of the proof
2187 for (unsigned k
= 0; k
< explanationVector
.size(); ++k
) {
2188 proofRecipe
->addBaseAssertion(explanationVector
[k
].node
.negate());
2194 void TheoryEngine::setUserAttribute(const std::string
& attr
,
2196 const std::vector
<Node
>& node_values
,
2197 const std::string
& str_value
)
2199 Trace("te-attr") << "set user attribute " << attr
<< " " << n
<< endl
;
2200 if( d_attr_handle
.find( attr
)!=d_attr_handle
.end() ){
2201 for( size_t i
=0; i
<d_attr_handle
[attr
].size(); i
++ ){
2202 d_attr_handle
[attr
][i
]->setUserAttribute(attr
, n
, node_values
, str_value
);
2205 //unhandled exception?
2209 void TheoryEngine::handleUserAttribute(const char* attr
, Theory
* t
) {
2210 Trace("te-attr") << "Handle user attribute " << attr
<< " " << t
<< endl
;
2211 std::string
str( attr
);
2212 d_attr_handle
[ str
].push_back( t
);
2215 void TheoryEngine::checkTheoryAssertionsWithModel(bool hardFailure
) {
2216 for(TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
2217 Theory
* theory
= d_theoryTable
[theoryId
];
2218 if(theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
2219 for(context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
2220 it_end
= theory
->facts_end();
2223 Node assertion
= (*it
).assertion
;
2224 Node val
= getModel()->getValue(assertion
);
2231 << " has an asserted fact that the model doesn't satisfy."
2233 << "The fact: " << assertion
<< endl
2234 << "Model value: " << val
<< endl
;
2242 std::pair
<bool, Node
> TheoryEngine::entailmentCheck(theory::TheoryOfMode mode
, TNode lit
, const EntailmentCheckParameters
* params
, EntailmentCheckSideEffects
* seffects
) {
2243 TNode atom
= (lit
.getKind() == kind::NOT
) ? lit
[0] : lit
;
2244 if( atom
.getKind()==kind::AND
|| atom
.getKind()==kind::OR
|| atom
.getKind()==kind::IMPLIES
){
2245 //Boolean connective, recurse
2246 std::vector
< Node
> children
;
2247 bool pol
= (lit
.getKind()!=kind::NOT
);
2248 bool is_conjunction
= pol
==(lit
.getKind()==kind::AND
);
2249 for( unsigned i
=0; i
<atom
.getNumChildren(); i
++ ){
2251 if( pol
==( lit
.getKind()==kind::IMPLIES
&& i
==0 ) ){
2252 ch
= atom
[i
].negate();
2254 std::pair
<bool, Node
> chres
= entailmentCheck( mode
, ch
, params
, seffects
);
2256 if( !is_conjunction
){
2259 children
.push_back( chres
.second
);
2261 }else if( !chres
.first
&& is_conjunction
){
2262 return std::pair
<bool, Node
>(false, Node::null());
2265 if( is_conjunction
){
2266 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, children
));
2268 return std::pair
<bool, Node
>(false, Node::null());
2270 }else if( atom
.getKind()==kind::ITE
|| ( atom
.getKind()==kind::EQUAL
&& atom
[0].getType().isBoolean() ) ){
2271 bool pol
= (lit
.getKind()!=kind::NOT
);
2272 for( unsigned r
=0; r
<2; r
++ ){
2277 std::pair
<bool, Node
> chres
= entailmentCheck( mode
, ch
, params
, seffects
);
2279 Node ch2
= atom
[ atom
.getKind()==kind::ITE
? r
+1 : 1 ];
2280 if( pol
==( atom
.getKind()==kind::ITE
? true : r
==1 ) ){
2283 std::pair
<bool, Node
> chres2
= entailmentCheck( mode
, ch2
, params
, seffects
);
2285 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, chres
.second
, chres2
.second
));
2291 return std::pair
<bool, Node
>(false, Node::null());
2293 //it is a theory atom
2294 theory::TheoryId tid
= theory::Theory::theoryOf(mode
, atom
);
2295 theory::Theory
* th
= theoryOf(tid
);
2298 Assert(params
== NULL
|| tid
== params
->getTheoryId());
2299 Assert(seffects
== NULL
|| tid
== seffects
->getTheoryId());
2300 Trace("theory-engine-entc") << "Entailment check : " << lit
<< std::endl
;
2302 std::pair
<bool, Node
> chres
= th
->entailmentCheck(lit
, params
, seffects
);
2307 void TheoryEngine::spendResource(unsigned amount
)
2309 d_resourceManager
->spendResource(amount
);
2312 void TheoryEngine::enableTheoryAlternative(const std::string
& name
){
2313 Debug("TheoryEngine::enableTheoryAlternative")
2314 << "TheoryEngine::enableTheoryAlternative(" << name
<< ")" << std::endl
;
2316 d_theoryAlternatives
.insert(name
);
2319 bool TheoryEngine::useTheoryAlternative(const std::string
& name
) {
2320 return d_theoryAlternatives
.find(name
) != d_theoryAlternatives
.end();
2324 TheoryEngine::Statistics::Statistics(theory::TheoryId theory
):
2325 conflicts(getStatsPrefix(theory
) + "::conflicts", 0),
2326 propagations(getStatsPrefix(theory
) + "::propagations", 0),
2327 lemmas(getStatsPrefix(theory
) + "::lemmas", 0),
2328 requirePhase(getStatsPrefix(theory
) + "::requirePhase", 0),
2329 restartDemands(getStatsPrefix(theory
) + "::restartDemands", 0)
2331 smtStatisticsRegistry()->registerStat(&conflicts
);
2332 smtStatisticsRegistry()->registerStat(&propagations
);
2333 smtStatisticsRegistry()->registerStat(&lemmas
);
2334 smtStatisticsRegistry()->registerStat(&requirePhase
);
2335 smtStatisticsRegistry()->registerStat(&restartDemands
);
2338 TheoryEngine::Statistics::~Statistics() {
2339 smtStatisticsRegistry()->unregisterStat(&conflicts
);
2340 smtStatisticsRegistry()->unregisterStat(&propagations
);
2341 smtStatisticsRegistry()->unregisterStat(&lemmas
);
2342 smtStatisticsRegistry()->unregisterStat(&requirePhase
);
2343 smtStatisticsRegistry()->unregisterStat(&restartDemands
);
2346 }/* CVC4 namespace */