Unsat core infrastruture and API (SMT-LIB compliance to come).
[cvc5.git] / src / theory / theory_engine.cpp
1 /********************* */
2 /*! \file theory_engine.cpp
3 ** \verbatim
4 ** Original author: Morgan Deters
5 ** Major contributors: Dejan Jovanovic
6 ** Minor contributors (to current version): Christopher L. Conway, Tianyi Liang, Kshitij Bansal, Clark Barrett, Liana Hadarean, Andrew Reynolds, Tim King
7 ** This file is part of the CVC4 project.
8 ** Copyright (c) 2009-2014 New York University and The University of Iowa
9 ** See the file COPYING in the top-level source directory for licensing
10 ** information.\endverbatim
11 **
12 ** \brief The theory engine
13 **
14 ** The theory engine.
15 **/
16
17 #include <vector>
18 #include <list>
19
20 #include "theory/arith/arith_ite_utils.h"
21
22 #include "decision/decision_engine.h"
23
24 #include "expr/attribute.h"
25 #include "expr/node.h"
26 #include "expr/node_builder.h"
27 #include "options/options.h"
28 #include "util/lemma_output_channel.h"
29
30 #include "theory/theory.h"
31 #include "theory/theory_engine.h"
32 #include "theory/rewriter.h"
33 #include "theory/theory_traits.h"
34
35 #include "smt/logic_exception.h"
36
37 #include "proof/proof_manager.h"
38
39 #include "util/node_visitor.h"
40 #include "util/ite_removal.h"
41
42 //#include "theory/ite_simplifier.h"
43 //#include "theory/ite_compressor.h"
44 #include "theory/ite_utilities.h"
45 #include "theory/unconstrained_simplifier.h"
46
47 #include "theory/theory_model.h"
48
49 #include "theory/quantifiers_engine.h"
50 #include "theory/quantifiers/theory_quantifiers.h"
51 #include "theory/quantifiers/options.h"
52 #include "theory/quantifiers/model_engine.h"
53 #include "theory/quantifiers/first_order_model.h"
54
55 #include "theory/uf/equality_engine.h"
56 //#include "theory/rewriterules/efficient_e_matching.h"
57 #include "theory/bv/theory_bv_utils.h"
58 #include "theory/bv/options.h"
59
60 #include "proof/proof_manager.h"
61
62 using namespace std;
63
64 using namespace CVC4;
65 using namespace CVC4::theory;
66
67 void TheoryEngine::finishInit() {
68 // initialize the quantifiers engine
69 d_quantEngine = new QuantifiersEngine(d_context, d_userContext, this);
70
71 if (d_logicInfo.isQuantified()) {
72 d_quantEngine->finishInit();
73 Assert(d_masterEqualityEngine == 0);
74 d_masterEqualityEngine = new eq::EqualityEngine(d_masterEENotify,getSatContext(), "theory::master");
75
76 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
77 if (d_theoryTable[theoryId]) {
78 d_theoryTable[theoryId]->setQuantifiersEngine(d_quantEngine);
79 d_theoryTable[theoryId]->setMasterEqualityEngine(d_masterEqualityEngine);
80 }
81 }
82 }
83
84 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
85 if (d_theoryTable[theoryId]) {
86 d_theoryTable[theoryId]->finishInit();
87 }
88 }
89 }
90
91 void TheoryEngine::eqNotifyNewClass(TNode t){
92 d_quantEngine->addTermToDatabase( t );
93 if( d_logicInfo.isQuantified() && options::quantConflictFind() ){
94 d_quantEngine->getConflictFind()->newEqClass( t );
95 }
96 }
97
98 void TheoryEngine::eqNotifyPreMerge(TNode t1, TNode t2){
99 //TODO: add notification to efficient E-matching
100 if( d_logicInfo.isQuantified() ){
101 //d_quantEngine->getEfficientEMatcher()->merge( t1, t2 );
102 if( options::quantConflictFind() ){
103 d_quantEngine->getConflictFind()->merge( t1, t2 );
104 }
105 }
106 }
107
108 void TheoryEngine::eqNotifyPostMerge(TNode t1, TNode t2){
109
110 }
111
112 void TheoryEngine::eqNotifyDisequal(TNode t1, TNode t2, TNode reason){
113 if( d_logicInfo.isQuantified() ){
114 if( options::quantConflictFind() ){
115 d_quantEngine->getConflictFind()->assertDisequal( t1, t2 );
116 }
117 }
118 }
119
120
121 TheoryEngine::TheoryEngine(context::Context* context,
122 context::UserContext* userContext,
123 RemoveITE& iteRemover,
124 const LogicInfo& logicInfo)
125 : d_propEngine(NULL),
126 d_decisionEngine(NULL),
127 d_context(context),
128 d_userContext(userContext),
129 d_logicInfo(logicInfo),
130 d_sharedTerms(this, context),
131 d_masterEqualityEngine(NULL),
132 d_masterEENotify(*this),
133 d_quantEngine(NULL),
134 d_curr_model(NULL),
135 d_curr_model_builder(NULL),
136 d_ppCache(),
137 d_possiblePropagations(context),
138 d_hasPropagated(context),
139 d_inConflict(context, false),
140 d_hasShutDown(false),
141 d_incomplete(context, false),
142 d_propagationMap(context),
143 d_propagationMapTimestamp(context, 0),
144 d_propagatedLiterals(context),
145 d_propagatedLiteralsIndex(context, 0),
146 d_atomRequests(context),
147 d_iteRemover(iteRemover),
148 d_combineTheoriesTime("TheoryEngine::combineTheoriesTime"),
149 d_true(),
150 d_false(),
151 d_interrupted(false),
152 d_inPreregister(false),
153 d_factsAsserted(context, false),
154 d_preRegistrationVisitor(this, context),
155 d_sharedTermsVisitor(d_sharedTerms),
156 d_unconstrainedSimp(new UnconstrainedSimplifier(context, logicInfo)),
157 d_bvToBoolPreprocessor(),
158 d_arithSubstitutionsAdded("zzz::arith::substitutions", 0)
159 {
160 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
161 d_theoryTable[theoryId] = NULL;
162 d_theoryOut[theoryId] = NULL;
163 }
164
165 // build model information if applicable
166 d_curr_model = new theory::TheoryModel(userContext, "DefaultModel", true);
167 d_curr_model_builder = new theory::TheoryEngineModelBuilder(this);
168
169 StatisticsRegistry::registerStat(&d_combineTheoriesTime);
170 d_true = NodeManager::currentNM()->mkConst<bool>(true);
171 d_false = NodeManager::currentNM()->mkConst<bool>(false);
172
173 PROOF (ProofManager::initTheoryProof(); );
174
175 d_iteUtilities = new ITEUtilities(d_iteRemover.getContainsVisitor());
176
177 StatisticsRegistry::registerStat(&d_arithSubstitutionsAdded);
178 }
179
180 TheoryEngine::~TheoryEngine() {
181 Assert(d_hasShutDown);
182
183 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
184 if(d_theoryTable[theoryId] != NULL) {
185 delete d_theoryTable[theoryId];
186 delete d_theoryOut[theoryId];
187 }
188 }
189
190 delete d_curr_model_builder;
191 delete d_curr_model;
192
193 delete d_quantEngine;
194
195 delete d_masterEqualityEngine;
196
197 StatisticsRegistry::unregisterStat(&d_combineTheoriesTime);
198
199 delete d_unconstrainedSimp;
200
201 delete d_iteUtilities;
202
203 StatisticsRegistry::unregisterStat(&d_arithSubstitutionsAdded);
204 }
205
206 void TheoryEngine::interrupt() throw(ModalException) {
207 d_interrupted = true;
208 }
209
210 void TheoryEngine::preRegister(TNode preprocessed) {
211
212 if(Dump.isOn("missed-t-propagations")) {
213 d_possiblePropagations.push_back(preprocessed);
214 }
215 d_preregisterQueue.push(preprocessed);
216
217 if (!d_inPreregister) {
218 // We're in pre-register
219 d_inPreregister = true;
220
221 // Process the pre-registration queue
222 while (!d_preregisterQueue.empty()) {
223 // Get the next atom to pre-register
224 preprocessed = d_preregisterQueue.front();
225 d_preregisterQueue.pop();
226
227 if (d_logicInfo.isSharingEnabled() && preprocessed.getKind() == kind::EQUAL) {
228 // When sharing is enabled, we propagate from the shared terms manager also
229 d_sharedTerms.addEqualityToPropagate(preprocessed);
230 }
231
232 // Pre-register the terms in the atom
233 Theory::Set theories = NodeVisitor<PreRegisterVisitor>::run(d_preRegistrationVisitor, preprocessed);
234 theories = Theory::setRemove(THEORY_BOOL, theories);
235 // Remove the top theory, if any more that means multiple theories were involved
236 bool multipleTheories = Theory::setRemove(Theory::theoryOf(preprocessed), theories);
237 TheoryId i;
238 // These checks don't work with finite model finding, because it
239 // uses Rational constants to represent cardinality constraints,
240 // even though arithmetic isn't actually involved.
241 if(!options::finiteModelFind()) {
242 while((i = Theory::setPop(theories)) != THEORY_LAST) {
243 if(!d_logicInfo.isTheoryEnabled(i)) {
244 LogicInfo newLogicInfo = d_logicInfo.getUnlockedCopy();
245 newLogicInfo.enableTheory(i);
246 newLogicInfo.lock();
247 stringstream ss;
248 ss << "The logic was specified as " << d_logicInfo.getLogicString()
249 << ", which doesn't include " << i
250 << ", but found a term in that theory." << endl
251 << "You might want to extend your logic to "
252 << newLogicInfo.getLogicString() << endl;
253 throw LogicException(ss.str());
254 }
255 }
256 }
257 if (multipleTheories) {
258 // Collect the shared terms if there are multiple theories
259 NodeVisitor<SharedTermsVisitor>::run(d_sharedTermsVisitor, preprocessed);
260 }
261 }
262
263 // Leaving pre-register
264 d_inPreregister = false;
265 }
266 }
267
268 void TheoryEngine::printAssertions(const char* tag) {
269 if (Trace.isOn(tag)) {
270
271 for (TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
272 Theory* theory = d_theoryTable[theoryId];
273 if (theory && d_logicInfo.isTheoryEnabled(theoryId)) {
274 Trace(tag) << "--------------------------------------------" << endl;
275 Trace(tag) << "Assertions of " << theory->getId() << ": " << endl;
276 context::CDList<Assertion>::const_iterator it = theory->facts_begin(), it_end = theory->facts_end();
277 for (unsigned i = 0; it != it_end; ++ it, ++i) {
278 if ((*it).isPreregistered) {
279 Trace(tag) << "[" << i << "]: ";
280 } else {
281 Trace(tag) << "(" << i << "): ";
282 }
283 Trace(tag) << (*it).assertion << endl;
284 }
285
286 if (d_logicInfo.isSharingEnabled()) {
287 Trace(tag) << "Shared terms of " << theory->getId() << ": " << endl;
288 context::CDList<TNode>::const_iterator it = theory->shared_terms_begin(), it_end = theory->shared_terms_end();
289 for (unsigned i = 0; it != it_end; ++ it, ++i) {
290 Trace(tag) << "[" << i << "]: " << (*it) << endl;
291 }
292 }
293 }
294 }
295 }
296 }
297
298 void TheoryEngine::dumpAssertions(const char* tag) {
299 if (Dump.isOn(tag)) {
300 Dump(tag) << CommentCommand("Starting completeness check");
301 for (TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
302 Theory* theory = d_theoryTable[theoryId];
303 if (theory && d_logicInfo.isTheoryEnabled(theoryId)) {
304 Dump(tag) << CommentCommand("Completeness check");
305 Dump(tag) << PushCommand();
306
307 // Dump the shared terms
308 if (d_logicInfo.isSharingEnabled()) {
309 Dump(tag) << CommentCommand("Shared terms");
310 context::CDList<TNode>::const_iterator it = theory->shared_terms_begin(), it_end = theory->shared_terms_end();
311 for (unsigned i = 0; it != it_end; ++ it, ++i) {
312 stringstream ss;
313 ss << (*it);
314 Dump(tag) << CommentCommand(ss.str());
315 }
316 }
317
318 // Dump the assertions
319 Dump(tag) << CommentCommand("Assertions");
320 context::CDList<Assertion>::const_iterator it = theory->facts_begin(), it_end = theory->facts_end();
321 for (; it != it_end; ++ it) {
322 // Get the assertion
323 Node assertionNode = (*it).assertion;
324 // Purify all the terms
325
326 if ((*it).isPreregistered) {
327 Dump(tag) << CommentCommand("Preregistered");
328 } else {
329 Dump(tag) << CommentCommand("Shared assertion");
330 }
331 Dump(tag) << AssertCommand(assertionNode.toExpr());
332 }
333 Dump(tag) << CheckSatCommand();
334
335 Dump(tag) << PopCommand();
336 }
337 }
338 }
339 }
340
341 /**
342 * Check all (currently-active) theories for conflicts.
343 * @param effort the effort level to use
344 */
345 void TheoryEngine::check(Theory::Effort effort) {
346
347 d_propEngine->checkTime();
348
349 // Reset the interrupt flag
350 d_interrupted = false;
351
352 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
353 #undef CVC4_FOR_EACH_THEORY_STATEMENT
354 #endif
355 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
356 if (theory::TheoryTraits<THEORY>::hasCheck && d_logicInfo.isTheoryEnabled(THEORY)) { \
357 theoryOf(THEORY)->check(effort); \
358 if (d_inConflict) { \
359 break; \
360 } \
361 }
362
363 // Do the checking
364 try {
365
366 // Mark the output channel unused (if this is FULL_EFFORT, and nothing
367 // is done by the theories, no additional check will be needed)
368 d_outputChannelUsed = false;
369
370 // Mark the lemmas flag (no lemmas added)
371 d_lemmasAdded = false;
372
373 Debug("theory") << "TheoryEngine::check(" << effort << "): d_factsAsserted = " << (d_factsAsserted ? "true" : "false") << endl;
374
375 // If in full effort, we have a fake new assertion just to jumpstart the checking
376 if (Theory::fullEffort(effort)) {
377 d_factsAsserted = true;
378 }
379
380 // Check until done
381 while (d_factsAsserted && !d_inConflict && !d_lemmasAdded) {
382
383 Debug("theory") << "TheoryEngine::check(" << effort << "): running check" << endl;
384
385 Trace("theory::assertions") << endl;
386 if (Trace.isOn("theory::assertions")) {
387 printAssertions("theory::assertions");
388 }
389
390 // Note that we've discharged all the facts
391 d_factsAsserted = false;
392
393 // Do the checking
394 CVC4_FOR_EACH_THEORY;
395
396 if(Dump.isOn("missed-t-conflicts")) {
397 Dump("missed-t-conflicts")
398 << CommentCommand("Completeness check for T-conflicts; expect sat")
399 << CheckSatCommand();
400 }
401
402 Debug("theory") << "TheoryEngine::check(" << effort << "): running propagation after the initial check" << endl;
403
404 // We are still satisfiable, propagate as much as possible
405 propagate(effort);
406
407 // We do combination if all has been processed and we are in fullcheck
408 if (Theory::fullEffort(effort) && d_logicInfo.isSharingEnabled() && !d_factsAsserted && !d_lemmasAdded) {
409 // Do the combination
410 Debug("theory") << "TheoryEngine::check(" << effort << "): running combination" << endl;
411 combineTheories();
412 }
413 }
414
415 // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
416 if( effort == Theory::EFFORT_FULL && ! d_inConflict && ! needCheck() ) {
417 //d_theoryTable[THEORY_STRINGS]->check(Theory::EFFORT_LAST_CALL);
418 if(d_logicInfo.isQuantified()) {
419 // quantifiers engine must pass effort last call check
420 d_quantEngine->check(Theory::EFFORT_LAST_CALL);
421 // if we have given up, then possibly flip decision
422 if(options::flipDecision()) {
423 if(d_incomplete && !d_inConflict && !needCheck()) {
424 ((theory::quantifiers::TheoryQuantifiers*) d_theoryTable[THEORY_QUANTIFIERS])->flipDecision();
425 }
426 }
427 // if returning incomplete or SAT, we have ensured that the model in the quantifiers engine has been built
428 } else if(options::produceModels()) {
429 // must build model at this point
430 d_curr_model_builder->buildModel(d_curr_model, true);
431 }
432 Trace("theory::assertions-model") << endl;
433 if (Trace.isOn("theory::assertions-model")) {
434 printAssertions("theory::assertions-model");
435 }
436 }
437
438 Debug("theory") << "TheoryEngine::check(" << effort << "): done, we are " << (d_inConflict ? "unsat" : "sat") << (d_lemmasAdded ? " with new lemmas" : " with no new lemmas") << endl;
439
440 if(!d_inConflict && Theory::fullEffort(effort) && d_masterEqualityEngine != NULL && !d_lemmasAdded) {
441 AlwaysAssert(d_masterEqualityEngine->consistent());
442 }
443 } catch(const theory::Interrupted&) {
444 Trace("theory") << "TheoryEngine::check() => interrupted" << endl;
445 }
446 // If fulleffort, check all theories
447 if(Dump.isOn("theory::fullcheck") && Theory::fullEffort(effort)) {
448 if (!d_inConflict && !needCheck()) {
449 dumpAssertions("theory::fullcheck");
450 }
451 }
452 }
453
454 void TheoryEngine::combineTheories() {
455
456 Debug("sharing") << "TheoryEngine::combineTheories()" << endl;
457
458 TimerStat::CodeTimer combineTheoriesTimer(d_combineTheoriesTime);
459
460 // Care graph we'll be building
461 CareGraph careGraph;
462
463 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
464 #undef CVC4_FOR_EACH_THEORY_STATEMENT
465 #endif
466 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
467 if (theory::TheoryTraits<THEORY>::isParametric && d_logicInfo.isTheoryEnabled(THEORY)) { \
468 theoryOf(THEORY)->getCareGraph(careGraph); \
469 }
470
471 // Call on each parametric theory to give us its care graph
472 CVC4_FOR_EACH_THEORY;
473
474 Debug("sharing") << "TheoryEngine::combineTheories(): care graph size = " << careGraph.size() << endl;
475
476 // Now add splitters for the ones we are interested in
477 CareGraph::const_iterator care_it = careGraph.begin();
478 CareGraph::const_iterator care_it_end = careGraph.end();
479 for (; care_it != care_it_end; ++ care_it) {
480 const CarePair& carePair = *care_it;
481
482 Debug("sharing") << "TheoryEngine::combineTheories(): checking " << carePair.a << " = " << carePair.b << " from " << carePair.theory << endl;
483
484 Assert(d_sharedTerms.isShared(carePair.a) || carePair.a.isConst());
485 Assert(d_sharedTerms.isShared(carePair.b) || carePair.b.isConst());
486
487 // The equality in question (order for no repetition)
488 Node equality = carePair.a.eqNode(carePair.b);
489
490 // We need to split on it
491 Debug("sharing") << "TheoryEngine::combineTheories(): requesting a split " << endl;
492 lemma(equality.orNode(equality.notNode()), false, false, false, carePair.theory);
493 }
494 }
495
496 void TheoryEngine::propagate(Theory::Effort effort) {
497 // Reset the interrupt flag
498 d_interrupted = false;
499
500 // Definition of the statement that is to be run by every theory
501 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
502 #undef CVC4_FOR_EACH_THEORY_STATEMENT
503 #endif
504 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
505 if (theory::TheoryTraits<THEORY>::hasPropagate && d_logicInfo.isTheoryEnabled(THEORY)) { \
506 theoryOf(THEORY)->propagate(effort); \
507 }
508
509 // Reset the interrupt flag
510 d_interrupted = false;
511
512 // Propagate for each theory using the statement above
513 CVC4_FOR_EACH_THEORY;
514
515 if(Dump.isOn("missed-t-propagations")) {
516 for(unsigned i = 0; i < d_possiblePropagations.size(); ++i) {
517 Node atom = d_possiblePropagations[i];
518 bool value;
519 if(d_propEngine->hasValue(atom, value)) {
520 continue;
521 }
522 // Doesn't have a value, check it (and the negation)
523 if(d_hasPropagated.find(atom) == d_hasPropagated.end()) {
524 Dump("missed-t-propagations")
525 << CommentCommand("Completeness check for T-propagations; expect invalid")
526 << EchoCommand(atom.toString())
527 << QueryCommand(atom.toExpr())
528 << EchoCommand(atom.notNode().toString())
529 << QueryCommand(atom.notNode().toExpr());
530 }
531 }
532 }
533 }
534
535 Node TheoryEngine::getNextDecisionRequest() {
536 // Definition of the statement that is to be run by every theory
537 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
538 #undef CVC4_FOR_EACH_THEORY_STATEMENT
539 #endif
540 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
541 if (theory::TheoryTraits<THEORY>::hasGetNextDecisionRequest && d_logicInfo.isTheoryEnabled(THEORY)) { \
542 Node n = theoryOf(THEORY)->getNextDecisionRequest(); \
543 if(! n.isNull()) { \
544 return n; \
545 } \
546 }
547
548 // Request decision from each theory using the statement above
549 CVC4_FOR_EACH_THEORY;
550
551 return TNode();
552 }
553
554 bool TheoryEngine::properConflict(TNode conflict) const {
555 bool value;
556 if (conflict.getKind() == kind::AND) {
557 for (unsigned i = 0; i < conflict.getNumChildren(); ++ i) {
558 if (! getPropEngine()->hasValue(conflict[i], value)) {
559 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
560 << conflict[i] << endl;
561 return false;
562 }
563 if (! value) {
564 Debug("properConflict") << "Bad conflict is due to false atom: "
565 << conflict[i] << endl;
566 return false;
567 }
568 if (conflict[i] != Rewriter::rewrite(conflict[i])) {
569 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
570 << conflict[i] << " vs " << Rewriter::rewrite(conflict[i]) << endl;
571 return false;
572 }
573 }
574 } else {
575 if (! getPropEngine()->hasValue(conflict, value)) {
576 Debug("properConflict") << "Bad conflict is due to unassigned atom: "
577 << conflict << endl;
578 return false;
579 }
580 if(! value) {
581 Debug("properConflict") << "Bad conflict is due to false atom: "
582 << conflict << endl;
583 return false;
584 }
585 if (conflict != Rewriter::rewrite(conflict)) {
586 Debug("properConflict") << "Bad conflict is due to atom not in normal form: "
587 << conflict << " vs " << Rewriter::rewrite(conflict) << endl;
588 return false;
589 }
590 }
591 return true;
592 }
593
594 bool TheoryEngine::properPropagation(TNode lit) const {
595 if(!getPropEngine()->isSatLiteral(lit)) {
596 return false;
597 }
598 bool b;
599 return !getPropEngine()->hasValue(lit, b);
600 }
601
602 bool TheoryEngine::properExplanation(TNode node, TNode expl) const {
603 // Explanation must be either a conjunction of true literals that have true SAT values already
604 // or a singled literal that has a true SAT value already.
605 if (expl.getKind() == kind::AND) {
606 for (unsigned i = 0; i < expl.getNumChildren(); ++ i) {
607 bool value;
608 if (!d_propEngine->hasValue(expl[i], value) || !value) {
609 return false;
610 }
611 }
612 } else {
613 bool value;
614 return d_propEngine->hasValue(expl, value) && value;
615 }
616 return true;
617 }
618
619 void TheoryEngine::collectModelInfo( theory::TheoryModel* m, bool fullModel ){
620 //have shared term engine collectModelInfo
621 // d_sharedTerms.collectModelInfo( m, fullModel );
622 // Consult each active theory to get all relevant information
623 // concerning the model.
624 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId < theory::THEORY_LAST; ++theoryId) {
625 if(d_logicInfo.isTheoryEnabled(theoryId)) {
626 Trace("model-builder") << " CollectModelInfo on theory: " << theoryId << endl;
627 d_theoryTable[theoryId]->collectModelInfo( m, fullModel );
628 }
629 }
630 // Get the Boolean variables
631 vector<TNode> boolVars;
632 d_propEngine->getBooleanVariables(boolVars);
633 vector<TNode>::iterator it, iend = boolVars.end();
634 bool hasValue, value;
635 for (it = boolVars.begin(); it != iend; ++it) {
636 TNode var = *it;
637 hasValue = d_propEngine->hasValue(var, value);
638 // TODO: Assert that hasValue is true?
639 if (!hasValue) {
640 value = false;
641 }
642 Trace("model-builder-assertions") << "(assert" << (value ? " " : " (not ") << var << (value ? ");" : "));") << endl;
643 m->assertPredicate(var, value);
644 }
645 }
646
647 /* get model */
648 TheoryModel* TheoryEngine::getModel() {
649 Debug("model") << "TheoryEngine::getModel()" << endl;
650 if( d_logicInfo.isQuantified() ) {
651 Debug("model") << "Get model from quantifiers engine." << endl;
652 return d_quantEngine->getModel();
653 } else {
654 Debug("model") << "Get default model." << endl;
655 return d_curr_model;
656 }
657 }
658
659 bool TheoryEngine::presolve() {
660 // Reset the interrupt flag
661 d_interrupted = false;
662
663 try {
664 // Definition of the statement that is to be run by every theory
665 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
666 #undef CVC4_FOR_EACH_THEORY_STATEMENT
667 #endif
668 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
669 if (theory::TheoryTraits<THEORY>::hasPresolve) { \
670 theoryOf(THEORY)->presolve(); \
671 if(d_inConflict) { \
672 return true; \
673 } \
674 }
675
676 // Presolve for each theory using the statement above
677 CVC4_FOR_EACH_THEORY;
678 } catch(const theory::Interrupted&) {
679 Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl;
680 }
681 // return whether we have a conflict
682 return false;
683 }/* TheoryEngine::presolve() */
684
685 void TheoryEngine::postsolve() {
686 // Reset the interrupt flag
687 d_interrupted = false;
688 bool CVC4_UNUSED wasInConflict = d_inConflict;
689
690 try {
691 // Definition of the statement that is to be run by every theory
692 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
693 #undef CVC4_FOR_EACH_THEORY_STATEMENT
694 #endif
695 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
696 if (theory::TheoryTraits<THEORY>::hasPostsolve) { \
697 theoryOf(THEORY)->postsolve(); \
698 Assert(! d_inConflict || wasInConflict, "conflict raised during postsolve()"); \
699 }
700
701 // Postsolve for each theory using the statement above
702 CVC4_FOR_EACH_THEORY;
703 } catch(const theory::Interrupted&) {
704 Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl;
705 }
706 }/* TheoryEngine::postsolve() */
707
708
709 void TheoryEngine::notifyRestart() {
710 // Reset the interrupt flag
711 d_interrupted = false;
712
713 // Definition of the statement that is to be run by every theory
714 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
715 #undef CVC4_FOR_EACH_THEORY_STATEMENT
716 #endif
717 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
718 if (theory::TheoryTraits<THEORY>::hasNotifyRestart && d_logicInfo.isTheoryEnabled(THEORY)) { \
719 theoryOf(THEORY)->notifyRestart(); \
720 }
721
722 // notify each theory using the statement above
723 CVC4_FOR_EACH_THEORY;
724 }
725
726 void TheoryEngine::ppStaticLearn(TNode in, NodeBuilder<>& learned) {
727 // Reset the interrupt flag
728 d_interrupted = false;
729
730 // Definition of the statement that is to be run by every theory
731 #ifdef CVC4_FOR_EACH_THEORY_STATEMENT
732 #undef CVC4_FOR_EACH_THEORY_STATEMENT
733 #endif
734 #define CVC4_FOR_EACH_THEORY_STATEMENT(THEORY) \
735 if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) { \
736 theoryOf(THEORY)->ppStaticLearn(in, learned); \
737 }
738
739 // static learning for each theory using the statement above
740 CVC4_FOR_EACH_THEORY;
741 }
742
743 void TheoryEngine::shutdown() {
744 // Set this first; if a Theory shutdown() throws an exception,
745 // at least the destruction of the TheoryEngine won't confound
746 // matters.
747 d_hasShutDown = true;
748
749 // Shutdown all the theories
750 for(TheoryId theoryId = theory::THEORY_FIRST; theoryId < theory::THEORY_LAST; ++theoryId) {
751 if(d_theoryTable[theoryId]) {
752 theoryOf(theoryId)->shutdown();
753 }
754 }
755
756 d_ppCache.clear();
757 }
758
759 theory::Theory::PPAssertStatus TheoryEngine::solve(TNode literal, SubstitutionMap& substitutionOut) {
760 // Reset the interrupt flag
761 d_interrupted = false;
762
763 TNode atom = literal.getKind() == kind::NOT ? literal[0] : literal;
764 Trace("theory::solve") << "TheoryEngine::solve(" << literal << "): solving with " << theoryOf(atom)->getId() << endl;
765
766 if(! d_logicInfo.isTheoryEnabled(Theory::theoryOf(atom)) &&
767 Theory::theoryOf(atom) != THEORY_SAT_SOLVER) {
768 stringstream ss;
769 ss << "The logic was specified as " << d_logicInfo.getLogicString()
770 << ", which doesn't include " << Theory::theoryOf(atom)
771 << ", but got a preprocessing-time fact for that theory." << endl
772 << "The fact:" << endl
773 << literal;
774 throw LogicException(ss.str());
775 }
776
777 Theory::PPAssertStatus solveStatus = theoryOf(atom)->ppAssert(literal, substitutionOut);
778 Trace("theory::solve") << "TheoryEngine::solve(" << literal << ") => " << solveStatus << endl;
779 return solveStatus;
780 }
781
782 // Recursively traverse a term and call the theory rewriter on its sub-terms
783 Node TheoryEngine::ppTheoryRewrite(TNode term) {
784 NodeMap::iterator find = d_ppCache.find(term);
785 if (find != d_ppCache.end()) {
786 return (*find).second;
787 }
788 unsigned nc = term.getNumChildren();
789 if (nc == 0) {
790 return theoryOf(term)->ppRewrite(term);
791 }
792 Trace("theory-pp") << "ppTheoryRewrite { " << term << endl;
793
794 Node newTerm;
795 if (theoryOf(term)->ppDontRewriteSubterm(term)) {
796 newTerm = Rewriter::rewrite(term);
797 } else {
798 NodeBuilder<> newNode(term.getKind());
799 if (term.getMetaKind() == kind::metakind::PARAMETERIZED) {
800 newNode << term.getOperator();
801 }
802 unsigned i;
803 for (i = 0; i < nc; ++i) {
804 newNode << ppTheoryRewrite(term[i]);
805 }
806 newTerm = Rewriter::rewrite(Node(newNode));
807 }
808 Node newTerm2 = theoryOf(newTerm)->ppRewrite(newTerm);
809 if (newTerm != newTerm2) {
810 newTerm = ppTheoryRewrite(Rewriter::rewrite(newTerm2));
811 }
812 d_ppCache[term] = newTerm;
813 Trace("theory-pp")<< "ppTheoryRewrite returning " << newTerm << "}" << endl;
814 return newTerm;
815 }
816
817
818 void TheoryEngine::preprocessStart()
819 {
820 d_ppCache.clear();
821 }
822
823
824 struct preprocess_stack_element {
825 TNode node;
826 bool children_added;
827 preprocess_stack_element(TNode node)
828 : node(node), children_added(false) {}
829 };/* struct preprocess_stack_element */
830
831
832 Node TheoryEngine::preprocess(TNode assertion) {
833
834 Trace("theory::preprocess") << "TheoryEngine::preprocess(" << assertion << ")" << endl;
835
836 // Do a topological sort of the subexpressions and substitute them
837 vector<preprocess_stack_element> toVisit;
838 toVisit.push_back(assertion);
839
840 while (!toVisit.empty())
841 {
842 // The current node we are processing
843 preprocess_stack_element& stackHead = toVisit.back();
844 TNode current = stackHead.node;
845
846 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion << "): processing " << current << endl;
847
848 // If node already in the cache we're done, pop from the stack
849 NodeMap::iterator find = d_ppCache.find(current);
850 if (find != d_ppCache.end()) {
851 toVisit.pop_back();
852 continue;
853 }
854
855 if(! d_logicInfo.isTheoryEnabled(Theory::theoryOf(current)) &&
856 Theory::theoryOf(current) != THEORY_SAT_SOLVER) {
857 stringstream ss;
858 ss << "The logic was specified as " << d_logicInfo.getLogicString()
859 << ", which doesn't include " << Theory::theoryOf(current)
860 << ", but got a preprocessing-time fact for that theory." << endl
861 << "The fact:" << endl
862 << current;
863 throw LogicException(ss.str());
864 }
865
866 // If this is an atom, we preprocess its terms with the theory ppRewriter
867 if (Theory::theoryOf(current) != THEORY_BOOL) {
868 Node ppRewritten = ppTheoryRewrite(current);
869 d_ppCache[current] = ppRewritten;
870 Assert(Rewriter::rewrite(d_ppCache[current]) == d_ppCache[current]);
871 continue;
872 }
873
874 // Not yet substituted, so process
875 if (stackHead.children_added) {
876 // Children have been processed, so substitute
877 NodeBuilder<> builder(current.getKind());
878 if (current.getMetaKind() == kind::metakind::PARAMETERIZED) {
879 builder << current.getOperator();
880 }
881 for (unsigned i = 0; i < current.getNumChildren(); ++ i) {
882 Assert(d_ppCache.find(current[i]) != d_ppCache.end());
883 builder << d_ppCache[current[i]];
884 }
885 // Mark the substitution and continue
886 Node result = builder;
887 if (result != current) {
888 result = Rewriter::rewrite(result);
889 }
890 Debug("theory::internal") << "TheoryEngine::preprocess(" << assertion << "): setting " << current << " -> " << result << endl;
891 d_ppCache[current] = result;
892 toVisit.pop_back();
893 } else {
894 // Mark that we have added the children if any
895 if (current.getNumChildren() > 0) {
896 stackHead.children_added = true;
897 // We need to add the children
898 for(TNode::iterator child_it = current.begin(); child_it != current.end(); ++ child_it) {
899 TNode childNode = *child_it;
900 NodeMap::iterator childFind = d_ppCache.find(childNode);
901 if (childFind == d_ppCache.end()) {
902 toVisit.push_back(childNode);
903 }
904 }
905 } else {
906 // No children, so we're done
907 Debug("substitution::internal") << "SubstitutionMap::internalSubstitute(" << assertion << "): setting " << current << " -> " << current << endl;
908 d_ppCache[current] = current;
909 toVisit.pop_back();
910 }
911 }
912 }
913
914 // Return the substituted version
915 return d_ppCache[assertion];
916 }
917
918 bool TheoryEngine::markPropagation(TNode assertion, TNode originalAssertion, theory::TheoryId toTheoryId, theory::TheoryId fromTheoryId) {
919
920 // What and where we are asserting
921 NodeTheoryPair toAssert(assertion, toTheoryId, d_propagationMapTimestamp);
922 // What and where it came from
923 NodeTheoryPair toExplain(originalAssertion, fromTheoryId, d_propagationMapTimestamp);
924
925 // See if the theory already got this literal
926 PropagationMap::const_iterator find = d_propagationMap.find(toAssert);
927 if (find != d_propagationMap.end()) {
928 // The theory already knows this
929 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl;
930 return false;
931 }
932
933 Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp << "] " << assertion << ", " << toTheoryId << " from " << originalAssertion << ", " << fromTheoryId << endl;
934
935 // Mark the propagation
936 d_propagationMap[toAssert] = toExplain;
937 d_propagationMapTimestamp = d_propagationMapTimestamp + 1;
938
939 return true;
940 }
941
942
943 void TheoryEngine::assertToTheory(TNode assertion, TNode originalAssertion, theory::TheoryId toTheoryId, theory::TheoryId fromTheoryId) {
944
945 Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion << ", " << toTheoryId << ", " << fromTheoryId << ")" << endl;
946
947 Assert(toTheoryId != fromTheoryId);
948 if(! d_logicInfo.isTheoryEnabled(toTheoryId) &&
949 toTheoryId != THEORY_SAT_SOLVER) {
950 stringstream ss;
951 ss << "The logic was specified as " << d_logicInfo.getLogicString()
952 << ", which doesn't include " << toTheoryId
953 << ", but got an asserted fact to that theory." << endl
954 << "The fact:" << endl
955 << assertion;
956 throw LogicException(ss.str());
957 }
958
959 if (d_inConflict) {
960 return;
961 }
962
963 // If sharing is disabled, things are easy
964 if (!d_logicInfo.isSharingEnabled()) {
965 Assert(assertion == originalAssertion);
966 if (fromTheoryId == THEORY_SAT_SOLVER) {
967 // Send to the apropriate theory
968 theory::Theory* toTheory = theoryOf(toTheoryId);
969 // We assert it, and we know it's preregistereed
970 toTheory->assertFact(assertion, true);
971 // Mark that we have more information
972 d_factsAsserted = true;
973 } else {
974 Assert(toTheoryId == THEORY_SAT_SOLVER);
975 // Check for propositional conflict
976 bool value;
977 if (d_propEngine->hasValue(assertion, value)) {
978 if (!value) {
979 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion << ", " << toTheoryId << ", " << fromTheoryId << "): conflict (no sharing)" << endl;
980 d_inConflict = true;
981 } else {
982 return;
983 }
984 }
985 d_propagatedLiterals.push_back(assertion);
986 }
987 return;
988 }
989
990 // Polarity of the assertion
991 bool polarity = assertion.getKind() != kind::NOT;
992
993 // Atom of the assertion
994 TNode atom = polarity ? assertion : assertion[0];
995
996 // If sending to the shared terms database, it's also simple
997 if (toTheoryId == THEORY_BUILTIN) {
998 Assert(atom.getKind() == kind::EQUAL, "atom should be an EQUALity, not `%s'", atom.toString().c_str());
999 if (markPropagation(assertion, originalAssertion, toTheoryId, fromTheoryId)) {
1000 d_sharedTerms.assertEquality(atom, polarity, assertion);
1001 }
1002 return;
1003 }
1004
1005 // Things from the SAT solver are already normalized, so they go
1006 // directly to the apropriate theory
1007 if (fromTheoryId == THEORY_SAT_SOLVER) {
1008 // We know that this is normalized, so just send it off to the theory
1009 if (markPropagation(assertion, originalAssertion, toTheoryId, fromTheoryId)) {
1010 // Is it preregistered
1011 bool preregistered = d_propEngine->isSatLiteral(assertion) && Theory::theoryOf(assertion) == toTheoryId;
1012 // We assert it
1013 theoryOf(toTheoryId)->assertFact(assertion, preregistered);
1014 // Mark that we have more information
1015 d_factsAsserted = true;
1016 }
1017 return;
1018 }
1019
1020 // Propagations to the SAT solver are just enqueued for pickup by
1021 // the SAT solver later
1022 if (toTheoryId == THEORY_SAT_SOLVER) {
1023 if (markPropagation(assertion, originalAssertion, toTheoryId, fromTheoryId)) {
1024 // Enqueue for propagation to the SAT solver
1025 d_propagatedLiterals.push_back(assertion);
1026 // Check for propositional conflicts
1027 bool value;
1028 if (d_propEngine->hasValue(assertion, value) && !value) {
1029 Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion << ", " << toTheoryId << ", " << fromTheoryId << "): conflict (sharing)" << endl;
1030 d_inConflict = true;
1031 }
1032 }
1033 return;
1034 }
1035
1036 Assert(atom.getKind() == kind::EQUAL);
1037
1038 // Normalize
1039 Node normalizedLiteral = Rewriter::rewrite(assertion);
1040
1041 // See if it rewrites false directly -> conflict
1042 if (normalizedLiteral.isConst()) {
1043 if (!normalizedLiteral.getConst<bool>()) {
1044 // Mark the propagation for explanations
1045 if (markPropagation(normalizedLiteral, originalAssertion, toTheoryId, fromTheoryId)) {
1046 // Get the explanation (conflict will figure out where it came from)
1047 conflict(normalizedLiteral, toTheoryId);
1048 } else {
1049 Unreachable();
1050 }
1051 return;
1052 }
1053 }
1054
1055 // Try and assert (note that we assert the non-normalized one)
1056 if (markPropagation(assertion, originalAssertion, toTheoryId, fromTheoryId)) {
1057 // Check if has been pre-registered with the theory
1058 bool preregistered = d_propEngine->isSatLiteral(assertion) && Theory::theoryOf(assertion) == toTheoryId;
1059 // Assert away
1060 theoryOf(toTheoryId)->assertFact(assertion, preregistered);
1061 d_factsAsserted = true;
1062 }
1063
1064 return;
1065 }
1066
1067 void TheoryEngine::assertFact(TNode literal)
1068 {
1069 Trace("theory") << "TheoryEngine::assertFact(" << literal << ")" << endl;
1070
1071 d_propEngine->checkTime();
1072
1073 // If we're in conflict, nothing to do
1074 if (d_inConflict) {
1075 return;
1076 }
1077
1078 // Get the atom
1079 bool polarity = literal.getKind() != kind::NOT;
1080 TNode atom = polarity ? literal : literal[0];
1081
1082 if (d_logicInfo.isSharingEnabled()) {
1083
1084 // If any shared terms, it's time to do sharing work
1085 if (d_sharedTerms.hasSharedTerms(atom)) {
1086 // Notify the theories the shared terms
1087 SharedTermsDatabase::shared_terms_iterator it = d_sharedTerms.begin(atom);
1088 SharedTermsDatabase::shared_terms_iterator it_end = d_sharedTerms.end(atom);
1089 for (; it != it_end; ++ it) {
1090 TNode term = *it;
1091 Theory::Set theories = d_sharedTerms.getTheoriesToNotify(atom, term);
1092 for (TheoryId id = THEORY_FIRST; id != THEORY_LAST; ++ id) {
1093 if (Theory::setContains(id, theories)) {
1094 theoryOf(id)->addSharedTermInternal(term);
1095 }
1096 }
1097 d_sharedTerms.markNotified(term, theories);
1098 }
1099 }
1100
1101 // If it's an equality, assert it to the shared term manager, even though the terms are not
1102 // yet shared. As the terms become shared later, the shared terms manager will then add them
1103 // to the assert the equality to the interested theories
1104 if (atom.getKind() == kind::EQUAL) {
1105 // Assert it to the the owning theory
1106 assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
1107 // Shared terms manager will assert to interested theories directly, as the terms become shared
1108 assertToTheory(literal, literal, /* to */ THEORY_BUILTIN, /* from */ THEORY_SAT_SOLVER);
1109
1110 // Now, let's check for any atom triggers from lemmas
1111 AtomRequests::atom_iterator it = d_atomRequests.getAtomIterator(atom);
1112 while (!it.done()) {
1113 const AtomRequests::Request& request = it.get();
1114 Node toAssert = polarity ? (Node) request.atom : request.atom.notNode();
1115 Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal << "): sending requested " << toAssert << endl;
1116 assertToTheory(toAssert, literal, request.toTheory, THEORY_SAT_SOLVER);
1117 it.next();
1118 }
1119
1120 } else {
1121 // Not an equality, just assert to the appropriate theory
1122 assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
1123 }
1124 } else {
1125 // Assert the fact to the appropriate theory directly
1126 assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
1127 }
1128 }
1129
1130 bool TheoryEngine::propagate(TNode literal, theory::TheoryId theory) {
1131
1132 Debug("theory::propagate") << "TheoryEngine::propagate(" << literal << ", " << theory << ")" << endl;
1133
1134 d_propEngine->checkTime();
1135
1136 if(Dump.isOn("t-propagations")) {
1137 Dump("t-propagations") << CommentCommand("negation of theory propagation: expect valid")
1138 << QueryCommand(literal.toExpr());
1139 }
1140 if(Dump.isOn("missed-t-propagations")) {
1141 d_hasPropagated.insert(literal);
1142 }
1143
1144 // Get the atom
1145 bool polarity = literal.getKind() != kind::NOT;
1146 TNode atom = polarity ? literal : literal[0];
1147
1148 if (d_logicInfo.isSharingEnabled() && atom.getKind() == kind::EQUAL) {
1149 if (d_propEngine->isSatLiteral(literal)) {
1150 // We propagate SAT literals to SAT
1151 assertToTheory(literal, literal, /* to */ THEORY_SAT_SOLVER, /* from */ theory);
1152 }
1153 if (theory != THEORY_BUILTIN) {
1154 // Assert to the shared terms database
1155 assertToTheory(literal, literal, /* to */ THEORY_BUILTIN, /* from */ theory);
1156 }
1157 } else {
1158 // Just send off to the SAT solver
1159 Assert(d_propEngine->isSatLiteral(literal));
1160 assertToTheory(literal, literal, /* to */ THEORY_SAT_SOLVER, /* from */ theory);
1161 }
1162
1163 return !d_inConflict;
1164 }
1165
1166
1167 theory::EqualityStatus TheoryEngine::getEqualityStatus(TNode a, TNode b) {
1168 Assert(a.getType().isComparableTo(b.getType()));
1169 if (d_sharedTerms.isShared(a) && d_sharedTerms.isShared(b)) {
1170 if (d_sharedTerms.areEqual(a,b)) {
1171 return EQUALITY_TRUE_AND_PROPAGATED;
1172 }
1173 else if (d_sharedTerms.areDisequal(a,b)) {
1174 return EQUALITY_FALSE_AND_PROPAGATED;
1175 }
1176 }
1177 return theoryOf(Theory::theoryOf(a.getType()))->getEqualityStatus(a, b);
1178 }
1179
1180 Node TheoryEngine::getModelValue(TNode var) {
1181 Assert(d_sharedTerms.isShared(var));
1182 return theoryOf(Theory::theoryOf(var.getType()))->getModelValue(var);
1183 }
1184
1185 void TheoryEngine::printInstantiations( std::ostream& out ) {
1186 if( d_quantEngine ){
1187 d_quantEngine->printInstantiations( out );
1188 }
1189 }
1190
1191 static Node mkExplanation(const std::vector<NodeTheoryPair>& explanation) {
1192
1193 std::set<TNode> all;
1194 for (unsigned i = 0; i < explanation.size(); ++ i) {
1195 Assert(explanation[i].theory == THEORY_SAT_SOLVER);
1196 all.insert(explanation[i].node);
1197 }
1198
1199 if (all.size() == 0) {
1200 // Normalize to true
1201 return NodeManager::currentNM()->mkConst<bool>(true);
1202 }
1203
1204 if (all.size() == 1) {
1205 // All the same, or just one
1206 return explanation[0].node;
1207 }
1208
1209 NodeBuilder<> conjunction(kind::AND);
1210 std::set<TNode>::const_iterator it = all.begin();
1211 std::set<TNode>::const_iterator it_end = all.end();
1212 while (it != it_end) {
1213 conjunction << *it;
1214 ++ it;
1215 }
1216
1217 return conjunction;
1218 }
1219
1220
1221 Node TheoryEngine::getExplanation(TNode node) {
1222 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node << "): current propagation index = " << d_propagationMapTimestamp << endl;
1223
1224 bool polarity = node.getKind() != kind::NOT;
1225 TNode atom = polarity ? node : node[0];
1226
1227 // If we're not in shared mode, explanations are simple
1228 if (!d_logicInfo.isSharingEnabled()) {
1229 Node explanation = theoryOf(atom)->explain(node);
1230 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node << ") => " << explanation << endl;
1231 return explanation;
1232 }
1233
1234 // Initial thing to explain
1235 NodeTheoryPair toExplain(node, THEORY_SAT_SOLVER, d_propagationMapTimestamp);
1236 Assert(d_propagationMap.find(toExplain) != d_propagationMap.end());
1237 // Create the workplace for explanations
1238 std::vector<NodeTheoryPair> explanationVector;
1239 explanationVector.push_back(d_propagationMap[toExplain]);
1240 // Process the explanation
1241 getExplanation(explanationVector);
1242 Node explanation = mkExplanation(explanationVector);
1243
1244 Debug("theory::explain") << "TheoryEngine::getExplanation(" << node << ") => " << explanation << endl;
1245
1246 return explanation;
1247 }
1248
1249 struct AtomsCollect {
1250
1251 std::vector<TNode> d_atoms;
1252 std::hash_set<TNode, TNodeHashFunction> d_visited;
1253
1254 public:
1255
1256 typedef void return_type;
1257
1258 bool alreadyVisited(TNode current, TNode parent) {
1259 // Check if already visited
1260 if (d_visited.find(current) != d_visited.end()) return true;
1261 // Don't visit non-boolean
1262 if (!current.getType().isBoolean()) return true;
1263 // New node
1264 return false;
1265 }
1266
1267 void visit(TNode current, TNode parent) {
1268 if (Theory::theoryOf(current) != theory::THEORY_BOOL) {
1269 d_atoms.push_back(current);
1270 }
1271 d_visited.insert(current);
1272 }
1273
1274 void start(TNode node) {}
1275 void done(TNode node) {}
1276
1277 std::vector<TNode> getAtoms() const {
1278 return d_atoms;
1279 }
1280 };
1281
1282 void TheoryEngine::ensureLemmaAtoms(const std::vector<TNode>& atoms, theory::TheoryId atomsTo) {
1283 for (unsigned i = 0; i < atoms.size(); ++ i) {
1284
1285 // Non-equality atoms are either owned by theory or they don't make sense
1286 if (atoms[i].getKind() != kind::EQUAL) {
1287 continue;
1288 }
1289
1290 // The equality
1291 Node eq = atoms[i];
1292 // Simple normalization to not repeat stuff
1293 if (eq[0] > eq[1]) {
1294 eq = eq[1].eqNode(eq[0]);
1295 }
1296
1297 // Rewrite the equality
1298 Node eqNormalized = Rewriter::rewrite(atoms[i]);
1299
1300 Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq << " with nf " << eqNormalized << endl;
1301
1302 // If the equality is a boolean constant, we send immediately
1303 if (eqNormalized.isConst()) {
1304 if (eqNormalized.getConst<bool>()) {
1305 assertToTheory(eq, eqNormalized, /** to */ atomsTo, /** Sat solver */ theory::THEORY_SAT_SOLVER);
1306 } else {
1307 assertToTheory(eq.notNode(), eqNormalized.notNode(), /** to */ atomsTo, /** Sat solver */ theory::THEORY_SAT_SOLVER);
1308 }
1309 continue;
1310 }
1311
1312 Assert(eqNormalized.getKind() == kind::EQUAL);
1313
1314
1315 // If the normalization did the just flips, keep the flip
1316 if (eqNormalized[0] == eq[1] && eqNormalized[1] == eq[0]) {
1317 eq = eqNormalized;
1318 }
1319
1320 // Check if the equality is already known by the sat solver
1321 if (d_propEngine->isSatLiteral(eqNormalized)) {
1322 bool value;
1323 if (d_propEngine->hasValue(eqNormalized, value)) {
1324 if (value) {
1325 assertToTheory(eq, eqNormalized, atomsTo, theory::THEORY_SAT_SOLVER);
1326 continue;
1327 } else {
1328 assertToTheory(eq.notNode(), eqNormalized.notNode(), atomsTo, theory::THEORY_SAT_SOLVER);
1329 continue;
1330 }
1331 }
1332 }
1333
1334 // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1335 // then we must figure it out
1336 if (eqNormalized != eq || Theory::theoryOf(eq) != atomsTo) {
1337 // If you get eqNormalized, send atoms[i] to atomsTo
1338 d_atomRequests.add(eqNormalized, eq, atomsTo);
1339 }
1340 }
1341 }
1342
1343 theory::LemmaStatus TheoryEngine::lemma(TNode node, bool negated, bool removable, bool preprocess, theory::TheoryId atomsTo) {
1344
1345 // Do we need to check atoms
1346 if (atomsTo != theory::THEORY_LAST) {
1347 Debug("theory::atoms") << "TheoryEngine::lemma(" << node << ", " << atomsTo << ")" << endl;
1348 AtomsCollect collectAtoms;
1349 NodeVisitor<AtomsCollect>::run(collectAtoms, node);
1350 ensureLemmaAtoms(collectAtoms.getAtoms(), atomsTo);
1351 }
1352
1353 if(Dump.isOn("t-lemmas")) {
1354 Node n = node;
1355 if (negated) {
1356 n = node.negate();
1357 }
1358 Dump("t-lemmas") << CommentCommand("theory lemma: expect valid")
1359 << QueryCommand(n.toExpr());
1360 }
1361
1362 // Share with other portfolio threads
1363 if(options::lemmaOutputChannel() != NULL) {
1364 options::lemmaOutputChannel()->notifyNewLemma(node.toExpr());
1365 }
1366
1367 // Run theory preprocessing, maybe
1368 Node ppNode = preprocess ? this->preprocess(node) : Node(node);
1369
1370 // Remove the ITEs
1371 std::vector<Node> additionalLemmas;
1372 IteSkolemMap iteSkolemMap;
1373 additionalLemmas.push_back(ppNode);
1374 d_iteRemover.run(additionalLemmas, iteSkolemMap);
1375 additionalLemmas[0] = theory::Rewriter::rewrite(additionalLemmas[0]);
1376
1377 if(Debug.isOn("lemma-ites")) {
1378 Debug("lemma-ites") << "removed ITEs from lemma: " << ppNode << endl;
1379 Debug("lemma-ites") << " + now have the following "
1380 << additionalLemmas.size() << " lemma(s):" << endl;
1381 for(std::vector<Node>::const_iterator i = additionalLemmas.begin();
1382 i != additionalLemmas.end();
1383 ++i) {
1384 Debug("lemma-ites") << " + " << *i << endl;
1385 }
1386 Debug("lemma-ites") << endl;
1387 }
1388
1389 // assert to prop engine
1390 d_propEngine->assertLemma(additionalLemmas[0], negated, removable, RULE_INVALID, node);
1391 for (unsigned i = 1; i < additionalLemmas.size(); ++ i) {
1392 additionalLemmas[i] = theory::Rewriter::rewrite(additionalLemmas[i]);
1393 d_propEngine->assertLemma(additionalLemmas[i], false, removable, RULE_INVALID, node);
1394 }
1395
1396 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1397 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1398 if(negated) {
1399 // Can't we just get rid of passing around this 'negated' stuff?
1400 // Is it that hard for the propEngine to figure that out itself?
1401 // (I like the use of triple negation <evil laugh>.) --K
1402 additionalLemmas[0] = additionalLemmas[0].notNode();
1403 negated = false;
1404 }
1405 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1406 // WARNING: Below this point don't assume additionalLemmas[0] to be not negated.
1407
1408 // assert to decision engine
1409 if(!removable) {
1410 d_decisionEngine->addAssertions(additionalLemmas, 1, iteSkolemMap);
1411 }
1412
1413 // Mark that we added some lemmas
1414 d_lemmasAdded = true;
1415
1416 // Lemma analysis isn't online yet; this lemma may only live for this
1417 // user level.
1418 return theory::LemmaStatus(additionalLemmas[0], d_userContext->getLevel());
1419 }
1420
1421 void TheoryEngine::conflict(TNode conflict, TheoryId theoryId) {
1422
1423 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict << ", " << theoryId << ")" << endl;
1424
1425 // Mark that we are in conflict
1426 d_inConflict = true;
1427
1428 if(Dump.isOn("t-conflicts")) {
1429 Dump("t-conflicts") << CommentCommand("theory conflict: expect unsat")
1430 << CheckSatCommand(conflict.toExpr());
1431 }
1432
1433 // In the multiple-theories case, we need to reconstruct the conflict
1434 if (d_logicInfo.isSharingEnabled()) {
1435 // Create the workplace for explanations
1436 std::vector<NodeTheoryPair> explanationVector;
1437 explanationVector.push_back(NodeTheoryPair(conflict, theoryId, d_propagationMapTimestamp));
1438 // Process the explanation
1439 getExplanation(explanationVector);
1440 Node fullConflict = mkExplanation(explanationVector);
1441 Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict << ", " << theoryId << "): full = " << fullConflict << endl;
1442 Assert(properConflict(fullConflict));
1443 lemma(fullConflict, true, true, false, THEORY_LAST);
1444 } else {
1445 // When only one theory, the conflict should need no processing
1446 Assert(properConflict(conflict));
1447 lemma(conflict, true, true, false, THEORY_LAST);
1448 }
1449 }
1450
1451 void TheoryEngine::staticInitializeBVOptions(const std::vector<Node>& assertions) {
1452 bool useSlicer = true;
1453 if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_ON) {
1454 if (options::incrementalSolving())
1455 throw ModalException("Slicer does not currently support incremental mode. Use --bv-eq-slicer=off");
1456 if (options::produceModels())
1457 throw ModalException("Slicer does not currently support model generation. Use --bv-eq-slicer=off");
1458 useSlicer = true;
1459
1460 } else if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_OFF) {
1461 return;
1462
1463 } else if (options::bitvectorEqualitySlicer() == bv::BITVECTOR_SLICER_AUTO) {
1464 if (options::incrementalSolving() ||
1465 options::produceModels())
1466 return;
1467
1468 useSlicer = true;
1469 bv::utils::TNodeBoolMap cache;
1470 for (unsigned i = 0; i < assertions.size(); ++i) {
1471 useSlicer = useSlicer && bv::utils::isCoreTerm(assertions[i], cache);
1472 }
1473 }
1474
1475 if (useSlicer) {
1476 bv::TheoryBV* bv_theory = (bv::TheoryBV*)d_theoryTable[THEORY_BV];
1477 bv_theory->enableCoreTheorySlicer();
1478 }
1479
1480 }
1481
1482 void TheoryEngine::ppBvToBool(const std::vector<Node>& assertions, std::vector<Node>& new_assertions) {
1483 d_bvToBoolPreprocessor.liftBvToBool(assertions, new_assertions);
1484 }
1485
1486 bool TheoryEngine::ppBvAbstraction(const std::vector<Node>& assertions, std::vector<Node>& new_assertions) {
1487 bv::TheoryBV* bv_theory = (bv::TheoryBV*)d_theoryTable[THEORY_BV];
1488 return bv_theory->applyAbstraction(assertions, new_assertions);
1489 }
1490
1491 void TheoryEngine::mkAckermanizationAsssertions(std::vector<Node>& assertions) {
1492 bv::TheoryBV* bv_theory = (bv::TheoryBV*)d_theoryTable[THEORY_BV];
1493 bv_theory->mkAckermanizationAsssertions(assertions);
1494 }
1495
1496 Node TheoryEngine::ppSimpITE(TNode assertion)
1497 {
1498 if(!d_iteRemover.containsTermITE(assertion)){
1499 return assertion;
1500 }else{
1501
1502 Node result = d_iteUtilities->simpITE(assertion);
1503 Node res_rewritten = Rewriter::rewrite(result);
1504
1505 if(options::simplifyWithCareEnabled()){
1506 Chat() << "starting simplifyWithCare()" << endl;
1507 Node postSimpWithCare = d_iteUtilities->simplifyWithCare(res_rewritten);
1508 Chat() << "ending simplifyWithCare()"
1509 << " post simplifyWithCare()" << postSimpWithCare.getId() << endl;
1510 result = Rewriter::rewrite(postSimpWithCare);
1511 }else{
1512 result = res_rewritten;
1513 }
1514
1515 return result;
1516 }
1517 }
1518
1519 bool TheoryEngine::donePPSimpITE(std::vector<Node>& assertions){
1520 bool result = true;
1521 bool simpDidALotOfWork = d_iteUtilities->simpIteDidALotOfWorkHeuristic();
1522 if(simpDidALotOfWork){
1523 if(options::compressItes()){
1524 result = d_iteUtilities->compress(assertions);
1525 }
1526
1527 if(result){
1528 // if false, don't bother to reclaim memory here.
1529 NodeManager* nm = NodeManager::currentNM();
1530 if(nm->poolSize() >= options::zombieHuntThreshold()){
1531 Chat() << "..ite simplifier did quite a bit of work.. " << nm->poolSize() << endl;
1532 Chat() << "....node manager contains " << nm->poolSize() << " nodes before cleanup" << endl;
1533 d_iteUtilities->clear();
1534 Rewriter::garbageCollect();
1535 d_iteRemover.garbageCollect();
1536 nm->reclaimZombiesUntil(options::zombieHuntThreshold());
1537 Chat() << "....node manager contains " << nm->poolSize() << " nodes after cleanup" << endl;
1538 }
1539 }
1540 }
1541
1542 // Do theory specific preprocessing passes
1543 if(d_logicInfo.isTheoryEnabled(theory::THEORY_ARITH)){
1544 if(!simpDidALotOfWork){
1545 ContainsTermITEVisitor& contains = *d_iteRemover.getContainsVisitor();
1546 arith::ArithIteUtils aiteu(contains, d_userContext, getModel());
1547 bool anyItes = false;
1548 for(size_t i = 0; i < assertions.size(); ++i){
1549 Node curr = assertions[i];
1550 if(contains.containsTermITE(curr)){
1551 anyItes = true;
1552 Node res = aiteu.reduceVariablesInItes(curr);
1553 Debug("arith::ite::red") << "@ " << i << " ... " << curr << endl << " ->" << res << endl;
1554 if(curr != res){
1555 Node more = aiteu.reduceConstantIteByGCD(res);
1556 Debug("arith::ite::red") << " gcd->" << more << endl;
1557 assertions[i] = more;
1558 }
1559 }
1560 }
1561 if(!anyItes){
1562 unsigned prevSubCount = aiteu.getSubCount();
1563 aiteu.learnSubstitutions(assertions);
1564 if(prevSubCount < aiteu.getSubCount()){
1565 d_arithSubstitutionsAdded += aiteu.getSubCount() - prevSubCount;
1566 bool anySuccess = false;
1567 for(size_t i = 0, N = assertions.size(); i < N; ++i){
1568 Node curr = assertions[i];
1569 Node next = Rewriter::rewrite(aiteu.applySubstitutions(curr));
1570 Node res = aiteu.reduceVariablesInItes(next);
1571 Debug("arith::ite::red") << "@ " << i << " ... " << next << endl << " ->" << res << endl;
1572 Node more = aiteu.reduceConstantIteByGCD(res);
1573 Debug("arith::ite::red") << " gcd->" << more << endl;
1574 if(more != next){
1575 anySuccess = true;
1576 break;
1577 }
1578 }
1579 for(size_t i = 0, N = assertions.size(); anySuccess && i < N; ++i){
1580 Node curr = assertions[i];
1581 Node next = Rewriter::rewrite(aiteu.applySubstitutions(curr));
1582 Node res = aiteu.reduceVariablesInItes(next);
1583 Debug("arith::ite::red") << "@ " << i << " ... " << next << endl << " ->" << res << endl;
1584 Node more = aiteu.reduceConstantIteByGCD(res);
1585 Debug("arith::ite::red") << " gcd->" << more << endl;
1586 assertions[i] = Rewriter::rewrite(more);
1587 }
1588 }
1589 }
1590 }
1591 }
1592 return result;
1593 }
1594
1595 void TheoryEngine::getExplanation(std::vector<NodeTheoryPair>& explanationVector)
1596 {
1597 Assert(explanationVector.size() > 0);
1598
1599 unsigned i = 0; // Index of the current literal we are processing
1600 unsigned j = 0; // Index of the last literal we are keeping
1601
1602 while (i < explanationVector.size()) {
1603
1604 // Get the current literal to explain
1605 NodeTheoryPair toExplain = explanationVector[i];
1606
1607 Debug("theory::explain") << "TheoryEngine::explain(): processing [" << toExplain.timestamp << "] " << toExplain.node << " sent from " << toExplain.theory << endl;
1608
1609 // If a true constant or a negation of a false constant we can ignore it
1610 if (toExplain.node.isConst() && toExplain.node.getConst<bool>()) {
1611 ++ i;
1612 continue;
1613 }
1614 if (toExplain.node.getKind() == kind::NOT && toExplain.node[0].isConst() && !toExplain.node[0].getConst<bool>()) {
1615 ++ i;
1616 continue;
1617 }
1618
1619 // If from the SAT solver, keep it
1620 if (toExplain.theory == THEORY_SAT_SOLVER) {
1621 explanationVector[j++] = explanationVector[i++];
1622 continue;
1623 }
1624
1625 // If an and, expand it
1626 if (toExplain.node.getKind() == kind::AND) {
1627 Debug("theory::explain") << "TheoryEngine::explain(): expanding " << toExplain.node << " got from " << toExplain.theory << endl;
1628 for (unsigned k = 0; k < toExplain.node.getNumChildren(); ++ k) {
1629 NodeTheoryPair newExplain(toExplain.node[k], toExplain.theory, toExplain.timestamp);
1630 explanationVector.push_back(newExplain);
1631 }
1632 ++ i;
1633 continue;
1634 }
1635
1636 // See if it was sent to the theory by another theory
1637 PropagationMap::const_iterator find = d_propagationMap.find(toExplain);
1638 if (find != d_propagationMap.end()) {
1639 // There is some propagation, check if its a timely one
1640 if ((*find).second.timestamp < toExplain.timestamp) {
1641 explanationVector.push_back((*find).second);
1642 ++ i;
1643 continue;
1644 }
1645 }
1646
1647 // It was produced by the theory, so ask for an explanation
1648 Node explanation;
1649 if (toExplain.theory == THEORY_BUILTIN) {
1650 explanation = d_sharedTerms.explain(toExplain.node);
1651 } else {
1652 explanation = theoryOf(toExplain.theory)->explain(toExplain.node);
1653 }
1654 Debug("theory::explain") << "TheoryEngine::explain(): got explanation " << explanation << " got from " << toExplain.theory << endl;
1655 Assert(explanation != toExplain.node, "wasn't sent to you, so why are you explaining it trivially");
1656 // Mark the explanation
1657 NodeTheoryPair newExplain(explanation, toExplain.theory, toExplain.timestamp);
1658 explanationVector.push_back(newExplain);
1659 ++ i;
1660 }
1661
1662 // Keep only the relevant literals
1663 explanationVector.resize(j);
1664 }
1665
1666
1667 void TheoryEngine::ppUnconstrainedSimp(vector<Node>& assertions)
1668 {
1669 d_unconstrainedSimp->processAssertions(assertions);
1670 }
1671
1672
1673 void TheoryEngine::setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value) {
1674 Trace("te-attr") << "set user attribute " << attr << " " << n << endl;
1675 if( d_attr_handle.find( attr )!=d_attr_handle.end() ){
1676 for( size_t i=0; i<d_attr_handle[attr].size(); i++ ){
1677 d_attr_handle[attr][i]->setUserAttribute(attr, n, node_values, str_value);
1678 }
1679 } else {
1680 //unhandled exception?
1681 }
1682 }
1683
1684 void TheoryEngine::handleUserAttribute(const char* attr, Theory* t) {
1685 Trace("te-attr") << "Handle user attribute " << attr << " " << t << endl;
1686 std::string str( attr );
1687 d_attr_handle[ str ].push_back( t );
1688 }
1689
1690 void TheoryEngine::checkTheoryAssertionsWithModel() {
1691 for(TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
1692 Theory* theory = d_theoryTable[theoryId];
1693 if(theory && d_logicInfo.isTheoryEnabled(theoryId)) {
1694 for(context::CDList<Assertion>::const_iterator it = theory->facts_begin(),
1695 it_end = theory->facts_end();
1696 it != it_end;
1697 ++it) {
1698 Node assertion = (*it).assertion;
1699 Node val = getModel()->getValue(assertion);
1700 if(val != d_true) {
1701 stringstream ss;
1702 ss << theoryId << " has an asserted fact that the model doesn't satisfy." << endl
1703 << "The fact: " << assertion << endl
1704 << "Model value: " << val << endl;
1705 InternalError(ss.str());
1706 }
1707 }
1708 }
1709 }
1710 }
1711
1712 std::pair<bool, Node> TheoryEngine::entailmentCheck(theory::TheoryOfMode mode, TNode lit, const EntailmentCheckParameters* params, EntailmentCheckSideEffects* seffects) {
1713 TNode atom = (lit.getKind() == kind::NOT) ? lit[0] : lit;
1714 theory::TheoryId tid = theory::Theory::theoryOf(mode, atom);
1715 theory::Theory* th = theoryOf(tid);
1716
1717 Assert(th != NULL);
1718 Assert(params == NULL || tid == params->getTheoryId());
1719 Assert(seffects == NULL || tid == seffects->getTheoryId());
1720
1721 return th->entailmentCheck(lit, params, seffects);
1722 }