Update copyright headers.
[cvc5.git] / src / theory / theory.cpp
1 /********************* */
2 /*! \file theory.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Andrew Reynolds, Tim King, Mathias Preiner
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
11 **
12 ** \brief Base for theory interface.
13 **
14 ** Base for theory interface.
15 **/
16
17 #include "theory/theory.h"
18
19 #include <iostream>
20 #include <sstream>
21 #include <string>
22 #include <vector>
23
24 #include "base/check.h"
25 #include "expr/node_algorithm.h"
26 #include "options/smt_options.h"
27 #include "options/theory_options.h"
28 #include "smt/smt_statistics_registry.h"
29 #include "theory/ext_theory.h"
30 #include "theory/quantifiers_engine.h"
31 #include "theory/substitutions.h"
32 #include "theory/theory_rewriter.h"
33
34 using namespace std;
35
36 namespace CVC4 {
37 namespace theory {
38
39 /** Default value for the uninterpreted sorts is the UF theory */
40 TheoryId Theory::s_uninterpretedSortOwner = THEORY_UF;
41
42 std::ostream& operator<<(std::ostream& os, Theory::Effort level){
43 switch(level){
44 case Theory::EFFORT_STANDARD:
45 os << "EFFORT_STANDARD"; break;
46 case Theory::EFFORT_FULL:
47 os << "EFFORT_FULL"; break;
48 case Theory::EFFORT_LAST_CALL:
49 os << "EFFORT_LAST_CALL"; break;
50 default:
51 Unreachable();
52 }
53 return os;
54 }/* ostream& operator<<(ostream&, Theory::Effort) */
55
56 Theory::Theory(TheoryId id,
57 context::Context* satContext,
58 context::UserContext* userContext,
59 OutputChannel& out,
60 Valuation valuation,
61 const LogicInfo& logicInfo,
62 ProofNodeManager* pnm,
63 std::string name)
64 : d_id(id),
65 d_satContext(satContext),
66 d_userContext(userContext),
67 d_logicInfo(logicInfo),
68 d_facts(satContext),
69 d_factsHead(satContext, 0),
70 d_sharedTermsIndex(satContext, 0),
71 d_careGraph(NULL),
72 d_quantEngine(NULL),
73 d_decManager(nullptr),
74 d_instanceName(name),
75 d_checkTime(getStatsPrefix(id) + name + "::checkTime"),
76 d_computeCareGraphTime(getStatsPrefix(id) + name
77 + "::computeCareGraphTime"),
78 d_sharedTerms(satContext),
79 d_out(&out),
80 d_valuation(valuation),
81 d_equalityEngine(nullptr),
82 d_allocEqualityEngine(nullptr),
83 d_theoryState(nullptr),
84 d_inferManager(nullptr),
85 d_pnm(pnm)
86 {
87 smtStatisticsRegistry()->registerStat(&d_checkTime);
88 smtStatisticsRegistry()->registerStat(&d_computeCareGraphTime);
89 }
90
91 Theory::~Theory() {
92 smtStatisticsRegistry()->unregisterStat(&d_checkTime);
93 smtStatisticsRegistry()->unregisterStat(&d_computeCareGraphTime);
94 }
95
96 bool Theory::needsEqualityEngine(EeSetupInfo& esi)
97 {
98 // by default, this theory does not use an (official) equality engine
99 return false;
100 }
101
102 void Theory::setEqualityEngine(eq::EqualityEngine* ee)
103 {
104 // set the equality engine pointer
105 d_equalityEngine = ee;
106 if (d_theoryState != nullptr)
107 {
108 d_theoryState->setEqualityEngine(ee);
109 }
110 if (d_inferManager != nullptr)
111 {
112 d_inferManager->setEqualityEngine(ee);
113 }
114 }
115
116 void Theory::setQuantifiersEngine(QuantifiersEngine* qe)
117 {
118 Assert(d_quantEngine == nullptr);
119 // quantifiers engine may be null if not in quantified logic
120 d_quantEngine = qe;
121 }
122
123 void Theory::setDecisionManager(DecisionManager* dm)
124 {
125 Assert(d_decManager == nullptr);
126 Assert(dm != nullptr);
127 d_decManager = dm;
128 }
129
130 void Theory::finishInitStandalone()
131 {
132 EeSetupInfo esi;
133 if (needsEqualityEngine(esi))
134 {
135 // always associated with the same SAT context as the theory (d_satContext)
136 d_allocEqualityEngine.reset(new eq::EqualityEngine(
137 *esi.d_notify, d_satContext, esi.d_name, esi.d_constantsAreTriggers));
138 // use it as the official equality engine
139 setEqualityEngine(d_allocEqualityEngine.get());
140 }
141 finishInit();
142 }
143
144 TheoryId Theory::theoryOf(options::TheoryOfMode mode, TNode node)
145 {
146 TheoryId tid = THEORY_BUILTIN;
147 switch(mode) {
148 case options::TheoryOfMode::THEORY_OF_TYPE_BASED:
149 // Constants, variables, 0-ary constructors
150 if (node.isVar())
151 {
152 if (node.getKind() == kind::BOOLEAN_TERM_VARIABLE)
153 {
154 tid = THEORY_UF;
155 }
156 else
157 {
158 tid = Theory::theoryOf(node.getType());
159 }
160 }
161 else if (node.isConst())
162 {
163 tid = Theory::theoryOf(node.getType());
164 }
165 else if (node.getKind() == kind::EQUAL)
166 {
167 // Equality is owned by the theory that owns the domain
168 tid = Theory::theoryOf(node[0].getType());
169 }
170 else
171 {
172 // Regular nodes are owned by the kind
173 tid = kindToTheoryId(node.getKind());
174 }
175 break;
176 case options::TheoryOfMode::THEORY_OF_TERM_BASED:
177 // Variables
178 if (node.isVar())
179 {
180 if (Theory::theoryOf(node.getType()) != theory::THEORY_BOOL)
181 {
182 // We treat the variables as uninterpreted
183 tid = s_uninterpretedSortOwner;
184 }
185 else
186 {
187 if (node.getKind() == kind::BOOLEAN_TERM_VARIABLE)
188 {
189 // Boolean vars go to UF
190 tid = THEORY_UF;
191 }
192 else
193 {
194 // Except for the Boolean ones
195 tid = THEORY_BOOL;
196 }
197 }
198 }
199 else if (node.isConst())
200 {
201 // Constants go to the theory of the type
202 tid = Theory::theoryOf(node.getType());
203 }
204 else if (node.getKind() == kind::EQUAL)
205 { // Equality
206 // If one of them is an ITE, it's irelevant, since they will get
207 // replaced out anyhow
208 if (node[0].getKind() == kind::ITE)
209 {
210 tid = Theory::theoryOf(node[0].getType());
211 }
212 else if (node[1].getKind() == kind::ITE)
213 {
214 tid = Theory::theoryOf(node[1].getType());
215 }
216 else
217 {
218 TNode l = node[0];
219 TNode r = node[1];
220 TypeNode ltype = l.getType();
221 TypeNode rtype = r.getType();
222 if (ltype != rtype)
223 {
224 tid = Theory::theoryOf(l.getType());
225 }
226 else
227 {
228 // If both sides belong to the same theory the choice is easy
229 TheoryId T1 = Theory::theoryOf(l);
230 TheoryId T2 = Theory::theoryOf(r);
231 if (T1 == T2)
232 {
233 tid = T1;
234 }
235 else
236 {
237 TheoryId T3 = Theory::theoryOf(ltype);
238 // This is a case of
239 // * x*y = f(z) -> UF
240 // * x = c -> UF
241 // * f(x) = read(a, y) -> either UF or ARRAY
242 // at least one of the theories has to be parametric, i.e. theory
243 // of the type is different from the theory of the term
244 if (T1 == T3)
245 {
246 tid = T2;
247 }
248 else if (T2 == T3)
249 {
250 tid = T1;
251 }
252 else
253 {
254 // If both are parametric, we take the smaller one (arbitrary)
255 tid = T1 < T2 ? T1 : T2;
256 }
257 }
258 }
259 }
260 }
261 else
262 {
263 // Regular nodes are owned by the kind
264 tid = kindToTheoryId(node.getKind());
265 }
266 break;
267 default:
268 Unreachable();
269 }
270 Trace("theory::internal") << "theoryOf(" << mode << ", " << node << ") -> " << tid << std::endl;
271 return tid;
272 }
273
274 void Theory::notifySharedTerm(TNode n)
275 {
276 // do nothing
277 }
278
279 void Theory::computeCareGraph() {
280 Debug("sharing") << "Theory::computeCareGraph<" << getId() << ">()" << endl;
281 for (unsigned i = 0; i < d_sharedTerms.size(); ++ i) {
282 TNode a = d_sharedTerms[i];
283 TypeNode aType = a.getType();
284 for (unsigned j = i + 1; j < d_sharedTerms.size(); ++ j) {
285 TNode b = d_sharedTerms[j];
286 if (b.getType() != aType) {
287 // We don't care about the terms of different types
288 continue;
289 }
290 switch (d_valuation.getEqualityStatus(a, b)) {
291 case EQUALITY_TRUE_AND_PROPAGATED:
292 case EQUALITY_FALSE_AND_PROPAGATED:
293 // If we know about it, we should have propagated it, so we can skip
294 break;
295 default:
296 // Let's split on it
297 addCarePair(a, b);
298 break;
299 }
300 }
301 }
302 }
303
304 void Theory::printFacts(std::ostream& os) const {
305 unsigned i, n = d_facts.size();
306 for(i = 0; i < n; i++){
307 const Assertion& a_i = d_facts[i];
308 Node assertion = a_i;
309 os << d_id << '[' << i << ']' << " " << assertion << endl;
310 }
311 }
312
313 void Theory::debugPrintFacts() const{
314 DebugChannel.getStream() << "Theory::debugPrintFacts()" << endl;
315 printFacts(DebugChannel.getStream());
316 }
317
318 bool Theory::isLegalElimination(TNode x, TNode val)
319 {
320 Assert(x.isVar());
321 if (x.getKind() == kind::BOOLEAN_TERM_VARIABLE
322 || val.getKind() == kind::BOOLEAN_TERM_VARIABLE)
323 {
324 return false;
325 }
326 if (expr::hasSubterm(val, x))
327 {
328 return false;
329 }
330 if (!val.getType().isSubtypeOf(x.getType()))
331 {
332 return false;
333 }
334 if (!options::produceModels())
335 {
336 // don't care about the model, we are fine
337 return true;
338 }
339 // if there is a model object
340 TheoryModel* tm = d_valuation.getModel();
341 Assert(tm != nullptr);
342 return tm->isLegalElimination(x, val);
343 }
344
345 std::unordered_set<TNode, TNodeHashFunction> Theory::currentlySharedTerms() const{
346 std::unordered_set<TNode, TNodeHashFunction> currentlyShared;
347 for (shared_terms_iterator i = shared_terms_begin(),
348 i_end = shared_terms_end(); i != i_end; ++i) {
349 currentlyShared.insert (*i);
350 }
351 return currentlyShared;
352 }
353
354 bool Theory::collectModelInfo(TheoryModel* m, const std::set<Node>& termSet)
355 {
356 // if we are using an equality engine, assert it to the model
357 if (d_equalityEngine != nullptr)
358 {
359 if (!m->assertEqualityEngine(d_equalityEngine, &termSet))
360 {
361 return false;
362 }
363 }
364 // now, collect theory-specific value assigments
365 return collectModelValues(m, termSet);
366 }
367
368 void Theory::computeRelevantTerms(std::set<Node>& termSet)
369 {
370 // by default, there are no additional relevant terms
371 }
372
373 bool Theory::collectModelValues(TheoryModel* m, const std::set<Node>& termSet)
374 {
375 return true;
376 }
377
378 Theory::PPAssertStatus Theory::ppAssert(TrustNode tin,
379 TrustSubstitutionMap& outSubstitutions)
380 {
381 TNode in = tin.getNode();
382 if (in.getKind() == kind::EQUAL)
383 {
384 // (and (= x t) phi) can be replaced by phi[x/t] if
385 // 1) x is a variable
386 // 2) x is not in the term t
387 // 3) x : T and t : S, then S <: T
388 if (in[0].isVar() && isLegalElimination(in[0], in[1])
389 && in[0].getKind() != kind::BOOLEAN_TERM_VARIABLE)
390 {
391 outSubstitutions.addSubstitutionSolved(in[0], in[1], tin);
392 return PP_ASSERT_STATUS_SOLVED;
393 }
394 if (in[1].isVar() && isLegalElimination(in[1], in[0])
395 && in[1].getKind() != kind::BOOLEAN_TERM_VARIABLE)
396 {
397 outSubstitutions.addSubstitutionSolved(in[1], in[0], tin);
398 return PP_ASSERT_STATUS_SOLVED;
399 }
400 if (in[0].isConst() && in[1].isConst())
401 {
402 if (in[0] != in[1])
403 {
404 return PP_ASSERT_STATUS_CONFLICT;
405 }
406 }
407 }
408
409 return PP_ASSERT_STATUS_UNSOLVED;
410 }
411
412 std::pair<bool, Node> Theory::entailmentCheck(TNode lit)
413 {
414 return make_pair(false, Node::null());
415 }
416
417 void Theory::addCarePair(TNode t1, TNode t2) {
418 if (d_careGraph) {
419 d_careGraph->insert(CarePair(t1, t2, d_id));
420 }
421 }
422
423 void Theory::getCareGraph(CareGraph* careGraph) {
424 Assert(careGraph != NULL);
425
426 Trace("sharing") << "Theory<" << getId() << ">::getCareGraph()" << std::endl;
427 TimerStat::CodeTimer computeCareGraphTime(d_computeCareGraphTime);
428 d_careGraph = careGraph;
429 computeCareGraph();
430 d_careGraph = NULL;
431 }
432
433 EqualityStatus Theory::getEqualityStatus(TNode a, TNode b)
434 {
435 // if not using an equality engine, then by default we don't know the status
436 if (d_equalityEngine == nullptr)
437 {
438 return EQUALITY_UNKNOWN;
439 }
440 Trace("sharing") << "Theory<" << getId() << ">::getEqualityStatus(" << a << ", " << b << ")" << std::endl;
441 Assert(d_equalityEngine->hasTerm(a) && d_equalityEngine->hasTerm(b));
442
443 // Check for equality (simplest)
444 if (d_equalityEngine->areEqual(a, b))
445 {
446 // The terms are implied to be equal
447 return EQUALITY_TRUE;
448 }
449
450 // Check for disequality
451 if (d_equalityEngine->areDisequal(a, b, false))
452 {
453 // The terms are implied to be dis-equal
454 return EQUALITY_FALSE;
455 }
456
457 // All other terms are unknown, which is conservative. A theory may override
458 // this method if it knows more information.
459 return EQUALITY_UNKNOWN;
460 }
461
462 void Theory::check(Effort level)
463 {
464 // see if we are already done (as an optimization)
465 if (done() && level < EFFORT_FULL)
466 {
467 return;
468 }
469 Assert(d_theoryState!=nullptr);
470 // standard calls for resource, stats
471 d_out->spendResource(ResourceManager::Resource::TheoryCheckStep);
472 TimerStat::CodeTimer checkTimer(d_checkTime);
473 Trace("theory-check") << "Theory::preCheck " << level << " " << d_id
474 << std::endl;
475 // pre-check at level
476 if (preCheck(level))
477 {
478 // check aborted for a theory-specific reason
479 return;
480 }
481 Assert(d_theoryState != nullptr);
482 Trace("theory-check") << "Theory::process fact queue " << d_id << std::endl;
483 // process the pending fact queue
484 while (!done() && !d_theoryState->isInConflict())
485 {
486 // Get the next assertion from the fact queue
487 Assertion assertion = get();
488 TNode fact = assertion.d_assertion;
489 Trace("theory-check") << "Theory::preNotifyFact " << fact << " " << d_id
490 << std::endl;
491 bool polarity = fact.getKind() != kind::NOT;
492 TNode atom = polarity ? fact : fact[0];
493 // call the pre-notify method
494 if (preNotifyFact(atom, polarity, fact, assertion.d_isPreregistered, false))
495 {
496 // handled in theory-specific way that doesn't involve equality engine
497 continue;
498 }
499 Trace("theory-check") << "Theory::assert " << fact << " " << d_id
500 << std::endl;
501 // Theories that don't have an equality engine should always return true
502 // for preNotifyFact
503 Assert(d_equalityEngine != nullptr);
504 // assert to the equality engine
505 if (atom.getKind() == kind::EQUAL)
506 {
507 d_equalityEngine->assertEquality(atom, polarity, fact);
508 }
509 else
510 {
511 d_equalityEngine->assertPredicate(atom, polarity, fact);
512 }
513 Trace("theory-check") << "Theory::notifyFact " << fact << " " << d_id
514 << std::endl;
515 // notify the theory of the new fact, which is not internal
516 notifyFact(atom, polarity, fact, false);
517 }
518 Trace("theory-check") << "Theory::postCheck " << d_id << std::endl;
519 // post-check at level
520 postCheck(level);
521 Trace("theory-check") << "Theory::finish check " << d_id << std::endl;
522 }
523
524 bool Theory::preCheck(Effort level) { return false; }
525
526 void Theory::postCheck(Effort level) {}
527
528 bool Theory::preNotifyFact(
529 TNode atom, bool polarity, TNode fact, bool isPrereg, bool isInternal)
530 {
531 return false;
532 }
533
534 void Theory::notifyFact(TNode atom, bool polarity, TNode fact, bool isInternal)
535 {
536 }
537
538 void Theory::preRegisterTerm(TNode node) {}
539
540 void Theory::addSharedTerm(TNode n)
541 {
542 Debug("sharing") << "Theory::addSharedTerm<" << getId() << ">(" << n << ")"
543 << std::endl;
544 Debug("theory::assertions")
545 << "Theory::addSharedTerm<" << getId() << ">(" << n << ")" << std::endl;
546 d_sharedTerms.push_back(n);
547 // now call theory-specific method notifySharedTerm
548 notifySharedTerm(n);
549 // if we have an equality engine, add the trigger term
550 if (d_equalityEngine != nullptr)
551 {
552 d_equalityEngine->addTriggerTerm(n, d_id);
553 }
554 }
555
556 eq::EqualityEngine* Theory::getEqualityEngine()
557 {
558 // get the assigned equality engine, which is a pointer stored in this class
559 return d_equalityEngine;
560 }
561
562 }/* CVC4::theory namespace */
563 }/* CVC4 namespace */