1 /********************* */
4 ** Top contributors (to current version):
5 ** Tim King, Mathias Preiner, Dejan Jovanovic
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 Base for theory interface.
14 ** Base for theory interface.
17 #include "theory/theory.h"
24 #include "base/check.h"
25 #include "expr/node_algorithm.h"
26 #include "options/theory_options.h"
27 #include "smt/smt_statistics_registry.h"
28 #include "theory/ext_theory.h"
29 #include "theory/quantifiers_engine.h"
30 #include "theory/substitutions.h"
31 #include "theory/theory_rewriter.h"
38 /** Default value for the uninterpreted sorts is the UF theory */
39 TheoryId
Theory::s_uninterpretedSortOwner
= THEORY_UF
;
41 std::ostream
& operator<<(std::ostream
& os
, Theory::Effort level
){
43 case Theory::EFFORT_STANDARD
:
44 os
<< "EFFORT_STANDARD"; break;
45 case Theory::EFFORT_FULL
:
46 os
<< "EFFORT_FULL"; break;
47 case Theory::EFFORT_LAST_CALL
:
48 os
<< "EFFORT_LAST_CALL"; break;
53 }/* ostream& operator<<(ostream&, Theory::Effort) */
55 Theory::Theory(TheoryId id
,
56 context::Context
* satContext
,
57 context::UserContext
* userContext
,
60 const LogicInfo
& logicInfo
,
61 ProofNodeManager
* pnm
,
64 d_satContext(satContext
),
65 d_userContext(userContext
),
66 d_logicInfo(logicInfo
),
69 d_factsHead(satContext
, 0),
70 d_sharedTermsIndex(satContext
, 0),
73 d_decManager(nullptr),
75 d_checkTime(getStatsPrefix(id
) + name
+ "::checkTime"),
76 d_computeCareGraphTime(getStatsPrefix(id
) + name
77 + "::computeCareGraphTime"),
78 d_sharedTerms(satContext
),
80 d_valuation(valuation
),
81 d_equalityEngine(nullptr),
82 d_allocEqualityEngine(nullptr),
83 d_theoryState(nullptr),
84 d_proofsEnabled(false)
86 smtStatisticsRegistry()->registerStat(&d_checkTime
);
87 smtStatisticsRegistry()->registerStat(&d_computeCareGraphTime
);
91 smtStatisticsRegistry()->unregisterStat(&d_checkTime
);
92 smtStatisticsRegistry()->unregisterStat(&d_computeCareGraphTime
);
95 bool Theory::needsEqualityEngine(EeSetupInfo
& esi
)
97 // by default, this theory does not use an (official) equality engine
101 void Theory::setEqualityEngine(eq::EqualityEngine
* ee
)
103 // set the equality engine pointer
104 d_equalityEngine
= ee
;
105 if (d_theoryState
!= nullptr)
107 d_theoryState
->setEqualityEngine(ee
);
111 void Theory::setQuantifiersEngine(QuantifiersEngine
* qe
)
113 Assert(d_quantEngine
== nullptr);
114 // quantifiers engine may be null if not in quantified logic
118 void Theory::setDecisionManager(DecisionManager
* dm
)
120 Assert(d_decManager
== nullptr);
121 Assert(dm
!= nullptr);
125 void Theory::finishInitStandalone()
128 if (needsEqualityEngine(esi
))
130 // always associated with the same SAT context as the theory (d_satContext)
131 d_allocEqualityEngine
.reset(new eq::EqualityEngine(
132 *esi
.d_notify
, d_satContext
, esi
.d_name
, esi
.d_constantsAreTriggers
));
133 // use it as the official equality engine
134 setEqualityEngine(d_allocEqualityEngine
.get());
139 TheoryId
Theory::theoryOf(options::TheoryOfMode mode
, TNode node
)
141 TheoryId tid
= THEORY_BUILTIN
;
143 case options::TheoryOfMode::THEORY_OF_TYPE_BASED
:
144 // Constants, variables, 0-ary constructors
147 if (node
.getKind() == kind::BOOLEAN_TERM_VARIABLE
)
153 tid
= Theory::theoryOf(node
.getType());
156 else if (node
.isConst())
158 tid
= Theory::theoryOf(node
.getType());
160 else if (node
.getKind() == kind::EQUAL
)
162 // Equality is owned by the theory that owns the domain
163 tid
= Theory::theoryOf(node
[0].getType());
167 // Regular nodes are owned by the kind
168 tid
= kindToTheoryId(node
.getKind());
171 case options::TheoryOfMode::THEORY_OF_TERM_BASED
:
175 if (Theory::theoryOf(node
.getType()) != theory::THEORY_BOOL
)
177 // We treat the variables as uninterpreted
178 tid
= s_uninterpretedSortOwner
;
182 if (node
.getKind() == kind::BOOLEAN_TERM_VARIABLE
)
184 // Boolean vars go to UF
189 // Except for the Boolean ones
194 else if (node
.isConst())
196 // Constants go to the theory of the type
197 tid
= Theory::theoryOf(node
.getType());
199 else if (node
.getKind() == kind::EQUAL
)
201 // If one of them is an ITE, it's irelevant, since they will get
202 // replaced out anyhow
203 if (node
[0].getKind() == kind::ITE
)
205 tid
= Theory::theoryOf(node
[0].getType());
207 else if (node
[1].getKind() == kind::ITE
)
209 tid
= Theory::theoryOf(node
[1].getType());
215 TypeNode ltype
= l
.getType();
216 TypeNode rtype
= r
.getType();
219 tid
= Theory::theoryOf(l
.getType());
223 // If both sides belong to the same theory the choice is easy
224 TheoryId T1
= Theory::theoryOf(l
);
225 TheoryId T2
= Theory::theoryOf(r
);
232 TheoryId T3
= Theory::theoryOf(ltype
);
234 // * x*y = f(z) -> UF
236 // * f(x) = read(a, y) -> either UF or ARRAY
237 // at least one of the theories has to be parametric, i.e. theory
238 // of the type is different from the theory of the term
249 // If both are parametric, we take the smaller one (arbitrary)
250 tid
= T1
< T2
? T1
: T2
;
258 // Regular nodes are owned by the kind
259 tid
= kindToTheoryId(node
.getKind());
265 Trace("theory::internal") << "theoryOf(" << mode
<< ", " << node
<< ") -> " << tid
<< std::endl
;
269 void Theory::notifySharedTerm(TNode n
)
271 // TODO (project #39): this will move to addSharedTerm, as every theory with
272 // an equality does this in their notifySharedTerm method.
273 // if we have an equality engine, add the trigger term
274 if (d_equalityEngine
!= nullptr)
276 d_equalityEngine
->addTriggerTerm(n
, d_id
);
280 void Theory::computeCareGraph() {
281 Debug("sharing") << "Theory::computeCareGraph<" << getId() << ">()" << endl
;
282 for (unsigned i
= 0; i
< d_sharedTerms
.size(); ++ i
) {
283 TNode a
= d_sharedTerms
[i
];
284 TypeNode aType
= a
.getType();
285 for (unsigned j
= i
+ 1; j
< d_sharedTerms
.size(); ++ j
) {
286 TNode b
= d_sharedTerms
[j
];
287 if (b
.getType() != aType
) {
288 // We don't care about the terms of different types
291 switch (d_valuation
.getEqualityStatus(a
, b
)) {
292 case EQUALITY_TRUE_AND_PROPAGATED
:
293 case EQUALITY_FALSE_AND_PROPAGATED
:
294 // If we know about it, we should have propagated it, so we can skip
305 void Theory::printFacts(std::ostream
& os
) const {
306 unsigned i
, n
= d_facts
.size();
307 for(i
= 0; i
< n
; i
++){
308 const Assertion
& a_i
= d_facts
[i
];
309 Node assertion
= a_i
;
310 os
<< d_id
<< '[' << i
<< ']' << " " << assertion
<< endl
;
314 void Theory::debugPrintFacts() const{
315 DebugChannel
.getStream() << "Theory::debugPrintFacts()" << endl
;
316 printFacts(DebugChannel
.getStream());
319 bool Theory::isLegalElimination(TNode x
, TNode val
)
322 if (x
.getKind() == kind::BOOLEAN_TERM_VARIABLE
323 || val
.getKind() == kind::BOOLEAN_TERM_VARIABLE
)
327 if (expr::hasSubterm(val
, x
))
331 if (!val
.getType().isSubtypeOf(x
.getType()))
335 if (!options::produceModels())
337 // don't care about the model, we are fine
340 // if there is a model object
341 TheoryModel
* tm
= d_valuation
.getModel();
342 Assert(tm
!= nullptr);
343 return tm
->isLegalElimination(x
, val
);
346 std::unordered_set
<TNode
, TNodeHashFunction
> Theory::currentlySharedTerms() const{
347 std::unordered_set
<TNode
, TNodeHashFunction
> currentlyShared
;
348 for (shared_terms_iterator i
= shared_terms_begin(),
349 i_end
= shared_terms_end(); i
!= i_end
; ++i
) {
350 currentlyShared
.insert (*i
);
352 return currentlyShared
;
355 bool Theory::collectModelInfo(TheoryModel
* m
)
357 std::set
<Node
> termSet
;
358 // Compute terms appearing in assertions and shared terms
359 computeRelevantTerms(termSet
);
360 // if we are using an equality engine, assert it to the model
361 if (d_equalityEngine
!= nullptr)
363 if (!m
->assertEqualityEngine(d_equalityEngine
, &termSet
))
368 // now, collect theory-specific value assigments
369 return collectModelValues(m
, termSet
);
372 void Theory::collectTerms(TNode n
,
374 set
<Node
>& termSet
) const
376 if (termSet
.find(n
) != termSet
.end()) {
379 Kind nk
= n
.getKind();
380 if (irrKinds
.find(nk
) == irrKinds
.end())
382 Trace("theory::collectTerms")
383 << "Theory::collectTerms: adding " << n
<< endl
;
386 if (nk
== kind::NOT
|| nk
== kind::EQUAL
|| !isLeaf(n
))
388 for(TNode::iterator child_it
= n
.begin(); child_it
!= n
.end(); ++child_it
) {
389 collectTerms(*child_it
, irrKinds
, termSet
);
394 void Theory::computeRelevantTermsInternal(std::set
<Node
>& termSet
,
395 std::set
<Kind
>& irrKinds
,
396 bool includeShared
) const
398 // Collect all terms appearing in assertions
399 irrKinds
.insert(kind::EQUAL
);
400 irrKinds
.insert(kind::NOT
);
401 context::CDList
<Assertion
>::const_iterator assert_it
= facts_begin(),
402 assert_it_end
= facts_end();
403 for (; assert_it
!= assert_it_end
; ++assert_it
)
405 collectTerms(*assert_it
, irrKinds
, termSet
);
412 // Add terms that are shared terms
413 std::set
<Kind
> kempty
;
414 context::CDList
<TNode
>::const_iterator shared_it
= shared_terms_begin(),
415 shared_it_end
= shared_terms_end();
416 for (; shared_it
!= shared_it_end
; ++shared_it
)
418 collectTerms(*shared_it
, kempty
, termSet
);
422 void Theory::computeRelevantTerms(std::set
<Node
>& termSet
, bool includeShared
)
424 std::set
<Kind
> irrKinds
;
425 computeRelevantTermsInternal(termSet
, irrKinds
, includeShared
);
428 bool Theory::collectModelValues(TheoryModel
* m
, const std::set
<Node
>& termSet
)
433 Theory::PPAssertStatus
Theory::ppAssert(TNode in
,
434 SubstitutionMap
& outSubstitutions
)
436 if (in
.getKind() == kind::EQUAL
)
438 // (and (= x t) phi) can be replaced by phi[x/t] if
439 // 1) x is a variable
440 // 2) x is not in the term t
441 // 3) x : T and t : S, then S <: T
442 if (in
[0].isVar() && isLegalElimination(in
[0], in
[1])
443 && in
[0].getKind() != kind::BOOLEAN_TERM_VARIABLE
)
445 outSubstitutions
.addSubstitution(in
[0], in
[1]);
446 return PP_ASSERT_STATUS_SOLVED
;
448 if (in
[1].isVar() && isLegalElimination(in
[1], in
[0])
449 && in
[1].getKind() != kind::BOOLEAN_TERM_VARIABLE
)
451 outSubstitutions
.addSubstitution(in
[1], in
[0]);
452 return PP_ASSERT_STATUS_SOLVED
;
454 if (in
[0].isConst() && in
[1].isConst())
458 return PP_ASSERT_STATUS_CONFLICT
;
463 return PP_ASSERT_STATUS_UNSOLVED
;
466 std::pair
<bool, Node
> Theory::entailmentCheck(TNode lit
)
468 return make_pair(false, Node::null());
471 void Theory::addCarePair(TNode t1
, TNode t2
) {
473 d_careGraph
->insert(CarePair(t1
, t2
, d_id
));
477 void Theory::getCareGraph(CareGraph
* careGraph
) {
478 Assert(careGraph
!= NULL
);
480 Trace("sharing") << "Theory<" << getId() << ">::getCareGraph()" << std::endl
;
481 TimerStat::CodeTimer
computeCareGraphTime(d_computeCareGraphTime
);
482 d_careGraph
= careGraph
;
487 EqualityStatus
Theory::getEqualityStatus(TNode a
, TNode b
)
489 // if not using an equality engine, then by default we don't know the status
490 if (d_equalityEngine
== nullptr)
492 return EQUALITY_UNKNOWN
;
494 Assert(d_equalityEngine
->hasTerm(a
) && d_equalityEngine
->hasTerm(b
));
496 // Check for equality (simplest)
497 if (d_equalityEngine
->areEqual(a
, b
))
499 // The terms are implied to be equal
500 return EQUALITY_TRUE
;
503 // Check for disequality
504 if (d_equalityEngine
->areDisequal(a
, b
, false))
506 // The terms are implied to be dis-equal
507 return EQUALITY_FALSE
;
510 // All other terms are unknown, which is conservative. A theory may override
511 // this method if it knows more information.
512 return EQUALITY_UNKNOWN
;
515 void Theory::check(Effort level
)
517 // see if we are already done (as an optimization)
518 if (done() && level
< EFFORT_FULL
)
522 Assert(d_theoryState
!=nullptr);
523 // standard calls for resource, stats
524 d_out
->spendResource(ResourceManager::Resource::TheoryCheckStep
);
525 TimerStat::CodeTimer
checkTimer(d_checkTime
);
526 // pre-check at level
529 // check aborted for a theory-specific reason
532 // process the pending fact queue
533 while (!done() && !d_theoryState
->isInConflict())
535 // Get the next assertion from the fact queue
536 Assertion assertion
= get();
537 TNode fact
= assertion
.d_assertion
;
538 bool polarity
= fact
.getKind() != kind::NOT
;
539 TNode atom
= polarity
? fact
: fact
[0];
540 // call the pre-notify method
541 if (preNotifyFact(atom
, polarity
, fact
, assertion
.d_isPreregistered
, false))
543 // handled in theory-specific way that doesn't involve equality engine
546 // Theories that don't have an equality engine should always return true
548 Assert(d_equalityEngine
!= nullptr);
549 // assert to the equality engine
550 if (atom
.getKind() == kind::EQUAL
)
552 d_equalityEngine
->assertEquality(atom
, polarity
, fact
);
556 d_equalityEngine
->assertPredicate(atom
, polarity
, fact
);
558 // notify the theory of the new fact, which is not internal
559 notifyFact(atom
, polarity
, fact
, false);
561 // post-check at level
565 bool Theory::preCheck(Effort level
) { return false; }
567 void Theory::postCheck(Effort level
) {}
569 bool Theory::preNotifyFact(
570 TNode atom
, bool polarity
, TNode fact
, bool isPrereg
, bool isInternal
)
575 void Theory::notifyFact(TNode atom
, bool polarity
, TNode fact
, bool isInternal
)
579 void Theory::preRegisterTerm(TNode node
) {}
581 void Theory::addSharedTerm(TNode n
)
583 Debug("sharing") << "Theory::addSharedTerm<" << getId() << ">(" << n
<< ")"
585 Debug("theory::assertions")
586 << "Theory::addSharedTerm<" << getId() << ">(" << n
<< ")" << std::endl
;
587 d_sharedTerms
.push_back(n
);
588 // now call theory-specific method notifySharedTerm
592 eq::EqualityEngine
* Theory::getEqualityEngine()
594 // get the assigned equality engine, which is a pointer stored in this class
595 return d_equalityEngine
;
598 }/* CVC4::theory namespace */
599 }/* CVC4 namespace */