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_STRINGS) \
86 CVC4_FOR_EACH_THEORY_STATEMENT(CVC4::theory::THEORY_QUANTIFIERS)
90 /* -------------------------------------------------------------------------- */
92 inline void flattenAnd(Node n
, std::vector
<TNode
>& out
){
93 Assert(n
.getKind() == kind::AND
);
94 for(Node::iterator i
=n
.begin(), i_end
=n
.end(); i
!= i_end
; ++i
){
96 if(curr
.getKind() == kind::AND
){
97 flattenAnd(curr
, out
);
104 inline Node
flattenAnd(Node n
){
105 std::vector
<TNode
> out
;
107 return NodeManager::currentNM()->mkNode(kind::AND
, out
);
111 * Compute the string for a given theory id. In this module, we use
112 * THEORY_SAT_SOLVER as an id, which is not a normal id but maps to
113 * THEORY_LAST. Thus, we need our own string conversion here.
115 * @param id The theory id
116 * @return The string corresponding to the theory id
118 std::string
getTheoryString(theory::TheoryId id
)
120 if (id
== theory::THEORY_SAT_SOLVER
)
122 return "THEORY_SAT_SOLVER";
126 std::stringstream ss
;
132 void TheoryEngine::finishInit() {
133 // NOTE: This seems to be required since
134 // theory::TheoryTraits<THEORY>::isParametric cannot be accessed without
135 // using the CVC4_FOR_EACH_THEORY_STATEMENT macro. -AJR
136 std::vector
<theory::Theory
*> paraTheories
;
137 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
138 #undef CVC4_FOR_EACH_THEORY_STATEMENT
140 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
141 if (theory::TheoryTraits<THEORY>::isParametric \
142 && d_logicInfo.isTheoryEnabled(THEORY)) \
144 paraTheories.push_back(theoryOf(THEORY)); \
146 // Collect the parametric theories, which are given to the theory combination
148 CVC4_FOR_EACH_THEORY
;
150 // Initialize the theory combination architecture
151 if (options::tcMode() == options::TcMode::CARE_GRAPH
)
153 d_tc
.reset(new CombinationCareGraph(*this, paraTheories
, d_pnm
));
157 Unimplemented() << "TheoryEngine::finishInit: theory combination mode "
158 << options::tcMode() << " not supported";
160 // create the relevance filter if any option requires it
161 if (options::relevanceFilter())
164 new RelevanceManager(d_userContext
, theory::Valuation(this)));
167 // initialize the quantifiers engine
168 if (d_logicInfo
.isQuantified())
170 // initialize the quantifiers engine
171 d_quantEngine
= new QuantifiersEngine(this, *d_decManager
.get(), d_pnm
);
173 // initialize the theory combination manager, which decides and allocates the
174 // equality engines to use for all theories.
177 // set the core equality engine on quantifiers engine
178 if (d_logicInfo
.isQuantified())
180 d_quantEngine
->setMasterEqualityEngine(d_tc
->getCoreEqualityEngine());
183 // finish initializing the theories by linking them with the appropriate
184 // utilities and then calling their finishInit method.
185 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
186 Theory
* t
= d_theoryTable
[theoryId
];
191 // setup the pointers to the utilities
192 const EeTheoryInfo
* eeti
= d_tc
->getEeTheoryInfo(theoryId
);
193 Assert(eeti
!= nullptr);
194 // the theory's official equality engine is the one specified by the
195 // equality engine manager
196 t
->setEqualityEngine(eeti
->d_usedEe
);
197 // set the quantifiers engine
198 t
->setQuantifiersEngine(d_quantEngine
);
199 // set the decision manager for the theory
200 t
->setDecisionManager(d_decManager
.get());
201 // finish initializing the theory
205 // finish initializing the quantifiers engine
206 if (d_logicInfo
.isQuantified())
208 d_quantEngine
->finishInit();
212 TheoryEngine::TheoryEngine(context::Context
* context
,
213 context::UserContext
* userContext
,
215 RemoveTermFormulas
& iteRemover
,
216 const LogicInfo
& logicInfo
,
217 OutputManager
& outMgr
)
218 : d_propEngine(nullptr),
220 d_userContext(userContext
),
221 d_logicInfo(logicInfo
),
225 d_pnm
!= nullptr ? new LazyCDProof(
226 d_pnm
, nullptr, d_userContext
, "TheoryEngine::LazyCDProof")
228 d_tepg(new TheoryEngineProofGenerator(d_pnm
, d_userContext
)),
229 d_sharedTerms(this, context
),
231 d_quantEngine(nullptr),
232 d_decManager(new DecisionManager(userContext
)),
233 d_relManager(nullptr),
234 d_preRegistrationVisitor(this, context
),
235 d_sharedTermsVisitor(d_sharedTerms
),
236 d_eager_model_building(false),
237 d_inConflict(context
, false),
239 d_hasShutDown(false),
240 d_incomplete(context
, false),
241 d_propagationMap(context
),
242 d_propagationMapTimestamp(context
, 0),
243 d_propagatedLiterals(context
),
244 d_propagatedLiteralsIndex(context
, 0),
245 d_atomRequests(context
),
246 d_tpp(*this, iteRemover
),
247 d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
250 d_interrupted(false),
251 d_resourceManager(rm
),
252 d_inPreregister(false),
253 d_factsAsserted(context
, false),
255 d_arithSubstitutionsAdded("theory::arith::zzz::arith::substitutions", 0)
257 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
;
260 d_theoryTable
[theoryId
] = NULL
;
261 d_theoryOut
[theoryId
] = NULL
;
264 smtStatisticsRegistry()->registerStat(&d_combineTheoriesTime
);
265 d_true
= NodeManager::currentNM()->mkConst
<bool>(true);
266 d_false
= NodeManager::currentNM()->mkConst
<bool>(false);
268 smtStatisticsRegistry()->registerStat(&d_arithSubstitutionsAdded
);
271 TheoryEngine::~TheoryEngine() {
272 Assert(d_hasShutDown
);
274 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
!= theory::THEORY_LAST
; ++ theoryId
) {
275 if(d_theoryTable
[theoryId
] != NULL
) {
276 delete d_theoryTable
[theoryId
];
277 delete d_theoryOut
[theoryId
];
281 delete d_quantEngine
;
283 smtStatisticsRegistry()->unregisterStat(&d_combineTheoriesTime
);
284 smtStatisticsRegistry()->unregisterStat(&d_arithSubstitutionsAdded
);
287 void TheoryEngine::interrupt() { d_interrupted
= true; }
288 void TheoryEngine::preRegister(TNode preprocessed
) {
289 Debug("theory") << "TheoryEngine::preRegister( " << preprocessed
<< ")"
291 d_preregisterQueue
.push(preprocessed
);
293 if (!d_inPreregister
) {
294 // We're in pre-register
295 d_inPreregister
= true;
297 // Process the pre-registration queue
298 while (!d_preregisterQueue
.empty()) {
299 // Get the next atom to pre-register
300 preprocessed
= d_preregisterQueue
.front();
301 d_preregisterQueue
.pop();
303 if (d_logicInfo
.isSharingEnabled() && preprocessed
.getKind() == kind::EQUAL
) {
304 // When sharing is enabled, we propagate from the shared terms manager also
305 d_sharedTerms
.addEqualityToPropagate(preprocessed
);
308 // the atom should not have free variables
309 Debug("theory") << "TheoryEngine::preRegister: " << preprocessed
311 Assert(!expr::hasFreeVar(preprocessed
));
313 // Pre-register the terms in the atom
314 theory::TheoryIdSet theories
= NodeVisitor
<PreRegisterVisitor
>::run(
315 d_preRegistrationVisitor
, preprocessed
);
316 theories
= TheoryIdSetUtil::setRemove(THEORY_BOOL
, theories
);
317 // Remove the top theory, if any more that means multiple theories were
319 bool multipleTheories
=
320 TheoryIdSetUtil::setRemove(Theory::theoryOf(preprocessed
), theories
);
321 if (Configuration::isAssertionBuild())
324 // This should never throw an exception, since theories should be
325 // guaranteed to be initialized.
326 // These checks don't work with finite model finding, because it
327 // uses Rational constants to represent cardinality constraints,
328 // even though arithmetic isn't actually involved.
329 if (!options::finiteModelFind())
331 while ((i
= TheoryIdSetUtil::setPop(theories
)) != THEORY_LAST
)
333 if (!d_logicInfo
.isTheoryEnabled(i
))
335 LogicInfo newLogicInfo
= d_logicInfo
.getUnlockedCopy();
336 newLogicInfo
.enableTheory(i
);
338 std::stringstream ss
;
339 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
340 << ", which doesn't include " << i
341 << ", but found a term in that theory." << std::endl
342 << "You might want to extend your logic to "
343 << newLogicInfo
.getLogicString() << std::endl
;
344 throw LogicException(ss
.str());
349 if (multipleTheories
) {
350 // Collect the shared terms if there are multiple theories
351 NodeVisitor
<SharedTermsVisitor
>::run(d_sharedTermsVisitor
,
356 // Leaving pre-register
357 d_inPreregister
= false;
361 void TheoryEngine::printAssertions(const char* tag
) {
362 if (Trace
.isOn(tag
)) {
364 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
365 Theory
* theory
= d_theoryTable
[theoryId
];
366 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
367 Trace(tag
) << "--------------------------------------------" << endl
;
368 Trace(tag
) << "Assertions of " << theory
->getId() << ": " << endl
;
370 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
373 for (unsigned i
= 0; it
!= it_end
; ++it
, ++i
)
375 if ((*it
).d_isPreregistered
)
377 Trace(tag
) << "[" << i
<< "]: ";
381 Trace(tag
) << "(" << i
<< "): ";
383 Trace(tag
) << (*it
).d_assertion
<< endl
;
387 if (d_logicInfo
.isSharingEnabled()) {
388 Trace(tag
) << "Shared terms of " << theory
->getId() << ": " << endl
;
389 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
390 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
391 Trace(tag
) << "[" << i
<< "]: " << (*it
) << endl
;
399 void TheoryEngine::dumpAssertions(const char* tag
) {
400 if (Dump
.isOn(tag
)) {
401 const Printer
& printer
= d_outMgr
.getPrinter();
402 std::ostream
& out
= d_outMgr
.getDumpOut();
403 printer
.toStreamCmdComment(out
, "Starting completeness check");
404 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
405 Theory
* theory
= d_theoryTable
[theoryId
];
406 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
407 printer
.toStreamCmdComment(out
, "Completeness check");
408 printer
.toStreamCmdPush(out
);
410 // Dump the shared terms
411 if (d_logicInfo
.isSharingEnabled()) {
412 printer
.toStreamCmdComment(out
, "Shared terms");
413 context::CDList
<TNode
>::const_iterator it
= theory
->shared_terms_begin(), it_end
= theory
->shared_terms_end();
414 for (unsigned i
= 0; it
!= it_end
; ++ it
, ++i
) {
417 printer
.toStreamCmdComment(out
, ss
.str());
421 // Dump the assertions
422 printer
.toStreamCmdComment(out
, "Assertions");
423 context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(), it_end
= theory
->facts_end();
424 for (; it
!= it_end
; ++ it
) {
426 Node assertionNode
= (*it
).d_assertion
;
427 // Purify all the terms
429 if ((*it
).d_isPreregistered
)
431 printer
.toStreamCmdComment(out
, "Preregistered");
435 printer
.toStreamCmdComment(out
, "Shared assertion");
437 printer
.toStreamCmdAssert(out
, assertionNode
);
439 printer
.toStreamCmdCheckSat(out
);
441 printer
.toStreamCmdPop(out
);
448 * Check all (currently-active) theories for conflicts.
449 * @param effort the effort level to use
451 void TheoryEngine::check(Theory::Effort effort
) {
454 // Reset the interrupt flag
455 d_interrupted
= false;
457 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
458 #undef CVC4_FOR_EACH_THEORY_STATEMENT
460 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
461 if (theory::TheoryTraits<THEORY>::hasCheck \
462 && d_logicInfo.isTheoryEnabled(THEORY)) \
464 theoryOf(THEORY)->check(effort); \
467 Debug("conflict") << THEORY << " in conflict. " << std::endl; \
475 // Mark the output channel unused (if this is FULL_EFFORT, and nothing
476 // is done by the theories, no additional check will be needed)
477 d_outputChannelUsed
= false;
479 // Mark the lemmas flag (no lemmas added)
480 d_lemmasAdded
= false;
482 Debug("theory") << "TheoryEngine::check(" << effort
<< "): d_factsAsserted = " << (d_factsAsserted
? "true" : "false") << endl
;
484 // If in full effort, we have a fake new assertion just to jumpstart the checking
485 if (Theory::fullEffort(effort
)) {
486 d_factsAsserted
= true;
487 // Reset round for the relevance manager, which notice only sets a flag
488 // to indicate that its information must be recomputed.
489 if (d_relManager
!= nullptr)
491 d_relManager
->resetRound();
497 while (d_factsAsserted
&& !d_inConflict
&& !d_lemmasAdded
) {
499 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running check" << endl
;
501 Trace("theory::assertions") << endl
;
502 if (Trace
.isOn("theory::assertions")) {
503 printAssertions("theory::assertions");
506 if(Theory::fullEffort(effort
)) {
507 Trace("theory::assertions::fulleffort") << endl
;
508 if (Trace
.isOn("theory::assertions::fulleffort")) {
509 printAssertions("theory::assertions::fulleffort");
513 // Note that we've discharged all the facts
514 d_factsAsserted
= false;
517 CVC4_FOR_EACH_THEORY
;
519 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running propagation after the initial check" << endl
;
521 // We are still satisfiable, propagate as much as possible
524 // We do combination if all has been processed and we are in fullcheck
525 if (Theory::fullEffort(effort
) && d_logicInfo
.isSharingEnabled() && !d_factsAsserted
&& !d_lemmasAdded
&& !d_inConflict
) {
526 // Do the combination
527 Debug("theory") << "TheoryEngine::check(" << effort
<< "): running combination" << endl
;
529 TimerStat::CodeTimer
combineTheoriesTimer(d_combineTheoriesTime
);
530 d_tc
->combineTheories();
532 if(d_logicInfo
.isQuantified()){
533 d_quantEngine
->notifyCombineTheories();
538 // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
539 if( Theory::fullEffort(effort
) && ! d_inConflict
&& ! needCheck() ) {
540 Trace("theory::assertions-model") << endl
;
541 if (Trace
.isOn("theory::assertions-model")) {
542 printAssertions("theory::assertions-model");
544 // reset the model in the combination engine
546 //checks for theories requiring the model go at last call
547 for (TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
548 if( theoryId
!=THEORY_QUANTIFIERS
){
549 Theory
* theory
= d_theoryTable
[theoryId
];
550 if (theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
551 if( theory
->needsCheckLastEffort() ){
552 if (!d_tc
->buildModel())
556 theory
->check(Theory::EFFORT_LAST_CALL
);
563 if(d_logicInfo
.isQuantified()) {
564 // quantifiers engine must check at last call effort
565 d_quantEngine
->check(Theory::EFFORT_LAST_CALL
);
568 if (!d_inConflict
&& !needCheck())
570 // If d_eager_model_building is false, then we only mark that we
571 // are in "SAT mode". We build the model later only if the user asks
572 // for it via getBuiltModel.
574 if (d_eager_model_building
)
581 Debug("theory") << "TheoryEngine::check(" << effort
<< "): done, we are " << (d_inConflict
? "unsat" : "sat") << (d_lemmasAdded
? " with new lemmas" : " with no new lemmas");
582 Debug("theory") << ", need check = " << (needCheck() ? "YES" : "NO") << endl
;
584 if( Theory::fullEffort(effort
) && !d_inConflict
&& !needCheck()) {
585 // Do post-processing of model from the theories (e.g. used for THEORY_SEP
586 // to construct heap model)
587 d_tc
->postProcessModel(d_incomplete
.get());
589 } catch(const theory::Interrupted
&) {
590 Trace("theory") << "TheoryEngine::check() => interrupted" << endl
;
592 // If fulleffort, check all theories
593 if(Dump
.isOn("theory::fullcheck") && Theory::fullEffort(effort
)) {
594 if (!d_inConflict
&& !needCheck()) {
595 dumpAssertions("theory::fullcheck");
600 void TheoryEngine::propagate(Theory::Effort effort
)
602 // Reset the interrupt flag
603 d_interrupted
= false;
605 // Definition of the statement that is to be run by every theory
606 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
607 #undef CVC4_FOR_EACH_THEORY_STATEMENT
609 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
610 if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
611 theoryOf(THEORY)->propagate(effort); \
614 // Reset the interrupt flag
615 d_interrupted
= false;
617 // Propagate for each theory using the statement above
618 CVC4_FOR_EACH_THEORY
;
621 Node
TheoryEngine::getNextDecisionRequest()
623 return d_decManager
->getNextDecisionRequest();
626 bool TheoryEngine::properConflict(TNode conflict
) const {
628 if (conflict
.getKind() == kind::AND
) {
629 for (unsigned i
= 0; i
< conflict
.getNumChildren(); ++ i
) {
630 if (! getPropEngine()->hasValue(conflict
[i
], value
)) {
631 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
632 << conflict
[i
] << endl
;
636 Debug("properConflict") << "Bad conflict is due to false atom: "
637 << conflict
[i
] << endl
;
640 if (conflict
[i
] != Rewriter::rewrite(conflict
[i
])) {
641 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
642 << conflict
[i
] << " vs " << Rewriter::rewrite(conflict
[i
]) << endl
;
647 if (! getPropEngine()->hasValue(conflict
, value
)) {
648 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
653 Debug("properConflict") << "Bad conflict is due to false atom: "
657 if (conflict
!= Rewriter::rewrite(conflict
)) {
658 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
659 << conflict
<< " vs " << Rewriter::rewrite(conflict
) << endl
;
666 TheoryModel
* TheoryEngine::getModel()
668 Assert(d_tc
!= nullptr);
669 TheoryModel
* m
= d_tc
->getModel();
670 Assert(m
!= nullptr);
674 TheoryModel
* TheoryEngine::getBuiltModel()
676 Assert(d_tc
!= nullptr);
677 // If this method was called, we should be in SAT mode, and produceModels
679 AlwaysAssert(options::produceModels());
682 // not available, perhaps due to interuption.
685 // must build model at this point
686 if (!d_tc
->buildModel())
690 return d_tc
->getModel();
693 bool TheoryEngine::buildModel()
695 Assert(d_tc
!= nullptr);
696 return d_tc
->buildModel();
699 bool TheoryEngine::getSynthSolutions(
700 std::map
<Node
, std::map
<Node
, Node
>>& sol_map
)
704 return d_quantEngine
->getSynthSolutions(sol_map
);
706 // we are not in a quantified logic, there is no synthesis solution
710 bool TheoryEngine::presolve() {
711 // Reset the interrupt flag
712 d_interrupted
= false;
714 // Reset the decision manager. This clears its decision strategies that are
715 // no longer valid in this user context.
716 d_decManager
->presolve();
719 // Definition of the statement that is to be run by every theory
720 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
721 #undef CVC4_FOR_EACH_THEORY_STATEMENT
723 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
724 if (theory::TheoryTraits<THEORY>::hasPresolve) { \
725 theoryOf(THEORY)->presolve(); \
731 // Presolve for each theory using the statement above
732 CVC4_FOR_EACH_THEORY
;
733 } catch(const theory::Interrupted
&) {
734 Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl
;
736 // return whether we have a conflict
738 }/* TheoryEngine::presolve() */
740 void TheoryEngine::postsolve() {
741 // no longer in SAT mode
743 // Reset the interrupt flag
744 d_interrupted
= false;
745 bool CVC4_UNUSED wasInConflict
= d_inConflict
;
748 // Definition of the statement that is to be run by every theory
749 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
750 #undef CVC4_FOR_EACH_THEORY_STATEMENT
752 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
753 if (theory::TheoryTraits<THEORY>::hasPostsolve) \
755 theoryOf(THEORY)->postsolve(); \
756 Assert(!d_inConflict || wasInConflict) \
757 << "conflict raised during postsolve()"; \
760 // Postsolve for each theory using the statement above
761 CVC4_FOR_EACH_THEORY
;
762 } catch(const theory::Interrupted
&) {
763 Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl
;
765 }/* TheoryEngine::postsolve() */
768 void TheoryEngine::notifyRestart() {
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>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
778 theoryOf(THEORY)->notifyRestart(); \
781 // notify each theory using the statement above
782 CVC4_FOR_EACH_THEORY
;
785 void TheoryEngine::ppStaticLearn(TNode in
, NodeBuilder
<>& learned
) {
786 // Reset the interrupt flag
787 d_interrupted
= false;
789 // Definition of the statement that is to be run by every theory
790 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
791 #undef CVC4_FOR_EACH_THEORY_STATEMENT
793 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
794 if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) { \
795 theoryOf(THEORY)->ppStaticLearn(in, learned); \
798 // static learning for each theory using the statement above
799 CVC4_FOR_EACH_THEORY
;
802 bool TheoryEngine::isRelevant(Node lit
) const
804 if (d_relManager
!= nullptr)
806 return d_relManager
->isRelevant(lit
);
808 // otherwise must assume its relevant
812 void TheoryEngine::shutdown() {
813 // Set this first; if a Theory shutdown() throws an exception,
814 // at least the destruction of the TheoryEngine won't confound
816 d_hasShutDown
= true;
818 // Shutdown all the theories
819 for(TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
; ++theoryId
) {
820 if(d_theoryTable
[theoryId
]) {
821 theoryOf(theoryId
)->shutdown();
828 theory::Theory::PPAssertStatus
TheoryEngine::solve(TNode literal
, SubstitutionMap
& substitutionOut
) {
829 // Reset the interrupt flag
830 d_interrupted
= false;
832 TNode atom
= literal
.getKind() == kind::NOT
? literal
[0] : literal
;
833 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< "): solving with " << theoryOf(atom
)->getId() << endl
;
835 if(! d_logicInfo
.isTheoryEnabled(Theory::theoryOf(atom
)) &&
836 Theory::theoryOf(atom
) != THEORY_SAT_SOLVER
) {
838 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
839 << ", which doesn't include " << Theory::theoryOf(atom
)
840 << ", but got a preprocessing-time fact for that theory." << endl
841 << "The fact:" << endl
843 throw LogicException(ss
.str());
846 Theory::PPAssertStatus solveStatus
= theoryOf(atom
)->ppAssert(literal
, substitutionOut
);
847 Trace("theory::solve") << "TheoryEngine::solve(" << literal
<< ") => " << solveStatus
<< endl
;
851 void TheoryEngine::preprocessStart() { d_tpp
.clearCache(); }
853 Node
TheoryEngine::preprocess(TNode assertion
) {
854 TrustNode trn
= d_tpp
.theoryPreprocess(assertion
);
860 return trn
.getNode();
863 void TheoryEngine::notifyPreprocessedAssertions(
864 const std::vector
<Node
>& assertions
) {
865 // call all the theories
866 for (TheoryId theoryId
= theory::THEORY_FIRST
; theoryId
< theory::THEORY_LAST
;
868 if (d_theoryTable
[theoryId
]) {
869 theoryOf(theoryId
)->ppNotifyAssertions(assertions
);
872 if (d_relManager
!= nullptr)
874 d_relManager
->notifyPreprocessedAssertions(assertions
);
878 bool TheoryEngine::markPropagation(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
880 // What and where we are asserting
881 NodeTheoryPair
toAssert(assertion
, toTheoryId
, d_propagationMapTimestamp
);
882 // What and where it came from
883 NodeTheoryPair
toExplain(originalAssertion
, fromTheoryId
, d_propagationMapTimestamp
);
885 // See if the theory already got this literal
886 PropagationMap::const_iterator find
= d_propagationMap
.find(toAssert
);
887 if (find
!= d_propagationMap
.end()) {
888 // The theory already knows this
889 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl
;
893 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp
<< "] " << assertion
<< ", " << toTheoryId
<< " from " << originalAssertion
<< ", " << fromTheoryId
<< endl
;
895 // Mark the propagation
896 d_propagationMap
[toAssert
] = toExplain
;
897 d_propagationMapTimestamp
= d_propagationMapTimestamp
+ 1;
903 void TheoryEngine::assertToTheory(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
) {
905 Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << originalAssertion
<< "," << toTheoryId
<< ", " << fromTheoryId
<< ")" << endl
;
907 Assert(toTheoryId
!= fromTheoryId
);
908 if(toTheoryId
!= THEORY_SAT_SOLVER
&&
909 ! d_logicInfo
.isTheoryEnabled(toTheoryId
)) {
911 ss
<< "The logic was specified as " << d_logicInfo
.getLogicString()
912 << ", which doesn't include " << toTheoryId
913 << ", but got an asserted fact to that theory." << endl
914 << "The fact:" << endl
916 throw LogicException(ss
.str());
923 // If sharing is disabled, things are easy
924 if (!d_logicInfo
.isSharingEnabled()) {
925 Assert(assertion
== originalAssertion
);
926 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
927 // Send to the apropriate theory
928 theory::Theory
* toTheory
= theoryOf(toTheoryId
);
929 // We assert it, and we know it's preregistereed
930 toTheory
->assertFact(assertion
, true);
931 // Mark that we have more information
932 d_factsAsserted
= true;
934 Assert(toTheoryId
== THEORY_SAT_SOLVER
);
935 // Check for propositional conflict
937 if (d_propEngine
->hasValue(assertion
, value
)) {
939 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion
<< ", " << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (no sharing)" << endl
;
940 Trace("dtview::conflict")
941 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
947 d_propagatedLiterals
.push_back(assertion
);
952 // Polarity of the assertion
953 bool polarity
= assertion
.getKind() != kind::NOT
;
955 // Atom of the assertion
956 TNode atom
= polarity
? assertion
: assertion
[0];
958 // If sending to the shared terms database, it's also simple
959 if (toTheoryId
== THEORY_BUILTIN
) {
960 Assert(atom
.getKind() == kind::EQUAL
)
961 << "atom should be an EQUALity, not `" << atom
<< "'";
962 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
963 d_sharedTerms
.assertEquality(atom
, polarity
, assertion
);
968 // Things from the SAT solver are already normalized, so they go
969 // directly to the apropriate theory
970 if (fromTheoryId
== THEORY_SAT_SOLVER
) {
971 // We know that this is normalized, so just send it off to the theory
972 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
973 // Is it preregistered
974 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
976 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
977 // Mark that we have more information
978 d_factsAsserted
= true;
983 // Propagations to the SAT solver are just enqueued for pickup by
984 // the SAT solver later
985 if (toTheoryId
== THEORY_SAT_SOLVER
) {
986 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
987 // Enqueue for propagation to the SAT solver
988 d_propagatedLiterals
.push_back(assertion
);
989 // Check for propositional conflicts
991 if (d_propEngine
->hasValue(assertion
, value
) && !value
) {
992 Trace("theory::propagate")
993 << "TheoryEngine::assertToTheory(" << assertion
<< ", "
994 << toTheoryId
<< ", " << fromTheoryId
<< "): conflict (sharing)"
996 Trace("dtview::conflict")
997 << ":THEORY-CONFLICT: " << assertion
<< std::endl
;
1004 Assert(atom
.getKind() == kind::EQUAL
);
1007 Node normalizedLiteral
= Rewriter::rewrite(assertion
);
1009 // See if it rewrites false directly -> conflict
1010 if (normalizedLiteral
.isConst()) {
1011 if (!normalizedLiteral
.getConst
<bool>()) {
1012 // Mark the propagation for explanations
1013 if (markPropagation(normalizedLiteral
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1014 // special case, trust node has no proof generator
1015 TrustNode trnn
= TrustNode::mkTrustConflict(normalizedLiteral
);
1016 // Get the explanation (conflict will figure out where it came from)
1017 conflict(trnn
, toTheoryId
);
1025 // Try and assert (note that we assert the non-normalized one)
1026 if (markPropagation(assertion
, originalAssertion
, toTheoryId
, fromTheoryId
)) {
1027 // Check if has been pre-registered with the theory
1028 bool preregistered
= d_propEngine
->isSatLiteral(assertion
) && Theory::theoryOf(assertion
) == toTheoryId
;
1030 theoryOf(toTheoryId
)->assertFact(assertion
, preregistered
);
1031 d_factsAsserted
= true;
1037 void TheoryEngine::assertFact(TNode literal
)
1039 Trace("theory") << "TheoryEngine::assertFact(" << literal
<< ")" << endl
;
1043 // If we're in conflict, nothing to do
1049 bool polarity
= literal
.getKind() != kind::NOT
;
1050 TNode atom
= polarity
? literal
: literal
[0];
1052 if (d_logicInfo
.isSharingEnabled()) {
1053 // If any shared terms, it's time to do sharing work
1054 if (d_sharedTerms
.hasSharedTerms(atom
)) {
1055 // Notify the theories the shared terms
1056 SharedTermsDatabase::shared_terms_iterator it
= d_sharedTerms
.begin(atom
);
1057 SharedTermsDatabase::shared_terms_iterator it_end
= d_sharedTerms
.end(atom
);
1058 for (; it
!= it_end
; ++ it
) {
1060 theory::TheoryIdSet theories
=
1061 d_sharedTerms
.getTheoriesToNotify(atom
, term
);
1062 for (TheoryId id
= THEORY_FIRST
; id
!= THEORY_LAST
; ++ id
) {
1063 if (TheoryIdSetUtil::setContains(id
, theories
))
1065 theoryOf(id
)->addSharedTerm(term
);
1068 d_sharedTerms
.markNotified(term
, theories
);
1072 // If it's an equality, assert it to the shared term manager, even though the terms are not
1073 // yet shared. As the terms become shared later, the shared terms manager will then add them
1074 // to the assert the equality to the interested theories
1075 if (atom
.getKind() == kind::EQUAL
) {
1076 // Assert it to the the owning theory
1077 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1078 // Shared terms manager will assert to interested theories directly, as
1079 // the terms become shared
1080 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ THEORY_SAT_SOLVER
);
1082 // Now, let's check for any atom triggers from lemmas
1083 AtomRequests::atom_iterator it
= d_atomRequests
.getAtomIterator(atom
);
1084 while (!it
.done()) {
1085 const AtomRequests::Request
& request
= it
.get();
1087 polarity
? (Node
)request
.d_atom
: request
.d_atom
.notNode();
1088 Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal
<< "): sending requested " << toAssert
<< endl
;
1090 toAssert
, literal
, request
.d_toTheory
, THEORY_SAT_SOLVER
);
1095 // Not an equality, just assert to the appropriate theory
1096 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1099 // Assert the fact to the appropriate theory directly
1100 assertToTheory(literal
, literal
, /* to */ Theory::theoryOf(atom
), /* from */ THEORY_SAT_SOLVER
);
1104 bool TheoryEngine::propagate(TNode literal
, theory::TheoryId theory
) {
1105 Debug("theory::propagate") << "TheoryEngine::propagate(" << literal
<< ", " << theory
<< ")" << endl
;
1107 Trace("dtview::prop") << std::string(d_context
->getLevel(), ' ')
1108 << ":THEORY-PROP: " << literal
<< endl
;
1113 bool polarity
= literal
.getKind() != kind::NOT
;
1114 TNode atom
= polarity
? literal
: literal
[0];
1116 if (d_logicInfo
.isSharingEnabled() && atom
.getKind() == kind::EQUAL
) {
1117 if (d_propEngine
->isSatLiteral(literal
)) {
1118 // We propagate SAT literals to SAT
1119 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1121 if (theory
!= THEORY_BUILTIN
) {
1122 // Assert to the shared terms database
1123 assertToTheory(literal
, literal
, /* to */ THEORY_BUILTIN
, /* from */ theory
);
1126 // Just send off to the SAT solver
1127 Assert(d_propEngine
->isSatLiteral(literal
));
1128 assertToTheory(literal
, literal
, /* to */ THEORY_SAT_SOLVER
, /* from */ theory
);
1131 return !d_inConflict
;
1134 const LogicInfo
& TheoryEngine::getLogicInfo() const { return d_logicInfo
; }
1136 theory::EqualityStatus
TheoryEngine::getEqualityStatus(TNode a
, TNode b
) {
1137 Assert(a
.getType().isComparableTo(b
.getType()));
1138 if (d_sharedTerms
.isShared(a
) && d_sharedTerms
.isShared(b
)) {
1139 if (d_sharedTerms
.areEqual(a
,b
)) {
1140 return EQUALITY_TRUE_AND_PROPAGATED
;
1142 else if (d_sharedTerms
.areDisequal(a
,b
)) {
1143 return EQUALITY_FALSE_AND_PROPAGATED
;
1146 return theoryOf(Theory::theoryOf(a
.getType()))->getEqualityStatus(a
, b
);
1149 Node
TheoryEngine::getModelValue(TNode var
) {
1152 // the model value of a constant must be itself
1155 Assert(d_sharedTerms
.isShared(var
));
1156 return theoryOf(Theory::theoryOf(var
.getType()))->getModelValue(var
);
1160 Node
TheoryEngine::ensureLiteral(TNode n
) {
1161 Debug("ensureLiteral") << "rewriting: " << n
<< std::endl
;
1162 Node rewritten
= Rewriter::rewrite(n
);
1163 Debug("ensureLiteral") << " got: " << rewritten
<< std::endl
;
1164 Node preprocessed
= preprocess(rewritten
);
1165 Debug("ensureLiteral") << "preprocessed: " << preprocessed
<< std::endl
;
1166 d_propEngine
->ensureLiteral(preprocessed
);
1167 return preprocessed
;
1171 void TheoryEngine::printInstantiations( std::ostream
& out
) {
1172 if( d_quantEngine
){
1173 d_quantEngine
->printInstantiations( out
);
1175 out
<< "Internal error : instantiations not available when quantifiers are not present." << std::endl
;
1180 void TheoryEngine::printSynthSolution( std::ostream
& out
) {
1181 if( d_quantEngine
){
1182 d_quantEngine
->printSynthSolution( out
);
1184 out
<< "Internal error : synth solution not available when quantifiers are not present." << std::endl
;
1189 void TheoryEngine::getInstantiatedQuantifiedFormulas( std::vector
< Node
>& qs
) {
1190 if( d_quantEngine
){
1191 d_quantEngine
->getInstantiatedQuantifiedFormulas( qs
);
1197 void TheoryEngine::getInstantiations( Node q
, std::vector
< Node
>& insts
) {
1198 if( d_quantEngine
){
1199 d_quantEngine
->getInstantiations( q
, insts
);
1205 void TheoryEngine::getInstantiationTermVectors( Node q
, std::vector
< std::vector
< Node
> >& tvecs
) {
1206 if( d_quantEngine
){
1207 d_quantEngine
->getInstantiationTermVectors( q
, tvecs
);
1213 void TheoryEngine::getInstantiations( std::map
< Node
, std::vector
< Node
> >& insts
) {
1214 if( d_quantEngine
){
1215 d_quantEngine
->getInstantiations( insts
);
1221 void TheoryEngine::getInstantiationTermVectors( std::map
< Node
, std::vector
< std::vector
< Node
> > >& insts
) {
1222 if( d_quantEngine
){
1223 d_quantEngine
->getInstantiationTermVectors( insts
);
1229 Node
TheoryEngine::getInstantiatedConjunction( Node q
) {
1230 if( d_quantEngine
){
1231 return d_quantEngine
->getInstantiatedConjunction( q
);
1234 return Node::null();
1239 static Node
mkExplanation(const std::vector
<NodeTheoryPair
>& explanation
) {
1241 std::set
<TNode
> all
;
1242 for (unsigned i
= 0; i
< explanation
.size(); ++ i
) {
1243 Assert(explanation
[i
].d_theory
== THEORY_SAT_SOLVER
);
1244 all
.insert(explanation
[i
].d_node
);
1247 if (all
.size() == 0) {
1248 // Normalize to true
1249 return NodeManager::currentNM()->mkConst
<bool>(true);
1252 if (all
.size() == 1) {
1253 // All the same, or just one
1254 return explanation
[0].d_node
;
1257 NodeBuilder
<> conjunction(kind::AND
);
1258 std::set
<TNode
>::const_iterator it
= all
.begin();
1259 std::set
<TNode
>::const_iterator it_end
= all
.end();
1260 while (it
!= it_end
) {
1268 TrustNode
TheoryEngine::getExplanation(TNode node
)
1270 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1271 << "): current propagation index = "
1272 << d_propagationMapTimestamp
<< endl
;
1274 bool polarity
= node
.getKind() != kind::NOT
;
1275 TNode atom
= polarity
? node
: node
[0];
1277 // If we're not in shared mode, explanations are simple
1278 if (!d_logicInfo
.isSharingEnabled())
1280 Debug("theory::explain")
1281 << "TheoryEngine::getExplanation: sharing is NOT enabled. "
1282 << " Responsible theory is: " << theoryOf(atom
)->getId() << std::endl
;
1284 TrustNode texplanation
= theoryOf(atom
)->explain(node
);
1285 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1286 << ") => " << texplanation
.getNode() << endl
;
1287 return texplanation
;
1290 Debug("theory::explain") << "TheoryEngine::getExplanation: sharing IS enabled"
1293 // Initial thing to explain
1294 NodeTheoryPair
toExplain(node
, THEORY_SAT_SOLVER
, d_propagationMapTimestamp
);
1295 Assert(d_propagationMap
.find(toExplain
) != d_propagationMap
.end());
1297 NodeTheoryPair nodeExplainerPair
= d_propagationMap
[toExplain
];
1298 Debug("theory::explain")
1299 << "TheoryEngine::getExplanation: explainer for node "
1300 << nodeExplainerPair
.d_node
1301 << " is theory: " << nodeExplainerPair
.d_theory
<< std::endl
;
1303 // Create the workplace for explanations
1304 std::vector
<NodeTheoryPair
> explanationVector
;
1305 explanationVector
.push_back(d_propagationMap
[toExplain
]);
1306 // Process the explanation
1307 TrustNode texplanation
= getExplanation(explanationVector
);
1308 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
<< ") => "
1309 << texplanation
.getNode() << endl
;
1310 return texplanation
;
1313 struct AtomsCollect
{
1315 std::vector
<TNode
> d_atoms
;
1316 std::unordered_set
<TNode
, TNodeHashFunction
> d_visited
;
1320 typedef void return_type
;
1322 bool alreadyVisited(TNode current
, TNode parent
) {
1323 // Check if already visited
1324 if (d_visited
.find(current
) != d_visited
.end()) return true;
1325 // Don't visit non-boolean
1326 if (!current
.getType().isBoolean()) return true;
1331 void visit(TNode current
, TNode parent
) {
1332 if (Theory::theoryOf(current
) != theory::THEORY_BOOL
) {
1333 d_atoms
.push_back(current
);
1335 d_visited
.insert(current
);
1338 void start(TNode node
) {}
1339 void done(TNode node
) {}
1341 std::vector
<TNode
> getAtoms() const {
1346 void TheoryEngine::ensureLemmaAtoms(const std::vector
<TNode
>& atoms
, theory::TheoryId atomsTo
) {
1347 for (unsigned i
= 0; i
< atoms
.size(); ++ i
) {
1349 // Non-equality atoms are either owned by theory or they don't make sense
1350 if (atoms
[i
].getKind() != kind::EQUAL
) {
1356 // Simple normalization to not repeat stuff
1357 if (eq
[0] > eq
[1]) {
1358 eq
= eq
[1].eqNode(eq
[0]);
1361 // Rewrite the equality
1362 Node eqNormalized
= Rewriter::rewrite(atoms
[i
]);
1364 Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq
<< " with nf " << eqNormalized
<< endl
;
1366 // If the equality is a boolean constant, we send immediately
1367 if (eqNormalized
.isConst()) {
1368 if (eqNormalized
.getConst
<bool>()) {
1369 assertToTheory(eq
, eqNormalized
, /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1371 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), /** to */ atomsTo
, /** Sat solver */ theory::THEORY_SAT_SOLVER
);
1374 }else if( eqNormalized
.getKind() != kind::EQUAL
){
1375 Assert(eqNormalized
.getKind() == kind::BOOLEAN_TERM_VARIABLE
1376 || (eqNormalized
.getKind() == kind::NOT
1377 && eqNormalized
[0].getKind() == kind::BOOLEAN_TERM_VARIABLE
));
1378 // this happens for Boolean term equalities V = true that are rewritten to V, we should skip
1379 // TODO : revisit this
1383 // If the normalization did the just flips, keep the flip
1384 if (eqNormalized
[0] == eq
[1] && eqNormalized
[1] == eq
[0]) {
1388 // Check if the equality is already known by the sat solver
1389 if (d_propEngine
->isSatLiteral(eqNormalized
)) {
1391 if (d_propEngine
->hasValue(eqNormalized
, value
)) {
1393 assertToTheory(eq
, eqNormalized
, atomsTo
, theory::THEORY_SAT_SOLVER
);
1396 assertToTheory(eq
.notNode(), eqNormalized
.notNode(), atomsTo
, theory::THEORY_SAT_SOLVER
);
1402 // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1403 // then we must figure it out
1404 if (eqNormalized
!= eq
|| Theory::theoryOf(eq
) != atomsTo
) {
1405 // If you get eqNormalized, send atoms[i] to atomsTo
1406 d_atomRequests
.add(eqNormalized
, eq
, atomsTo
);
1411 theory::LemmaStatus
TheoryEngine::lemma(theory::TrustNode tlemma
,
1412 theory::LemmaProperty p
,
1413 theory::TheoryId atomsTo
,
1414 theory::TheoryId from
)
1416 // For resource-limiting (also does a time check).
1418 Assert(tlemma
.getKind() == TrustNodeKind::LEMMA
1419 || tlemma
.getKind() == TrustNodeKind::CONFLICT
);
1421 Node node
= tlemma
.getNode();
1422 Node lemma
= tlemma
.getProven();
1424 // when proofs are enabled, we ensure the trust node has a generator by
1425 // adding a trust step to the lazy proof maintained by this class
1426 if (isProofEnabled())
1428 // ensure proof: set THEORY_LEMMA if no generator is provided
1429 if (tlemma
.getGenerator() == nullptr)
1431 // internal lemmas should have generators
1432 Assert(from
!= THEORY_LAST
);
1433 // add theory lemma step to proof
1434 Node tidn
= builtin::BuiltinProofRuleChecker::mkTheoryIdNode(from
);
1435 d_lazyProof
->addStep(lemma
, PfRule::THEORY_LEMMA
, {}, {lemma
, tidn
});
1436 // update the trust node
1437 tlemma
= TrustNode::mkTrustLemma(lemma
, d_lazyProof
.get());
1440 tlemma
.debugCheckClosed("te-proof-debug", "TheoryEngine::lemma_initial");
1443 // Do we need to check atoms
1444 if (atomsTo
!= theory::THEORY_LAST
) {
1445 Debug("theory::atoms") << "TheoryEngine::lemma(" << node
<< ", " << atomsTo
<< ")" << endl
;
1446 AtomsCollect collectAtoms
;
1447 NodeVisitor
<AtomsCollect
>::run(collectAtoms
, node
);
1448 ensureLemmaAtoms(collectAtoms
.getAtoms(), atomsTo
);
1451 if(Dump
.isOn("t-lemmas")) {
1452 // we dump the negation of the lemma, to show validity of the lemma
1453 Node n
= lemma
.negate();
1454 const Printer
& printer
= d_outMgr
.getPrinter();
1455 std::ostream
& out
= d_outMgr
.getDumpOut();
1456 printer
.toStreamCmdComment(out
, "theory lemma: expect valid");
1457 printer
.toStreamCmdCheckSat(out
, n
);
1459 bool removable
= isLemmaPropertyRemovable(p
);
1460 bool preprocess
= isLemmaPropertyPreprocess(p
);
1462 // call preprocessor
1463 std::vector
<TrustNode
> newLemmas
;
1464 std::vector
<Node
> newSkolems
;
1466 d_tpp
.preprocess(lemma
, newLemmas
, newSkolems
, preprocess
);
1467 // the preprocessed lemma
1469 if (tplemma
.isNull())
1475 Assert(tplemma
.getKind() == TrustNodeKind::REWRITE
);
1476 lemmap
= tplemma
.getNode();
1478 // must update the trust lemma
1479 if (lemmap
!= lemma
)
1481 // process the preprocessing
1482 if (isProofEnabled())
1484 Assert(d_lazyProof
!= nullptr);
1485 // add the original proof to the lazy proof
1486 d_lazyProof
->addLazyStep(tlemma
.getProven(), tlemma
.getGenerator());
1487 // only need to do anything if lemmap changed in a non-trivial way
1488 if (!CDProof::isSame(lemmap
, lemma
))
1490 d_lazyProof
->addLazyStep(tplemma
.getProven(),
1491 tplemma
.getGenerator(),
1493 "TheoryEngine::lemma_pp",
1495 PfRule::PREPROCESS_LEMMA
);
1496 // ---------- from d_lazyProof -------------- from theory preprocess
1497 // lemma lemma = lemmap
1498 // ------------------------------------------ MACRO_SR_PRED_TRANSFORM
1500 std::vector
<Node
> pfChildren
;
1501 pfChildren
.push_back(lemma
);
1502 pfChildren
.push_back(tplemma
.getProven());
1503 std::vector
<Node
> pfArgs
;
1504 pfArgs
.push_back(lemmap
);
1505 d_lazyProof
->addStep(
1506 lemmap
, PfRule::MACRO_SR_PRED_TRANSFORM
, pfChildren
, pfArgs
);
1509 tlemma
= TrustNode::mkTrustLemma(lemmap
, d_lazyProof
.get());
1513 // must use an assertion pipeline due to decision engine below
1514 AssertionPipeline lemmas
;
1515 // make the assertion pipeline
1516 lemmas
.push_back(lemmap
);
1517 lemmas
.updateRealAssertionsEnd();
1518 Assert(newSkolems
.size() == newLemmas
.size());
1519 for (size_t i
= 0, nsize
= newLemmas
.size(); i
< nsize
; i
++)
1521 // store skolem mapping here
1522 IteSkolemMap
& imap
= lemmas
.getIteSkolemMap();
1523 imap
[newSkolems
[i
]] = lemmas
.size();
1524 lemmas
.push_back(newLemmas
[i
].getNode());
1527 // If specified, we must add this lemma to the set of those that need to be
1528 // justified, where note we pass all auxiliary lemmas in lemmas, since these
1529 // by extension must be justified as well.
1530 if (d_relManager
!= nullptr && isLemmaPropertyNeedsJustify(p
))
1532 d_relManager
->notifyPreprocessedAssertions(lemmas
.ref());
1535 // do final checks on the lemmas we are about to send
1536 if (isProofEnabled())
1538 Assert(tlemma
.getGenerator() != nullptr);
1539 // ensure closed, make the proof node eagerly here to debug
1540 tlemma
.debugCheckClosed("te-proof-debug", "TheoryEngine::lemma");
1541 for (size_t i
= 0, lsize
= newLemmas
.size(); i
< lsize
; ++i
)
1543 Assert(newLemmas
[i
].getGenerator() != nullptr);
1544 newLemmas
[i
].debugCheckClosed("te-proof-debug",
1545 "TheoryEngine::lemma_new");
1549 // now, send the lemmas to the prop engine
1550 d_propEngine
->assertLemma(tlemma
.getProven(), false, removable
);
1551 for (size_t i
= 0, lsize
= newLemmas
.size(); i
< lsize
; ++i
)
1553 d_propEngine
->assertLemma(newLemmas
[i
].getProven(), false, removable
);
1556 // assert to decision engine
1559 d_propEngine
->addAssertionsToDecisionEngine(lemmas
);
1562 // Mark that we added some lemmas
1563 d_lemmasAdded
= true;
1565 // Lemma analysis isn't online yet; this lemma may only live for this
1567 Node retLemma
= lemmas
[0];
1568 if (lemmas
.size() > 1)
1570 // the returned lemma is the conjunction of all additional lemmas.
1571 retLemma
= NodeManager::currentNM()->mkNode(kind::AND
, lemmas
.ref());
1573 return theory::LemmaStatus(retLemma
, d_userContext
->getLevel());
1576 void TheoryEngine::conflict(theory::TrustNode tconflict
, TheoryId theoryId
)
1578 Assert(tconflict
.getKind() == TrustNodeKind::CONFLICT
);
1579 TNode conflict
= tconflict
.getNode();
1580 Trace("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", "
1581 << theoryId
<< ")" << endl
;
1582 Trace("te-proof-debug") << "Check closed conflict" << std::endl
;
1583 // doesn't require proof generator, yet, since THEORY_LEMMA is added below
1584 tconflict
.debugCheckClosed(
1585 "te-proof-debug", "TheoryEngine::conflict_initial", false);
1587 Trace("dtview::conflict") << ":THEORY-CONFLICT: " << conflict
<< std::endl
;
1589 // Mark that we are in conflict
1590 d_inConflict
= true;
1592 if(Dump
.isOn("t-conflicts")) {
1593 const Printer
& printer
= d_outMgr
.getPrinter();
1594 std::ostream
& out
= d_outMgr
.getDumpOut();
1595 printer
.toStreamCmdComment(out
, "theory conflict: expect unsat");
1596 printer
.toStreamCmdCheckSat(out
, conflict
);
1599 // In the multiple-theories case, we need to reconstruct the conflict
1600 if (d_logicInfo
.isSharingEnabled()) {
1601 // Create the workplace for explanations
1602 std::vector
<NodeTheoryPair
> vec
;
1604 NodeTheoryPair(conflict
, theoryId
, d_propagationMapTimestamp
));
1606 // Process the explanation
1607 TrustNode tncExp
= getExplanation(vec
);
1608 Trace("te-proof-debug")
1609 << "Check closed conflict explained with sharing" << std::endl
;
1610 tncExp
.debugCheckClosed("te-proof-debug",
1611 "TheoryEngine::conflict_explained_sharing");
1612 Node fullConflict
= tncExp
.getNode();
1614 if (isProofEnabled())
1616 Trace("te-proof-debug") << "Process conflict: " << conflict
<< std::endl
;
1617 Trace("te-proof-debug") << "Conflict " << tconflict
<< " from "
1618 << tconflict
.identifyGenerator() << std::endl
;
1619 Trace("te-proof-debug") << "Explanation " << tncExp
<< " from "
1620 << tncExp
.identifyGenerator() << std::endl
;
1621 Assert(d_lazyProof
!= nullptr);
1622 if (tconflict
.getGenerator() != nullptr)
1624 d_lazyProof
->addLazyStep(tconflict
.getProven(),
1625 tconflict
.getGenerator());
1629 // add theory lemma step
1630 Node tidn
= builtin::BuiltinProofRuleChecker::mkTheoryIdNode(theoryId
);
1631 Node conf
= tconflict
.getProven();
1632 d_lazyProof
->addStep(conf
, PfRule::THEORY_LEMMA
, {}, {conf
, tidn
});
1634 // store the explicit step, which should come from a different
1635 // generator, e.g. d_tepg.
1636 Node proven
= tncExp
.getProven();
1637 Assert(tncExp
.getGenerator() != d_lazyProof
.get());
1638 Trace("te-proof-debug") << "add lazy step " << tncExp
.identifyGenerator()
1639 << " for " << proven
<< std::endl
;
1640 d_lazyProof
->addLazyStep(proven
, tncExp
.getGenerator());
1641 pfgEnsureClosed(proven
,
1644 "TheoryEngine::conflict_during");
1645 Node fullConflictNeg
= fullConflict
.notNode();
1646 std::vector
<Node
> children
;
1647 children
.push_back(proven
);
1648 std::vector
<Node
> args
;
1649 args
.push_back(fullConflictNeg
);
1650 if (conflict
== d_false
)
1652 AlwaysAssert(proven
== fullConflictNeg
);
1656 if (fullConflict
!= conflict
)
1658 // ------------------------- explained ---------- from theory
1659 // fullConflict => conflict ~conflict
1660 // --------------------------------------------
1661 // MACRO_SR_PRED_TRANSFORM ~fullConflict
1662 children
.push_back(conflict
.notNode());
1663 args
.push_back(mkMethodId(MethodId::SB_LITERAL
));
1664 d_lazyProof
->addStep(
1665 fullConflictNeg
, PfRule::MACRO_SR_PRED_TRANSFORM
, children
, args
);
1669 // pass the processed trust node
1671 TrustNode::mkTrustConflict(fullConflict
, d_lazyProof
.get());
1672 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict
<< ", " << theoryId
<< "): full = " << fullConflict
<< endl
;
1673 Assert(properConflict(fullConflict
));
1674 Trace("te-proof-debug")
1675 << "Check closed conflict with sharing" << std::endl
;
1676 tconf
.debugCheckClosed("te-proof-debug", "TheoryEngine::conflict:sharing");
1677 lemma(tconf
, LemmaProperty::REMOVABLE
);
1679 // When only one theory, the conflict should need no processing
1680 Assert(properConflict(conflict
));
1681 // pass the trust node that was sent from the theory
1682 lemma(tconflict
, LemmaProperty::REMOVABLE
, THEORY_LAST
, theoryId
);
1686 theory::TrustNode
TheoryEngine::getExplanation(
1687 std::vector
<NodeTheoryPair
>& explanationVector
)
1689 Assert(explanationVector
.size() > 0);
1691 unsigned i
= 0; // Index of the current literal we are processing
1692 unsigned j
= 0; // Index of the last literal we are keeping
1694 // cache of nodes we have already explained by some theory
1695 std::unordered_map
<Node
, size_t, NodeHashFunction
> cache
;
1697 while (i
< explanationVector
.size()) {
1698 // Get the current literal to explain
1699 NodeTheoryPair toExplain
= explanationVector
[i
];
1701 Debug("theory::explain")
1702 << "[i=" << i
<< "] TheoryEngine::explain(): processing ["
1703 << toExplain
.d_timestamp
<< "] " << toExplain
.d_node
<< " sent from "
1704 << toExplain
.d_theory
<< endl
;
1706 if (cache
.find(toExplain
.d_node
) != cache
.end()
1707 && cache
[toExplain
.d_node
] < toExplain
.d_timestamp
)
1712 cache
[toExplain
.d_node
] = toExplain
.d_timestamp
;
1714 // If a true constant or a negation of a false constant we can ignore it
1715 if (toExplain
.d_node
.isConst() && toExplain
.d_node
.getConst
<bool>())
1720 if (toExplain
.d_node
.getKind() == kind::NOT
&& toExplain
.d_node
[0].isConst()
1721 && !toExplain
.d_node
[0].getConst
<bool>())
1727 // If from the SAT solver, keep it
1728 if (toExplain
.d_theory
== THEORY_SAT_SOLVER
)
1730 Debug("theory::explain") << "\tLiteral came from THEORY_SAT_SOLVER. Kepping it." << endl
;
1731 explanationVector
[j
++] = explanationVector
[i
++];
1735 // If an and, expand it
1736 if (toExplain
.d_node
.getKind() == kind::AND
)
1738 Debug("theory::explain")
1739 << "TheoryEngine::explain(): expanding " << toExplain
.d_node
1740 << " got from " << toExplain
.d_theory
<< endl
;
1741 for (unsigned k
= 0; k
< toExplain
.d_node
.getNumChildren(); ++k
)
1743 NodeTheoryPair
newExplain(
1744 toExplain
.d_node
[k
], toExplain
.d_theory
, toExplain
.d_timestamp
);
1745 explanationVector
.push_back(newExplain
);
1751 // See if it was sent to the theory by another theory
1752 PropagationMap::const_iterator find
= d_propagationMap
.find(toExplain
);
1753 if (find
!= d_propagationMap
.end()) {
1754 Debug("theory::explain")
1755 << "\tTerm was propagated by another theory (theory = "
1756 << getTheoryString((*find
).second
.d_theory
) << ")" << std::endl
;
1757 // There is some propagation, check if its a timely one
1758 if ((*find
).second
.d_timestamp
< toExplain
.d_timestamp
)
1760 Debug("theory::explain")
1761 << "\tRelevant timetsamp, pushing " << (*find
).second
.d_node
1762 << "to index = " << explanationVector
.size() << std::endl
;
1763 explanationVector
.push_back((*find
).second
);
1771 if (toExplain
.d_theory
== THEORY_BUILTIN
)
1773 explanation
= d_sharedTerms
.explain(toExplain
.d_node
);
1774 Debug("theory::explain") << "\tTerm was propagated by THEORY_BUILTIN. Explanation: " << explanation
<< std::endl
;
1778 TrustNode texp
= theoryOf(toExplain
.d_theory
)->explain(toExplain
.d_node
);
1779 explanation
= texp
.getNode();
1780 Debug("theory::explain") << "\tTerm was propagated by owner theory: "
1781 << theoryOf(toExplain
.d_theory
)->getId()
1782 << ". Explanation: " << explanation
<< std::endl
;
1785 Debug("theory::explain")
1786 << "TheoryEngine::explain(): got explanation " << explanation
1787 << " got from " << toExplain
.d_theory
<< endl
;
1788 Assert(explanation
!= toExplain
.d_node
)
1789 << "wasn't sent to you, so why are you explaining it trivially";
1790 // Mark the explanation
1791 NodeTheoryPair
newExplain(
1792 explanation
, toExplain
.d_theory
, toExplain
.d_timestamp
);
1793 explanationVector
.push_back(newExplain
);
1798 // Keep only the relevant literals
1799 explanationVector
.resize(j
);
1801 Node expNode
= mkExplanation(explanationVector
);
1802 return theory::TrustNode::mkTrustLemma(expNode
, nullptr);
1805 bool TheoryEngine::isProofEnabled() const { return d_pnm
!= nullptr; }
1807 void TheoryEngine::setUserAttribute(const std::string
& attr
,
1809 const std::vector
<Node
>& node_values
,
1810 const std::string
& str_value
)
1812 Trace("te-attr") << "set user attribute " << attr
<< " " << n
<< endl
;
1813 if( d_attr_handle
.find( attr
)!=d_attr_handle
.end() ){
1814 for( size_t i
=0; i
<d_attr_handle
[attr
].size(); i
++ ){
1815 d_attr_handle
[attr
][i
]->setUserAttribute(attr
, n
, node_values
, str_value
);
1818 //unhandled exception?
1822 void TheoryEngine::handleUserAttribute(const char* attr
, Theory
* t
) {
1823 Trace("te-attr") << "Handle user attribute " << attr
<< " " << t
<< endl
;
1824 std::string
str( attr
);
1825 d_attr_handle
[ str
].push_back( t
);
1828 void TheoryEngine::checkTheoryAssertionsWithModel(bool hardFailure
) {
1829 for(TheoryId theoryId
= THEORY_FIRST
; theoryId
< THEORY_LAST
; ++theoryId
) {
1830 Theory
* theory
= d_theoryTable
[theoryId
];
1831 if(theory
&& d_logicInfo
.isTheoryEnabled(theoryId
)) {
1832 for(context::CDList
<Assertion
>::const_iterator it
= theory
->facts_begin(),
1833 it_end
= theory
->facts_end();
1836 Node assertion
= (*it
).d_assertion
;
1837 if (!isRelevant(assertion
))
1839 // not relevant, skip
1842 Node val
= d_tc
->getModel()->getValue(assertion
);
1845 std::stringstream ss
;
1846 ss
<< " " << theoryId
1847 << " has an asserted fact that the model doesn't satisfy." << endl
1848 << "The fact: " << assertion
<< endl
1849 << "Model value: " << val
<< endl
;
1854 // Always an error if it is false
1855 InternalError() << ss
.str();
1859 // Otherwise just a warning. Notice this case may happen for
1860 // assertions with unevaluable operators, e.g. transcendental
1861 // functions. It also may happen for separation logic, where
1862 // check-model support is limited.
1863 Warning() << ss
.str();
1872 std::pair
<bool, Node
> TheoryEngine::entailmentCheck(options::TheoryOfMode mode
,
1875 TNode atom
= (lit
.getKind() == kind::NOT
) ? lit
[0] : lit
;
1876 if( atom
.getKind()==kind::AND
|| atom
.getKind()==kind::OR
|| atom
.getKind()==kind::IMPLIES
){
1877 //Boolean connective, recurse
1878 std::vector
< Node
> children
;
1879 bool pol
= (lit
.getKind()!=kind::NOT
);
1880 bool is_conjunction
= pol
==(lit
.getKind()==kind::AND
);
1881 for( unsigned i
=0; i
<atom
.getNumChildren(); i
++ ){
1883 if( pol
==( lit
.getKind()==kind::IMPLIES
&& i
==0 ) ){
1884 ch
= atom
[i
].negate();
1886 std::pair
<bool, Node
> chres
= entailmentCheck(mode
, ch
);
1888 if( !is_conjunction
){
1891 children
.push_back( chres
.second
);
1893 }else if( !chres
.first
&& is_conjunction
){
1894 return std::pair
<bool, Node
>(false, Node::null());
1897 if( is_conjunction
){
1898 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, children
));
1900 return std::pair
<bool, Node
>(false, Node::null());
1902 }else if( atom
.getKind()==kind::ITE
|| ( atom
.getKind()==kind::EQUAL
&& atom
[0].getType().isBoolean() ) ){
1903 bool pol
= (lit
.getKind()!=kind::NOT
);
1904 for( unsigned r
=0; r
<2; r
++ ){
1909 std::pair
<bool, Node
> chres
= entailmentCheck(mode
, ch
);
1911 Node ch2
= atom
[ atom
.getKind()==kind::ITE
? r
+1 : 1 ];
1912 if( pol
==( atom
.getKind()==kind::ITE
? true : r
==1 ) ){
1915 std::pair
<bool, Node
> chres2
= entailmentCheck(mode
, ch2
);
1917 return std::pair
<bool, Node
>(true, NodeManager::currentNM()->mkNode(kind::AND
, chres
.second
, chres2
.second
));
1923 return std::pair
<bool, Node
>(false, Node::null());
1925 //it is a theory atom
1926 theory::TheoryId tid
= theory::Theory::theoryOf(mode
, atom
);
1927 theory::Theory
* th
= theoryOf(tid
);
1930 Trace("theory-engine-entc") << "Entailment check : " << lit
<< std::endl
;
1932 std::pair
<bool, Node
> chres
= th
->entailmentCheck(lit
);
1937 void TheoryEngine::spendResource(ResourceManager::Resource r
)
1939 d_resourceManager
->spendResource(r
);
1942 }/* CVC4 namespace */