GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/theory/theory_engine.h Lines: 42 42 100.0 %
Date: 2021-11-07 Branches: 100 364 27.5 %

Line Exec Source
1
/******************************************************************************
2
 * Top contributors (to current version):
3
 *   Andrew Reynolds, Dejan Jovanovic, Morgan Deters
4
 *
5
 * This file is part of the cvc5 project.
6
 *
7
 * Copyright (c) 2009-2021 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.
11
 * ****************************************************************************
12
 *
13
 * The theory engine.
14
 */
15
16
#include "cvc5_private.h"
17
18
#ifndef CVC5__THEORY_ENGINE_H
19
#define CVC5__THEORY_ENGINE_H
20
21
#include <memory>
22
#include <vector>
23
24
#include "base/check.h"
25
#include "context/cdhashmap.h"
26
#include "expr/node.h"
27
#include "options/theory_options.h"
28
#include "proof/trust_node.h"
29
#include "smt/env_obj.h"
30
#include "theory/atom_requests.h"
31
#include "theory/engine_output_channel.h"
32
#include "theory/interrupted.h"
33
#include "theory/rewriter.h"
34
#include "theory/sort_inference.h"
35
#include "theory/theory.h"
36
#include "theory/theory_preprocessor.h"
37
#include "theory/trust_substitutions.h"
38
#include "theory/uf/equality_engine.h"
39
#include "theory/valuation.h"
40
#include "util/hash.h"
41
#include "util/statistics_stats.h"
42
#include "util/unsafe_interrupt_exception.h"
43
44
namespace cvc5 {
45
46
class Env;
47
class ResourceManager;
48
class TheoryEngineProofGenerator;
49
class ProofChecker;
50
51
/**
52
 * A pair of a theory and a node. This is used to mark the flow of
53
 * propagations between theories.
54
 */
55
653427621
struct NodeTheoryPair {
56
  Node d_node;
57
  theory::TheoryId d_theory;
58
  size_t d_timestamp;
59
95708901
  NodeTheoryPair(TNode n, theory::TheoryId t, size_t ts = 0)
60
95708901
      : d_node(n), d_theory(t), d_timestamp(ts)
61
  {
62
95708901
  }
63
65877080
  NodeTheoryPair() : d_theory(theory::THEORY_LAST), d_timestamp() {}
64
  // Comparison doesn't take into account the timestamp
65
114995319
  bool operator == (const NodeTheoryPair& pair) const {
66
114995319
    return d_node == pair.d_node && d_theory == pair.d_theory;
67
  }
68
};/* struct NodeTheoryPair */
69
70
struct NodeTheoryPairHashFunction {
71
  std::hash<Node> hashFunction;
72
  // Hash doesn't take into account the timestamp
73
180989939
  size_t operator()(const NodeTheoryPair& pair) const {
74
180989939
    uint64_t hash = fnv1a::fnv1a_64(std::hash<Node>()(pair.d_node));
75
180989939
    return static_cast<size_t>(fnv1a::fnv1a_64(pair.d_theory, hash));
76
  }
77
};/* struct NodeTheoryPairHashFunction */
78
79
80
/* Forward declarations */
81
namespace theory {
82
83
class CombinationEngine;
84
class DecisionManager;
85
class RelevanceManager;
86
class Rewriter;
87
class SharedSolver;
88
class TheoryModel;
89
90
}  // namespace theory
91
92
namespace prop {
93
class PropEngine;
94
}
95
96
/**
97
 * This is essentially an abstraction for a collection of theories.  A
98
 * TheoryEngine provides services to a PropEngine, making various
99
 * T-solvers look like a single unit to the propositional part of
100
 * cvc5.
101
 */
102
class TheoryEngine : protected EnvObj
103
{
104
  /** Shared terms database can use the internals notify the theories */
105
  friend class SharedTermsDatabase;
106
  friend class theory::EngineOutputChannel;
107
  friend class theory::CombinationEngine;
108
  friend class theory::SharedSolver;
109
110
 public:
111
  /** Constructs a theory engine */
112
  TheoryEngine(Env& env);
113
114
  /** Destroys a theory engine */
115
  ~TheoryEngine();
116
117
  void interrupt();
118
119
  /** "Spend" a resource during a search or preprocessing.*/
120
  void spendResource(Resource r);
121
122
  /**
123
   * Adds a theory. Only one theory per TheoryId can be present, so if
124
   * there is another theory it will be deleted.
125
   */
126
  template <class TheoryClass>
127
198585
  void addTheory(theory::TheoryId theoryId)
128
  {
129
198585
    Assert(d_theoryTable[theoryId] == NULL && d_theoryOut[theoryId] == NULL);
130
198585
    d_theoryOut[theoryId] = new theory::EngineOutputChannel(this, theoryId);
131
397170
    d_theoryTable[theoryId] =
132
198585
        new TheoryClass(d_env, *d_theoryOut[theoryId], theory::Valuation(this));
133
794340
    getRewriter()->registerTheoryRewriter(
134
595755
        theoryId, d_theoryTable[theoryId]->getTheoryRewriter());
135
198585
  }
136
137
  /** Register theory proof rule checkers to the given proof checker */
138
  void initializeProofChecker(ProofChecker* pc);
139
140
15340
  void setPropEngine(prop::PropEngine* propEngine)
141
  {
142
15340
    d_propEngine = propEngine;
143
15340
  }
144
145
  /**
146
   * Called when all initialization of options/logic is done, after theory
147
   * objects have been created.
148
   *
149
   * This initializes the quantifiers engine, the "official" equality engines
150
   * of each theory as required, and the model and model builder utilities.
151
   */
152
  void finishInit();
153
154
  /**
155
   * Get a pointer to the underlying propositional engine.
156
   */
157
2944019
  prop::PropEngine* getPropEngine() const { return d_propEngine; }
158
159
  /**
160
   * Get a pointer to the underlying quantifiers engine.
161
   */
162
24771
  theory::QuantifiersEngine* getQuantifiersEngine() const
163
  {
164
24771
    return d_quantEngine;
165
  }
166
  /**
167
   * Get a pointer to the underlying decision manager.
168
   */
169
  theory::DecisionManager* getDecisionManager() const
170
  {
171
    return d_decManager.get();
172
  }
173
174
  /**
175
   * Preprocess rewrite equality, called by the preprocessor to rewrite
176
   * equalities appearing in the input.
177
   */
178
  TrustNode ppRewriteEquality(TNode eq);
179
  /** Notify (preprocessed) assertions. */
180
  void notifyPreprocessedAssertions(const std::vector<Node>& assertions);
181
182
  /** Return whether or not we are incomplete (in the current context). */
183
9677
  bool isIncomplete() const { return d_incomplete; }
184
185
  /**
186
   * Returns true if we need another round of checking.  If this
187
   * returns true, check(FULL_EFFORT) _must_ be called by the
188
   * propositional layer before reporting SAT.
189
   *
190
   * This is especially necessary for incomplete theories that lazily
191
   * output some lemmas on FULL_EFFORT check (e.g. quantifier reasoning
192
   * outputing quantifier instantiations).  In such a case, a lemma can
193
   * be asserted that is simplified away (perhaps it's already true).
194
   * However, we must maintain the invariant that, if a theory uses the
195
   * OutputChannel, it implicitly requests that another check(FULL_EFFORT)
196
   * be performed before exit, even if no new facts are on its fact queue,
197
   * as it might decide to further instantiate some lemmas, precluding
198
   * a SAT response.
199
   */
200
6054665
  bool needCheck() const { return d_outputChannelUsed || d_lemmasAdded; }
201
  /**
202
   * Is the literal lit (possibly) critical for satisfying the input formula in
203
   * the current context? This call is applicable only during collectModelInfo
204
   * or during LAST_CALL effort.
205
   */
206
  bool isRelevant(Node lit) const;
207
  /**
208
   * This is called at shutdown time by the SolverEngine, just before
209
   * destruction.  It is important because there are destruction
210
   * ordering issues between PropEngine and Theory.
211
   */
212
  void shutdown();
213
214
  /**
215
   * Solve the given literal with a theory that owns it. The proof of tliteral
216
   * is carried in the trust node. The proof added to substitutionOut should
217
   * take this proof into account (when proofs are enabled).
218
   */
219
  theory::Theory::PPAssertStatus solve(
220
      TrustNode tliteral, theory::TrustSubstitutionMap& substitutionOut);
221
222
  /**
223
   * Preregister a Theory atom with the responsible theory (or
224
   * theories).
225
   */
226
  void preRegister(TNode preprocessed);
227
228
  /**
229
   * Assert the formula to the appropriate theory.
230
   * @param node the assertion
231
   */
232
  void assertFact(TNode node);
233
234
  /**
235
   * Check all (currently-active) theories for conflicts.
236
   * @param effort the effort level to use
237
   */
238
  void check(theory::Theory::Effort effort);
239
240
  /**
241
   * Calls ppStaticLearn() on all theories, accumulating their
242
   * combined contributions in the "learned" builder.
243
   */
244
  void ppStaticLearn(TNode in, NodeBuilder& learned);
245
246
  /**
247
   * Calls presolve() on all theories and returns true
248
   * if one of the theories discovers a conflict.
249
   */
250
  bool presolve();
251
252
  /**
253
   * Calls postsolve() on all theories.
254
   */
255
  void postsolve();
256
257
  /**
258
   * Calls notifyRestart() on all active theories.
259
   */
260
  void notifyRestart();
261
262
15203624
  void getPropagatedLiterals(std::vector<TNode>& literals)
263
  {
264
35154660
    for (; d_propagatedLiteralsIndex < d_propagatedLiterals.size();
265
19951036
         d_propagatedLiteralsIndex = d_propagatedLiteralsIndex + 1)
266
    {
267
19951036
      Debug("getPropagatedLiterals")
268
9975518
          << "TheoryEngine::getPropagatedLiterals: propagating: "
269
9975518
          << d_propagatedLiterals[d_propagatedLiteralsIndex] << std::endl;
270
9975518
      literals.push_back(d_propagatedLiterals[d_propagatedLiteralsIndex]);
271
    }
272
5228106
  }
273
274
  /**
275
   * Returns the next decision request, or null if none exist. The next
276
   * decision request is a literal that this theory engine prefers the SAT
277
   * solver to make as its next decision. Decision requests are managed by
278
   * the decision manager d_decManager.
279
   */
280
  Node getNextDecisionRequest();
281
282
  bool properConflict(TNode conflict) const;
283
284
  /**
285
   * Returns an explanation of the node propagated to the SAT solver.
286
   */
287
  TrustNode getExplanation(TNode node);
288
289
  /**
290
   * Get the pointer to the model object used by this theory engine.
291
   */
292
  theory::TheoryModel* getModel();
293
  /**
294
   * Get the current model for the current set of assertions. This method
295
   * should only be called immediately after a satisfiable or unknown
296
   * response to a check-sat call, and only if produceModels is true.
297
   *
298
   * If the model is not already built, this will cause this theory engine
299
   * to build the model.
300
   *
301
   * If the model is not available (for instance, if the last call to check-sat
302
   * was interrupted), then this returns the null pointer.
303
   */
304
  theory::TheoryModel* getBuiltModel();
305
  /**
306
   * This forces the model maintained by the combination engine to be built
307
   * if it has not been done so already. This should be called only during a
308
   * last call effort check after theory combination is run.
309
   *
310
   * @return true if the model was successfully built (possibly prior to this
311
   * call).
312
   */
313
  bool buildModel();
314
315
  /**
316
   * Get the theory associated to a given Node.
317
   *
318
   * @returns the theory, or NULL if the TNode is
319
   * of built-in type.
320
   */
321
3206124
  theory::Theory* theoryOf(TNode node) const
322
  {
323
3206124
    return d_theoryTable[theory::Theory::theoryOf(node)];
324
  }
325
326
  /**
327
   * Get the theory associated to a the given theory id.
328
   *
329
   * @returns the theory
330
   */
331
58878530
  theory::Theory* theoryOf(theory::TheoryId theoryId) const
332
  {
333
58878530
    Assert(theoryId < theory::THEORY_LAST);
334
58878530
    return d_theoryTable[theoryId];
335
  }
336
337
2270637
  bool isTheoryEnabled(theory::TheoryId theoryId) const
338
  {
339
2270637
    return d_logicInfo.isTheoryEnabled(theoryId);
340
  }
341
  /** get the logic info used by this theory engine */
342
  const LogicInfo& getLogicInfo() const;
343
  /** get the separation logic heap types */
344
  bool getSepHeapTypes(TypeNode& locType, TypeNode& dataType) const;
345
346
  /**
347
   * Declare heap. This is used for separation logics to set the location
348
   * and data types. It should be called only once, and before any separation
349
   * logic constraints are asserted to this theory engine.
350
   */
351
  void declareSepHeap(TypeNode locT, TypeNode dataT);
352
353
  /**
354
   * Returns the equality status of the two terms, from the theory
355
   * that owns the domain type.  The types of a and b must be the same.
356
   */
357
  theory::EqualityStatus getEqualityStatus(TNode a, TNode b);
358
359
  /**
360
   * Returns the value that a theory that owns the type of var currently
361
   * has (or null if none);
362
   */
363
  Node getModelValue(TNode var);
364
365
  /**
366
   * Get relevant assertions. This returns a set of assertions that are
367
   * currently asserted to this TheoryEngine that propositionally entail the
368
   * (preprocessed) input formula and all theory lemmas that have been marked
369
   * NEEDS_JUSTIFY. For more details on this, see relevance_manager.h.
370
   *
371
   * This method updates success to false if the set of relevant assertions
372
   * is not available. This may occur if we are not in SAT mode, if the
373
   * relevance manager is disabled (see option::relevanceFilter) or if the
374
   * relevance manager failed to compute relevant assertions due to an internal
375
   * error.
376
   */
377
  const std::unordered_set<TNode>& getRelevantAssertions(bool& success);
378
379
  /**
380
   * Get difficulty map, which populates dmap, mapping preprocessed assertions
381
   * to a value that estimates their difficulty for solving the current problem.
382
   *
383
   * For details, see theory/difficuly_manager.h.
384
   */
385
  void getDifficultyMap(std::map<Node, Node>& dmap);
386
387
  /**
388
   * Forwards an entailment check according to the given theoryOfMode.
389
   * See theory.h for documentation on entailmentCheck().
390
   */
391
  std::pair<bool, Node> entailmentCheck(options::TheoryOfMode mode, TNode lit);
392
393
5337
  theory::SortInference* getSortInference() { return d_sortInfer.get(); }
394
395
  /** Prints the assertions to the debug stream */
396
  void printAssertions(const char* tag);
397
398
  /**
399
   * Check that the theory assertions are satisfied in the model.
400
   * This function is called from the smt engine's checkModel routine.
401
   */
402
  void checkTheoryAssertionsWithModel(bool hardFailure);
403
404
 private:
405
  typedef context::
406
      CDHashMap<NodeTheoryPair, NodeTheoryPair, NodeTheoryPairHashFunction>
407
          PropagationMap;
408
409
  /**
410
   * Called by the theories to notify of a conflict.
411
   *
412
   * @param conflict The trust node containing the conflict and its proof
413
   * generator (if it exists),
414
   * @param theoryId The theory that sent the conflict
415
   */
416
  void conflict(TrustNode conflict, theory::TheoryId theoryId);
417
418
  /** set in conflict */
419
  void markInConflict();
420
421
  /**
422
   * Called by the theories to notify that the current branch is incomplete.
423
   */
424
  void setIncomplete(theory::TheoryId theory, theory::IncompleteId id);
425
426
  /**
427
   * Called by the output channel to propagate literals and facts
428
   * @return false if immediate conflict
429
   */
430
  bool propagate(TNode literal, theory::TheoryId theory);
431
432
  /**
433
   * Internal method to call the propagation routines and collect the
434
   * propagated literals.
435
   */
436
  void propagate(theory::Theory::Effort effort);
437
438
  /**
439
   * Assert the formula to the given theory.
440
   * @param assertion the assertion to send (not necesserily normalized)
441
   * @param original the assertion as it was sent in from the propagating theory
442
   * @param toTheoryId the theory to assert to
443
   * @param fromTheoryId the theory that sent it
444
   */
445
  void assertToTheory(TNode assertion,
446
                      TNode originalAssertion,
447
                      theory::TheoryId toTheoryId,
448
                      theory::TheoryId fromTheoryId);
449
450
  /**
451
   * Marks a theory propagation from a theory to a theory where a
452
   * theory could be the THEORY_SAT_SOLVER for literals coming from
453
   * or being propagated to the SAT solver. If the receiving theory
454
   * already recieved the literal, the method returns false, otherwise
455
   * it returns true.
456
   *
457
   * @param assertion the normalized assertion being sent
458
   * @param originalAssertion the actual assertion that was sent
459
   * @param toTheoryId the theory that is on the receiving end
460
   * @param fromTheoryId the theory that sent the assertion
461
   * @return true if a new assertion, false if theory already got it
462
   */
463
  bool markPropagation(TNode assertion,
464
                       TNode originalAssertions,
465
                       theory::TheoryId toTheoryId,
466
                       theory::TheoryId fromTheoryId);
467
468
  /**
469
   * Computes the explanation by traversing the propagation graph and
470
   * asking relevant theories to explain the propagations. Initially
471
   * the explanation vector should contain only the element (node, theory)
472
   * where the node is the one to be explained, and the theory is the
473
   * theory that sent the literal.
474
   */
475
  TrustNode getExplanation(std::vector<NodeTheoryPair>& explanationVector);
476
477
  /** Are proofs enabled? */
478
  bool isProofEnabled() const;
479
480
  /**
481
   * Get a pointer to the rewriter owned by the associated Env.
482
   */
483
  theory::Rewriter* getRewriter();
484
485
  /**
486
   * Adds a new lemma, returning its status.
487
   * @param node the lemma
488
   * @param p the properties of the lemma.
489
   * @param atomsTo the theory that atoms of the lemma should be sent to
490
   * @param from the theory that sent the lemma
491
   */
492
  void lemma(TrustNode node,
493
             theory::LemmaProperty p,
494
             theory::TheoryId from = theory::THEORY_LAST);
495
496
  /** Ensure atoms from the given node are sent to the given theory */
497
  void ensureLemmaAtoms(TNode n, theory::TheoryId atomsTo);
498
  /** Ensure that the given atoms are sent to the given theory */
499
  void ensureLemmaAtoms(const std::vector<TNode>& atoms,
500
                        theory::TheoryId atomsTo);
501
502
  /** Associated PropEngine engine */
503
  prop::PropEngine* d_propEngine;
504
505
  /**
506
   * A table of from theory IDs to theory pointers. Never use this table
507
   * directly, use theoryOf() instead.
508
   */
509
  theory::Theory* d_theoryTable[theory::THEORY_LAST];
510
511
  /**
512
   * A collection of theories that are "active" for the current run.
513
   * This set is provided by the user (as a logic string, say, in SMT-LIBv2
514
   * format input), or else by default it's all-inclusive.  This is important
515
   * because we can optimize for single-theory runs (no sharing), can reduce
516
   * the cost of walking the DAG on registration, etc.
517
   */
518
  const LogicInfo& d_logicInfo;
519
520
  /** The separation logic location and data types */
521
  TypeNode d_sepLocType;
522
  TypeNode d_sepDataType;
523
524
  //--------------------------------- new proofs
525
  /** Proof node manager used by this theory engine, if proofs are enabled */
526
  ProofNodeManager* d_pnm;
527
  /** The lazy proof object
528
   *
529
   * This stores instructions for how to construct proofs for all theory lemmas.
530
   */
531
  std::shared_ptr<LazyCDProof> d_lazyProof;
532
  /** The proof generator */
533
  std::shared_ptr<TheoryEngineProofGenerator> d_tepg;
534
  //--------------------------------- end new proofs
535
  /** The combination manager we are using */
536
  std::unique_ptr<theory::CombinationEngine> d_tc;
537
  /** The shared solver of the above combination engine. */
538
  theory::SharedSolver* d_sharedSolver;
539
  /** The quantifiers engine, which is owned by the quantifiers theory */
540
  theory::QuantifiersEngine* d_quantEngine;
541
  /**
542
   * The decision manager
543
   */
544
  std::unique_ptr<theory::DecisionManager> d_decManager;
545
  /** The relevance manager */
546
  std::unique_ptr<theory::RelevanceManager> d_relManager;
547
  /**
548
   * An empty set of relevant assertions, which is returned as a dummy value for
549
   * getRelevantAssertions when relevance is disabled.
550
   */
551
  std::unordered_set<TNode> d_emptyRelevantSet;
552
553
  /** are we in eager model building mode? (see setEagerModelBuilding). */
554
  bool d_eager_model_building;
555
556
  /**
557
   * Output channels for individual theories.
558
   */
559
  theory::EngineOutputChannel* d_theoryOut[theory::THEORY_LAST];
560
561
  /**
562
   * Are we in conflict.
563
   */
564
  context::CDO<bool> d_inConflict;
565
566
  /**
567
   * Are we in "SAT mode"? In this state, the user can query for the model.
568
   * This corresponds to the state in Figure 4.1, page 52 of the SMT-LIB
569
   * standard, version 2.6.
570
   */
571
  bool d_inSatMode;
572
573
  /**
574
   * Debugging flag to ensure that shutdown() is called before the
575
   * destructor.
576
   */
577
  bool d_hasShutDown;
578
579
  /**
580
   * True if a theory has notified us of incompleteness (at this
581
   * context level or below).
582
   */
583
  context::CDO<bool> d_incomplete;
584
  /** The theory and identifier that (most recently) set incomplete */
585
  context::CDO<theory::TheoryId> d_incompleteTheory;
586
  context::CDO<theory::IncompleteId> d_incompleteId;
587
588
  /**
589
   * Mapping of propagations from recievers to senders.
590
   */
591
  PropagationMap d_propagationMap;
592
593
  /**
594
   * Timestamp of propagations
595
   */
596
  context::CDO<size_t> d_propagationMapTimestamp;
597
598
  /**
599
   * Literals that are propagated by the theory. Note that these are TNodes.
600
   * The theory can only propagate nodes that have an assigned literal in the
601
   * SAT solver and are hence referenced in the SAT solver.
602
   */
603
  context::CDList<TNode> d_propagatedLiterals;
604
605
  /**
606
   * The index of the next literal to be propagated by a theory.
607
   */
608
  context::CDO<unsigned> d_propagatedLiteralsIndex;
609
610
  /**
611
   * A variable to mark if we added any lemmas.
612
   */
613
  bool d_lemmasAdded;
614
615
  /**
616
   * A variable to mark if the OutputChannel was "used" by any theory
617
   * since the start of the last check.  If it has been, we require
618
   * a FULL_EFFORT check before exiting and reporting SAT.
619
   *
620
   * See the documentation for the needCheck() function, below.
621
   */
622
  bool d_outputChannelUsed;
623
624
  /** Atom requests from lemmas */
625
  AtomRequests d_atomRequests;
626
627
  /** sort inference module */
628
  std::unique_ptr<theory::SortInference> d_sortInfer;
629
630
  /** Time spent in theory combination */
631
  TimerStat d_combineTheoriesTime;
632
633
  Node d_true;
634
  Node d_false;
635
636
  /** Whether we were just interrupted (or not) */
637
  bool d_interrupted;
638
639
  /**
640
   * Queue of nodes for pre-registration.
641
   */
642
  std::queue<TNode> d_preregisterQueue;
643
644
  /**
645
   * Boolean flag denoting we are in pre-registration.
646
   */
647
  bool d_inPreregister;
648
649
  /**
650
   * Did the theories get any new facts since the last time we called
651
   * check()
652
   */
653
  context::CDO<bool> d_factsAsserted;
654
655
}; /* class TheoryEngine */
656
657
}  // namespace cvc5
658
659
#endif /* CVC5__THEORY_ENGINE_H */