1 /********************* */
2 /*! \file theory_engine.h
4 ** Top contributors (to current version):
5 ** Dejan Jovanovic, Andrew Reynolds, 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 "cvc4_private.h"
19 #ifndef CVC4__THEORY_ENGINE_H
20 #define CVC4__THEORY_ENGINE_H
25 #include <unordered_map>
29 #include "base/check.h"
30 #include "context/cdhashset.h"
31 #include "expr/node.h"
32 #include "options/options.h"
33 #include "options/smt_options.h"
34 #include "options/theory_options.h"
35 #include "prop/prop_engine.h"
36 #include "smt/command.h"
37 #include "theory/atom_requests.h"
38 #include "theory/engine_output_channel.h"
39 #include "theory/interrupted.h"
40 #include "theory/rewriter.h"
41 #include "theory/sort_inference.h"
42 #include "theory/substitutions.h"
43 #include "theory/term_registration_visitor.h"
44 #include "theory/theory.h"
45 #include "theory/theory_preprocessor.h"
46 #include "theory/uf/equality_engine.h"
47 #include "theory/valuation.h"
48 #include "util/hash.h"
49 #include "util/resource_manager.h"
50 #include "util/statistics_registry.h"
51 #include "util/unsafe_interrupt_exception.h"
55 class ResourceManager
;
56 class LemmaProofRecipe
;
59 * A pair of a theory and a node. This is used to mark the flow of
60 * propagations between theories.
62 struct NodeTheoryPair
{
64 theory::TheoryId d_theory
;
66 NodeTheoryPair(TNode n
, theory::TheoryId t
, size_t ts
= 0)
67 : d_node(n
), d_theory(t
), d_timestamp(ts
)
70 NodeTheoryPair() : d_theory(theory::THEORY_LAST
), d_timestamp() {}
71 // Comparison doesn't take into account the timestamp
72 bool operator == (const NodeTheoryPair
& pair
) const {
73 return d_node
== pair
.d_node
&& d_theory
== pair
.d_theory
;
75 };/* struct NodeTheoryPair */
77 struct NodeTheoryPairHashFunction
{
78 NodeHashFunction hashFunction
;
79 // Hash doesn't take into account the timestamp
80 size_t operator()(const NodeTheoryPair
& pair
) const {
81 uint64_t hash
= fnv1a::fnv1a_64(NodeHashFunction()(pair
.d_node
));
82 return static_cast<size_t>(fnv1a::fnv1a_64(pair
.d_theory
, hash
));
84 };/* struct NodeTheoryPairHashFunction */
87 /* Forward declarations */
90 class CombinationEngine
;
91 class DecisionManager
;
92 class RelevanceManager
;
98 namespace quantifiers
{
102 class EntailmentCheckParameters
;
103 class EntailmentCheckSideEffects
;
104 }/* CVC4::theory namespace */
106 class RemoveTermFormulas
;
109 * This is essentially an abstraction for a collection of theories. A
110 * TheoryEngine provides services to a PropEngine, making various
111 * T-solvers look like a single unit to the propositional part of
116 /** Shared terms database can use the internals notify the theories */
117 friend class SharedTermsDatabase
;
118 friend class theory::CombinationEngine
;
119 friend class theory::quantifiers::TermDb
;
120 friend class theory::EngineOutputChannel
;
121 friend class theory::CombinationEngine
;
123 /** Associated PropEngine engine */
124 prop::PropEngine
* d_propEngine
;
127 context::Context
* d_context
;
129 /** Our user context */
130 context::UserContext
* d_userContext
;
133 * A table of from theory IDs to theory pointers. Never use this table
134 * directly, use theoryOf() instead.
136 theory::Theory
* d_theoryTable
[theory::THEORY_LAST
];
139 * A collection of theories that are "active" for the current run.
140 * This set is provided by the user (as a logic string, say, in SMT-LIBv2
141 * format input), or else by default it's all-inclusive. This is important
142 * because we can optimize for single-theory runs (no sharing), can reduce
143 * the cost of walking the DAG on registration, etc.
145 const LogicInfo
& d_logicInfo
;
148 * The database of shared terms.
150 SharedTermsDatabase d_sharedTerms
;
152 /** The combination manager we are using */
153 std::unique_ptr
<theory::CombinationEngine
> d_tc
;
155 * The quantifiers engine
157 theory::QuantifiersEngine
* d_quantEngine
;
159 * The decision manager
161 std::unique_ptr
<theory::DecisionManager
> d_decManager
;
162 /** The relevance manager */
163 std::unique_ptr
<theory::RelevanceManager
> d_relManager
;
165 /** Default visitor for pre-registration */
166 PreRegisterVisitor d_preRegistrationVisitor
;
168 /** Visitor for collecting shared terms */
169 SharedTermsVisitor d_sharedTermsVisitor
;
171 /** are we in eager model building mode? (see setEagerModelBuilding). */
172 bool d_eager_model_building
;
174 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
175 typedef std::unordered_map
<TNode
, Node
, TNodeHashFunction
> TNodeMap
;
178 * Used for "missed-t-propagations" dumping mode only. A set of all
179 * theory-propagable literals.
181 context::CDList
<TNode
> d_possiblePropagations
;
184 * Used for "missed-t-propagations" dumping mode only. A
185 * context-dependent set of those theory-propagable literals that
186 * have been propagated.
188 context::CDHashSet
<Node
, NodeHashFunction
> d_hasPropagated
;
191 * Output channels for individual theories.
193 theory::EngineOutputChannel
* d_theoryOut
[theory::THEORY_LAST
];
196 * Are we in conflict.
198 context::CDO
<bool> d_inConflict
;
201 * Are we in "SAT mode"? In this state, the user can query for the model.
202 * This corresponds to the state in Figure 4.1, page 52 of the SMT-LIB
203 * standard, version 2.6.
208 * Called by the theories to notify of a conflict.
210 void conflict(TNode conflict
, theory::TheoryId theoryId
);
213 * Debugging flag to ensure that shutdown() is called before the
219 * True if a theory has notified us of incompleteness (at this
220 * context level or below).
222 context::CDO
<bool> d_incomplete
;
225 * Called by the theories to notify that the current branch is incomplete.
227 void setIncomplete(theory::TheoryId theory
) {
232 * Mapping of propagations from recievers to senders.
234 typedef context::CDHashMap
<NodeTheoryPair
, NodeTheoryPair
, NodeTheoryPairHashFunction
> PropagationMap
;
235 PropagationMap d_propagationMap
;
238 * Timestamp of propagations
240 context::CDO
<size_t> d_propagationMapTimestamp
;
243 * Literals that are propagated by the theory. Note that these are TNodes.
244 * The theory can only propagate nodes that have an assigned literal in the
245 * SAT solver and are hence referenced in the SAT solver.
247 context::CDList
<TNode
> d_propagatedLiterals
;
250 * The index of the next literal to be propagated by a theory.
252 context::CDO
<unsigned> d_propagatedLiteralsIndex
;
255 * Called by the output channel to propagate literals and facts
256 * @return false if immediate conflict
258 bool propagate(TNode literal
, theory::TheoryId theory
);
261 * Internal method to call the propagation routines and collect the
262 * propagated literals.
264 void propagate(theory::Theory::Effort effort
);
267 * A variable to mark if we added any lemmas.
272 * A variable to mark if the OutputChannel was "used" by any theory
273 * since the start of the last check. If it has been, we require
274 * a FULL_EFFORT check before exiting and reporting SAT.
276 * See the documentation for the needCheck() function, below.
278 bool d_outputChannelUsed
;
280 /** Atom requests from lemmas */
281 AtomRequests d_atomRequests
;
284 * Adds a new lemma, returning its status.
285 * @param node the lemma
286 * @param negated should the lemma be asserted negated
287 * @param p the properties of the lemma.
289 theory::LemmaStatus
lemma(TNode node
,
292 theory::LemmaProperty p
,
293 theory::TheoryId atomsTo
);
295 /** Enusre that the given atoms are send to the given theory */
296 void ensureLemmaAtoms(const std::vector
<TNode
>& atoms
, theory::TheoryId theory
);
298 /** sort inference module */
299 SortInference d_sortInfer
;
301 /** The theory preprocessor */
302 theory::TheoryPreprocessor d_tpp
;
304 /** Time spent in theory combination */
305 TimerStat d_combineTheoriesTime
;
310 /** Whether we were just interrupted (or not) */
312 ResourceManager
* d_resourceManager
;
315 /** Constructs a theory engine */
316 TheoryEngine(context::Context
* context
,
317 context::UserContext
* userContext
,
319 RemoveTermFormulas
& iteRemover
,
320 const LogicInfo
& logic
);
322 /** Destroys a theory engine */
327 /** "Spend" a resource during a search or preprocessing.*/
328 void spendResource(ResourceManager::Resource r
);
331 * Adds a theory. Only one theory per TheoryId can be present, so if
332 * there is another theory it will be deleted.
334 template <class TheoryClass
>
335 inline void addTheory(theory::TheoryId theoryId
)
337 Assert(d_theoryTable
[theoryId
] == NULL
&& d_theoryOut
[theoryId
] == NULL
);
338 d_theoryOut
[theoryId
] = new theory::EngineOutputChannel(this, theoryId
);
339 d_theoryTable
[theoryId
] = new TheoryClass(d_context
,
341 *d_theoryOut
[theoryId
],
342 theory::Valuation(this),
345 theory::Rewriter::registerTheoryRewriter(
346 theoryId
, d_theoryTable
[theoryId
]->getTheoryRewriter());
349 void setPropEngine(prop::PropEngine
* propEngine
)
351 d_propEngine
= propEngine
;
355 * Called when all initialization of options/logic is done, after theory
356 * objects have been created.
358 * This initializes the quantifiers engine, the "official" equality engines
359 * of each theory as required, and the model and model builder utilities.
364 * Get a pointer to the underlying propositional engine.
366 inline prop::PropEngine
* getPropEngine() const {
371 * Get a pointer to the underlying sat context.
373 inline context::Context
* getSatContext() const {
378 * Get a pointer to the underlying user context.
380 inline context::Context
* getUserContext() const {
381 return d_userContext
;
385 * Get a pointer to the underlying quantifiers engine.
387 theory::QuantifiersEngine
* getQuantifiersEngine() const {
388 return d_quantEngine
;
391 * Get a pointer to the underlying decision manager.
393 theory::DecisionManager
* getDecisionManager() const
395 return d_decManager
.get();
400 * Queue of nodes for pre-registration.
402 std::queue
<TNode
> d_preregisterQueue
;
405 * Boolean flag denoting we are in pre-registration.
407 bool d_inPreregister
;
410 * Did the theories get any new facts since the last time we called
413 context::CDO
<bool> d_factsAsserted
;
416 * Assert the formula to the given theory.
417 * @param assertion the assertion to send (not necesserily normalized)
418 * @param original the assertion as it was sent in from the propagating theory
419 * @param toTheoryId the theory to assert to
420 * @param fromTheoryId the theory that sent it
422 void assertToTheory(TNode assertion
, TNode originalAssertion
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
);
425 * Marks a theory propagation from a theory to a theory where a
426 * theory could be the THEORY_SAT_SOLVER for literals coming from
427 * or being propagated to the SAT solver. If the receiving theory
428 * already recieved the literal, the method returns false, otherwise
431 * @param assertion the normalized assertion being sent
432 * @param originalAssertion the actual assertion that was sent
433 * @param toTheoryId the theory that is on the receiving end
434 * @param fromTheoryId the theory that sent the assertion
435 * @return true if a new assertion, false if theory already got it
437 bool markPropagation(TNode assertion
, TNode originalAssertions
, theory::TheoryId toTheoryId
, theory::TheoryId fromTheoryId
);
440 * Computes the explanation by travarsing the propagation graph and
441 * asking relevant theories to explain the propagations. Initially
442 * the explanation vector should contain only the element (node, theory)
443 * where the node is the one to be explained, and the theory is the
444 * theory that sent the literal. The lemmaProofRecipe will contain a list
445 * of the explanation steps required to produce the original node.
447 void getExplanation(std::vector
<NodeTheoryPair
>& explanationVector
, LemmaProofRecipe
* lemmaProofRecipe
);
451 * Signal the start of a new round of assertion preprocessing
453 void preprocessStart();
456 * Runs theory specific preprocessing on the non-Boolean parts of
457 * the formula. This is only called on input assertions, after ITEs
460 Node
preprocess(TNode node
);
462 /** Notify (preprocessed) assertions. */
463 void notifyPreprocessedAssertions(const std::vector
<Node
>& assertions
);
465 /** Return whether or not we are incomplete (in the current context). */
466 inline bool isIncomplete() const { return d_incomplete
; }
469 * Returns true if we need another round of checking. If this
470 * returns true, check(FULL_EFFORT) _must_ be called by the
471 * propositional layer before reporting SAT.
473 * This is especially necessary for incomplete theories that lazily
474 * output some lemmas on FULL_EFFORT check (e.g. quantifier reasoning
475 * outputing quantifier instantiations). In such a case, a lemma can
476 * be asserted that is simplified away (perhaps it's already true).
477 * However, we must maintain the invariant that, if a theory uses the
478 * OutputChannel, it implicitly requests that another check(FULL_EFFORT)
479 * be performed before exit, even if no new facts are on its fact queue,
480 * as it might decide to further instantiate some lemmas, precluding
483 inline bool needCheck() const {
484 return d_outputChannelUsed
|| d_lemmasAdded
;
487 * Is the literal lit (possibly) critical for satisfying the input formula in
488 * the current context? This call is applicable only during collectModelInfo
489 * or during LAST_CALL effort.
491 bool isRelevant(Node lit
) const;
493 * This is called at shutdown time by the SmtEngine, just before
494 * destruction. It is important because there are destruction
495 * ordering issues between PropEngine and Theory.
500 * Solve the given literal with a theory that owns it.
502 theory::Theory::PPAssertStatus
solve(TNode literal
,
503 theory::SubstitutionMap
& substitutionOut
);
506 * Preregister a Theory atom with the responsible theory (or
509 void preRegister(TNode preprocessed
);
512 * Assert the formula to the appropriate theory.
513 * @param node the assertion
515 void assertFact(TNode node
);
518 * Check all (currently-active) theories for conflicts.
519 * @param effort the effort level to use
521 void check(theory::Theory::Effort effort
);
524 * Calls ppStaticLearn() on all theories, accumulating their
525 * combined contributions in the "learned" builder.
527 void ppStaticLearn(TNode in
, NodeBuilder
<>& learned
);
530 * Calls presolve() on all theories and returns true
531 * if one of the theories discovers a conflict.
536 * Calls postsolve() on all theories.
541 * Calls notifyRestart() on all active theories.
543 void notifyRestart();
545 void getPropagatedLiterals(std::vector
<TNode
>& literals
) {
546 for (; d_propagatedLiteralsIndex
< d_propagatedLiterals
.size(); d_propagatedLiteralsIndex
= d_propagatedLiteralsIndex
+ 1) {
547 Debug("getPropagatedLiterals") << "TheoryEngine::getPropagatedLiterals: propagating: " << d_propagatedLiterals
[d_propagatedLiteralsIndex
] << std::endl
;
548 literals
.push_back(d_propagatedLiterals
[d_propagatedLiteralsIndex
]);
553 * Returns the next decision request, or null if none exist. The next
554 * decision request is a literal that this theory engine prefers the SAT
555 * solver to make as its next decision. Decision requests are managed by
556 * the decision manager d_decManager.
558 Node
getNextDecisionRequest();
560 bool properConflict(TNode conflict
) const;
563 * Returns an explanation of the node propagated to the SAT solver.
565 Node
getExplanation(TNode node
);
568 * Returns an explanation of the node propagated to the SAT solver and the theory
569 * that propagated it.
571 Node
getExplanationAndRecipe(TNode node
, LemmaProofRecipe
* proofRecipe
);
574 * Get the pointer to the model object used by this theory engine.
576 theory::TheoryModel
* getModel();
578 * Get the current model for the current set of assertions. This method
579 * should only be called immediately after a satisfiable or unknown
580 * response to a check-sat call, and only if produceModels is true.
582 * If the model is not already built, this will cause this theory engine
583 * to build the model.
585 * If the model is not available (for instance, if the last call to check-sat
586 * was interrupted), then this returns the null pointer.
588 theory::TheoryModel
* getBuiltModel();
590 * This forces the model maintained by the combination engine to be built
591 * if it has not been done so already. This should be called only during a
592 * last call effort check after theory combination is run.
594 * @return true if the model was successfully built (possibly prior to this
598 /** set eager model building
600 * If this method is called, then this TheoryEngine will henceforth build
601 * its model immediately after every satisfiability check that results
602 * in a satisfiable or unknown result. The motivation for this mode is to
603 * accomodate API users that get the model object from the TheoryEngine,
604 * where we want to ensure that this model is always valid.
605 * TODO (#2648): revisit this.
607 void setEagerModelBuilding() { d_eager_model_building
= true; }
609 /** get synth solutions
611 * This method returns true if there is a synthesis solution available. This
612 * is the case if the last call to check satisfiability originated in a
613 * check-synth call, and the synthesis solver successfully found a solution
614 * for all active synthesis conjectures.
616 * This method adds entries to sol_map that map functions-to-synthesize with
617 * their solutions, for all active conjectures. This should be called
618 * immediately after the solver answers unsat for sygus input.
620 * For details on what is added to sol_map, see
621 * SynthConjecture::getSynthSolutions.
623 bool getSynthSolutions(std::map
<Node
, std::map
<Node
, Node
> >& sol_map
);
626 * Get the theory associated to a given Node.
628 * @returns the theory, or NULL if the TNode is
631 inline theory::Theory
* theoryOf(TNode node
) const {
632 return d_theoryTable
[theory::Theory::theoryOf(node
)];
636 * Get the theory associated to a the given theory id.
638 * @returns the theory
640 inline theory::Theory
* theoryOf(theory::TheoryId theoryId
) const {
641 Assert(theoryId
< theory::THEORY_LAST
);
642 return d_theoryTable
[theoryId
];
645 inline bool isTheoryEnabled(theory::TheoryId theoryId
) const {
646 return d_logicInfo
.isTheoryEnabled(theoryId
);
648 /** get the logic info used by this theory engine */
649 const LogicInfo
& getLogicInfo() const;
651 * Returns the equality status of the two terms, from the theory
652 * that owns the domain type. The types of a and b must be the same.
654 theory::EqualityStatus
getEqualityStatus(TNode a
, TNode b
);
657 * Returns the value that a theory that owns the type of var currently
658 * has (or null if none);
660 Node
getModelValue(TNode var
);
663 * Takes a literal and returns an equivalent literal that is guaranteed to be a SAT literal
665 Node
ensureLiteral(TNode n
);
668 * Print all instantiations made by the quantifiers module.
670 void printInstantiations( std::ostream
& out
);
673 * Print solution for synthesis conjectures found by ce_guided_instantiation module
675 void printSynthSolution( std::ostream
& out
);
678 * Get list of quantified formulas that were instantiated
680 void getInstantiatedQuantifiedFormulas( std::vector
< Node
>& qs
);
683 * Get instantiation methods
684 * first inputs forall x.q[x] and returns ( q[a], ..., q[z] )
685 * second inputs forall x.q[x] and returns ( a, ..., z )
686 * third and fourth return mappings e.g. forall x.q1[x] -> ( q1[a]...q1[z] ) , ... , forall x.qn[x] -> ( qn[a]...qn[z] )
688 void getInstantiations( Node q
, std::vector
< Node
>& insts
);
689 void getInstantiationTermVectors( Node q
, std::vector
< std::vector
< Node
> >& tvecs
);
690 void getInstantiations( std::map
< Node
, std::vector
< Node
> >& insts
);
691 void getInstantiationTermVectors( std::map
< Node
, std::vector
< std::vector
< Node
> > >& insts
);
694 * Get instantiated conjunction, returns q[t1] ^ ... ^ q[tn] where t1...tn are current set of instantiations for q.
695 * Can be used for quantifier elimination when satisfiable and q[t1] ^ ... ^ q[tn] |= q
697 Node
getInstantiatedConjunction( Node q
);
700 * Forwards an entailment check according to the given theoryOfMode.
701 * See theory.h for documentation on entailmentCheck().
703 std::pair
<bool, Node
> entailmentCheck(options::TheoryOfMode mode
, TNode lit
);
707 /** Dump the assertions to the dump */
708 void dumpAssertions(const char* tag
);
710 /** For preprocessing pass lifting bit-vectors of size 1 to booleans */
713 SortInference
* getSortInference() { return &d_sortInfer
; }
715 /** Prints the assertions to the debug stream */
716 void printAssertions(const char* tag
);
720 std::map
< std::string
, std::vector
< theory::Theory
* > > d_attr_handle
;
723 /** Set user attribute.
725 * This function is called when an attribute is set by a user. In SMT-LIBv2
726 * this is done via the syntax (! n :attr)
728 void setUserAttribute(const std::string
& attr
,
730 const std::vector
<Node
>& node_values
,
731 const std::string
& str_value
);
733 /** Handle user attribute.
735 * Associates theory t with the attribute attr. Theory t will be
736 * notified whenever an attribute of name attr is set.
738 void handleUserAttribute(const char* attr
, theory::Theory
* t
);
741 * Check that the theory assertions are satisfied in the model.
742 * This function is called from the smt engine's checkModel routine.
744 void checkTheoryAssertionsWithModel(bool hardFailure
);
747 IntStat d_arithSubstitutionsAdded
;
749 };/* class TheoryEngine */
751 }/* CVC4 namespace */
753 #endif /* CVC4__THEORY_ENGINE_H */