Moving from the gnu extensions for hash maps to the c++11 hash maps
[cvc5.git] / src / theory / theory.h
1 /********************* */
2 /*! \file theory.h
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Dejan Jovanovic, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2017 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 of the theory interface.
13 **
14 ** Base of the theory interface.
15 **/
16
17 #include "cvc4_private.h"
18
19 #ifndef __CVC4__THEORY__THEORY_H
20 #define __CVC4__THEORY__THEORY_H
21
22 #include <iosfwd>
23 #include <map>
24 #include <set>
25 #include <string>
26 #include <unordered_set>
27
28 #include "context/cdlist.h"
29 #include "context/cdhashset.h"
30 #include "context/cdo.h"
31 #include "context/context.h"
32 #include "expr/node.h"
33 #include "lib/ffs.h"
34 #include "options/options.h"
35 #include "options/theory_options.h"
36 #include "options/theoryof_mode.h"
37 #include "smt/command.h"
38 #include "smt/dump.h"
39 #include "smt/logic_request.h"
40 #include "theory/assertion.h"
41 #include "theory/care_graph.h"
42 #include "theory/logic_info.h"
43 #include "theory/output_channel.h"
44 #include "theory/valuation.h"
45 #include "util/statistics_registry.h"
46
47 namespace CVC4 {
48
49 class TheoryEngine;
50
51 namespace theory {
52
53 class QuantifiersEngine;
54 class TheoryModel;
55 class SubstitutionMap;
56 class ExtTheory;
57
58 class EntailmentCheckParameters;
59 class EntailmentCheckSideEffects;
60
61 namespace rrinst {
62 class CandidateGenerator;
63 }/* CVC4::theory::rrinst namespace */
64
65 namespace eq {
66 class EqualityEngine;
67 }/* CVC4::theory::eq namespace */
68
69 /**
70 * Base class for T-solvers. Abstract DPLL(T).
71 *
72 * This is essentially an interface class. The TheoryEngine has
73 * pointers to Theory. Note that only one specific Theory type (e.g.,
74 * TheoryUF) can exist per NodeManager, because of how the
75 * RegisteredAttr works. (If you need multiple instances of the same
76 * theory, you'll have to write a multiplexed theory that dispatches
77 * all calls to them.)
78 */
79 class Theory {
80
81 private:
82
83 friend class ::CVC4::TheoryEngine;
84
85 // Disallow default construction, copy, assignment.
86 Theory() CVC4_UNDEFINED;
87 Theory(const Theory&) CVC4_UNDEFINED;
88 Theory& operator=(const Theory&) CVC4_UNDEFINED;
89
90 /** An integer identifying the type of the theory. */
91 TheoryId d_id;
92
93 /** Name of this theory instance. Along with the TheoryId this should provide
94 * an unique string identifier for each instance of a Theory class. We need
95 * this to ensure unique statistics names over multiple theory instances. */
96 std::string d_instanceName;
97
98 /** The SAT search context for the Theory. */
99 context::Context* d_satContext;
100
101 /** The user level assertion context for the Theory. */
102 context::UserContext* d_userContext;
103
104 /** Information about the logic we're operating within. */
105 const LogicInfo& d_logicInfo;
106
107 /**
108 * The assertFact() queue.
109 *
110 * These can not be TNodes as some atoms (such as equalities) are sent
111 * across theories without being stored in a global map.
112 */
113 context::CDList<Assertion> d_facts;
114
115 /** Index into the head of the facts list */
116 context::CDO<unsigned> d_factsHead;
117
118 /** Add shared term to the theory. */
119 void addSharedTermInternal(TNode node);
120
121 /** Indices for splitting on the shared terms. */
122 context::CDO<unsigned> d_sharedTermsIndex;
123
124 /** The care graph the theory will use during combination. */
125 CareGraph* d_careGraph;
126
127 /**
128 * Pointer to the quantifiers engine (or NULL, if quantifiers are not
129 * supported or not enabled). Not owned by the theory.
130 */
131 QuantifiersEngine* d_quantEngine;
132
133 /** Extended theory module or NULL. Owned by the theory. */
134 ExtTheory* d_extTheory;
135
136 protected:
137
138
139 // === STATISTICS ===
140 /** time spent in check calls */
141 TimerStat d_checkTime;
142 /** time spent in theory combination */
143 TimerStat d_computeCareGraphTime;
144
145 /**
146 * The only method to add suff to the care graph.
147 */
148 void addCarePair(TNode t1, TNode t2);
149
150 /**
151 * The function should compute the care graph over the shared terms.
152 * The default function returns all the pairs among the shared variables.
153 */
154 virtual void computeCareGraph();
155
156 /**
157 * A list of shared terms that the theory has.
158 */
159 context::CDList<TNode> d_sharedTerms;
160
161 /**
162 * Helper function for computeRelevantTerms
163 */
164 void collectTerms(TNode n, std::set<Node>& termSet) const;
165
166 /**
167 * Scans the current set of assertions and shared terms top-down
168 * until a theory-leaf is reached, and adds all terms found to
169 * termSet. This is used by collectModelInfo to delimit the set of
170 * terms that should be used when constructing a model
171 */
172 void computeRelevantTerms(std::set<Node>& termSet, bool includeShared = true) const;
173
174 /**
175 * Construct a Theory.
176 *
177 * The pair <id, instance> is assumed to uniquely identify this Theory
178 * w.r.t. the SmtEngine.
179 */
180 Theory(TheoryId id, context::Context* satContext,
181 context::UserContext* userContext, OutputChannel& out,
182 Valuation valuation, const LogicInfo& logicInfo,
183 std::string instance = "") throw(); // taking : No default.
184
185 /**
186 * This is called at shutdown time by the TheoryEngine, just before
187 * destruction. It is important because there are destruction
188 * ordering issues between PropEngine and Theory (based on what
189 * hard-links to Nodes are outstanding). As the fact queue might be
190 * nonempty, we ensure here that it's clear. If you overload this,
191 * you must make an explicit call here to this->Theory::shutdown()
192 * too.
193 */
194 virtual void shutdown() { }
195
196 /**
197 * The output channel for the Theory.
198 */
199 OutputChannel* d_out;
200
201 /**
202 * The valuation proxy for the Theory to communicate back with the
203 * theory engine (and other theories).
204 */
205 Valuation d_valuation;
206
207 /**
208 * Whether proofs are enabled
209 *
210 */
211 bool d_proofsEnabled;
212
213 /**
214 * Returns the next assertion in the assertFact() queue.
215 *
216 * @return the next assertion in the assertFact() queue
217 */
218 inline Assertion get();
219
220 const LogicInfo& getLogicInfo() const {
221 return d_logicInfo;
222 }
223
224 /**
225 * The theory that owns the uninterpreted sort.
226 */
227 static TheoryId s_uninterpretedSortOwner;
228
229 void printFacts(std::ostream& os) const;
230 void debugPrintFacts() const;
231
232 /**
233 * Whether proofs are enabled
234 *
235 */
236 bool d_proofEnabled;
237
238 public:
239
240 /**
241 * Return the ID of the theory responsible for the given type.
242 */
243 static inline TheoryId theoryOf(TypeNode typeNode) {
244 Trace("theory::internal") << "theoryOf(" << typeNode << ")" << std::endl;
245 TheoryId id;
246 if (typeNode.getKind() == kind::TYPE_CONSTANT) {
247 id = typeConstantToTheoryId(typeNode.getConst<TypeConstant>());
248 } else {
249 id = kindToTheoryId(typeNode.getKind());
250 }
251 if (id == THEORY_BUILTIN) {
252 Trace("theory::internal") << "theoryOf(" << typeNode << ") == " << s_uninterpretedSortOwner << std::endl;
253 return s_uninterpretedSortOwner;
254 }
255 return id;
256 }
257
258 /**
259 * Returns the ID of the theory responsible for the given node.
260 */
261 static TheoryId theoryOf(TheoryOfMode mode, TNode node);
262
263 /**
264 * Returns the ID of the theory responsible for the given node.
265 */
266 static inline TheoryId theoryOf(TNode node) {
267 return theoryOf(options::theoryOfMode(), node);
268 }
269
270 /**
271 * Set the owner of the uninterpreted sort.
272 */
273 static void setUninterpretedSortOwner(TheoryId theory) {
274 s_uninterpretedSortOwner = theory;
275 }
276
277 /**
278 * Get the owner of the uninterpreted sort.
279 */
280 static TheoryId getUninterpretedSortOwner() {
281 return s_uninterpretedSortOwner;
282 }
283
284 /**
285 * Checks if the node is a leaf node of this theory
286 */
287 inline bool isLeaf(TNode node) const {
288 return node.getNumChildren() == 0 || theoryOf(node) != d_id;
289 }
290
291 /**
292 * Checks if the node is a leaf node of a theory.
293 */
294 inline static bool isLeafOf(TNode node, TheoryId theoryId) {
295 return node.getNumChildren() == 0 || theoryOf(node) != theoryId;
296 }
297
298 /**
299 * Returns true if the assertFact queue is empty
300 */
301 bool done() const throw() {
302 return d_factsHead == d_facts.size();
303 }
304
305 /**
306 * Destructs a Theory.
307 */
308 virtual ~Theory();
309
310 /**
311 * Subclasses of Theory may add additional efforts. DO NOT CHECK
312 * equality with one of these values (e.g. if STANDARD xxx) but
313 * rather use range checks (or use the helper functions below).
314 * Normally we call QUICK_CHECK or STANDARD; at the leaves we call
315 * with FULL_EFFORT.
316 */
317 enum Effort {
318 /**
319 * Standard effort where theory need not do anything
320 */
321 EFFORT_STANDARD = 50,
322 /**
323 * Full effort requires the theory make sure its assertions are satisfiable or not
324 */
325 EFFORT_FULL = 100,
326 /**
327 * Combination effort means that the individual theories are already satisfied, and
328 * it is time to put some effort into propagation of shared term equalities
329 */
330 EFFORT_COMBINATION = 150,
331 /**
332 * Last call effort, reserved for quantifiers.
333 */
334 EFFORT_LAST_CALL = 200
335 };/* enum Effort */
336
337 static inline bool standardEffortOrMore(Effort e) CVC4_CONST_FUNCTION
338 { return e >= EFFORT_STANDARD; }
339 static inline bool standardEffortOnly(Effort e) CVC4_CONST_FUNCTION
340 { return e >= EFFORT_STANDARD && e < EFFORT_FULL; }
341 static inline bool fullEffort(Effort e) CVC4_CONST_FUNCTION
342 { return e == EFFORT_FULL; }
343 static inline bool combination(Effort e) CVC4_CONST_FUNCTION
344 { return e == EFFORT_COMBINATION; }
345
346 /**
347 * Get the id for this Theory.
348 */
349 TheoryId getId() const {
350 return d_id;
351 }
352
353 /**
354 * Returns a string that uniquely identifies this theory solver w.r.t. the
355 * SmtEngine.
356 */
357 std::string getFullInstanceName() const;
358
359
360 /**
361 * Get the SAT context associated to this Theory.
362 */
363 context::Context* getSatContext() const {
364 return d_satContext;
365 }
366
367 /**
368 * Get the context associated to this Theory.
369 */
370 context::UserContext* getUserContext() const {
371 return d_userContext;
372 }
373
374 /**
375 * Set the output channel associated to this theory.
376 */
377 void setOutputChannel(OutputChannel& out) {
378 d_out = &out;
379 }
380
381 /**
382 * Get the output channel associated to this theory.
383 */
384 OutputChannel& getOutputChannel() {
385 return *d_out;
386 }
387
388 /**
389 * Get the valuation associated to this theory.
390 */
391 Valuation& getValuation() {
392 return d_valuation;
393 }
394
395 /**
396 * Get the quantifiers engine associated to this theory.
397 */
398 QuantifiersEngine* getQuantifiersEngine() {
399 return d_quantEngine;
400 }
401
402 /**
403 * Get the quantifiers engine associated to this theory (const version).
404 */
405 const QuantifiersEngine* getQuantifiersEngine() const {
406 return d_quantEngine;
407 }
408
409 /**
410 * Finish theory initialization. At this point, options and the logic
411 * setting are final, and the master equality engine and quantifiers
412 * engine (if any) are initialized. This base class implementation
413 * does nothing.
414 */
415 virtual void finishInit() { }
416
417 /**
418 * Some theories have kinds that are effectively definitions and
419 * should be expanded before they are handled. Definitions allow
420 * a much wider range of actions than the normal forms given by the
421 * rewriter; they can enable other theories and create new terms.
422 * However no assumptions can be made about subterms having been
423 * expanded or rewritten. Where possible rewrite rules should be
424 * used, definitions should only be used when rewrites are not
425 * possible, for example in handling under-specified operations
426 * using partially defined functions.
427 */
428 virtual Node expandDefinition(LogicRequest &logicRequest, Node node) {
429 // by default, do nothing
430 return node;
431 }
432
433 /**
434 * Pre-register a term. Done one time for a Node per SAT context level.
435 */
436 virtual void preRegisterTerm(TNode) { }
437
438 /**
439 * Assert a fact in the current context.
440 */
441 void assertFact(TNode assertion, bool isPreregistered) {
442 Trace("theory") << "Theory<" << getId() << ">::assertFact["
443 << d_satContext->getLevel() << "](" << assertion << ", "
444 << (isPreregistered ? "true" : "false") << ")" << std::endl;
445 d_facts.push_back(Assertion(assertion, isPreregistered));
446 }
447
448 /**
449 * This method is called to notify a theory that the node n should
450 * be considered a "shared term" by this theory
451 */
452 virtual void addSharedTerm(TNode n) { }
453
454 /**
455 * Called to set the master equality engine.
456 */
457 virtual void setMasterEqualityEngine(eq::EqualityEngine* eq) { }
458
459 /** Called to set the quantifiers engine. */
460 virtual void setQuantifiersEngine(QuantifiersEngine* qe);
461
462 /** Setup an ExtTheory module for this Theory. Can only be called once. */
463 void setupExtTheory();
464
465 /**
466 * Return the current theory care graph. Theories should overload
467 * computeCareGraph to do the actual computation, and use addCarePair to add
468 * pairs to the care graph.
469 */
470 void getCareGraph(CareGraph* careGraph);
471
472 /**
473 * Return the status of two terms in the current context. Should be
474 * implemented in sub-theories to enable more efficient theory-combination.
475 */
476 virtual EqualityStatus getEqualityStatus(TNode a, TNode b) {
477 return EQUALITY_UNKNOWN;
478 }
479
480 /**
481 * Return the model value of the give shared term (or null if not available).
482 */
483 virtual Node getModelValue(TNode var) { return Node::null(); }
484
485 /**
486 * Check the current assignment's consistency.
487 *
488 * An implementation of check() is required to either:
489 * - return a conflict on the output channel,
490 * - be interrupted,
491 * - throw an exception
492 * - or call get() until done() is true.
493 */
494 virtual void check(Effort level = EFFORT_FULL) { }
495
496 /** Needs last effort check? */
497 virtual bool needsCheckLastEffort() { return false; }
498
499 /** T-propagate new literal assignments in the current context. */
500 virtual void propagate(Effort level = EFFORT_FULL) { }
501
502 /**
503 * Return an explanation for the literal represented by parameter n
504 * (which was previously propagated by this theory).
505 */
506 virtual Node explain(TNode n) {
507 Unimplemented("Theory %s propagated a node but doesn't implement the "
508 "Theory::explain() interface!", identify().c_str());
509 }
510
511 /**
512 * Get all relevant information in this theory regarding the current
513 * model. This should be called after a call to check( FULL_EFFORT )
514 * for all theories with no conflicts and no lemmas added.
515 */
516 virtual void collectModelInfo( TheoryModel* m ){ }
517
518 /** if theories want to do something with model after building, do it here */
519 virtual void postProcessModel( TheoryModel* m ){ }
520
521 /**
522 * Return a decision request, if the theory has one, or the NULL node
523 * otherwise.
524 * If returning non-null node, hould set priority to
525 * 0 if decision is necessary for model-soundness,
526 * 1 if decision is necessary for completeness,
527 * >1 otherwise.
528 */
529 virtual Node getNextDecisionRequest( unsigned& priority ) { return Node(); }
530
531 /**
532 * Statically learn from assertion "in," which has been asserted
533 * true at the top level. The theory should only add (via
534 * ::operator<< or ::append()) to the "learned" builder---it should
535 * *never* clear it. It is a conjunction to add to the formula at
536 * the top-level and may contain other theories' contributions.
537 */
538 virtual void ppStaticLearn(TNode in, NodeBuilder<>& learned) { }
539
540 enum PPAssertStatus {
541 /** Atom has been solved */
542 PP_ASSERT_STATUS_SOLVED,
543 /** Atom has not been solved */
544 PP_ASSERT_STATUS_UNSOLVED,
545 /** Atom is inconsistent */
546 PP_ASSERT_STATUS_CONFLICT
547 };
548
549 /**
550 * Given a literal, add the solved substitutions to the map, if any.
551 * The method should return true if the literal can be safely removed.
552 */
553 virtual PPAssertStatus ppAssert(TNode in, SubstitutionMap& outSubstitutions);
554
555 /**
556 * Given an atom of the theory coming from the input formula, this
557 * method can be overridden in a theory implementation to rewrite
558 * the atom into an equivalent form. This is only called just
559 * before an input atom to the engine.
560 */
561 virtual Node ppRewrite(TNode atom) { return atom; }
562
563 /**
564 * Don't preprocess subterm of this term
565 */
566 virtual bool ppDontRewriteSubterm(TNode atom) { return false; }
567
568 /**
569 * Notify preprocessed assertions. Called on new assertions after
570 * preprocessing before they are asserted to theory engine.
571 */
572 virtual void ppNotifyAssertions(const std::vector<Node>& assertions) {}
573
574 /**
575 * A Theory is called with presolve exactly one time per user
576 * check-sat. presolve() is called after preregistration,
577 * rewriting, and Boolean propagation, (other theories'
578 * propagation?), but the notified Theory has not yet had its
579 * check() or propagate() method called. A Theory may empty its
580 * assertFact() queue using get(). A Theory can raise conflicts,
581 * add lemmas, and propagate literals during presolve().
582 *
583 * NOTE: The presolve property must be added to the kinds file for
584 * the theory.
585 */
586 virtual void presolve() { }
587
588 /**
589 * A Theory is called with postsolve exactly one time per user
590 * check-sat. postsolve() is called after the query has completed
591 * (regardless of whether sat, unsat, or unknown), and after any
592 * model-querying related to the query has been performed.
593 * After this call, the theory will not get another check() or
594 * propagate() call until presolve() is called again. A Theory
595 * cannot raise conflicts, add lemmas, or propagate literals during
596 * postsolve().
597 */
598 virtual void postsolve() { }
599
600 /**
601 * Notification sent to the theory wheneven the search restarts.
602 * Serves as a good time to do some clean-up work, and you can
603 * assume you're at DL 0 for the purposes of Contexts. This function
604 * should not use the output channel.
605 */
606 virtual void notifyRestart() { }
607
608 /**
609 * Identify this theory (for debugging, dynamic configuration,
610 * etc..)
611 */
612 virtual std::string identify() const = 0;
613
614 /** Set user attribute
615 * This function is called when an attribute is set by a user. In SMT-LIBv2 this is done
616 * via the syntax (! n :attr)
617 */
618 virtual void setUserAttribute(const std::string& attr, Node n, std::vector<Node> node_values, std::string str_value) {
619 Unimplemented("Theory %s doesn't support Theory::setUserAttribute interface",
620 identify().c_str());
621 }
622
623 /** A set of theories */
624 typedef uint32_t Set;
625
626 /** A set of all theories */
627 static const Set AllTheories = (1 << theory::THEORY_LAST) - 1;
628
629 /** Pops a first theory off the set */
630 static inline TheoryId setPop(Set& set) {
631 uint32_t i = ffs(set); // Find First Set (bit)
632 if (i == 0) { return THEORY_LAST; }
633 TheoryId id = (TheoryId)(i-1);
634 set = setRemove(id, set);
635 return id;
636 }
637
638 /** Returns the size of a set of theories */
639 static inline size_t setSize(Set set) {
640 size_t count = 0;
641 while (setPop(set) != THEORY_LAST) {
642 ++ count;
643 }
644 return count;
645 }
646
647 /** Returns the index size of a set of theories */
648 static inline size_t setIndex(TheoryId id, Set set) {
649 Assert (setContains(id, set));
650 size_t count = 0;
651 while (setPop(set) != id) {
652 ++ count;
653 }
654 return count;
655 }
656
657 /** Add the theory to the set. If no set specified, just returns a singleton set */
658 static inline Set setInsert(TheoryId theory, Set set = 0) {
659 return set | (1 << theory);
660 }
661
662 /** Add the theory to the set. If no set specified, just returns a singleton set */
663 static inline Set setRemove(TheoryId theory, Set set = 0) {
664 return setDifference(set, setInsert(theory));
665 }
666
667 /** Check if the set contains the theory */
668 static inline bool setContains(TheoryId theory, Set set) {
669 return set & (1 << theory);
670 }
671
672 static inline Set setComplement(Set a) {
673 return (~a) & AllTheories;
674 }
675
676 static inline Set setIntersection(Set a, Set b) {
677 return a & b;
678 }
679
680 static inline Set setUnion(Set a, Set b) {
681 return a | b;
682 }
683
684 /** a - b */
685 static inline Set setDifference(Set a, Set b) {
686 return (~b) & a;
687 }
688
689 static inline std::string setToString(theory::Theory::Set theorySet) {
690 std::stringstream ss;
691 ss << "[";
692 for(unsigned theoryId = 0; theoryId < theory::THEORY_LAST; ++theoryId) {
693 if (theory::Theory::setContains((theory::TheoryId)theoryId, theorySet)) {
694 ss << (theory::TheoryId) theoryId << " ";
695 }
696 }
697 ss << "]";
698 return ss.str();
699 }
700
701 typedef context::CDList<Assertion>::const_iterator assertions_iterator;
702
703 /**
704 * Provides access to the facts queue, primarily intended for theory
705 * debugging purposes.
706 *
707 * @return the iterator to the beginning of the fact queue
708 */
709 assertions_iterator facts_begin() const {
710 return d_facts.begin();
711 }
712
713 /**
714 * Provides access to the facts queue, primarily intended for theory
715 * debugging purposes.
716 *
717 * @return the iterator to the end of the fact queue
718 */
719 assertions_iterator facts_end() const {
720 return d_facts.end();
721 }
722 /**
723 * Whether facts have been asserted to this theory.
724 *
725 * @return true iff facts have been asserted to this theory.
726 */
727 bool hasFacts() {
728 return !d_facts.empty();
729 }
730
731 /** Return total number of facts asserted to this theory */
732 size_t numAssertions() {
733 return d_facts.size();
734 }
735
736 typedef context::CDList<TNode>::const_iterator shared_terms_iterator;
737
738 /**
739 * Provides access to the shared terms, primarily intended for theory
740 * debugging purposes.
741 *
742 * @return the iterator to the beginning of the shared terms list
743 */
744 shared_terms_iterator shared_terms_begin() const {
745 return d_sharedTerms.begin();
746 }
747
748 /**
749 * Provides access to the facts queue, primarily intended for theory
750 * debugging purposes.
751 *
752 * @return the iterator to the end of the shared terms list
753 */
754 shared_terms_iterator shared_terms_end() const {
755 return d_sharedTerms.end();
756 }
757
758
759 /**
760 * This is a utility function for constructing a copy of the currently shared terms
761 * in a queriable form. As this is
762 */
763 std::unordered_set<TNode, TNodeHashFunction> currentlySharedTerms() const;
764
765 /**
766 * This allows the theory to be queried for whether a literal, lit, is
767 * entailed by the theory. This returns a pair of a Boolean and a node E.
768 *
769 * If the Boolean is true, then E is a formula that entails lit and E is propositionally
770 * entailed by the assertions to the theory.
771 *
772 * If the Boolean is false, it is "unknown" if lit is entailed and E may be
773 * any node.
774 *
775 * The literal lit is either an atom a or (not a), which must belong to the theory:
776 * There is some TheoryOfMode m s.t. Theory::theoryOf(m, a) == this->getId().
777 *
778 * There are NO assumptions that a or the subterms of a have been
779 * preprocessed in any form. This includes ppRewrite, rewriting,
780 * preregistering, registering, definition expansion or ITE removal!
781 *
782 * Theories are free to limit the amount of effort they use and so may
783 * always opt to return "unknown". Both "unknown" and "not entailed",
784 * may return for E a non-boolean Node (e.g. Node::null()). (There is no explicit output
785 * for the negation of lit is entailed.)
786 *
787 * If lit is theory valid, the return result may be the Boolean constant
788 * true for E.
789 *
790 * If lit is entailed by multiple assertions on the theory's getFact()
791 * queue, a_1, a_2, ... and a_k, this may return E=(and a_1 a_2 ... a_k) or
792 * another theory entailed explanation E=(and (and a_1 a_2) (and a3 a_4) ... a_k)
793 *
794 * If lit is entailed by a single assertion on the theory's getFact()
795 * queue, say a, this may return E=a.
796 *
797 * The theory may always return false!
798 *
799 * The search is controlled by the parameter params. For default behavior,
800 * this may be left NULL.
801 *
802 * Theories that want parameters extend the virtual EntailmentCheckParameters
803 * class. Users ask the theory for an appropriate subclass from the theory
804 * and configure that. How this is implemented is on a per theory basis.
805 *
806 * The search may provide additional output to guide the user of
807 * this function. This output is stored in a EntailmentCheckSideEffects*
808 * output parameter. The implementation of this is theory specific. For
809 * no output, this is NULL.
810 *
811 * Theories may not touch their output stream during an entailment check.
812 *
813 * @param lit a literal belonging to the theory.
814 * @param params the control parameters for the entailment check.
815 * @param out a theory specific output object of the entailment search.
816 * @return a pair <b,E> s.t. if b is true, then a formula E such that
817 * E |= lit in the theory.
818 */
819 virtual std::pair<bool, Node> entailmentCheck(
820 TNode lit, const EntailmentCheckParameters* params = NULL,
821 EntailmentCheckSideEffects* out = NULL);
822
823 /* equality engine TODO: use? */
824 virtual eq::EqualityEngine* getEqualityEngine() { return NULL; }
825
826 /* Get extended theory if one has been installed. */
827 ExtTheory* getExtTheory();
828
829 /* get current substitution at an effort
830 * input : vars
831 * output : subs, exp
832 * where ( exp[vars[i]] => vars[i] = subs[i] ) holds for all i
833 */
834 virtual bool getCurrentSubstitution(int effort, std::vector<Node>& vars,
835 std::vector<Node>& subs,
836 std::map<Node, std::vector<Node> >& exp) {
837 return false;
838 }
839
840 /* is extended function reduced */
841 virtual bool isExtfReduced( int effort, Node n, Node on, std::vector< Node >& exp ) { return n.isConst(); }
842
843 /**
844 * Get reduction for node
845 * If return value is not 0, then n is reduced.
846 * If return value <0 then n is reduced SAT-context-independently (e.g. by a
847 * lemma that persists at this user-context level).
848 * If nr is non-null, then ( n = nr ) should be added as a lemma by caller,
849 * and return value should be <0.
850 */
851 virtual int getReduction( int effort, Node n, Node& nr ) { return 0; }
852
853 /** Turn on proof-production mode. */
854 void produceProofs() { d_proofsEnabled = true; }
855
856 };/* class Theory */
857
858 std::ostream& operator<<(std::ostream& os, theory::Theory::Effort level);
859
860
861 inline theory::Assertion Theory::get() {
862 Assert( !done(), "Theory::get() called with assertion queue empty!" );
863
864 // Get the assertion
865 Assertion fact = d_facts[d_factsHead];
866 d_factsHead = d_factsHead + 1;
867
868 Trace("theory") << "Theory::get() => " << fact << " (" << d_facts.size() - d_factsHead << " left)" << std::endl;
869
870 if(Dump.isOn("state")) {
871 Dump("state") << AssertCommand(fact.assertion.toExpr());
872 }
873
874 return fact;
875 }
876
877 inline std::ostream& operator<<(std::ostream& out,
878 const CVC4::theory::Theory& theory) {
879 return out << theory.identify();
880 }
881
882 inline std::ostream& operator << (std::ostream& out, theory::Theory::PPAssertStatus status) {
883 switch (status) {
884 case theory::Theory::PP_ASSERT_STATUS_SOLVED:
885 out << "SOLVE_STATUS_SOLVED"; break;
886 case theory::Theory::PP_ASSERT_STATUS_UNSOLVED:
887 out << "SOLVE_STATUS_UNSOLVED"; break;
888 case theory::Theory::PP_ASSERT_STATUS_CONFLICT:
889 out << "SOLVE_STATUS_CONFLICT"; break;
890 default:
891 Unhandled();
892 }
893 return out;
894 }
895
896 class EntailmentCheckParameters {
897 private:
898 TheoryId d_tid;
899 protected:
900 EntailmentCheckParameters(TheoryId tid);
901 public:
902 TheoryId getTheoryId() const;
903 virtual ~EntailmentCheckParameters();
904 };/* class EntailmentCheckParameters */
905
906 class EntailmentCheckSideEffects {
907 private:
908 TheoryId d_tid;
909 protected:
910 EntailmentCheckSideEffects(TheoryId tid);
911 public:
912 TheoryId getTheoryId() const;
913 virtual ~EntailmentCheckSideEffects();
914 };/* class EntailmentCheckSideEffects */
915
916
917 class ExtTheory {
918 typedef context::CDHashMap<Node, bool, NodeHashFunction> NodeBoolMap;
919 typedef context::CDHashSet<Node, NodeHashFunction> NodeSet;
920 private:
921 // collect variables
922 static std::vector<Node> collectVars(Node n);
923 // is context dependent inactive
924 bool isContextIndependentInactive( Node n ) const;
925 //do inferences internal
926 bool doInferencesInternal(int effort, const std::vector<Node>& terms,
927 std::vector<Node>& nred, bool batch, bool isRed);
928 // send lemma
929 bool sendLemma( Node lem, bool preprocess = false );
930 // register term (recursive)
931 void registerTermRec(Node n, std::set<Node>* visited);
932
933 Theory * d_parent;
934 Node d_true;
935 //extended string terms, map to whether they are active
936 NodeBoolMap d_ext_func_terms;
937 //set of terms from d_ext_func_terms that are SAT-context-independently inactive
938 // (e.g. term t when a reduction lemma of the form t = t' was added)
939 NodeSet d_ci_inactive;
940 //watched term for checking if any non-reduced extended functions exist
941 context::CDO< Node > d_has_extf;
942 //extf kind
943 std::map< Kind, bool > d_extf_kind;
944 //information for each term in d_ext_func_terms
945 class ExtfInfo {
946 public:
947 //all variables in this term
948 std::vector< Node > d_vars;
949 };
950 std::map< Node, ExtfInfo > d_extf_info;
951
952 //cache of all lemmas sent
953 NodeSet d_lemmas;
954 NodeSet d_pp_lemmas;
955 bool d_cacheEnabled;
956 // if d_cacheEnabled=true :
957 //cache for getSubstitutedTerms
958 class SubsTermInfo {
959 public:
960 Node d_sterm;
961 std::vector< Node > d_exp;
962 };
963 std::map< int, std::map< Node, SubsTermInfo > > d_gst_cache;
964
965 public:
966 ExtTheory(Theory* p, bool cacheEnabled = false );
967 virtual ~ExtTheory() {}
968 // add extf kind
969 void addFunctionKind(Kind k) { d_extf_kind[k] = true; }
970 bool hasFunctionKind(Kind k) const {
971 return d_extf_kind.find(k) != d_extf_kind.end();
972 }
973 // register term
974 // adds n to d_ext_func_terms if addFunctionKind( n.getKind() ) was called
975 void registerTerm( Node n );
976 void registerTermRec( Node n );
977 // set n as reduced/inactive
978 // if contextDepend = false, then n remains inactive in the duration of this user-context level
979 void markReduced( Node n, bool contextDepend = true );
980 // mark that a and b are congruent terms: set b inactive, set a to inactive if b was inactive
981 void markCongruent( Node a, Node b );
982 //getSubstitutedTerms
983 // input : effort, terms
984 // output : sterms, exp, where ( exp[i] => terms[i] = sterms[i] ) for all i
985 Node getSubstitutedTerm( int effort, Node term, std::vector< Node >& exp, bool useCache = false );
986 void getSubstitutedTerms(int effort, const std::vector<Node>& terms,
987 std::vector<Node>& sterms,
988 std::vector<std::vector<Node> >& exp, bool useCache = false);
989 // doInferences
990 // * input : effort, terms, batch (whether to send one lemma or lemmas for
991 // all terms)
992 // * sends rewriting lemmas of the form ( exp => t = c ) where t is in terms
993 // and c is a constant, c = rewrite( t*sigma ) where exp |= sigma
994 // * output : nred (the terms that are still active)
995 // * return : true iff lemma is sent
996 bool doInferences(int effort, const std::vector<Node>& terms,
997 std::vector<Node>& nred, bool batch = true);
998 bool doInferences(int effort, std::vector<Node>& nred, bool batch = true);
999 //doReductions
1000 // same as doInferences, but will send reduction lemmas of the form ( t = t' )
1001 // where t is in terms, t' is equivalent, reduced term.
1002 bool doReductions(int effort, const std::vector<Node>& terms,
1003 std::vector<Node>& nred, bool batch = true);
1004 bool doReductions(int effort, std::vector<Node>& nred, bool batch = true);
1005
1006 //get the set of terms from d_ext_func_terms
1007 void getTerms( std::vector< Node >& terms );
1008 // has active term
1009 bool hasActiveTerm();
1010 // is n active
1011 bool isActive(Node n);
1012 // get the set of active terms from d_ext_func_terms
1013 std::vector<Node> getActive() const;
1014 // get the set of active terms from d_ext_func_terms of kind k
1015 std::vector<Node> getActive(Kind k) const;
1016 //clear cache
1017 void clearCache();
1018 };
1019
1020 }/* CVC4::theory namespace */
1021 }/* CVC4 namespace */
1022
1023 #endif /* __CVC4__THEORY__THEORY_H */