1 /********************* */
2 /*! \file theory_engine.cpp
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Dejan Jovanovic, Morgan Deters
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2020 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/quantifiers_options.h"
32 #include "options/theory_options.h"
33 #include "preprocessing/assertion_pipeline.h"
34 #include "printer/printer.h"
36 #include "smt/logic_exception.h"
37 #include "smt/term_formula_removal.h"
38 #include "theory/arith/arith_ite_utils.h"
39 #include "theory/bv/theory_bv_utils.h"
40 #include "theory/care_graph.h"
41 #include "theory/combination_care_graph.h"
42 #include "theory/decision_manager.h"
43 #include "theory/quantifiers/first_order_model.h"
44 #include "theory/quantifiers/fmf/model_engine.h"
45 #include "theory/quantifiers/theory_quantifiers.h"
46 #include "theory/quantifiers_engine.h"
47 #include "theory/relevance_manager.h"
48 #include "theory/rewriter.h"
49 #include "theory/theory.h"
50 #include "theory/theory_engine_proof_generator.h"
51 #include "theory/theory_id.h"
52 #include "theory/theory_model.h"
53 #include "theory/theory_traits.h"
54 #include "theory/uf/equality_engine.h"
55 #include "util/resource_manager.h"
59 using namespace CVC4::preprocessing
;
60 using namespace CVC4::theory
;
64 /* -------------------------------------------------------------------------- */
69 * IMPORTANT: The order of the theories is important. For example, strings
70 * depends on arith, quantifiers needs to come as the very last.
71 * Do not change this order.
74 #define CVC4_FOR_EACH_THEORY \
75 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BUILTIN) \
76 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BOOL) \
77 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_UF) \
78 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_ARITH) \
79 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BV) \
80 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_FP) \
81 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_ARRAYS) \
82 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_DATATYPES) \
83 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_SEP) \
84 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_SETS) \
85 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_BAGS) \
86 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_STRINGS) \
87 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_QUANTIFIERS)
91 /* -------------------------------------------------------------------------- */
93 inline void flattenAnd(Node n
, std::vector
<TNode
>& out
){
94 Assert(n
.getKind() == kind::AND
);
95 for(Node::iterator i
=n
.begin(), i_end
=n
.end(); i
!= i_end
; ++i
){
97 if(curr
.getKind() == kind::AND
){
98 flattenAnd(curr
, out
);
105 inline Node
flattenAnd(Node n
){
106 std::vector
<TNode
> out
;
108 return NodeManager::currentNM()->mkNode(kind::AND
, out
);
112 * Compute the string for a given theory id. In this module, we use
113 * THEORY_SAT_SOLVER as an id, which is not a normal id but maps to
114 * THEORY_LAST. Thus, we need our own string conversion here.
116 * @param id The theory id
117 * @return The string corresponding to the theory id
119 std::string
getTheoryString(theory::TheoryId id
)
121 if (id
== theory::THEORY_SAT_SOLVER
)
123 return "THEORY_SAT_SOLVER";
127 std::stringstream ss
;
133 void TheoryEngine::finishInit() {
134 // NOTE: This seems to be required since
135 // theory::TheoryTraits<THEORY>::isParametric cannot be accessed without
136 // using the CVC4_FOR_EACH_THEORY_STATEMENT macro. -AJR
137 std::vector
<theory::Theory
*> paraTheories
;
138 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
139 #undef CVC4_FOR_EACH_THEORY_STATEMENT
141 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
142 if (theory::TheoryTraits<THEORY>::isParametric \
143 && d_logicInfo.isTheoryEnabled(THEORY)) \
145 paraTheories.push_back(theoryOf(THEORY)); \
147 // Collect the parametric theories, which are given to the theory combination
149 CVC4_FOR_EACH_THEORY
;
151 // Initialize the theory combination architecture
152 if (options::tcMode() == options::TcMode::CARE_GRAPH
)
154 d_tc
.reset(new CombinationCareGraph(*this, paraTheories
, d_pnm
));
158 Unimplemented() << "TheoryEngine::finishInit: theory combination mode "
159 << options::tcMode() << " not supported";
161 // create the relevance filter if any option requires it
162 if (options::relevanceFilter())
165 new RelevanceManager(d_userContext
, theory::Valuation(this)));
168 // initialize the quantifiers engine
169 if (d_logicInfo
.isQuantified())
171 // initialize the quantifiers engine
172 d_quantEngine
= new QuantifiersEngine(this, *d_decManager
.get(), d_pnm
);
174 // initialize the theory combination manager, which decides and allocates the
175 // equality engines to use for all theories.
178 // set the core equality engine on quantifiers engine
179 if (d_logicInfo
.isQuantified())
181 d_quantEngine
->setMasterEqualityEngine(d_tc
->getCoreEqualityEngine());
184 // finish initializing the theories by linking them with the appropriate
185 // utilities and then calling their finishInit method.
186 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
187 Theory
* t
= d_theoryTable
[theoryId
];
192 // setup the pointers to the utilities
193 const EeTheoryInfo
* eeti
= d_tc
->getEeTheoryInfo(theoryId
);
194 Assert(eeti
!= nullptr);
195 // the theory's official equality engine is the one specified by the
196 // equality engine manager
197 t
->setEqualityEngine(eeti
->d_usedEe
);
198 // set the quantifiers engine
199 t
->setQuantifiersEngine(d_quantEngine
);
200 // set the decision manager for the theory
201 t
->setDecisionManager(d_decManager
.get());
202 // finish initializing the theory
206 // finish initializing the quantifiers engine
207 if (d_logicInfo
.isQuantified())
209 d_quantEngine
->finishInit();
213 TheoryEngine::TheoryEngine(context::Context
* context
,
214 context::UserContext
* userContext
,
216 RemoveTermFormulas
& iteRemover
,
217 const LogicInfo
& logicInfo
,
218 OutputManager
& outMgr
)
219 : d_propEngine(nullptr),
221 d_userContext(userContext
),
222 d_logicInfo(logicInfo
),
226 d_pnm
!= nullptr ? new LazyCDProof(
227 d_pnm
, nullptr, d_userContext
, "TheoryEngine::LazyCDProof")
229 d_tepg(new TheoryEngineProofGenerator(d_pnm
, d_userContext
)),
230 d_sharedTerms(this, context
),
232 d_quantEngine(nullptr),
233 d_decManager(new DecisionManager(userContext
)),
234 d_relManager(nullptr),
235 d_preRegistrationVisitor(this, context
),
236 d_sharedTermsVisitor(d_sharedTerms
),
237 d_eager_model_building(false),
238 d_inConflict(context
, false),
240 d_hasShutDown(false),
241 d_incomplete(context
, false),
242 d_propagationMap(context
),
243 d_propagationMapTimestamp(context
, 0),
244 d_propagatedLiterals(context
),
245 d_propagatedLiteralsIndex(context
, 0),
246 d_atomRequests(context
),
247 d_tpp(*this, iteRemover
),
248 d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
251 d_interrupted(false),
252 d_resourceManager(rm
),
253 d_inPreregister(false),
254 d_factsAsserted(context
, false),
256 d_arithSubstitutionsAdded("theory::arith::zzz::arith::substitutions", 0)
258 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
;
261 d_theoryTable
[theoryId
] = NULL
;
262 d_theoryOut
[theoryId
] = NULL
;
265 smtStatisticsRegistry()->registerStat(&d_combineTheoriesTime
);
266 d_true
= NodeManager::currentNM()->mkConst
<bool>(true);
267 d_false
= NodeManager::currentNM()->mkConst
<bool>(false);
269 smtStatisticsRegistry()->registerStat(&d_arithSubstitutionsAdded
);
272 TheoryEngine::~TheoryEngine() {
273 Assert(d_hasShutDown
);
275 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
276 if(d_theoryTable
[theoryId
] != NULL
) {
277 delete d_theoryTable
[theoryId
];
278 delete d_theoryOut
[theoryId
];
282 delete d_quantEngine
;
284 smtStatisticsRegistry()->unregisterStat(&d_combineTheoriesTime
);
285 smtStatisticsRegistry()->unregisterStat(&d_arithSubstitutionsAdded
);
288 void TheoryEngine::interrupt() { d_interrupted
= true; }
289 void TheoryEngine::preRegister(TNode preprocessed
) {
290 Debug("theory") << "TheoryEngine::preRegister( " << preprocessed
<< ")"
292 d_preregisterQueue
.push(preprocessed
);
294 if (!d_inPreregister
) {
295 // We're in pre-register
296 d_inPreregister
= true;
298 // Process the pre-registration queue
299 while (!d_preregisterQueue
.empty()) {
300 // Get the next atom to pre-register
301 preprocessed
= d_preregisterQueue
.front();
302 d_preregisterQueue
.pop();
304 if (d_logicInfo
.isSharingEnabled() && preprocessed
.getKind() == kind::EQUAL
) {
305 // When sharing is enabled, we propagate from the shared terms manager also
306 d_sharedTerms
.addEqualityToPropagate(preprocessed
);
309 // the atom should not have free variables
310 Debug("theory") << "TheoryEngine::preRegister: " << preprocessed
312 Assert(!expr::hasFreeVar(preprocessed
));
314 // Pre-register the terms in the atom
315 theory::TheoryIdSet theories
= NodeVisitor
<PreRegisterVisitor
>::run(
316 d_preRegistrationVisitor
, preprocessed
);
317 theories
= TheoryIdSetUtil::setRemove(THEORY_BOOL
, theories
);
318 // Remove the top theory, if any more that means multiple theories were
320 bool multipleTheories
=
321 TheoryIdSetUtil::setRemove(Theory::theoryOf(preprocessed
), theories
);
322 if (Configuration::isAssertionBuild())
325 // This should never throw an exception, since theories should be
326 // guaranteed to be initialized.
327 // These checks don't work with finite model finding, because it
328 // uses Rational constants to represent cardinality constraints,
329 // even though arithmetic isn't actually involved.
330 if (!options::finiteModelFind())
332 while ((i
= TheoryIdSetUtil::setPop(theories
)) != THEORY_LAST
)
334 if (!d_logicInfo
.isTheoryEnabled(i
))
336 LogicInfo newLogicInfo
= d_logicInfo
.getUnlockedCopy();
337 newLogicInfo
.enableTheory(i
);
339 std::stringstream ss
;
340 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
341 << ", which doesn't include " << i
342 << ", but found a term in that theory." << std::endl
343 << "You might want to extend your logic to "
344 << newLogicInfo
.getLogicString() << std::endl
;
345 throw LogicException(ss
.str());
350 if (multipleTheories
) {
351 // Collect the shared terms if there are multiple theories
352 NodeVisitor
<SharedTermsVisitor
>::run(d_sharedTermsVisitor
,
357 // Leaving pre-register
358 d_inPreregister
= false;
362 void TheoryEngine::printAssertions(const char* tag
) {
363 if (Trace
.isOn(tag
)) {
365 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
366 Theory
* theory
= d_theoryTable
[theoryId
];
367 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
368 Trace(tag
) << "--------------------------------------------" << endl
;
369 Trace(tag
) << "Assertions of " << theory
->getId() << ": " << endl
;
371 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
374 for (unsigned i
= 0; it
!= it_end
; ++it
, ++i
)
376 if ((*it
).d_isPreregistered
)
378 Trace(tag
) << "[" << i
<< "]: ";
382 Trace(tag
) << "(" << i
<< "): ";
384 Trace(tag
) << (*it
).d_assertion
<< endl
;
388 if (d_logicInfo
.isSharingEnabled()) {
389 Trace(tag
) << "Shared terms of " << theory
->getId() << ": " << endl
;
390 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
391 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
392 Trace(tag
) << "[" << i
<< "]: " << (*it
) << endl
;
400 void TheoryEngine::dumpAssertions(const char* tag
) {
401 if (Dump
.isOn(tag
)) {
402 const Printer
& printer
= d_outMgr
.getPrinter();
403 std::ostream
& out
= d_outMgr
.getDumpOut();
404 printer
.toStreamCmdComment(out
, "Starting completeness check");
405 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
406 Theory
* theory
= d_theoryTable
[theoryId
];
407 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
408 printer
.toStreamCmdComment(out
, "Completeness check");
409 printer
.toStreamCmdPush(out
);
411 // Dump the shared terms
412 if (d_logicInfo
.isSharingEnabled()) {
413 printer
.toStreamCmdComment(out
, "Shared terms");
414 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
415 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
418 printer
.toStreamCmdComment(out
, ss
.str());
422 // Dump the assertions
423 printer
.toStreamCmdComment(out
, "Assertions");
424 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(), it_end
= theory
->facts_end();
425 for (; it
!= it_end
; ++ it
) {
427 Node assertionNode
= (*it
).d_assertion
;
428 // Purify all the terms
430 if ((*it
).d_isPreregistered
)
432 printer
.toStreamCmdComment(out
, "Preregistered");
436 printer
.toStreamCmdComment(out
, "Shared assertion");
438 printer
.toStreamCmdAssert(out
, assertionNode
);
440 printer
.toStreamCmdCheckSat(out
);
442 printer
.toStreamCmdPop(out
);
449 * Check all (currently-active) theories for conflicts.
450 * @param effort the effort level to use
452 void TheoryEngine::check(Theory::Effort effort
) {
455 // Reset the interrupt flag
456 d_interrupted
= false;
458 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
459 #undef CVC4_FOR_EACH_THEORY_STATEMENT
461 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
462 if (theory::TheoryTraits<THEORY>::hasCheck \
463 && d_logicInfo.isTheoryEnabled(THEORY)) \
465 theoryOf(THEORY)->check(effort); \
468 Debug("conflict") << THEORY << " in conflict. " << std::endl; \
476 // Mark the output channel unused (if this is FULL_EFFORT, and nothing
477 // is done by the theories, no additional check will be needed)
478 d_outputChannelUsed
= false;
480 // Mark the lemmas flag (no lemmas added)
481 d_lemmasAdded
= false;
483 Debug("theory") << "TheoryEngine::check(" << effort
<< "): d_factsAsserted = " << (d_factsAsserted
? "true" : "false") << endl
;
485 // If in full effort, we have a fake new assertion just to jumpstart the checking
486 if (Theory::fullEffort(effort
)) {
487 d_factsAsserted
= true;
488 // Reset round for the relevance manager, which notice only sets a flag
489 // to indicate that its information must be recomputed.
490 if (d_relManager
!= nullptr)
492 d_relManager
->resetRound();
498 while (d_factsAsserted
&& !d_inConflict
&& !d_lemmasAdded
) {
500 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running check" << endl
;
502 Trace("theory::assertions") << endl
;
503 if (Trace
.isOn("theory::assertions")) {
504 printAssertions("theory::assertions");
507 if(Theory::fullEffort(effort
)) {
508 Trace("theory::assertions::fulleffort") << endl
;
509 if (Trace
.isOn("theory::assertions::fulleffort")) {
510 printAssertions("theory::assertions::fulleffort");
514 // Note that we've discharged all the facts
515 d_factsAsserted
= false;
518 CVC4_FOR_EACH_THEORY
;
520 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running propagation after the initial check" << endl
;
522 // We are still satisfiable, propagate as much as possible
525 // We do combination if all has been processed and we are in fullcheck
526 if (Theory::fullEffort(effort
) && d_logicInfo
.isSharingEnabled() && !d_factsAsserted
&& !d_lemmasAdded
&& !d_inConflict
) {
527 // Do the combination
528 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running combination" << endl
;
530 TimerStat::CodeTimer
combineTheoriesTimer(d_combineTheoriesTime
);
531 d_tc
->combineTheories();
533 if(d_logicInfo
.isQuantified()){
534 d_quantEngine
->notifyCombineTheories();
539 // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
540 if( Theory::fullEffort(effort
) && ! d_inConflict
&& ! needCheck() ) {
541 Trace("theory::assertions-model") << endl
;
542 if (Trace
.isOn("theory::assertions-model")) {
543 printAssertions("theory::assertions-model");
545 // reset the model in the combination engine
547 //checks for theories requiring the model go at last call
548 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
549 if( theoryId
!=THEORY_QUANTIFIERS
){
550 Theory
* theory
= d_theoryTable
[theoryId
];
551 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
552 if( theory
->needsCheckLastEffort() ){
553 if (!d_tc
->buildModel())
557 theory
->check(Theory::EFFORT_LAST_CALL
);
564 if(d_logicInfo
.isQuantified()) {
565 // quantifiers engine must check at last call effort
566 d_quantEngine
->check(Theory::EFFORT_LAST_CALL
);
569 if (!d_inConflict
&& !needCheck())
571 // If d_eager_model_building is false, then we only mark that we
572 // are in "SAT mode". We build the model later only if the user asks
573 // for it via getBuiltModel.
575 if (d_eager_model_building
)
582 Debug("theory") << "TheoryEngine::check(" << effort
<< "): done, we are " << (d_inConflict
? "unsat" : "sat") << (d_lemmasAdded
? " with new lemmas" : " with no new lemmas");
583 Debug("theory") << ", need check = " << (needCheck() ? "YES" : "NO") << endl
;
585 if( Theory::fullEffort(effort
) && !d_inConflict
&& !needCheck()) {
586 // Do post-processing of model from the theories (e.g. used for THEORY_SEP
587 // to construct heap model)
588 d_tc
->postProcessModel(d_incomplete
.get());
590 } catch(const theory::Interrupted
&) {
591 Trace("theory") << "TheoryEngine::check() => interrupted" << endl
;
593 // If fulleffort, check all theories
594 if(Dump
.isOn("theory::fullcheck") && Theory::fullEffort(effort
)) {
595 if (!d_inConflict
&& !needCheck()) {
596 dumpAssertions("theory::fullcheck");
601 void TheoryEngine::propagate(Theory::Effort effort
)
603 // Reset the interrupt flag
604 d_interrupted
= false;
606 // Definition of the statement that is to be run by every theory
607 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
608 #undef CVC4_FOR_EACH_THEORY_STATEMENT
610 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
611 if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
612 theoryOf(THEORY)->propagate(effort); \
615 // Reset the interrupt flag
616 d_interrupted
= false;
618 // Propagate for each theory using the statement above
619 CVC4_FOR_EACH_THEORY
;
622 Node
TheoryEngine::getNextDecisionRequest()
624 return d_decManager
->getNextDecisionRequest();
627 bool TheoryEngine::properConflict(TNode conflict
) const {
629 if (conflict
.getKind() == kind::AND
) {
630 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++ i
) {
631 if (! getPropEngine()->hasValue(conflict
[i
], value
)) {
632 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
633 << conflict
[i
] << endl
;
637 Debug("properConflict") << "Bad conflict is due to false atom: "
638 << conflict
[i
] << endl
;
641 if (conflict
[i
] != Rewriter::rewrite(conflict
[i
])) {
642 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
643 << conflict
[i
] << " vs " << Rewriter::rewrite(conflict
[i
]) << endl
;
648 if (! getPropEngine()->hasValue(conflict
, value
)) {
649 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
654 Debug("properConflict") << "Bad conflict is due to false atom: "
658 if (conflict
!= Rewriter::rewrite(conflict
)) {
659 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
660 << conflict
<< " vs " << Rewriter::rewrite(conflict
) << endl
;
667 TheoryModel
* TheoryEngine::getModel()
669 Assert(d_tc
!= nullptr);
670 TheoryModel
* m
= d_tc
->getModel();
671 Assert(m
!= nullptr);
675 TheoryModel
* TheoryEngine::getBuiltModel()
677 Assert(d_tc
!= nullptr);
678 // If this method was called, we should be in SAT mode, and produceModels
680 AlwaysAssert(options::produceModels());
683 // not available, perhaps due to interuption.
686 // must build model at this point
687 if (!d_tc
->buildModel())
691 return d_tc
->getModel();
694 bool TheoryEngine::buildModel()
696 Assert(d_tc
!= nullptr);
697 return d_tc
->buildModel();
700 bool TheoryEngine::getSynthSolutions(
701 std::map
<Node
, std::map
<Node
, Node
>>& sol_map
)
705 return d_quantEngine
->getSynthSolutions(sol_map
);
707 // we are not in a quantified logic, there is no synthesis solution
711 bool TheoryEngine::presolve() {
712 // Reset the interrupt flag
713 d_interrupted
= false;
715 // Reset the decision manager. This clears its decision strategies that are
716 // no longer valid in this user context.
717 d_decManager
->presolve();
720 // Definition of the statement that is to be run by every theory
721 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
722 #undef CVC4_FOR_EACH_THEORY_STATEMENT
724 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
725 if (theory::TheoryTraits<THEORY>::hasPresolve) { \
726 theoryOf(THEORY)->presolve(); \
732 // Presolve for each theory using the statement above
733 CVC4_FOR_EACH_THEORY
;
734 } catch(const theory::Interrupted
&) {
735 Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl
;
737 // return whether we have a conflict
739 }/* TheoryEngine::presolve() */
741 void TheoryEngine::postsolve() {
742 // no longer in SAT mode
744 // Reset the interrupt flag
745 d_interrupted
= false;
746 bool CVC4_UNUSED wasInConflict
= d_inConflict
;
749 // Definition of the statement that is to be run by every theory
750 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
751 #undef CVC4_FOR_EACH_THEORY_STATEMENT
753 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
754 if (theory::TheoryTraits<THEORY>::hasPostsolve) \
756 theoryOf(THEORY)->postsolve(); \
757 Assert(!d_inConflict || wasInConflict) \
758 << "conflict raised during postsolve()"; \
761 // Postsolve for each theory using the statement above
762 CVC4_FOR_EACH_THEORY
;
763 } catch(const theory::Interrupted
&) {
764 Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl
;
766 }/* TheoryEngine::postsolve() */
769 void TheoryEngine::notifyRestart() {
770 // Reset the interrupt flag
771 d_interrupted
= false;
773 // Definition of the statement that is to be run by every theory
774 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
775 #undef CVC4_FOR_EACH_THEORY_STATEMENT
777 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
778 if (theory::TheoryTraits<THEORY>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
779 theoryOf(THEORY)->notifyRestart(); \
782 // notify each theory using the statement above
783 CVC4_FOR_EACH_THEORY
;
786 void TheoryEngine::ppStaticLearn(TNode in
, NodeBuilder
<>& learned
) {
787 // Reset the interrupt flag
788 d_interrupted
= false;
790 // Definition of the statement that is to be run by every theory
791 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
792 #undef CVC4_FOR_EACH_THEORY_STATEMENT
794 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
795 if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) { \
796 theoryOf(THEORY)->ppStaticLearn(in, learned); \
799 // static learning for each theory using the statement above
800 CVC4_FOR_EACH_THEORY
;
803 bool TheoryEngine::isRelevant(Node lit
) const
805 if (d_relManager
!= nullptr)
807 return d_relManager
->isRelevant(lit
);
809 // otherwise must assume its relevant
813 void TheoryEngine::shutdown() {
814 // Set this first; if a Theory shutdown() throws an exception,
815 // at least the destruction of the TheoryEngine won't confound
817 d_hasShutDown
= true;
819 // Shutdown all the theories
820 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
821 if(d_theoryTable
[theoryId
]) {
822 theoryOf(theoryId
)->shutdown();
829 theory::Theory::PPAssertStatus
TheoryEngine::solve(TNode literal
, SubstitutionMap
& substitutionOut
) {
830 // Reset the interrupt flag
831 d_interrupted
= false;
833 TNode atom
= literal
.getKind() == kind::NOT
? literal
[0] : literal
;
834 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< "): solving with " << theoryOf(atom
)->getId() << endl
;
836 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(atom
)) &&
837 Theory::theoryOf(atom
) != THEORY_SAT_SOLVER
) {
839 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
840 << ", which doesn't include " << Theory::theoryOf(atom
)
841 << ", but got a preprocessing-time fact for that theory." << endl
842 << "The fact:" << endl
844 throw LogicException(ss
.str());
847 Theory::PPAssertStatus solveStatus
= theoryOf(atom
)->ppAssert(literal
, substitutionOut
);
848 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< ") => " << solveStatus
<< endl
;
852 void TheoryEngine::preprocessStart() { d_tpp
.clearCache(); }
854 Node
TheoryEngine::preprocess(TNode assertion
) {
855 TrustNode trn
= d_tpp
.theoryPreprocess(assertion
);
861 return trn
.getNode();
864 void TheoryEngine::notifyPreprocessedAssertions(
865 const std::vector
<Node
>& assertions
) {
866 // call all the theories
867 for (TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
;
869 if (d_theoryTable
[theoryId
]) {
870 theoryOf(theoryId
)->ppNotifyAssertions(assertions
);
873 if (d_relManager
!= nullptr)
875 d_relManager
->notifyPreprocessedAssertions(assertions
);
879 bool TheoryEngine::markPropagation(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
881 // What and where we are asserting
882 NodeTheoryPair
toAssert(assertion
, toTheoryId
, d_propagationMapTimestamp
);
883 // What and where it came from
884 NodeTheoryPair
toExplain(originalAssertion
, fromTheoryId
, d_propagationMapTimestamp
);
886 // See if the theory already got this literal
887 PropagationMap::const_iterator find
= d_propagationMap
.find(toAssert
);
888 if (find
!= d_propagationMap
.end()) {
889 // The theory already knows this
890 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl
;
894 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp
<< "] " << assertion
<< ", " << toTheoryId
<< " from " << originalAssertion
<< ", " << fromTheoryId
<< endl
;
896 // Mark the propagation
897 d_propagationMap
[toAssert
] = toExplain
;
898 d_propagationMapTimestamp
= d_propagationMapTimestamp
+ 1;
904 void TheoryEngine::assertToTheory(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
906 Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << originalAssertion
<< "," << toTheoryId
<< ", " << fromTheoryId
<< ")" << endl
;
908 Assert(toTheoryId
!= fromTheoryId
);
909 if(toTheoryId
!= THEORY_SAT_SOLVER
&&
910 ! d_logicInfo
.isTheoryEnabled(toTheoryId
)) {
912 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
913 << ", which doesn't include " << toTheoryId
914 << ", but got an asserted fact to that theory." << endl
915 << "The fact:" << endl
917 throw LogicException(ss
.str());
924 // If sharing is disabled, things are easy
925 if (!d_logicInfo
.isSharingEnabled()) {
926 Assert(assertion
== originalAssertion
);
927 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
928 // Send to the apropriate theory
929 theory::Theory
* toTheory
= theoryOf(toTheoryId
);
930 // We assert it, and we know it's preregistereed
931 toTheory
->assertFact(assertion
, true);
932 // Mark that we have more information
933 d_factsAsserted
= true;
935 Assert(toTheoryId
== THEORY_SAT_SOLVER
);
936 // Check for propositional conflict
938 if (d_propEngine
->hasValue(assertion
, value
)) {
940 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (no sharing)" << endl
;
941 Trace("dtview::conflict")
942 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
948 d_propagatedLiterals
.push_back(assertion
);
953 // Polarity of the assertion
954 bool polarity
= assertion
.getKind() != kind::NOT
;
956 // Atom of the assertion
957 TNode atom
= polarity
? assertion
: assertion
[0];
959 // If sending to the shared terms database, it's also simple
960 if (toTheoryId
== THEORY_BUILTIN
) {
961 Assert(atom
.getKind() == kind::EQUAL
)
962 << "atom should be an EQUALity, not `" << atom
<< "'";
963 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
964 d_sharedTerms
.assertEquality(atom
, polarity
, assertion
);
969 // Things from the SAT solver are already normalized, so they go
970 // directly to the apropriate theory
971 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
972 // We know that this is normalized, so just send it off to the theory
973 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
974 // Is it preregistered
975 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
977 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
978 // Mark that we have more information
979 d_factsAsserted
= true;
984 // Propagations to the SAT solver are just enqueued for pickup by
985 // the SAT solver later
986 if (toTheoryId
== THEORY_SAT_SOLVER
) {
987 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
988 // Enqueue for propagation to the SAT solver
989 d_propagatedLiterals
.push_back(assertion
);
990 // Check for propositional conflicts
992 if (d_propEngine
->hasValue(assertion
, value
) && !value
) {
993 Trace("theory::propagate")
994 << "TheoryEngine::assertToTheory(" << assertion
<< ", "
995 << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (sharing)"
997 Trace("dtview::conflict")
998 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
1005 Assert(atom
.getKind() == kind::EQUAL
);
1008 Node normalizedLiteral
= Rewriter::rewrite(assertion
);
1010 // See if it rewrites false directly -> conflict
1011 if (normalizedLiteral
.isConst()) {
1012 if (!normalizedLiteral
.getConst
<bool>()) {
1013 // Mark the propagation for explanations
1014 if (markPropagation(normalizedLiteral
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1015 // special case, trust node has no proof generator
1016 TrustNode trnn
= TrustNode::mkTrustConflict(normalizedLiteral
);
1017 // Get the explanation (conflict will figure out where it came from)
1018 conflict(trnn
, toTheoryId
);
1026 // Try and assert (note that we assert the non-normalized one)
1027 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1028 // Check if has been pre-registered with the theory
1029 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1031 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1032 d_factsAsserted
= true;
1038 void TheoryEngine::assertFact(TNode literal
)
1040 Trace("theory") << "TheoryEngine::assertFact(" << literal
<< ")" << endl
;
1044 // If we're in conflict, nothing to do
1050 bool polarity
= literal
.getKind() != kind::NOT
;
1051 TNode atom
= polarity
? literal
: literal
[0];
1053 if (d_logicInfo
.isSharingEnabled()) {
1054 // If any shared terms, it's time to do sharing work
1055 if (d_sharedTerms
.hasSharedTerms(atom
)) {
1056 // Notify the theories the shared terms
1057 SharedTermsDatabase::shared_terms_iterator it
= d_sharedTerms
.begin(atom
);
1058 SharedTermsDatabase::shared_terms_iterator it_end
= d_sharedTerms
.end(atom
);
1059 for (; it
!= it_end
; ++ it
) {
1061 theory::TheoryIdSet theories
=
1062 d_sharedTerms
.getTheoriesToNotify(atom
, term
);
1063 for (TheoryId id
= THEORY_FIRST
; id
!= THEORY_LAST
; ++ id
) {
1064 if (TheoryIdSetUtil::setContains(id
, theories
))
1066 theoryOf(id
)->addSharedTerm(term
);
1069 d_sharedTerms
.markNotified(term
, theories
);
1073 // If it's an equality, assert it to the shared term manager, even though the terms are not
1074 // yet shared. As the terms become shared later, the shared terms manager will then add them
1075 // to the assert the equality to the interested theories
1076 if (atom
.getKind() == kind::EQUAL
) {
1077 // Assert it to the the owning theory
1078 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1079 // Shared terms manager will assert to interested theories directly, as
1080 // the terms become shared
1081 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ THEORY_SAT_SOLVER
);
1083 // Now, let's check for any atom triggers from lemmas
1084 AtomRequests::atom_iterator it
= d_atomRequests
.getAtomIterator(atom
);
1085 while (!it
.done()) {
1086 const AtomRequests::Request
& request
= it
.get();
1088 polarity
? (Node
)request
.d_atom
: request
.d_atom
.notNode();
1089 Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal
<< "): sending requested " << toAssert
<< endl
;
1091 toAssert
, literal
, request
.d_toTheory
, THEORY_SAT_SOLVER
);
1096 // Not an equality, just assert to the appropriate theory
1097 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1100 // Assert the fact to the appropriate theory directly
1101 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1105 bool TheoryEngine::propagate(TNode literal
, theory::TheoryId theory
) {
1106 Debug("theory::propagate") << "TheoryEngine::propagate(" << literal
<< ", " << theory
<< ")" << endl
;
1108 Trace("dtview::prop") << std::string(d_context
->getLevel(), ' ')
1109 << ":THEORY-PROP: " << literal
<< endl
;
1114 bool polarity
= literal
.getKind() != kind::NOT
;
1115 TNode atom
= polarity
? literal
: literal
[0];
1117 if (d_logicInfo
.isSharingEnabled() && atom
.getKind() == kind::EQUAL
) {
1118 if (d_propEngine
->isSatLiteral(literal
)) {
1119 // We propagate SAT literals to SAT
1120 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1122 if (theory
!= THEORY_BUILTIN
) {
1123 // Assert to the shared terms database
1124 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ theory
);
1127 // Just send off to the SAT solver
1128 Assert(d_propEngine
->isSatLiteral(literal
));
1129 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1132 return !d_inConflict
;
1135 const LogicInfo
& TheoryEngine::getLogicInfo() const { return d_logicInfo
; }
1137 theory::EqualityStatus
TheoryEngine::getEqualityStatus(TNode a
, TNode b
) {
1138 Assert(a
.getType().isComparableTo(b
.getType()));
1139 if (d_sharedTerms
.isShared(a
) && d_sharedTerms
.isShared(b
)) {
1140 if (d_sharedTerms
.areEqual(a
,b
)) {
1141 return EQUALITY_TRUE_AND_PROPAGATED
;
1143 else if (d_sharedTerms
.areDisequal(a
,b
)) {
1144 return EQUALITY_FALSE_AND_PROPAGATED
;
1147 return theoryOf(Theory::theoryOf(a
.getType()))->getEqualityStatus(a
, b
);
1150 Node
TheoryEngine::getModelValue(TNode var
) {
1153 // the model value of a constant must be itself
1156 Assert(d_sharedTerms
.isShared(var
));
1157 return theoryOf(Theory::theoryOf(var
.getType()))->getModelValue(var
);
1161 Node
TheoryEngine::ensureLiteral(TNode n
) {
1162 Debug("ensureLiteral") << "rewriting: " << n
<< std::endl
;
1163 Node rewritten
= Rewriter::rewrite(n
);
1164 Debug("ensureLiteral") << " got: " << rewritten
<< std::endl
;
1165 Node preprocessed
= preprocess(rewritten
);
1166 Debug("ensureLiteral") << "preprocessed: " << preprocessed
<< std::endl
;
1167 d_propEngine
->ensureLiteral(preprocessed
);
1168 return preprocessed
;
1172 void TheoryEngine::printInstantiations( std::ostream
& out
) {
1173 if( d_quantEngine
){
1174 d_quantEngine
->printInstantiations( out
);
1176 out
<< "Internal error : instantiations not available when quantifiers are not present." << std::endl
;
1181 void TheoryEngine::printSynthSolution( std::ostream
& out
) {
1182 if( d_quantEngine
){
1183 d_quantEngine
->printSynthSolution( out
);
1185 out
<< "Internal error : synth solution not available when quantifiers are not present." << std::endl
;
1190 void TheoryEngine::getInstantiatedQuantifiedFormulas( std::vector
< Node
>& qs
) {
1191 if( d_quantEngine
){
1192 d_quantEngine
->getInstantiatedQuantifiedFormulas( qs
);
1198 void TheoryEngine::getInstantiations( Node q
, std::vector
< Node
>& insts
) {
1199 if( d_quantEngine
){
1200 d_quantEngine
->getInstantiations( q
, insts
);
1206 void TheoryEngine::getInstantiationTermVectors( Node q
, std::vector
< std::vector
< Node
> >& tvecs
) {
1207 if( d_quantEngine
){
1208 d_quantEngine
->getInstantiationTermVectors( q
, tvecs
);
1214 void TheoryEngine::getInstantiations( std::map
< Node
, std::vector
< Node
> >& insts
) {
1215 if( d_quantEngine
){
1216 d_quantEngine
->getInstantiations( insts
);
1222 void TheoryEngine::getInstantiationTermVectors( std::map
< Node
, std::vector
< std::vector
< Node
> > >& insts
) {
1223 if( d_quantEngine
){
1224 d_quantEngine
->getInstantiationTermVectors( insts
);
1230 Node
TheoryEngine::getInstantiatedConjunction( Node q
) {
1231 if( d_quantEngine
){
1232 return d_quantEngine
->getInstantiatedConjunction( q
);
1235 return Node::null();
1240 static Node
mkExplanation(const std::vector
<NodeTheoryPair
>& explanation
) {
1242 std::set
<TNode
> all
;
1243 for (unsigned i
= 0; i
< explanation
.size(); ++ i
) {
1244 Assert(explanation
[i
].d_theory
== THEORY_SAT_SOLVER
);
1245 all
.insert(explanation
[i
].d_node
);
1248 if (all
.size() == 0) {
1249 // Normalize to true
1250 return NodeManager::currentNM()->mkConst
<bool>(true);
1253 if (all
.size() == 1) {
1254 // All the same, or just one
1255 return explanation
[0].d_node
;
1258 NodeBuilder
<> conjunction(kind::AND
);
1259 std::set
<TNode
>::const_iterator it
= all
.begin();
1260 std::set
<TNode
>::const_iterator it_end
= all
.end();
1261 while (it
!= it_end
) {
1269 TrustNode
TheoryEngine::getExplanation(TNode node
)
1271 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1272 << "): current propagation index = "
1273 << d_propagationMapTimestamp
<< endl
;
1275 bool polarity
= node
.getKind() != kind::NOT
;
1276 TNode atom
= polarity
? node
: node
[0];
1278 // If we're not in shared mode, explanations are simple
1279 if (!d_logicInfo
.isSharingEnabled())
1281 Debug("theory::explain")
1282 << "TheoryEngine::getExplanation: sharing is NOT enabled. "
1283 << " Responsible theory is: " << theoryOf(atom
)->getId() << std::endl
;
1285 TrustNode texplanation
= theoryOf(atom
)->explain(node
);
1286 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1287 << ") => " << texplanation
.getNode() << endl
;
1288 return texplanation
;
1291 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing IS enabled"
1294 // Initial thing to explain
1295 NodeTheoryPair
toExplain(node
, THEORY_SAT_SOLVER
, d_propagationMapTimestamp
);
1296 Assert(d_propagationMap
.find(toExplain
) != d_propagationMap
.end());
1298 NodeTheoryPair nodeExplainerPair
= d_propagationMap
[toExplain
];
1299 Debug("theory::explain")
1300 << "TheoryEngine::getExplanation: explainer for node "
1301 << nodeExplainerPair
.d_node
1302 << " is theory: " << nodeExplainerPair
.d_theory
<< std::endl
;
1304 // Create the workplace for explanations
1305 std::vector
<NodeTheoryPair
> explanationVector
;
1306 explanationVector
.push_back(d_propagationMap
[toExplain
]);
1307 // Process the explanation
1308 TrustNode texplanation
= getExplanation(explanationVector
);
1309 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => "
1310 << texplanation
.getNode() << endl
;
1311 return texplanation
;
1314 struct AtomsCollect
{
1316 std::vector
<TNode
> d_atoms
;
1317 std::unordered_set
<TNode
, TNodeHashFunction
> d_visited
;
1321 typedef void return_type
;
1323 bool alreadyVisited(TNode current
, TNode parent
) {
1324 // Check if already visited
1325 if (d_visited
.find(current
) != d_visited
.end()) return true;
1326 // Don't visit non-boolean
1327 if (!current
.getType().isBoolean()) return true;
1332 void visit(TNode current
, TNode parent
) {
1333 if (Theory::theoryOf(current
) != theory::THEORY_BOOL
) {
1334 d_atoms
.push_back(current
);
1336 d_visited
.insert(current
);
1339 void start(TNode node
) {}
1340 void done(TNode node
) {}
1342 std::vector
<TNode
> getAtoms() const {
1347 void TheoryEngine::ensureLemmaAtoms(const std::vector
<TNode
>& atoms
, theory::TheoryId atomsTo
) {
1348 for (unsigned i
= 0; i
< atoms
.size(); ++ i
) {
1350 // Non-equality atoms are either owned by theory or they don't make sense
1351 if (atoms
[i
].getKind() != kind::EQUAL
) {
1357 // Simple normalization to not repeat stuff
1358 if (eq
[0] > eq
[1]) {
1359 eq
= eq
[1].eqNode(eq
[0]);
1362 // Rewrite the equality
1363 Node eqNormalized
= Rewriter::rewrite(atoms
[i
]);
1365 Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq
<< " with nf " << eqNormalized
<< endl
;
1367 // If the equality is a boolean constant, we send immediately
1368 if (eqNormalized
.isConst()) {
1369 if (eqNormalized
.getConst
<bool>()) {
1370 assertToTheory(eq
, eqNormalized
, /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1372 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1375 }else if( eqNormalized
.getKind() != kind::EQUAL
){
1376 Assert(eqNormalized
.getKind() == kind::BOOLEAN_TERM_VARIABLE
1377 || (eqNormalized
.getKind() == kind::NOT
1378 && eqNormalized
[0].getKind() == kind::BOOLEAN_TERM_VARIABLE
));
1379 // this happens for Boolean term equalities V = true that are rewritten to V, we should skip
1380 // TODO : revisit this
1384 // If the normalization did the just flips, keep the flip
1385 if (eqNormalized
[0] == eq
[1] && eqNormalized
[1] == eq
[0]) {
1389 // Check if the equality is already known by the sat solver
1390 if (d_propEngine
->isSatLiteral(eqNormalized
)) {
1392 if (d_propEngine
->hasValue(eqNormalized
, value
)) {
1394 assertToTheory(eq
, eqNormalized
, atomsTo
, theory::THEORY_SAT_SOLVER
);
1397 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), atomsTo
, theory::THEORY_SAT_SOLVER
);
1403 // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1404 // then we must figure it out
1405 if (eqNormalized
!= eq
|| Theory::theoryOf(eq
) != atomsTo
) {
1406 // If you get eqNormalized, send atoms[i] to atomsTo
1407 d_atomRequests
.add(eqNormalized
, eq
, atomsTo
);
1412 theory::LemmaStatus
TheoryEngine::lemma(theory::TrustNode tlemma
,
1413 theory::LemmaProperty p
,
1414 theory::TheoryId atomsTo
,
1415 theory::TheoryId from
)
1417 // For resource-limiting (also does a time check).
1419 Assert(tlemma
.getKind() == TrustNodeKind::LEMMA
1420 || tlemma
.getKind() == TrustNodeKind::CONFLICT
);
1422 Node node
= tlemma
.getNode();
1423 Node lemma
= tlemma
.getProven();
1425 // when proofs are enabled, we ensure the trust node has a generator by
1426 // adding a trust step to the lazy proof maintained by this class
1427 if (isProofEnabled())
1429 // ensure proof: set THEORY_LEMMA if no generator is provided
1430 if (tlemma
.getGenerator() == nullptr)
1432 // internal lemmas should have generators
1433 Assert(from
!= THEORY_LAST
);
1434 // add theory lemma step to proof
1435 Node tidn
= builtin::BuiltinProofRuleChecker::mkTheoryIdNode(from
);
1436 d_lazyProof
->addStep(lemma
, PfRule::THEORY_LEMMA
, {}, {lemma
, tidn
});
1437 // update the trust node
1438 tlemma
= TrustNode::mkTrustLemma(lemma
, d_lazyProof
.get());
1441 tlemma
.debugCheckClosed("te-proof-debug", "TheoryEngine::lemma_initial");
1444 // Do we need to check atoms
1445 if (atomsTo
!= theory::THEORY_LAST
) {
1446 Debug("theory::atoms") << "TheoryEngine::lemma(" << node
<< ", " << atomsTo
<< ")" << endl
;
1447 AtomsCollect collectAtoms
;
1448 NodeVisitor
<AtomsCollect
>::run(collectAtoms
, node
);
1449 ensureLemmaAtoms(collectAtoms
.getAtoms(), atomsTo
);
1452 if(Dump
.isOn("t-lemmas")) {
1453 // we dump the negation of the lemma, to show validity of the lemma
1454 Node n
= lemma
.negate();
1455 const Printer
& printer
= d_outMgr
.getPrinter();
1456 std::ostream
& out
= d_outMgr
.getDumpOut();
1457 printer
.toStreamCmdComment(out
, "theory lemma: expect valid");
1458 printer
.toStreamCmdCheckSat(out
, n
);
1460 bool removable
= isLemmaPropertyRemovable(p
);
1461 bool preprocess
= isLemmaPropertyPreprocess(p
);
1463 // call preprocessor
1464 std::vector
<TrustNode
> newLemmas
;
1465 std::vector
<Node
> newSkolems
;
1467 d_tpp
.preprocess(lemma
, newLemmas
, newSkolems
, preprocess
);
1468 // the preprocessed lemma
1470 if (tplemma
.isNull())
1476 Assert(tplemma
.getKind() == TrustNodeKind::REWRITE
);
1477 lemmap
= tplemma
.getNode();
1479 // must update the trust lemma
1480 if (lemmap
!= lemma
)
1482 // process the preprocessing
1483 if (isProofEnabled())
1485 Assert(d_lazyProof
!= nullptr);
1486 // add the original proof to the lazy proof
1487 d_lazyProof
->addLazyStep(tlemma
.getProven(), tlemma
.getGenerator());
1488 // only need to do anything if lemmap changed in a non-trivial way
1489 if (!CDProof::isSame(lemmap
, lemma
))
1491 d_lazyProof
->addLazyStep(tplemma
.getProven(),
1492 tplemma
.getGenerator(),
1494 "TheoryEngine::lemma_pp",
1496 PfRule::PREPROCESS_LEMMA
);
1497 // ---------- from d_lazyProof -------------- from theory preprocess
1498 // lemma lemma = lemmap
1499 // ------------------------------------------ MACRO_SR_PRED_TRANSFORM
1501 std::vector
<Node
> pfChildren
;
1502 pfChildren
.push_back(lemma
);
1503 pfChildren
.push_back(tplemma
.getProven());
1504 std::vector
<Node
> pfArgs
;
1505 pfArgs
.push_back(lemmap
);
1506 d_lazyProof
->addStep(
1507 lemmap
, PfRule::MACRO_SR_PRED_TRANSFORM
, pfChildren
, pfArgs
);
1510 tlemma
= TrustNode::mkTrustLemma(lemmap
, d_lazyProof
.get());
1514 // must use an assertion pipeline due to decision engine below
1515 AssertionPipeline lemmas
;
1516 // make the assertion pipeline
1517 lemmas
.push_back(lemmap
);
1518 lemmas
.updateRealAssertionsEnd();
1519 Assert(newSkolems
.size() == newLemmas
.size());
1520 for (size_t i
= 0, nsize
= newLemmas
.size(); i
< nsize
; i
++)
1522 // store skolem mapping here
1523 IteSkolemMap
& imap
= lemmas
.getIteSkolemMap();
1524 imap
[newSkolems
[i
]] = lemmas
.size();
1525 lemmas
.push_back(newLemmas
[i
].getNode());
1528 // If specified, we must add this lemma to the set of those that need to be
1529 // justified, where note we pass all auxiliary lemmas in lemmas, since these
1530 // by extension must be justified as well.
1531 if (d_relManager
!= nullptr && isLemmaPropertyNeedsJustify(p
))
1533 d_relManager
->notifyPreprocessedAssertions(lemmas
.ref());
1536 // do final checks on the lemmas we are about to send
1537 if (isProofEnabled())
1539 Assert(tlemma
.getGenerator() != nullptr);
1540 // ensure closed, make the proof node eagerly here to debug
1541 tlemma
.debugCheckClosed("te-proof-debug", "TheoryEngine::lemma");
1542 for (size_t i
= 0, lsize
= newLemmas
.size(); i
< lsize
; ++i
)
1544 Assert(newLemmas
[i
].getGenerator() != nullptr);
1545 newLemmas
[i
].debugCheckClosed("te-proof-debug",
1546 "TheoryEngine::lemma_new");
1550 // now, send the lemmas to the prop engine
1551 d_propEngine
->assertLemma(tlemma
.getProven(), false, removable
);
1552 for (size_t i
= 0, lsize
= newLemmas
.size(); i
< lsize
; ++i
)
1554 d_propEngine
->assertLemma(newLemmas
[i
].getProven(), false, removable
);
1557 // assert to decision engine
1560 d_propEngine
->addAssertionsToDecisionEngine(lemmas
);
1563 // Mark that we added some lemmas
1564 d_lemmasAdded
= true;
1566 // Lemma analysis isn't online yet; this lemma may only live for this
1568 Node retLemma
= lemmas
[0];
1569 if (lemmas
.size() > 1)
1571 // the returned lemma is the conjunction of all additional lemmas.
1572 retLemma
= NodeManager::currentNM()->mkNode(kind::AND
, lemmas
.ref());
1574 return theory::LemmaStatus(retLemma
, d_userContext
->getLevel());
1577 void TheoryEngine::conflict(theory::TrustNode tconflict
, TheoryId theoryId
)
1579 Assert(tconflict
.getKind() == TrustNodeKind::CONFLICT
);
1580 TNode conflict
= tconflict
.getNode();
1581 Trace("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", "
1582 << theoryId
<< ")" << endl
;
1583 Trace("te-proof-debug") << "Check closed conflict" << std::endl
;
1584 // doesn't require proof generator, yet, since THEORY_LEMMA is added below
1585 tconflict
.debugCheckClosed(
1586 "te-proof-debug", "TheoryEngine::conflict_initial", false);
1588 Trace("dtview::conflict") << ":THEORY-CONFLICT: " << conflict
<< std::endl
;
1590 // Mark that we are in conflict
1591 d_inConflict
= true;
1593 if(Dump
.isOn("t-conflicts")) {
1594 const Printer
& printer
= d_outMgr
.getPrinter();
1595 std::ostream
& out
= d_outMgr
.getDumpOut();
1596 printer
.toStreamCmdComment(out
, "theory conflict: expect unsat");
1597 printer
.toStreamCmdCheckSat(out
, conflict
);
1600 // In the multiple-theories case, we need to reconstruct the conflict
1601 if (d_logicInfo
.isSharingEnabled()) {
1602 // Create the workplace for explanations
1603 std::vector
<NodeTheoryPair
> vec
;
1605 NodeTheoryPair(conflict
, theoryId
, d_propagationMapTimestamp
));
1607 // Process the explanation
1608 TrustNode tncExp
= getExplanation(vec
);
1609 Trace("te-proof-debug")
1610 << "Check closed conflict explained with sharing" << std::endl
;
1611 tncExp
.debugCheckClosed("te-proof-debug",
1612 "TheoryEngine::conflict_explained_sharing");
1613 Node fullConflict
= tncExp
.getNode();
1615 if (isProofEnabled())
1617 Trace("te-proof-debug") << "Process conflict: " << conflict
<< std::endl
;
1618 Trace("te-proof-debug") << "Conflict " << tconflict
<< " from "
1619 << tconflict
.identifyGenerator() << std::endl
;
1620 Trace("te-proof-debug") << "Explanation " << tncExp
<< " from "
1621 << tncExp
.identifyGenerator() << std::endl
;
1622 Assert(d_lazyProof
!= nullptr);
1623 if (tconflict
.getGenerator() != nullptr)
1625 d_lazyProof
->addLazyStep(tconflict
.getProven(),
1626 tconflict
.getGenerator());
1630 // add theory lemma step
1631 Node tidn
= builtin::BuiltinProofRuleChecker::mkTheoryIdNode(theoryId
);
1632 Node conf
= tconflict
.getProven();
1633 d_lazyProof
->addStep(conf
, PfRule::THEORY_LEMMA
, {}, {conf
, tidn
});
1635 // store the explicit step, which should come from a different
1636 // generator, e.g. d_tepg.
1637 Node proven
= tncExp
.getProven();
1638 Assert(tncExp
.getGenerator() != d_lazyProof
.get());
1639 Trace("te-proof-debug") << "add lazy step " << tncExp
.identifyGenerator()
1640 << " for " << proven
<< std::endl
;
1641 d_lazyProof
->addLazyStep(proven
, tncExp
.getGenerator());
1642 pfgEnsureClosed(proven
,
1645 "TheoryEngine::conflict_during");
1646 Node fullConflictNeg
= fullConflict
.notNode();
1647 std::vector
<Node
> children
;
1648 children
.push_back(proven
);
1649 std::vector
<Node
> args
;
1650 args
.push_back(fullConflictNeg
);
1651 if (conflict
== d_false
)
1653 AlwaysAssert(proven
== fullConflictNeg
);
1657 if (fullConflict
!= conflict
)
1659 // ------------------------- explained ---------- from theory
1660 // fullConflict => conflict ~conflict
1661 // --------------------------------------------
1662 // MACRO_SR_PRED_TRANSFORM ~fullConflict
1663 children
.push_back(conflict
.notNode());
1664 args
.push_back(mkMethodId(MethodId::SB_LITERAL
));
1665 d_lazyProof
->addStep(
1666 fullConflictNeg
, PfRule::MACRO_SR_PRED_TRANSFORM
, children
, args
);
1670 // pass the processed trust node
1672 TrustNode::mkTrustConflict(fullConflict
, d_lazyProof
.get());
1673 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< "): full = " << fullConflict
<< endl
;
1674 Assert(properConflict(fullConflict
));
1675 Trace("te-proof-debug")
1676 << "Check closed conflict with sharing" << std::endl
;
1677 tconf
.debugCheckClosed("te-proof-debug", "TheoryEngine::conflict:sharing");
1678 lemma(tconf
, LemmaProperty::REMOVABLE
);
1680 // When only one theory, the conflict should need no processing
1681 Assert(properConflict(conflict
));
1682 // pass the trust node that was sent from the theory
1683 lemma(tconflict
, LemmaProperty::REMOVABLE
, THEORY_LAST
, theoryId
);
1687 theory::TrustNode
TheoryEngine::getExplanation(
1688 std::vector
<NodeTheoryPair
>& explanationVector
)
1690 Assert(explanationVector
.size() > 0);
1692 unsigned i
= 0; // Index of the current literal we are processing
1693 unsigned j
= 0; // Index of the last literal we are keeping
1695 // cache of nodes we have already explained by some theory
1696 std::unordered_map
<Node
, size_t, NodeHashFunction
> cache
;
1698 while (i
< explanationVector
.size()) {
1699 // Get the current literal to explain
1700 NodeTheoryPair toExplain
= explanationVector
[i
];
1702 Debug("theory::explain")
1703 << "[i=" << i
<< "] TheoryEngine::explain(): processing ["
1704 << toExplain
.d_timestamp
<< "] " << toExplain
.d_node
<< " sent from "
1705 << toExplain
.d_theory
<< endl
;
1707 if (cache
.find(toExplain
.d_node
) != cache
.end()
1708 && cache
[toExplain
.d_node
] < toExplain
.d_timestamp
)
1713 cache
[toExplain
.d_node
] = toExplain
.d_timestamp
;
1715 // If a true constant or a negation of a false constant we can ignore it
1716 if (toExplain
.d_node
.isConst() && toExplain
.d_node
.getConst
<bool>())
1721 if (toExplain
.d_node
.getKind() == kind::NOT
&& toExplain
.d_node
[0].isConst()
1722 && !toExplain
.d_node
[0].getConst
<bool>())
1728 // If from the SAT solver, keep it
1729 if (toExplain
.d_theory
== THEORY_SAT_SOLVER
)
1731 Debug("theory::explain") << "\tLiteral came from THEORY_SAT_SOLVER. Kepping it." << endl
;
1732 explanationVector
[j
++] = explanationVector
[i
++];
1736 // If an and, expand it
1737 if (toExplain
.d_node
.getKind() == kind::AND
)
1739 Debug("theory::explain")
1740 << "TheoryEngine::explain(): expanding " << toExplain
.d_node
1741 << " got from " << toExplain
.d_theory
<< endl
;
1742 for (unsigned k
= 0; k
< toExplain
.d_node
.getNumChildren(); ++k
)
1744 NodeTheoryPair
newExplain(
1745 toExplain
.d_node
[k
], toExplain
.d_theory
, toExplain
.d_timestamp
);
1746 explanationVector
.push_back(newExplain
);
1752 // See if it was sent to the theory by another theory
1753 PropagationMap::const_iterator find
= d_propagationMap
.find(toExplain
);
1754 if (find
!= d_propagationMap
.end()) {
1755 Debug("theory::explain")
1756 << "\tTerm was propagated by another theory (theory = "
1757 << getTheoryString((*find
).second
.d_theory
) << ")" << std::endl
;
1758 // There is some propagation, check if its a timely one
1759 if ((*find
).second
.d_timestamp
< toExplain
.d_timestamp
)
1761 Debug("theory::explain")
1762 << "\tRelevant timetsamp, pushing " << (*find
).second
.d_node
1763 << "to index = " << explanationVector
.size() << std::endl
;
1764 explanationVector
.push_back((*find
).second
);
1772 if (toExplain
.d_theory
== THEORY_BUILTIN
)
1774 explanation
= d_sharedTerms
.explain(toExplain
.d_node
);
1775 Debug("theory::explain") << "\tTerm was propagated by THEORY_BUILTIN. Explanation: " << explanation
<< std::endl
;
1779 TrustNode texp
= theoryOf(toExplain
.d_theory
)->explain(toExplain
.d_node
);
1780 explanation
= texp
.getNode();
1781 Debug("theory::explain") << "\tTerm was propagated by owner theory: "
1782 << theoryOf(toExplain
.d_theory
)->getId()
1783 << ". Explanation: " << explanation
<< std::endl
;
1786 Debug("theory::explain")
1787 << "TheoryEngine::explain(): got explanation " << explanation
1788 << " got from " << toExplain
.d_theory
<< endl
;
1789 Assert(explanation
!= toExplain
.d_node
)
1790 << "wasn't sent to you, so why are you explaining it trivially";
1791 // Mark the explanation
1792 NodeTheoryPair
newExplain(
1793 explanation
, toExplain
.d_theory
, toExplain
.d_timestamp
);
1794 explanationVector
.push_back(newExplain
);
1799 // Keep only the relevant literals
1800 explanationVector
.resize(j
);
1802 Node expNode
= mkExplanation(explanationVector
);
1803 return theory::TrustNode::mkTrustLemma(expNode
, nullptr);
1806 bool TheoryEngine::isProofEnabled() const { return d_pnm
!= nullptr; }
1808 void TheoryEngine::setUserAttribute(const std::string
& attr
,
1810 const std::vector
<Node
>& node_values
,
1811 const std::string
& str_value
)
1813 Trace("te-attr") << "set user attribute " << attr
<< " " << n
<< endl
;
1814 if( d_attr_handle
.find( attr
)!=d_attr_handle
.end() ){
1815 for( size_t i
=0; i
<d_attr_handle
[attr
].size(); i
++ ){
1816 d_attr_handle
[attr
][i
]->setUserAttribute(attr
, n
, node_values
, str_value
);
1819 //unhandled exception?
1823 void TheoryEngine::handleUserAttribute(const char* attr
, Theory
* t
) {
1824 Trace("te-attr") << "Handle user attribute " << attr
<< " " << t
<< endl
;
1825 std::string
str( attr
);
1826 d_attr_handle
[ str
].push_back( t
);
1829 void TheoryEngine::checkTheoryAssertionsWithModel(bool hardFailure
) {
1830 for(TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
1831 Theory
* theory
= d_theoryTable
[theoryId
];
1832 if(theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
1833 for(context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
1834 it_end
= theory
->facts_end();
1837 Node assertion
= (*it
).d_assertion
;
1838 if (!isRelevant(assertion
))
1840 // not relevant, skip
1843 Node val
= d_tc
->getModel()->getValue(assertion
);
1846 std::stringstream ss
;
1847 ss
<< " " << theoryId
1848 << " has an asserted fact that the model doesn't satisfy." << endl
1849 << "The fact: " << assertion
<< endl
1850 << "Model value: " << val
<< endl
;
1855 // Always an error if it is false
1856 InternalError() << ss
.str();
1860 // Otherwise just a warning. Notice this case may happen for
1861 // assertions with unevaluable operators, e.g. transcendental
1862 // functions. It also may happen for separation logic, where
1863 // check-model support is limited.
1864 Warning() << ss
.str();
1873 std::pair
<bool, Node
> TheoryEngine::entailmentCheck(options::TheoryOfMode mode
,
1876 TNode atom
= (lit
.getKind() == kind::NOT
) ? lit
[0] : lit
;
1877 if( atom
.getKind()==kind::AND
|| atom
.getKind()==kind::OR
|| atom
.getKind()==kind::IMPLIES
){
1878 //Boolean connective, recurse
1879 std::vector
< Node
> children
;
1880 bool pol
= (lit
.getKind()!=kind::NOT
);
1881 bool is_conjunction
= pol
==(lit
.getKind()==kind::AND
);
1882 for( unsigned i
=0; i
<atom
.getNumChildren(); i
++ ){
1884 if( pol
==( lit
.getKind()==kind::IMPLIES
&& i
==0 ) ){
1885 ch
= atom
[i
].negate();
1887 std::pair
<bool, Node
> chres
= entailmentCheck(mode
, ch
);
1889 if( !is_conjunction
){
1892 children
.push_back( chres
.second
);
1894 }else if( !chres
.first
&& is_conjunction
){
1895 return std::pair
<bool, Node
>(false, Node::null());
1898 if( is_conjunction
){
1899 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, children
));
1901 return std::pair
<bool, Node
>(false, Node::null());
1903 }else if( atom
.getKind()==kind::ITE
|| ( atom
.getKind()==kind::EQUAL
&& atom
[0].getType().isBoolean() ) ){
1904 bool pol
= (lit
.getKind()!=kind::NOT
);
1905 for( unsigned r
=0; r
<2; r
++ ){
1910 std::pair
<bool, Node
> chres
= entailmentCheck(mode
, ch
);
1912 Node ch2
= atom
[ atom
.getKind()==kind::ITE
? r
+1 : 1 ];
1913 if( pol
==( atom
.getKind()==kind::ITE
? true : r
==1 ) ){
1916 std::pair
<bool, Node
> chres2
= entailmentCheck(mode
, ch2
);
1918 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, chres
.second
, chres2
.second
));
1924 return std::pair
<bool, Node
>(false, Node::null());
1926 //it is a theory atom
1927 theory::TheoryId tid
= theory::Theory::theoryOf(mode
, atom
);
1928 theory::Theory
* th
= theoryOf(tid
);
1931 Trace("theory-engine-entc") << "Entailment check : " << lit
<< std::endl
;
1933 std::pair
<bool, Node
> chres
= th
->entailmentCheck(lit
);
1938 void TheoryEngine::spendResource(ResourceManager::Resource r
)
1940 d_resourceManager
->spendResource(r
);
1943 }/* CVC4 namespace */