GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/theory/theory_engine.cpp Lines: 715 853 83.8 %
Date: 2021-11-07 Branches: 1802 4362 41.3 %

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 "theory/theory_engine.h"
17
18
#include <sstream>
19
20
#include "base/map_util.h"
21
#include "decision/decision_engine.h"
22
#include "expr/attribute.h"
23
#include "expr/node_builder.h"
24
#include "expr/node_visitor.h"
25
#include "options/quantifiers_options.h"
26
#include "options/smt_options.h"
27
#include "options/theory_options.h"
28
#include "printer/printer.h"
29
#include "proof/lazy_proof.h"
30
#include "proof/proof_checker.h"
31
#include "proof/proof_ensure_closed.h"
32
#include "prop/prop_engine.h"
33
#include "smt/env.h"
34
#include "smt/logic_exception.h"
35
#include "theory/combination_care_graph.h"
36
#include "theory/decision_manager.h"
37
#include "theory/quantifiers/first_order_model.h"
38
#include "theory/quantifiers_engine.h"
39
#include "theory/relevance_manager.h"
40
#include "theory/rewriter.h"
41
#include "theory/shared_solver.h"
42
#include "theory/theory.h"
43
#include "theory/theory_engine_proof_generator.h"
44
#include "theory/theory_id.h"
45
#include "theory/theory_model.h"
46
#include "theory/theory_traits.h"
47
#include "theory/uf/equality_engine.h"
48
#include "util/resource_manager.h"
49
50
using namespace std;
51
52
using namespace cvc5::theory;
53
54
namespace cvc5 {
55
56
/* -------------------------------------------------------------------------- */
57
58
namespace theory {
59
60
/**
61
 * IMPORTANT: The order of the theories is important. For example, strings
62
 *            depends on arith, quantifiers needs to come as the very last.
63
 *            Do not change this order.
64
 */
65
66
#define CVC5_FOR_EACH_THEORY                                     \
67
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_BUILTIN)   \
68
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_BOOL)      \
69
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_UF)        \
70
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_ARITH)     \
71
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_BV)        \
72
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_FP)        \
73
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_ARRAYS)    \
74
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_DATATYPES) \
75
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_SEP)       \
76
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_SETS)      \
77
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_BAGS)      \
78
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_STRINGS)   \
79
  CVC5_FOR_EACH_THEORY_STATEMENT(cvc5::theory::THEORY_QUANTIFIERS)
80
81
}  // namespace theory
82
83
/* -------------------------------------------------------------------------- */
84
85
inline void flattenAnd(Node n, std::vector<TNode>& out){
86
  Assert(n.getKind() == kind::AND);
87
  for(Node::iterator i=n.begin(), i_end=n.end(); i != i_end; ++i){
88
    Node curr = *i;
89
    if(curr.getKind() == kind::AND){
90
      flattenAnd(curr, out);
91
    }else{
92
      out.push_back(curr);
93
    }
94
  }
95
}
96
97
inline Node flattenAnd(Node n){
98
  std::vector<TNode> out;
99
  flattenAnd(n, out);
100
  return NodeManager::currentNM()->mkNode(kind::AND, out);
101
}
102
103
/**
104
 * Compute the string for a given theory id. In this module, we use
105
 * THEORY_SAT_SOLVER as an id, which is not a normal id but maps to
106
 * THEORY_LAST. Thus, we need our own string conversion here.
107
 *
108
 * @param id The theory id
109
 * @return The string corresponding to the theory id
110
 */
111
2250334
std::string getTheoryString(theory::TheoryId id)
112
{
113
2250334
  if (id == theory::THEORY_SAT_SOLVER)
114
  {
115
1585376
    return "THEORY_SAT_SOLVER";
116
  }
117
  else
118
  {
119
1329916
    std::stringstream ss;
120
664958
    ss << id;
121
664958
    return ss.str();
122
  }
123
}
124
125
15273
void TheoryEngine::finishInit()
126
{
127
15273
  Trace("theory") << "Begin TheoryEngine::finishInit" << std::endl;
128
  // NOTE: This seems to be required since
129
  // theory::TheoryTraits<THEORY>::isParametric cannot be accessed without
130
  // using the CVC5_FOR_EACH_THEORY_STATEMENT macro. -AJR
131
30546
  std::vector<theory::Theory*> paraTheories;
132
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
133
#undef CVC5_FOR_EACH_THEORY_STATEMENT
134
#endif
135
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)   \
136
  if (theory::TheoryTraits<THEORY>::isParametric \
137
      && d_logicInfo.isTheoryEnabled(THEORY))    \
138
  {                                              \
139
    paraTheories.push_back(theoryOf(THEORY));    \
140
  }
141
  // Collect the parametric theories, which are given to the theory combination
142
  // manager below
143
15273
  CVC5_FOR_EACH_THEORY;
144
145
  // Initialize the theory combination architecture
146
15273
  if (options().theory.tcMode == options::TcMode::CARE_GRAPH)
147
  {
148
15273
    d_tc.reset(new CombinationCareGraph(d_env, *this, paraTheories));
149
  }
150
  else
151
  {
152
    Unimplemented() << "TheoryEngine::finishInit: theory combination mode "
153
                    << options().theory.tcMode << " not supported";
154
  }
155
  // create the relevance filter if any option requires it
156
15273
  if (options().theory.relevanceFilter || options().smt.produceDifficulty)
157
  {
158
23
    d_relManager.reset(new RelevanceManager(userContext(), Valuation(this)));
159
  }
160
161
  // initialize the quantifiers engine
162
15273
  if (d_logicInfo.isQuantified())
163
  {
164
    // get the quantifiers engine, which is initialized by the quantifiers
165
    // theory
166
12150
    d_quantEngine = d_theoryTable[THEORY_QUANTIFIERS]->getQuantifiersEngine();
167
12150
    Assert(d_quantEngine != nullptr);
168
  }
169
  // finish initializing the quantifiers engine, which must come before
170
  // initializing theory combination, since quantifiers engine may have a
171
  // special model builder object
172
15273
  if (d_logicInfo.isQuantified())
173
  {
174
12150
    d_quantEngine->finishInit(this);
175
  }
176
  // initialize the theory combination manager, which decides and allocates the
177
  // equality engines to use for all theories.
178
15273
  d_tc->finishInit();
179
  // get pointer to the shared solver
180
15273
  d_sharedSolver = d_tc->getSharedSolver();
181
182
  // finish initializing the theories by linking them with the appropriate
183
  // utilities and then calling their finishInit method.
184
213822
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
185
198549
    Theory* t = d_theoryTable[theoryId];
186
198549
    if (t == nullptr)
187
    {
188
      continue;
189
    }
190
    // setup the pointers to the utilities
191
198549
    const EeTheoryInfo* eeti = d_tc->getEeTheoryInfo(theoryId);
192
198549
    Assert(eeti != nullptr);
193
    // the theory's official equality engine is the one specified by the
194
    // equality engine manager
195
198549
    t->setEqualityEngine(eeti->d_usedEe);
196
    // set the quantifiers engine
197
198549
    t->setQuantifiersEngine(d_quantEngine);
198
    // set the decision manager for the theory
199
198549
    t->setDecisionManager(d_decManager.get());
200
    // finish initializing the theory
201
198549
    t->finishInit();
202
  }
203
15273
  Trace("theory") << "End TheoryEngine::finishInit" << std::endl;
204
15273
}
205
206
15273
TheoryEngine::TheoryEngine(Env& env)
207
    : EnvObj(env),
208
      d_propEngine(nullptr),
209
15273
      d_logicInfo(env.getLogicInfo()),
210
15273
      d_pnm(d_env.isTheoryProofProducing() ? d_env.getProofNodeManager()
211
                                           : nullptr),
212
      d_lazyProof(
213
15273
          d_pnm != nullptr ? new LazyCDProof(
214
10744
              d_pnm, nullptr, userContext(), "TheoryEngine::LazyCDProof")
215
                           : nullptr),
216
15273
      d_tepg(new TheoryEngineProofGenerator(d_pnm, userContext())),
217
      d_tc(nullptr),
218
      d_sharedSolver(nullptr),
219
      d_quantEngine(nullptr),
220
15273
      d_decManager(new DecisionManager(userContext())),
221
      d_relManager(nullptr),
222
      d_inConflict(context(), false),
223
      d_inSatMode(false),
224
      d_hasShutDown(false),
225
      d_incomplete(context(), false),
226
      d_incompleteTheory(context(), THEORY_BUILTIN),
227
      d_incompleteId(context(), IncompleteId::UNKNOWN),
228
      d_propagationMap(context()),
229
      d_propagationMapTimestamp(context(), 0),
230
      d_propagatedLiterals(context()),
231
      d_propagatedLiteralsIndex(context(), 0),
232
      d_atomRequests(context()),
233
15273
      d_combineTheoriesTime(statisticsRegistry().registerTimer(
234
30546
          "TheoryEngine::combineTheoriesTime")),
235
      d_true(),
236
      d_false(),
237
      d_interrupted(false),
238
      d_inPreregister(false),
239
132928
      d_factsAsserted(context(), false)
240
{
241
213822
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST;
242
      ++ theoryId)
243
  {
244
198549
    d_theoryTable[theoryId] = NULL;
245
198549
    d_theoryOut[theoryId] = NULL;
246
  }
247
248
15273
  if (options().smt.sortInference)
249
  {
250
20
    d_sortInfer.reset(new SortInference(env));
251
  }
252
253
15273
  d_true = NodeManager::currentNM()->mkConst<bool>(true);
254
15273
  d_false = NodeManager::currentNM()->mkConst<bool>(false);
255
15273
}
256
257
45804
TheoryEngine::~TheoryEngine() {
258
15268
  Assert(d_hasShutDown);
259
260
213752
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId != theory::THEORY_LAST; ++ theoryId) {
261
198484
    if(d_theoryTable[theoryId] != NULL) {
262
198436
      delete d_theoryTable[theoryId];
263
198436
      delete d_theoryOut[theoryId];
264
    }
265
  }
266
30536
}
267
268
void TheoryEngine::interrupt() { d_interrupted = true; }
269
1218861
void TheoryEngine::preRegister(TNode preprocessed) {
270
2437722
  Debug("theory") << "TheoryEngine::preRegister( " << preprocessed << ")"
271
1218861
                  << std::endl;
272
1218861
  d_preregisterQueue.push(preprocessed);
273
274
1218861
  if (!d_inPreregister) {
275
    // We're in pre-register
276
1141705
    d_inPreregister = true;
277
278
    // Process the pre-registration queue
279
3579419
    while (!d_preregisterQueue.empty()) {
280
      // Get the next atom to pre-register
281
1218861
      preprocessed = d_preregisterQueue.front();
282
1218861
      d_preregisterQueue.pop();
283
284
      // the atom should not have free variables
285
2437722
      Debug("theory") << "TheoryEngine::preRegister: " << preprocessed
286
1218861
                      << std::endl;
287
1218861
      if (Configuration::isAssertionBuild())
288
      {
289
2437722
        std::unordered_set<Node> fvs;
290
1218861
        expr::getFreeVariables(preprocessed, fvs);
291
1218861
        if (!fvs.empty())
292
        {
293
          Unhandled() << "Preregistered term with free variable: "
294
                      << preprocessed << ", fv=" << *fvs.begin();
295
        }
296
      }
297
      // should not have witness
298
1218861
      Assert(!expr::hasSubtermKind(kind::WITNESS, preprocessed));
299
300
      // pre-register with the shared solver, which handles
301
      // calling prepregister on individual theories, adding shared terms,
302
      // and setting up equalities to propagate in the shared term database.
303
1218861
      Assert(d_sharedSolver != nullptr);
304
1218865
      d_sharedSolver->preRegister(preprocessed);
305
    }
306
307
    // Leaving pre-register
308
1141701
    d_inPreregister = false;
309
  }
310
1218857
}
311
312
void TheoryEngine::printAssertions(const char* tag) {
313
  if (Trace.isOn(tag)) {
314
315
    for (TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
316
      Theory* theory = d_theoryTable[theoryId];
317
      if (theory && d_logicInfo.isTheoryEnabled(theoryId)) {
318
        Trace(tag) << "--------------------------------------------" << endl;
319
        Trace(tag) << "Assertions of " << theory->getId() << ": " << endl;
320
        {
321
          context::CDList<Assertion>::const_iterator it = theory->facts_begin(),
322
                                                     it_end =
323
                                                         theory->facts_end();
324
          for (unsigned i = 0; it != it_end; ++it, ++i)
325
          {
326
            if ((*it).d_isPreregistered)
327
            {
328
              Trace(tag) << "[" << i << "]: ";
329
            }
330
            else
331
            {
332
              Trace(tag) << "(" << i << "): ";
333
            }
334
            Trace(tag) << (*it).d_assertion << endl;
335
          }
336
        }
337
338
        if (d_logicInfo.isSharingEnabled()) {
339
          Trace(tag) << "Shared terms of " << theory->getId() << ": " << endl;
340
          context::CDList<TNode>::const_iterator it = theory->shared_terms_begin(), it_end = theory->shared_terms_end();
341
          for (unsigned i = 0; it != it_end; ++ it, ++i) {
342
              Trace(tag) << "[" << i << "]: " << (*it) << endl;
343
          }
344
        }
345
      }
346
    }
347
  }
348
}
349
350
/**
351
 * Check all (currently-active) theories for conflicts.
352
 * @param effort the effort level to use
353
 */
354
5228125
void TheoryEngine::check(Theory::Effort effort) {
355
  // spendResource();
356
357
  // Reset the interrupt flag
358
5228125
  d_interrupted = false;
359
360
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
361
#undef CVC5_FOR_EACH_THEORY_STATEMENT
362
#endif
363
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)                      \
364
  if (theory::TheoryTraits<THEORY>::hasCheck                        \
365
      && d_logicInfo.isTheoryEnabled(THEORY))                       \
366
  {                                                                 \
367
    theoryOf(THEORY)->check(effort);                                \
368
    if (d_inConflict)                                               \
369
    {                                                               \
370
      Debug("conflict") << THEORY << " in conflict. " << std::endl; \
371
      break;                                                        \
372
    }                                                               \
373
  }
374
375
  // Do the checking
376
  try {
377
378
    // Mark the output channel unused (if this is FULL_EFFORT, and nothing
379
    // is done by the theories, no additional check will be needed)
380
5228125
    d_outputChannelUsed = false;
381
382
    // Mark the lemmas flag (no lemmas added)
383
5228125
    d_lemmasAdded = false;
384
385
5228125
    Debug("theory") << "TheoryEngine::check(" << effort << "): d_factsAsserted = " << (d_factsAsserted ? "true" : "false") << endl;
386
387
    // If in full effort, we have a fake new assertion just to jumpstart the checking
388
5228125
    if (Theory::fullEffort(effort)) {
389
91128
      d_factsAsserted = true;
390
      // Reset round for the relevance manager, which notice only sets a flag
391
      // to indicate that its information must be recomputed.
392
91128
      if (d_relManager != nullptr)
393
      {
394
141
        d_relManager->resetRound();
395
      }
396
91128
      d_tc->resetRound();
397
    }
398
399
    // Check until done
400
14826487
    while (d_factsAsserted && !d_inConflict && !d_lemmasAdded) {
401
402
4966668
      Debug("theory") << "TheoryEngine::check(" << effort << "): running check" << endl;
403
404
4966668
      Trace("theory::assertions") << endl;
405
4966668
      if (Trace.isOn("theory::assertions")) {
406
        printAssertions("theory::assertions");
407
      }
408
409
4966668
      if(Theory::fullEffort(effort)) {
410
100045
        Trace("theory::assertions::fulleffort") << endl;
411
100045
        if (Trace.isOn("theory::assertions::fulleffort")) {
412
          printAssertions("theory::assertions::fulleffort");
413
        }
414
      }
415
416
      // Note that we've discharged all the facts
417
4966668
      d_factsAsserted = false;
418
419
      // Do the checking
420
4966668
      CVC5_FOR_EACH_THEORY;
421
422
4799181
      Debug("theory") << "TheoryEngine::check(" << effort << "): running propagation after the initial check" << endl;
423
424
      // We are still satisfiable, propagate as much as possible
425
4799181
      propagate(effort);
426
427
      // We do combination if all has been processed and we are in fullcheck
428
9670386
      if (Theory::fullEffort(effort) && d_logicInfo.isSharingEnabled()
429
4864488
          && !d_factsAsserted && !needCheck() && !d_inConflict)
430
      {
431
        // Do the combination
432
32878
        Debug("theory") << "TheoryEngine::check(" << effort << "): running combination" << endl;
433
        {
434
65756
          TimerStat::CodeTimer combineTheoriesTimer(d_combineTheoriesTime);
435
32878
          d_tc->combineTheories();
436
        }
437
32878
        if(d_logicInfo.isQuantified()){
438
22130
          d_quantEngine->notifyCombineTheories();
439
        }
440
      }
441
    }
442
443
    // Must consult quantifiers theory for last call to ensure sat, or otherwise add a lemma
444
5228121
    if( Theory::fullEffort(effort) && ! d_inConflict && ! needCheck() ) {
445
29793
      Trace("theory::assertions-model") << endl;
446
29793
      if (Trace.isOn("theory::assertions-model")) {
447
        printAssertions("theory::assertions-model");
448
      }
449
      // reset the model in the combination engine
450
29793
      d_tc->resetModel();
451
      //checks for theories requiring the model go at last call
452
417102
      for (TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
453
387309
        if( theoryId!=THEORY_QUANTIFIERS ){
454
357516
          Theory* theory = d_theoryTable[theoryId];
455
357516
          if (theory && d_logicInfo.isTheoryEnabled(theoryId)) {
456
192726
            if( theory->needsCheckLastEffort() ){
457
16246
              if (!d_tc->buildModel())
458
              {
459
                break;
460
              }
461
16246
              theory->check(Theory::EFFORT_LAST_CALL);
462
            }
463
          }
464
        }
465
      }
466
29793
      if (!d_inConflict)
467
      {
468
29793
        if(d_logicInfo.isQuantified()) {
469
          // quantifiers engine must check at last call effort
470
23392
          d_quantEngine->check(Theory::EFFORT_LAST_CALL);
471
        }
472
      }
473
      // notify the relevant manager
474
29778
      if (d_relManager != nullptr)
475
      {
476
120
        d_relManager->notifyCandidateModel(getModel());
477
      }
478
29778
      if (!d_inConflict && !needCheck())
479
      {
480
        // We only mark that we are in "SAT mode". We build the model later only
481
        // if the user asks for it via getBuiltModel.
482
9679
        d_inSatMode = true;
483
      }
484
    }
485
486
5228106
    Debug("theory") << "TheoryEngine::check(" << effort << "): done, we are " << (d_inConflict ? "unsat" : "sat") << (d_lemmasAdded ? " with new lemmas" : " with no new lemmas");
487
5228106
    Debug("theory") << ", need check = " << (needCheck() ? "YES" : "NO") << endl;
488
489
5228106
    if( Theory::fullEffort(effort) && !d_inConflict && !needCheck()) {
490
      // Do post-processing of model from the theories (e.g. used for THEORY_SEP
491
      // to construct heap model)
492
9679
      d_tc->postProcessModel(d_incomplete.get());
493
    }
494
  } catch(const theory::Interrupted&) {
495
    Trace("theory") << "TheoryEngine::check() => interrupted" << endl;
496
  }
497
5228106
}
498
499
4799181
void TheoryEngine::propagate(Theory::Effort effort)
500
{
501
  // Reset the interrupt flag
502
4799181
  d_interrupted = false;
503
504
  // Definition of the statement that is to be run by every theory
505
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
506
#undef CVC5_FOR_EACH_THEORY_STATEMENT
507
#endif
508
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)   \
509
  if (theory::TheoryTraits<THEORY>::hasPropagate \
510
      && d_logicInfo.isTheoryEnabled(THEORY))    \
511
  {                                              \
512
    theoryOf(THEORY)->propagate(effort);         \
513
  }
514
515
  // Reset the interrupt flag
516
4799181
  d_interrupted = false;
517
518
  // Propagate for each theory using the statement above
519
4799181
  CVC5_FOR_EACH_THEORY;
520
4799181
}
521
522
3530070
Node TheoryEngine::getNextDecisionRequest()
523
{
524
3530070
  return d_decManager->getNextDecisionRequest();
525
}
526
527
153277
bool TheoryEngine::properConflict(TNode conflict) const {
528
  bool value;
529
153277
  if (conflict.getKind() == kind::AND) {
530
1829166
    for (unsigned i = 0; i < conflict.getNumChildren(); ++ i) {
531
1676505
      if (! getPropEngine()->hasValue(conflict[i], value)) {
532
        Debug("properConflict") << "Bad conflict is due to unassigned atom: "
533
                                << conflict[i] << endl;
534
        return false;
535
      }
536
1676505
      if (! value) {
537
        Debug("properConflict") << "Bad conflict is due to false atom: "
538
                                << conflict[i] << endl;
539
        return false;
540
      }
541
1676505
      if (conflict[i] != rewrite(conflict[i]))
542
      {
543
        Debug("properConflict")
544
            << "Bad conflict is due to atom not in normal form: " << conflict[i]
545
            << " vs " << rewrite(conflict[i]) << endl;
546
        return false;
547
      }
548
    }
549
  } else {
550
616
    if (! getPropEngine()->hasValue(conflict, value)) {
551
      Debug("properConflict") << "Bad conflict is due to unassigned atom: "
552
                              << conflict << endl;
553
      return false;
554
    }
555
616
    if(! value) {
556
      Debug("properConflict") << "Bad conflict is due to false atom: "
557
                              << conflict << endl;
558
      return false;
559
    }
560
616
    if (conflict != rewrite(conflict))
561
    {
562
      Debug("properConflict")
563
          << "Bad conflict is due to atom not in normal form: " << conflict
564
          << " vs " << rewrite(conflict) << endl;
565
      return false;
566
    }
567
  }
568
153277
  return true;
569
}
570
571
18102874
TheoryModel* TheoryEngine::getModel()
572
{
573
18102874
  Assert(d_tc != nullptr);
574
18102874
  TheoryModel* m = d_tc->getModel();
575
18102874
  Assert(m != nullptr);
576
18102874
  return m;
577
}
578
579
12699
TheoryModel* TheoryEngine::getBuiltModel()
580
{
581
12699
  Assert(d_tc != nullptr);
582
  // If this method was called, we should be in SAT mode, and produceModels
583
  // should be true.
584
12699
  AlwaysAssert(options().smt.produceModels);
585
12699
  if (!d_inSatMode)
586
  {
587
    // not available, perhaps due to interuption.
588
    return nullptr;
589
  }
590
  // must build model at this point
591
12699
  if (!d_tc->buildModel())
592
  {
593
    return nullptr;
594
  }
595
12698
  return d_tc->getModel();
596
}
597
598
16552
bool TheoryEngine::buildModel()
599
{
600
16552
  Assert(d_tc != nullptr);
601
16552
  return d_tc->buildModel();
602
}
603
604
20560
bool TheoryEngine::presolve() {
605
  // Reset the interrupt flag
606
20560
  d_interrupted = false;
607
608
  // Reset the decision manager. This clears its decision strategies that are
609
  // no longer valid in this user context.
610
20560
  d_decManager->presolve();
611
612
  try {
613
    // Definition of the statement that is to be run by every theory
614
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
615
#undef CVC5_FOR_EACH_THEORY_STATEMENT
616
#endif
617
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)   \
618
  if (theory::TheoryTraits<THEORY>::hasPresolve) \
619
  {                                              \
620
    theoryOf(THEORY)->presolve();                \
621
    if (d_inConflict)                            \
622
    {                                            \
623
      return true;                               \
624
    }                                            \
625
  }
626
627
    // Presolve for each theory using the statement above
628
20560
    CVC5_FOR_EACH_THEORY;
629
  } catch(const theory::Interrupted&) {
630
    Trace("theory") << "TheoryEngine::presolve() => interrupted" << endl;
631
  }
632
  // return whether we have a conflict
633
20560
  return false;
634
}/* TheoryEngine::presolve() */
635
636
20537
void TheoryEngine::postsolve() {
637
  // no longer in SAT mode
638
20537
  d_inSatMode = false;
639
  // Reset the interrupt flag
640
20537
  d_interrupted = false;
641
20537
  CVC5_UNUSED bool wasInConflict = d_inConflict;
642
643
  try {
644
    // Definition of the statement that is to be run by every theory
645
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
646
#undef CVC5_FOR_EACH_THEORY_STATEMENT
647
#endif
648
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)    \
649
  if (theory::TheoryTraits<THEORY>::hasPostsolve) \
650
  {                                               \
651
    theoryOf(THEORY)->postsolve();                \
652
    Assert(!d_inConflict || wasInConflict)        \
653
        << "conflict raised during postsolve()";  \
654
  }
655
656
    // Postsolve for each theory using the statement above
657
    CVC5_FOR_EACH_THEORY;
658
  } catch(const theory::Interrupted&) {
659
    Trace("theory") << "TheoryEngine::postsolve() => interrupted" << endl;
660
  }
661
20537
}/* TheoryEngine::postsolve() */
662
663
664
2701
void TheoryEngine::notifyRestart() {
665
  // Reset the interrupt flag
666
2701
  d_interrupted = false;
667
668
  // Definition of the statement that is to be run by every theory
669
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
670
#undef CVC5_FOR_EACH_THEORY_STATEMENT
671
#endif
672
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)       \
673
  if (theory::TheoryTraits<THEORY>::hasNotifyRestart \
674
      && d_logicInfo.isTheoryEnabled(THEORY))        \
675
  {                                                  \
676
    theoryOf(THEORY)->notifyRestart();               \
677
  }
678
679
  // notify each theory using the statement above
680
2701
  CVC5_FOR_EACH_THEORY;
681
2701
}
682
683
250978
void TheoryEngine::ppStaticLearn(TNode in, NodeBuilder& learned)
684
{
685
  // Reset the interrupt flag
686
250978
  d_interrupted = false;
687
688
  // Definition of the statement that is to be run by every theory
689
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
690
#undef CVC5_FOR_EACH_THEORY_STATEMENT
691
#endif
692
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY)        \
693
  if (theory::TheoryTraits<THEORY>::hasPpStaticLearn) \
694
  {                                                   \
695
    theoryOf(THEORY)->ppStaticLearn(in, learned);     \
696
  }
697
698
  // static learning for each theory using the statement above
699
250978
  CVC5_FOR_EACH_THEORY;
700
250978
}
701
702
112830
bool TheoryEngine::isRelevant(Node lit) const
703
{
704
112830
  if (d_relManager != nullptr)
705
  {
706
2482
    return d_relManager->isRelevant(lit);
707
  }
708
  // otherwise must assume its relevant
709
110348
  return true;
710
}
711
712
15268
void TheoryEngine::shutdown() {
713
  // Set this first; if a Theory shutdown() throws an exception,
714
  // at least the destruction of the TheoryEngine won't confound
715
  // matters.
716
15268
  d_hasShutDown = true;
717
718
  // Shutdown all the theories
719
213752
  for(TheoryId theoryId = theory::THEORY_FIRST; theoryId < theory::THEORY_LAST; ++theoryId) {
720
198484
    if(d_theoryTable[theoryId]) {
721
198436
      theoryOf(theoryId)->shutdown();
722
    }
723
  }
724
15268
}
725
726
97409
theory::Theory::PPAssertStatus TheoryEngine::solve(
727
    TrustNode tliteral, TrustSubstitutionMap& substitutionOut)
728
{
729
  // Reset the interrupt flag
730
97409
  d_interrupted = false;
731
732
194818
  TNode literal = tliteral.getNode();
733
194818
  TNode atom = literal.getKind() == kind::NOT ? literal[0] : literal;
734
97409
  Trace("theory::solve") << "TheoryEngine::solve(" << literal << "): solving with " << theoryOf(atom)->getId() << endl;
735
736
194818
  if(! d_logicInfo.isTheoryEnabled(Theory::theoryOf(atom)) &&
737
97409
     Theory::theoryOf(atom) != THEORY_SAT_SOLVER) {
738
    stringstream ss;
739
    ss << "The logic was specified as " << d_logicInfo.getLogicString()
740
       << ", which doesn't include " << Theory::theoryOf(atom)
741
       << ", but got a preprocessing-time fact for that theory." << endl
742
       << "The fact:" << endl
743
       << literal;
744
    throw LogicException(ss.str());
745
  }
746
747
  Theory::PPAssertStatus solveStatus =
748
97409
      theoryOf(atom)->ppAssert(tliteral, substitutionOut);
749
97409
  Trace("theory::solve") << "TheoryEngine::solve(" << literal << ") => " << solveStatus << endl;
750
194818
  return solveStatus;
751
}
752
753
228399
TrustNode TheoryEngine::ppRewriteEquality(TNode eq)
754
{
755
228399
  Assert(eq.getKind() == kind::EQUAL);
756
456798
  std::vector<SkolemLemma> lems;
757
228399
  TrustNode trn = theoryOf(eq)->ppRewrite(eq, lems);
758
  // should never introduce a skolem to eliminate an equality
759
228399
  Assert(lems.empty());
760
456798
  return trn;
761
}
762
763
19095
void TheoryEngine::notifyPreprocessedAssertions(
764
    const std::vector<Node>& assertions) {
765
  // call all the theories
766
267330
  for (TheoryId theoryId = theory::THEORY_FIRST; theoryId < theory::THEORY_LAST;
767
       ++theoryId) {
768
248235
    if (d_theoryTable[theoryId]) {
769
248235
      theoryOf(theoryId)->ppNotifyAssertions(assertions);
770
    }
771
  }
772
19095
  if (d_relManager != nullptr)
773
  {
774
19
    d_relManager->notifyPreprocessedAssertions(assertions);
775
  }
776
19095
}
777
778
46608780
bool TheoryEngine::markPropagation(TNode assertion, TNode originalAssertion, theory::TheoryId toTheoryId, theory::TheoryId fromTheoryId) {
779
  // What and where we are asserting
780
93217560
  NodeTheoryPair toAssert(assertion, toTheoryId, d_propagationMapTimestamp);
781
  // What and where it came from
782
93217560
  NodeTheoryPair toExplain(originalAssertion, fromTheoryId, d_propagationMapTimestamp);
783
784
  // See if the theory already got this literal
785
46608780
  PropagationMap::const_iterator find = d_propagationMap.find(toAssert);
786
46608780
  if (find != d_propagationMap.end()) {
787
    // The theory already knows this
788
13670240
    Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): already there" << endl;
789
13670240
    return false;
790
  }
791
792
32938540
  Trace("theory::assertToTheory") << "TheoryEngine::markPropagation(): marking [" << d_propagationMapTimestamp << "] " << assertion << ", " << toTheoryId << " from " << originalAssertion << ", " << fromTheoryId << endl;
793
794
  // Mark the propagation
795
32938540
  d_propagationMap[toAssert] = toExplain;
796
32938540
  d_propagationMapTimestamp = d_propagationMapTimestamp + 1;
797
798
32938540
  return true;
799
}
800
801
802
52474027
void TheoryEngine::assertToTheory(TNode assertion, TNode originalAssertion, theory::TheoryId toTheoryId, theory::TheoryId fromTheoryId) {
803
52474027
  Trace("theory::assertToTheory") << "TheoryEngine::assertToTheory(" << assertion << ", " << originalAssertion << "," << toTheoryId << ", " << fromTheoryId << ")" << endl;
804
805
52474027
  Assert(toTheoryId != fromTheoryId);
806
87864740
  if(toTheoryId != THEORY_SAT_SOLVER &&
807
35390713
     ! d_logicInfo.isTheoryEnabled(toTheoryId)) {
808
    stringstream ss;
809
    ss << "The logic was specified as " << d_logicInfo.getLogicString()
810
       << ", which doesn't include " << toTheoryId
811
       << ", but got an asserted fact to that theory." << endl
812
       << "The fact:" << endl
813
       << assertion;
814
    throw LogicException(ss.str());
815
  }
816
817
52474027
  if (d_inConflict) {
818
86440
    return;
819
  }
820
821
  // If sharing is disabled, things are easy
822
52387587
  if (!d_logicInfo.isSharingEnabled()) {
823
5778807
    Assert(assertion == originalAssertion);
824
5778807
    if (fromTheoryId == THEORY_SAT_SOLVER) {
825
      // Send to the apropriate theory
826
4175289
      theory::Theory* toTheory = theoryOf(toTheoryId);
827
      // We assert it, and we know it's preregistereed
828
4175289
      toTheory->assertFact(assertion, true);
829
      // Mark that we have more information
830
4175289
      d_factsAsserted = true;
831
    } else {
832
1603518
      Assert(toTheoryId == THEORY_SAT_SOLVER);
833
      // Check for propositional conflict
834
      bool value;
835
1603518
      if (d_propEngine->hasValue(assertion, value)) {
836
1053556
        if (!value) {
837
25701
          Trace("theory::propagate") << "TheoryEngine::assertToTheory(" << assertion << ", " << toTheoryId << ", " << fromTheoryId << "): conflict (no sharing)" << endl;
838
51402
          Trace("dtview::conflict")
839
25701
              << ":THEORY-CONFLICT: " << assertion << std::endl;
840
25701
          markInConflict();
841
        } else {
842
1027855
          return;
843
        }
844
      }
845
575663
      d_propagatedLiterals.push_back(assertion);
846
    }
847
4750952
    return;
848
  }
849
850
  // determine the actual theory that will process/explain the fact, which is
851
  // THEORY_BUILTIN if the theory uses the central equality engine
852
46608780
  TheoryId toTheoryIdProp = (Theory::expUsingCentralEqualityEngine(toTheoryId))
853
46608780
                                ? THEORY_BUILTIN
854
46608780
                                : toTheoryId;
855
  // If sending to the shared solver, it's also simple
856
46608780
  if (toTheoryId == THEORY_BUILTIN) {
857
14645582
    if (markPropagation(
858
            assertion, originalAssertion, toTheoryIdProp, fromTheoryId))
859
    {
860
      // assert to the shared solver
861
7897718
      bool polarity = assertion.getKind() != kind::NOT;
862
15795436
      TNode atom = polarity ? assertion : assertion[0];
863
7897718
      d_sharedSolver->assertShared(atom, polarity, assertion);
864
    }
865
14645582
    return;
866
  }
867
868
  // Things from the SAT solver are already normalized, so they go
869
  // directly to the apropriate theory
870
31963198
  if (fromTheoryId == THEORY_SAT_SOLVER) {
871
    // We know that this is normalized, so just send it off to the theory
872
11690170
    if (markPropagation(
873
            assertion, originalAssertion, toTheoryIdProp, fromTheoryId))
874
    {
875
      // Is it preregistered
876
11556775
      bool preregistered = d_propEngine->isSatLiteral(assertion) && Theory::theoryOf(assertion) == toTheoryId;
877
      // We assert it
878
11556775
      theoryOf(toTheoryId)->assertFact(assertion, preregistered);
879
      // Mark that we have more information
880
11556775
      d_factsAsserted = true;
881
    }
882
11690170
    return;
883
  }
884
885
  // Propagations to the SAT solver are just enqueued for pickup by
886
  // the SAT solver later
887
20273028
  if (toTheoryId == THEORY_SAT_SOLVER) {
888
15422709
    Assert(toTheoryIdProp == toTheoryId);
889
15422709
    if (markPropagation(assertion, originalAssertion, toTheoryId, fromTheoryId)) {
890
      // Enqueue for propagation to the SAT solver
891
9400283
      d_propagatedLiterals.push_back(assertion);
892
      // Check for propositional conflicts
893
      bool value;
894
9400283
      if (d_propEngine->hasValue(assertion, value) && !value) {
895
85920
        Trace("theory::propagate")
896
42960
            << "TheoryEngine::assertToTheory(" << assertion << ", "
897
42960
            << toTheoryId << ", " << fromTheoryId << "): conflict (sharing)"
898
42960
            << endl;
899
85920
        Trace("dtview::conflict")
900
42960
            << ":THEORY-CONFLICT: " << assertion << std::endl;
901
42960
        markInConflict();
902
      }
903
    }
904
15422709
    return;
905
  }
906
907
4850319
  Assert(assertion.getKind() == kind::EQUAL
908
         || (assertion.getKind() == kind::NOT
909
             && assertion[0].getKind() == kind::EQUAL));
910
911
  // Normalize
912
9700638
  Node normalizedLiteral = rewrite(assertion);
913
914
  // See if it rewrites false directly -> conflict
915
4850319
  if (normalizedLiteral.isConst()) {
916
22476
    if (!normalizedLiteral.getConst<bool>()) {
917
      // Mark the propagation for explanations
918
414
      if (markPropagation(normalizedLiteral,
919
                          originalAssertion,
920
                          toTheoryIdProp,
921
                          fromTheoryId))
922
      {
923
        // special case, trust node has no proof generator
924
828
        TrustNode trnn = TrustNode::mkTrustConflict(normalizedLiteral);
925
        // Get the explanation (conflict will figure out where it came from)
926
414
        conflict(trnn, toTheoryId);
927
      } else {
928
        Unreachable();
929
      }
930
414
      return;
931
    }
932
  }
933
934
  // Try and assert (note that we assert the non-normalized one)
935
4849905
  if (markPropagation(
936
          assertion, originalAssertion, toTheoryIdProp, fromTheoryId))
937
  {
938
    // Check if has been pre-registered with the theory
939
4083350
    bool preregistered = d_propEngine->isSatLiteral(assertion) && Theory::theoryOf(assertion) == toTheoryId;
940
    // Assert away
941
4083350
    theoryOf(toTheoryId)->assertFact(assertion, preregistered);
942
4083350
    d_factsAsserted = true;
943
  }
944
945
4849905
  return;
946
}
947
948
15849302
void TheoryEngine::assertFact(TNode literal)
949
{
950
15849302
  Trace("theory") << "TheoryEngine::assertFact(" << literal << ")" << endl;
951
952
  // spendResource();
953
954
  // If we're in conflict, nothing to do
955
15849302
  if (d_inConflict) {
956
36427
    return;
957
  }
958
959
  // Get the atom
960
15812875
  bool polarity = literal.getKind() != kind::NOT;
961
31625750
  TNode atom = polarity ? literal : literal[0];
962
963
15812875
  if (d_logicInfo.isSharingEnabled()) {
964
    // If any shared terms, it's time to do sharing work
965
11637586
    d_sharedSolver->preNotifySharedFact(atom);
966
967
    // If it's an equality, assert it to the shared term manager, even though the terms are not
968
    // yet shared. As the terms become shared later, the shared terms manager will then add them
969
    // to the assert the equality to the interested theories
970
11637586
    if (atom.getKind() == kind::EQUAL) {
971
      // Assert it to the the owning theory
972
5939635
      assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
973
      // Shared terms manager will assert to interested theories directly, as
974
      // the terms become shared
975
5939635
      assertToTheory(literal, literal, /* to */ THEORY_BUILTIN, /* from */ THEORY_SAT_SOLVER);
976
977
      // Now, let's check for any atom triggers from lemmas
978
5939635
      AtomRequests::atom_iterator it = d_atomRequests.getAtomIterator(atom);
979
5980203
      while (!it.done()) {
980
20284
        const AtomRequests::Request& request = it.get();
981
        Node toAssert =
982
40568
            polarity ? (Node)request.d_atom : request.d_atom.notNode();
983
40568
        Debug("theory::atoms") << "TheoryEngine::assertFact(" << literal
984
20284
                               << "): sending requested " << toAssert << endl;
985
20284
        assertToTheory(
986
20284
            toAssert, literal, request.d_toTheory, THEORY_SAT_SOLVER);
987
20284
        it.next();
988
      }
989
990
    } else {
991
      // Not an equality, just assert to the appropriate theory
992
5697951
      assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
993
    }
994
  } else {
995
    // Assert the fact to the appropriate theory directly
996
4175289
    assertToTheory(literal, literal, /* to */ Theory::theoryOf(atom), /* from */ THEORY_SAT_SOLVER);
997
  }
998
}
999
1000
19777562
bool TheoryEngine::propagate(TNode literal, theory::TheoryId theory) {
1001
39555124
  Debug("theory::propagate")
1002
19777562
      << "TheoryEngine::propagate(" << literal << ", " << theory << ")" << endl;
1003
1004
39555124
  Trace("dtview::prop") << std::string(context()->getLevel(), ' ')
1005
19777562
                        << ":THEORY-PROP: " << literal << endl;
1006
1007
  // spendResource();
1008
1009
  // Get the atom
1010
19777562
  bool polarity = literal.getKind() != kind::NOT;
1011
39555124
  TNode atom = polarity ? literal : literal[0];
1012
1013
19777562
  if (d_logicInfo.isSharingEnabled() && atom.getKind() == kind::EQUAL) {
1014
14998247
    if (d_propEngine->isSatLiteral(literal)) {
1015
      // We propagate SAT literals to SAT
1016
12303999
      assertToTheory(literal, literal, /* to */ THEORY_SAT_SOLVER, /* from */ theory);
1017
    }
1018
14998247
    if (theory != THEORY_BUILTIN) {
1019
      // Assert to the shared terms database
1020
8731067
      assertToTheory(literal, literal, /* to */ THEORY_BUILTIN, /* from */ theory);
1021
    }
1022
  } else {
1023
    // Just send off to the SAT solver
1024
4779315
    Assert(d_propEngine->isSatLiteral(literal));
1025
4779315
    assertToTheory(literal, literal, /* to */ THEORY_SAT_SOLVER, /* from */ theory);
1026
  }
1027
1028
39555124
  return !d_inConflict;
1029
}
1030
1031
15310
const LogicInfo& TheoryEngine::getLogicInfo() const { return d_logicInfo; }
1032
1033
1439
bool TheoryEngine::getSepHeapTypes(TypeNode& locType, TypeNode& dataType) const
1034
{
1035
1439
  if (d_sepLocType.isNull())
1036
  {
1037
1417
    return false;
1038
  }
1039
22
  locType = d_sepLocType;
1040
22
  dataType = d_sepDataType;
1041
22
  return true;
1042
}
1043
1044
120
void TheoryEngine::declareSepHeap(TypeNode locT, TypeNode dataT)
1045
{
1046
120
  Theory* tsep = theoryOf(THEORY_SEP);
1047
120
  if (tsep == nullptr)
1048
  {
1049
    Assert(false) << "TheoryEngine::declareSepHeap called without the "
1050
                     "separation logic theory enabled";
1051
    return;
1052
  }
1053
1054
  // Definition of the statement that is to be run by every theory
1055
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
1056
#undef CVC5_FOR_EACH_THEORY_STATEMENT
1057
#endif
1058
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY) \
1059
  theoryOf(THEORY)->declareSepHeap(locT, dataT);
1060
1061
  // notify each theory using the statement above
1062
120
  CVC5_FOR_EACH_THEORY;
1063
1064
  // remember the types we have set
1065
118
  d_sepLocType = locT;
1066
118
  d_sepDataType = dataT;
1067
}
1068
1069
1364448
theory::EqualityStatus TheoryEngine::getEqualityStatus(TNode a, TNode b) {
1070
1364448
  Assert(a.getType().isComparableTo(b.getType()));
1071
1364448
  return d_sharedSolver->getEqualityStatus(a, b);
1072
}
1073
1074
const std::unordered_set<TNode>& TheoryEngine::getRelevantAssertions(
1075
    bool& success)
1076
{
1077
  // if we are not in SAT mode, or there is no relevance manager, we fail
1078
  if (!d_inSatMode || d_relManager == nullptr)
1079
  {
1080
    success = false;
1081
    return d_emptyRelevantSet;
1082
  }
1083
  return d_relManager->getRelevantAssertions(success);
1084
}
1085
1086
4
void TheoryEngine::getDifficultyMap(std::map<Node, Node>& dmap)
1087
{
1088
4
  Assert(d_relManager != nullptr);
1089
4
  d_relManager->getDifficultyMap(dmap);
1090
4
}
1091
1092
4527
Node TheoryEngine::getModelValue(TNode var) {
1093
4527
  if (var.isConst())
1094
  {
1095
    // the model value of a constant must be itself
1096
    return var;
1097
  }
1098
4527
  Assert(d_sharedSolver->isShared(var));
1099
4527
  return theoryOf(Theory::theoryOf(var.getType()))->getModelValue(var);
1100
}
1101
1102
120613
TrustNode TheoryEngine::getExplanation(TNode node)
1103
{
1104
241226
  Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1105
120613
                           << "): current propagation index = "
1106
120613
                           << d_propagationMapTimestamp << endl;
1107
120613
  bool polarity = node.getKind() != kind::NOT;
1108
241226
  TNode atom = polarity ? node : node[0];
1109
1110
  // If we're not in shared mode, explanations are simple
1111
120613
  if (!d_logicInfo.isSharingEnabled())
1112
  {
1113
68476
    Debug("theory::explain")
1114
34238
        << "TheoryEngine::getExplanation: sharing is NOT enabled. "
1115
34238
        << " Responsible theory is: " << theoryOf(atom)->getId() << std::endl;
1116
1117
68476
    TrustNode texplanation = theoryOf(atom)->explain(node);
1118
68476
    Node explanation = texplanation.getNode();
1119
68476
    Debug("theory::explain") << "TheoryEngine::getExplanation(" << node
1120
34238
                             << ") => " << explanation << endl;
1121
34238
    if (isProofEnabled())
1122
    {
1123
9571
      texplanation.debugCheckClosed(
1124
          "te-proof-exp", "texplanation no share", false);
1125
      // check if no generator, if so, add THEORY_LEMMA
1126
9571
      if (texplanation.getGenerator() == nullptr)
1127
      {
1128
        Node proven = texplanation.getProven();
1129
        TheoryId tid = theoryOf(atom)->getId();
1130
        Node tidn = builtin::BuiltinProofRuleChecker::mkTheoryIdNode(tid);
1131
        d_lazyProof->addStep(proven, PfRule::THEORY_LEMMA, {}, {proven, tidn});
1132
        texplanation =
1133
            TrustNode::mkTrustPropExp(node, explanation, d_lazyProof.get());
1134
      }
1135
    }
1136
34238
    return texplanation;
1137
  }
1138
1139
172750
  Debug("theory::explain") << "TheoryEngine::getExplanation: sharing IS enabled"
1140
86375
                           << std::endl;
1141
1142
  // Initial thing to explain
1143
172750
  NodeTheoryPair toExplain(node, THEORY_SAT_SOLVER, d_propagationMapTimestamp);
1144
86375
  Assert(d_propagationMap.find(toExplain) != d_propagationMap.end());
1145
1146
172750
  NodeTheoryPair nodeExplainerPair = d_propagationMap[toExplain];
1147
172750
  Debug("theory::explain")
1148
86375
      << "TheoryEngine::getExplanation: explainer for node "
1149
86375
      << nodeExplainerPair.d_node
1150
86375
      << " is theory: " << nodeExplainerPair.d_theory << std::endl;
1151
1152
  // Create the workplace for explanations
1153
172750
  std::vector<NodeTheoryPair> vec{d_propagationMap[toExplain]};
1154
  // Process the explanation
1155
172750
  TrustNode texplanation = getExplanation(vec);
1156
172750
  Debug("theory::explain") << "TheoryEngine::getExplanation(" << node << ") => "
1157
86375
                           << texplanation.getNode() << endl;
1158
86375
  return texplanation;
1159
}
1160
1161
83116
struct AtomsCollect {
1162
1163
  std::vector<TNode> d_atoms;
1164
  std::unordered_set<TNode> d_visited;
1165
1166
 public:
1167
  typedef void return_type;
1168
1169
516896
  bool alreadyVisited(TNode current, TNode parent) {
1170
    // Check if already visited
1171
516896
    if (d_visited.find(current) != d_visited.end()) return true;
1172
    // Don't visit non-boolean
1173
476974
    if (!current.getType().isBoolean()) return true;
1174
    // New node
1175
388490
    return false;
1176
  }
1177
1178
130042
  void visit(TNode current, TNode parent) {
1179
130042
    if (Theory::theoryOf(current) != theory::THEORY_BOOL) {
1180
48562
      d_atoms.push_back(current);
1181
    }
1182
130042
    d_visited.insert(current);
1183
130042
  }
1184
1185
41558
  void start(TNode node) {}
1186
41558
  void done(TNode node) {}
1187
1188
41558
  std::vector<TNode> getAtoms() const {
1189
41558
    return d_atoms;
1190
  }
1191
};
1192
1193
41558
void TheoryEngine::ensureLemmaAtoms(TNode n, theory::TheoryId atomsTo)
1194
{
1195
41558
  Assert(atomsTo != THEORY_LAST);
1196
83116
  Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(" << n << ", "
1197
41558
                         << atomsTo << ")" << endl;
1198
83116
  AtomsCollect collectAtoms;
1199
41558
  NodeVisitor<AtomsCollect>::run(collectAtoms, n);
1200
41558
  ensureLemmaAtoms(collectAtoms.getAtoms(), atomsTo);
1201
41558
}
1202
1203
41558
void TheoryEngine::ensureLemmaAtoms(const std::vector<TNode>& atoms, theory::TheoryId atomsTo) {
1204
90120
  for (unsigned i = 0; i < atoms.size(); ++ i) {
1205
1206
    // Non-equality atoms are either owned by theory or they don't make sense
1207
48562
    if (atoms[i].getKind() != kind::EQUAL) {
1208
51238
      continue;
1209
    }
1210
1211
    // The equality
1212
45886
    Node eq = atoms[i];
1213
    // Simple normalization to not repeat stuff
1214
39922
    if (eq[0] > eq[1]) {
1215
      eq = eq[1].eqNode(eq[0]);
1216
    }
1217
1218
    // Rewrite the equality
1219
45886
    Node eqNormalized = rewrite(atoms[i]);
1220
1221
79844
    Debug("theory::atoms") << "TheoryEngine::ensureLemmaAtoms(): " << eq
1222
39922
                           << " with nf " << eqNormalized << endl;
1223
1224
    // If the equality is a boolean constant, we send immediately
1225
39926
    if (eqNormalized.isConst()) {
1226
4
      if (eqNormalized.getConst<bool>()) {
1227
        assertToTheory(eq, eqNormalized, /** to */ atomsTo, /** Sat solver */ theory::THEORY_SAT_SOLVER);
1228
      } else {
1229
4
        assertToTheory(eq.notNode(), eqNormalized.notNode(), /** to */ atomsTo, /** Sat solver */ theory::THEORY_SAT_SOLVER);
1230
      }
1231
4
      continue;
1232
39918
    }else if( eqNormalized.getKind() != kind::EQUAL){
1233
      Assert(eqNormalized.getKind() == kind::BOOLEAN_TERM_VARIABLE
1234
             || (eqNormalized.getKind() == kind::NOT
1235
                 && eqNormalized[0].getKind() == kind::BOOLEAN_TERM_VARIABLE));
1236
      // this happens for Boolean term equalities V = true that are rewritten to V, we should skip
1237
      //  TODO : revisit this
1238
      continue;
1239
    }
1240
1241
    // If the normalization did the just flips, keep the flip
1242
39918
    if (eqNormalized[0] == eq[1] && eqNormalized[1] == eq[0]) {
1243
1704
      eq = eqNormalized;
1244
    }
1245
1246
    // Check if the equality is already known by the sat solver
1247
39918
    if (d_propEngine->isSatLiteral(eqNormalized)) {
1248
      bool value;
1249
34673
      if (d_propEngine->hasValue(eqNormalized, value)) {
1250
67908
        if (value) {
1251
33916
          assertToTheory(eq, eqNormalized, atomsTo, theory::THEORY_SAT_SOLVER);
1252
67870
          continue;
1253
        } else {
1254
38
          assertToTheory(eq.notNode(), eqNormalized.notNode(), atomsTo, theory::THEORY_SAT_SOLVER);
1255
38
          continue;
1256
        }
1257
      }
1258
    }
1259
1260
    // If the theory is asking about a different form, or the form is ok but if will go to a different theory
1261
    // then we must figure it out
1262
5964
    if (eqNormalized != eq || Theory::theoryOf(eq) != atomsTo) {
1263
      // If you get eqNormalized, send atoms[i] to atomsTo
1264
4945
      d_atomRequests.add(eqNormalized, eq, atomsTo);
1265
    }
1266
  }
1267
41558
}
1268
1269
518401
void TheoryEngine::lemma(TrustNode tlemma,
1270
                         theory::LemmaProperty p,
1271
                         theory::TheoryId from)
1272
{
1273
  // For resource-limiting (also does a time check).
1274
  // spendResource();
1275
518401
  Assert(tlemma.getKind() == TrustNodeKind::LEMMA
1276
         || tlemma.getKind() == TrustNodeKind::CONFLICT);
1277
  // get the node
1278
1036802
  Node node = tlemma.getNode();
1279
1036802
  Node lemma = tlemma.getProven();
1280
1281
518401
  Assert(!expr::hasFreeVar(lemma));
1282
1283
  // when proofs are enabled, we ensure the trust node has a generator by
1284
  // adding a trust step to the lazy proof maintained by this class
1285
518401
  if (isProofEnabled())
1286
  {
1287
    // ensure proof: set THEORY_LEMMA if no generator is provided
1288
70722
    if (tlemma.getGenerator() == nullptr)
1289
    {
1290
      // internal lemmas should have generators
1291
6770
      Assert(from != THEORY_LAST);
1292
      // add theory lemma step to proof
1293
13540
      Node tidn = builtin::BuiltinProofRuleChecker::mkTheoryIdNode(from);
1294
6770
      d_lazyProof->addStep(lemma, PfRule::THEORY_LEMMA, {}, {lemma, tidn});
1295
      // update the trust node
1296
6770
      tlemma = TrustNode::mkTrustLemma(lemma, d_lazyProof.get());
1297
    }
1298
    // ensure closed
1299
70722
    tlemma.debugCheckClosed("te-proof-debug", "TheoryEngine::lemma_initial");
1300
  }
1301
1302
  // assert the lemma
1303
518403
  d_propEngine->assertLemma(tlemma, p);
1304
1305
  // If specified, we must add this lemma to the set of those that need to be
1306
  // justified, where note we pass all auxiliary lemmas in skAsserts as well,
1307
  // since these by extension must be justified as well.
1308
518399
  if (d_relManager != nullptr)
1309
  {
1310
1134
    std::vector<Node> skAsserts;
1311
1134
    std::vector<Node> sks;
1312
    Node retLemma =
1313
1134
        d_propEngine->getPreprocessedTerm(tlemma.getProven(), skAsserts, sks);
1314
567
    if (isLemmaPropertyNeedsJustify(p))
1315
    {
1316
      d_relManager->notifyPreprocessedAssertion(retLemma);
1317
      d_relManager->notifyPreprocessedAssertions(skAsserts);
1318
    }
1319
567
    d_relManager->notifyLemma(retLemma);
1320
  }
1321
1322
  // Mark that we added some lemmas
1323
518399
  d_lemmasAdded = true;
1324
518399
}
1325
1326
221938
void TheoryEngine::markInConflict()
1327
{
1328
#ifdef CVC5_FOR_EACH_THEORY_STATEMENT
1329
#undef CVC5_FOR_EACH_THEORY_STATEMENT
1330
#endif
1331
#define CVC5_FOR_EACH_THEORY_STATEMENT(THEORY) \
1332
  theoryOf(THEORY)->notifyInConflict();
1333
221938
  CVC5_FOR_EACH_THEORY;
1334
221938
  d_inConflict = true;
1335
221938
}
1336
1337
153277
void TheoryEngine::conflict(TrustNode tconflict, TheoryId theoryId)
1338
{
1339
153277
  Assert(tconflict.getKind() == TrustNodeKind::CONFLICT);
1340
1341
306554
  TNode conflict = tconflict.getNode();
1342
306554
  Debug("theory::conflict") << "TheoryEngine::conflict(" << conflict << ", "
1343
153277
                            << theoryId << ")" << endl;
1344
153277
  Trace("te-proof-debug") << "Check closed conflict" << std::endl;
1345
  // doesn't require proof generator, yet, since THEORY_LEMMA is added below
1346
153277
  tconflict.debugCheckClosed(
1347
      "te-proof-debug", "TheoryEngine::conflict_initial", false);
1348
1349
153277
  Trace("dtview::conflict") << ":THEORY-CONFLICT: " << conflict << std::endl;
1350
1351
  // Mark that we are in conflict
1352
153277
  markInConflict();
1353
1354
  // In the multiple-theories case, we need to reconstruct the conflict
1355
153277
  if (d_logicInfo.isSharingEnabled()) {
1356
    // Create the workplace for explanations
1357
263798
    std::vector<NodeTheoryPair> vec;
1358
131899
    vec.push_back(
1359
263798
        NodeTheoryPair(conflict, theoryId, d_propagationMapTimestamp));
1360
1361
    // Process the explanation
1362
263798
    TrustNode tncExp = getExplanation(vec);
1363
263798
    Node fullConflict = tncExp.getNode();
1364
1365
131899
    if (isProofEnabled())
1366
    {
1367
29582
      Trace("te-proof-debug")
1368
14791
          << "Check closed conflict explained with sharing" << std::endl;
1369
14791
      tncExp.debugCheckClosed("te-proof-debug",
1370
                              "TheoryEngine::conflict_explained_sharing");
1371
14791
      Trace("te-proof-debug") << "Process conflict: " << conflict << std::endl;
1372
29582
      Trace("te-proof-debug") << "Conflict " << tconflict << " from "
1373
14791
                              << tconflict.identifyGenerator() << std::endl;
1374
29582
      Trace("te-proof-debug") << "Explanation " << tncExp << " from "
1375
14791
                              << tncExp.identifyGenerator() << std::endl;
1376
14791
      Assert(d_lazyProof != nullptr);
1377
14791
      if (tconflict.getGenerator() != nullptr)
1378
      {
1379
14353
        d_lazyProof->addLazyStep(tconflict.getProven(),
1380
                                 tconflict.getGenerator());
1381
      }
1382
      else
1383
      {
1384
        // add theory lemma step
1385
876
        Node tidn = builtin::BuiltinProofRuleChecker::mkTheoryIdNode(theoryId);
1386
876
        Node conf = tconflict.getProven();
1387
438
        d_lazyProof->addStep(conf, PfRule::THEORY_LEMMA, {}, {conf, tidn});
1388
      }
1389
      // store the explicit step, which should come from a different
1390
      // generator, e.g. d_tepg.
1391
29582
      Node proven = tncExp.getProven();
1392
14791
      Assert(tncExp.getGenerator() != d_lazyProof.get());
1393
29582
      Trace("te-proof-debug") << "add lazy step " << tncExp.identifyGenerator()
1394
14791
                              << " for " << proven << std::endl;
1395
14791
      d_lazyProof->addLazyStep(proven, tncExp.getGenerator());
1396
14791
      pfgEnsureClosed(proven,
1397
14791
                      d_lazyProof.get(),
1398
                      "te-proof-debug",
1399
                      "TheoryEngine::conflict_during");
1400
29582
      Node fullConflictNeg = fullConflict.notNode();
1401
29582
      std::vector<Node> children;
1402
14791
      children.push_back(proven);
1403
29582
      std::vector<Node> args;
1404
14791
      args.push_back(fullConflictNeg);
1405
14791
      if (conflict == d_false)
1406
      {
1407
120
        AlwaysAssert(proven == fullConflictNeg);
1408
      }
1409
      else
1410
      {
1411
14671
        if (!CDProof::isSame(fullConflict, conflict))
1412
        {
1413
          // ------------------------- explained  ---------- from theory
1414
          // fullConflict => conflict              ~conflict
1415
          // ------------------------------------------ MACRO_SR_PRED_TRANSFORM
1416
          // ~fullConflict
1417
14203
          children.push_back(conflict.notNode());
1418
14203
          args.push_back(mkMethodId(MethodId::SB_LITERAL));
1419
14203
          d_lazyProof->addStep(
1420
              fullConflictNeg, PfRule::MACRO_SR_PRED_TRANSFORM, children, args);
1421
        }
1422
      }
1423
    }
1424
    // pass the processed trust node
1425
    TrustNode tconf =
1426
263798
        TrustNode::mkTrustConflict(fullConflict, d_lazyProof.get());
1427
263798
    Debug("theory::conflict")
1428
131899
        << "TheoryEngine::conflict(" << conflict << ", " << theoryId
1429
131899
        << "): full = " << fullConflict << endl;
1430
131899
    Assert(properConflict(fullConflict));
1431
263798
    Trace("te-proof-debug")
1432
131899
        << "Check closed conflict with sharing" << std::endl;
1433
131899
    if (isProofEnabled())
1434
    {
1435
14791
      tconf.debugCheckClosed("te-proof-debug", "TheoryEngine::conflict:sharing");
1436
    }
1437
131899
    lemma(tconf, LemmaProperty::REMOVABLE);
1438
  } else {
1439
    // When only one theory, the conflict should need no processing
1440
21378
    Assert(properConflict(conflict));
1441
    // pass the trust node that was sent from the theory
1442
21378
    lemma(tconflict, LemmaProperty::REMOVABLE, theoryId);
1443
  }
1444
153277
}
1445
1446
5021
void TheoryEngine::setIncomplete(theory::TheoryId theory,
1447
                                 theory::IncompleteId id)
1448
{
1449
5021
  d_incomplete = true;
1450
5021
  d_incompleteTheory = theory;
1451
5021
  d_incompleteId = id;
1452
5021
}
1453
1454
218274
TrustNode TheoryEngine::getExplanation(
1455
    std::vector<NodeTheoryPair>& explanationVector)
1456
{
1457
218274
  Assert(explanationVector.size() == 1);
1458
436548
  Node conclusion = explanationVector[0].d_node;
1459
  // if the theory explains using the central equality engine, we always start
1460
  // with THEORY_BUILTIN.
1461
218274
  if (Theory::expUsingCentralEqualityEngine(explanationVector[0].d_theory))
1462
  {
1463
47663
    explanationVector[0].d_theory = THEORY_BUILTIN;
1464
  }
1465
436548
  std::shared_ptr<LazyCDProof> lcp;
1466
218274
  if (isProofEnabled())
1467
  {
1468
40908
    Trace("te-proof-exp") << "=== TheoryEngine::getExplanation " << conclusion
1469
20454
                          << std::endl;
1470
    // We do not use auto-symmetry in this proof, since in very rare cases, it
1471
    // is possible that the proof of explanations is cyclic when considering
1472
    // (dis)equalities modulo symmetry, where such a proof looks like:
1473
    // x = y
1474
    // -----
1475
    //   A    ...
1476
    // ----------
1477
    //   y = x
1478
    // Notice that this complication arises since propagations consider
1479
    // equalities that are not in rewritten form. This complication would not
1480
    // exist otherwise. It is the shared term database that introduces these
1481
    // unrewritten equalities; it must do so since theory combination requires
1482
    // communicating arrangements between shared terms, and the rewriter
1483
    // for arithmetic equalities does not preserve terms, e.g. x=y may become
1484
    // x+-1*y=0.
1485
40908
    lcp.reset(new LazyCDProof(d_pnm,
1486
                              nullptr,
1487
                              nullptr,
1488
                              "TheoryEngine::LazyCDProof::getExplanation",
1489
20454
                              false));
1490
  }
1491
218274
  unsigned i = 0; // Index of the current literal we are processing
1492
1493
436548
  std::unique_ptr<std::set<Node>> inputAssertions = nullptr;
1494
  // the overall explanation
1495
436548
  std::set<TNode> exp;
1496
  // vector of trust nodes to explain at the end
1497
436548
  std::vector<std::pair<TheoryId, TrustNode>> texplains;
1498
  // cache of nodes we have already explained by some theory
1499
436548
  std::unordered_map<Node, size_t> cache;
1500
1501
9169790
  while (i < explanationVector.size()) {
1502
    // Get the current literal to explain
1503
4859215
    NodeTheoryPair toExplain = explanationVector[i];
1504
1505
8951516
    Debug("theory::explain")
1506
4475758
        << "[i=" << i << "] TheoryEngine::explain(): processing ["
1507
4475758
        << toExplain.d_timestamp << "] " << toExplain.d_node << " sent from "
1508
4475758
        << toExplain.d_theory << endl;
1509
1510
9081063
    if (cache.find(toExplain.d_node) != cache.end()
1511
4475758
        && cache[toExplain.d_node] < toExplain.d_timestamp)
1512
    {
1513
129547
      ++i;
1514
129547
      continue;
1515
    }
1516
4346211
    cache[toExplain.d_node] = toExplain.d_timestamp;
1517
1518
    // If a true constant or a negation of a false constant we can ignore it
1519
8706427
    if ((toExplain.d_node.isConst() && toExplain.d_node.getConst<bool>())
1520
13038633
        || (toExplain.d_node.getKind() == kind::NOT
1521
4854652
            && toExplain.d_node[0].isConst()
1522
4346211
            && !toExplain.d_node[0].getConst<bool>()))
1523
    {
1524
13591
      ++ i;
1525
      // if we are building a proof
1526
13591
      if (lcp != nullptr)
1527
      {
1528
3288
        Trace("te-proof-exp")
1529
1644
            << "- explain " << toExplain.d_node << " trivially..." << std::endl;
1530
        // ------------------MACRO_SR_PRED_INTRO
1531
        // toExplain.d_node
1532
3288
        std::vector<Node> children;
1533
3288
        std::vector<Node> args;
1534
1644
        args.push_back(toExplain.d_node);
1535
1644
        lcp->addStep(
1536
            toExplain.d_node, PfRule::MACRO_SR_PRED_INTRO, children, args);
1537
      }
1538
13591
      continue;
1539
    }
1540
1541
    // If from the SAT solver, keep it
1542
5889716
    if (toExplain.d_theory == THEORY_SAT_SOLVER)
1543
    {
1544
3114192
      Debug("theory::explain")
1545
1557096
          << "\tLiteral came from THEORY_SAT_SOLVER. Keeping it." << endl;
1546
1557096
      exp.insert(explanationVector[i++].d_node);
1547
      // it will be a free assumption in the proof
1548
1557096
      Trace("te-proof-exp") << "- keep " << toExplain.d_node << std::endl;
1549
1557096
      continue;
1550
    }
1551
1552
    // If an and, expand it
1553
2775524
    if (toExplain.d_node.getKind() == kind::AND)
1554
    {
1555
815300
      Debug("theory::explain")
1556
407650
          << "TheoryEngine::explain(): expanding " << toExplain.d_node
1557
407650
          << " got from " << toExplain.d_theory << endl;
1558
407650
      size_t nchild = toExplain.d_node.getNumChildren();
1559
2297260
      for (size_t k = 0; k < nchild; ++k)
1560
      {
1561
        NodeTheoryPair newExplain(
1562
3779220
            toExplain.d_node[k], toExplain.d_theory, toExplain.d_timestamp);
1563
1889610
        explanationVector.push_back(newExplain);
1564
      }
1565
407650
      if (lcp != nullptr)
1566
      {
1567
93486
        Trace("te-proof-exp")
1568
46743
            << "- AND expand " << toExplain.d_node << std::endl;
1569
        // delay explanation, use a dummy trust node
1570
        TrustNode tnAndExp = TrustNode::mkTrustPropExp(
1571
93486
            toExplain.d_node, toExplain.d_node, nullptr);
1572
46743
        texplains.push_back(
1573
93486
            std::pair<TheoryId, TrustNode>(THEORY_LAST, tnAndExp));
1574
      }
1575
407650
      ++ i;
1576
407650
      continue;
1577
    }
1578
1579
    // See if it was sent to the theory by another theory
1580
2367874
    PropagationMap::const_iterator find = d_propagationMap.find(toExplain);
1581
2367874
    if (find != d_propagationMap.end()) {
1582
4500668
      Debug("theory::explain")
1583
2250334
          << "\tTerm was propagated by another theory (theory = "
1584
2250334
          << getTheoryString((*find).second.d_theory) << ")" << std::endl;
1585
      // There is some propagation, check if its a timely one
1586
2250334
      if ((*find).second.d_timestamp < toExplain.d_timestamp)
1587
      {
1588
3968834
        Debug("theory::explain")
1589
1984417
            << "\tRelevant timetsamp, pushing " << (*find).second.d_node
1590
1984417
            << "to index = " << explanationVector.size() << std::endl;
1591
1984417
        explanationVector.push_back((*find).second);
1592
1984417
        ++i;
1593
1594
1984417
        if (lcp != nullptr)
1595
        {
1596
218198
          if (toExplain.d_node != (*find).second.d_node)
1597
          {
1598
6666
            Trace("te-proof-exp")
1599
3333
                << "- t-explained cached: " << toExplain.d_node << " by "
1600
3333
                << (*find).second.d_node << std::endl;
1601
            // delay explanation, use a dummy trust node that says that
1602
            // (*find).second.d_node explains toExplain.d_node.
1603
            TrustNode tnRewExp = TrustNode::mkTrustPropExp(
1604
6666
                toExplain.d_node, (*find).second.d_node, nullptr);
1605
3333
            texplains.push_back(
1606
6666
                std::pair<TheoryId, TrustNode>(THEORY_LAST, tnRewExp));
1607
          }
1608
        }
1609
1984417
        continue;
1610
      }
1611
    }
1612
    // It was produced by the theory, so ask for an explanation
1613
    TrustNode texplanation =
1614
766914
        d_sharedSolver->explain(toExplain.d_node, toExplain.d_theory);
1615
383457
    if (lcp != nullptr)
1616
    {
1617
45677
      texplanation.debugCheckClosed("te-proof-exp", "texplanation", false);
1618
91354
      Trace("te-proof-exp")
1619
45677
          << "- t-explained[" << toExplain.d_theory << "]: " << toExplain.d_node
1620
45677
          << " by " << texplanation.getNode() << std::endl;
1621
      // should prove the propagation we asked for
1622
45677
      Assert(texplanation.getKind() == TrustNodeKind::PROP_EXP
1623
             && texplanation.getProven()[1] == toExplain.d_node);
1624
      // We add it to the list of theory explanations, to be processed at
1625
      // the end of this method. We wait to explain here because it may
1626
      // be that a later explanation may preempt the need for proving this
1627
      // step. For instance, if the conclusion lit is later added as an
1628
      // assumption in the final explanation. This avoids cyclic proofs.
1629
45677
      texplains.push_back(
1630
91354
          std::pair<TheoryId, TrustNode>(toExplain.d_theory, texplanation));
1631
    }
1632
766914
    Node explanation = texplanation.getNode();
1633
1634
766914
    Debug("theory::explain")
1635
383457
        << "TheoryEngine::explain(): got explanation " << explanation
1636
383457
        << " got from " << toExplain.d_theory << endl;
1637
383457
    Assert(explanation != toExplain.d_node)
1638
        << "wasn't sent to you, so why are you explaining it trivially, for "
1639
           "fact "
1640
        << explanation;
1641
    // Mark the explanation
1642
    NodeTheoryPair newExplain(
1643
766914
        explanation, toExplain.d_theory, toExplain.d_timestamp);
1644
383457
    explanationVector.push_back(newExplain);
1645
1646
383457
    ++ i;
1647
  }
1648
1649
  // make the explanation node
1650
436548
  Node expNode;
1651
218274
  if (exp.size() == 0)
1652
  {
1653
    // Normalize to true
1654
45
    expNode = NodeManager::currentNM()->mkConst<bool>(true);
1655
  }
1656
218229
  else if (exp.size() == 1)
1657
  {
1658
    // All the same, or just one
1659
6940
    expNode = *exp.begin();
1660
  }
1661
  else
1662
  {
1663
422578
    NodeBuilder conjunction(kind::AND);
1664
211289
    std::set<TNode>::const_iterator it = exp.begin();
1665
211289
    std::set<TNode>::const_iterator it_end = exp.end();
1666
3207151
    while (it != it_end)
1667
    {
1668
1497931
      conjunction << *it;
1669
1497931
      ++it;
1670
    }
1671
211289
    expNode = conjunction;
1672
  }
1673
  // if we are building a proof, go back through the explanations and
1674
  // build the proof
1675
218274
  if (lcp != nullptr)
1676
  {
1677
20454
    if (Trace.isOn("te-proof-exp"))
1678
    {
1679
      Trace("te-proof-exp") << "Explanation is:" << std::endl;
1680
      for (TNode e : exp)
1681
      {
1682
        Trace("te-proof-exp") << "  " << e << std::endl;
1683
      }
1684
      Trace("te-proof-exp") << "=== Replay explanations..." << std::endl;
1685
    }
1686
    // Now, go back and add the necessary steps of theory explanations, i.e.
1687
    // add those that prove things that aren't in the final explanation. We
1688
    // iterate in reverse order so that most recent steps take priority. This
1689
    // avoids cyclic proofs in the lazy proof we are building (lcp).
1690
95753
    for (std::vector<std::pair<TheoryId, TrustNode>>::reverse_iterator
1691
20454
             it = texplains.rbegin(),
1692
20454
             itEnd = texplains.rend();
1693
116207
         it != itEnd;
1694
         ++it)
1695
    {
1696
139421
      TrustNode trn = it->second;
1697
95753
      Assert(trn.getKind() == TrustNodeKind::PROP_EXP);
1698
139421
      Node proven = trn.getProven();
1699
95753
      Assert(proven.getKind() == kind::IMPLIES);
1700
139421
      Node tConc = proven[1];
1701
95753
      Trace("te-proof-exp") << "- Process " << trn << std::endl;
1702
100145
      if (exp.find(tConc) != exp.end())
1703
      {
1704
        // already added to proof
1705
4392
        Trace("te-proof-exp") << "...already added" << std::endl;
1706
4392
        continue;
1707
      }
1708
      // remember that we've explained this formula, to avoid cycles in lcp
1709
91361
      exp.insert(tConc);
1710
91361
      TheoryId ttid = it->first;
1711
135029
      Node tExp = proven[0];
1712
91361
      if (ttid == THEORY_LAST)
1713
      {
1714
47693
        if (tConc == tExp)
1715
        {
1716
          // dummy trust node, do AND expansion
1717
45590
          Assert(tConc.getKind() == kind::AND);
1718
          // tConc[0] ... tConc[n]
1719
          // ---------------------- AND_INTRO
1720
          // tConc
1721
91180
          std::vector<Node> pfChildren;
1722
45590
          pfChildren.insert(pfChildren.end(), tConc.begin(), tConc.end());
1723
45590
          lcp->addStep(tConc, PfRule::AND_INTRO, pfChildren, {});
1724
45590
          Trace("te-proof-exp") << "...via AND_INTRO" << std::endl;
1725
45590
          continue;
1726
        }
1727
        // otherwise should hold by rewriting
1728
2103
        Assert(rewrite(tConc) == rewrite(tExp));
1729
        // tExp
1730
        // ---- MACRO_SR_PRED_TRANSFORM
1731
        // tConc
1732
2103
        lcp->addStep(tConc, PfRule::MACRO_SR_PRED_TRANSFORM, {tExp}, {tConc});
1733
2103
        Trace("te-proof-exp") << "...via MACRO_SR_PRED_TRANSFORM" << std::endl;
1734
2103
        continue;
1735
      }
1736
43668
      if (tExp == tConc)
1737
      {
1738
        // trivial
1739
        Trace("te-proof-exp") << "...trivial" << std::endl;
1740
        continue;
1741
      }
1742
      //       ------------- Via theory
1743
      // tExp  tExp => tConc
1744
      // ---------------------------------MODUS_PONENS
1745
      // tConc
1746
43668
      if (trn.getGenerator() != nullptr)
1747
      {
1748
43223
        Trace("te-proof-exp") << "...via theory generator" << std::endl;
1749
43223
        lcp->addLazyStep(proven, trn.getGenerator());
1750
      }
1751
      else
1752
      {
1753
445
        Trace("te-proof-exp") << "...via trust THEORY_LEMMA" << std::endl;
1754
        // otherwise, trusted theory lemma
1755
890
        Node tidn = builtin::BuiltinProofRuleChecker::mkTheoryIdNode(ttid);
1756
445
        lcp->addStep(proven, PfRule::THEORY_LEMMA, {}, {proven, tidn});
1757
      }
1758
87336
      std::vector<Node> pfChildren;
1759
43668
      pfChildren.push_back(trn.getNode());
1760
43668
      pfChildren.push_back(proven);
1761
43668
      lcp->addStep(tConc, PfRule::MODUS_PONENS, pfChildren, {});
1762
    }
1763
    // If we don't have a step and the conclusion is not part of the
1764
    // explanation (for unit T-conflicts), it must be by symmetry. We must do
1765
    // this manually since lcp does not have auto-symmetry enabled due to the
1766
    // complication mentioned above.
1767
20454
    if (!lcp->hasStep(conclusion) && exp.find(conclusion) == exp.end())
1768
    {
1769
      Node sconc = CDProof::getSymmFact(conclusion);
1770
      if (!sconc.isNull())
1771
      {
1772
        lcp->addStep(conclusion, PfRule::SYMM, {sconc}, {});
1773
      }
1774
      else
1775
      {
1776
        Assert(false)
1777
            << "TheoryEngine::getExplanation: no step found for conclusion "
1778
            << conclusion;
1779
      }
1780
    }
1781
    // store in the proof generator
1782
40908
    TrustNode trn = d_tepg->mkTrustExplain(conclusion, expNode, lcp);
1783
    // return the trust node
1784
20454
    return trn;
1785
  }
1786
1787
197820
  return TrustNode::mkTrustPropExp(conclusion, expNode, nullptr);
1788
}
1789
1790
1034711
bool TheoryEngine::isProofEnabled() const { return d_pnm != nullptr; }
1791
1792
2185
void TheoryEngine::checkTheoryAssertionsWithModel(bool hardFailure) {
1793
30590
  for(TheoryId theoryId = THEORY_FIRST; theoryId < THEORY_LAST; ++theoryId) {
1794
28405
    Theory* theory = d_theoryTable[theoryId];
1795
28405
    if(theory && d_logicInfo.isTheoryEnabled(theoryId)) {
1796
116400
      for(context::CDList<Assertion>::const_iterator it = theory->facts_begin(),
1797
13478
            it_end = theory->facts_end();
1798
116400
          it != it_end;
1799
          ++it) {
1800
205844
        Node assertion = (*it).d_assertion;
1801
102922
        if (!isRelevant(assertion))
1802
        {
1803
          // not relevant, skip
1804
          continue;
1805
        }
1806
205844
        Node val = d_tc->getModel()->getValue(assertion);
1807
102922
        if (val != d_true)
1808
        {
1809
10
          std::stringstream ss;
1810
10
          ss << " " << theoryId
1811
10
             << " has an asserted fact that the model doesn't satisfy." << endl
1812
10
             << "The fact: " << assertion << endl
1813
5
             << "Model value: " << val << endl;
1814
5
          if (hardFailure)
1815
          {
1816
5
            if (val == d_false)
1817
            {
1818
              // Always an error if it is false
1819
              InternalError() << ss.str();
1820
            }
1821
            else
1822
            {
1823
              // Otherwise just a warning. Notice this case may happen for
1824
              // assertions with unevaluable operators, e.g. transcendental
1825
              // functions. It also may happen for separation logic, where
1826
              // check-model support is limited.
1827
5
              warning() << ss.str();
1828
            }
1829
          }
1830
        }
1831
      }
1832
    }
1833
  }
1834
2185
}
1835
1836
8478
std::pair<bool, Node> TheoryEngine::entailmentCheck(options::TheoryOfMode mode,
1837
                                                    TNode lit)
1838
{
1839
16956
  TNode atom = (lit.getKind() == kind::NOT) ? lit[0] : lit;
1840
8478
  if( atom.getKind()==kind::AND || atom.getKind()==kind::OR || atom.getKind()==kind::IMPLIES ){
1841
    //Boolean connective, recurse
1842
    std::vector< Node > children;
1843
    bool pol = (lit.getKind()!=kind::NOT);
1844
    bool is_conjunction = pol==(lit.getKind()==kind::AND);
1845
    for( unsigned i=0; i<atom.getNumChildren(); i++ ){
1846
      Node ch = atom[i];
1847
      if( pol==( lit.getKind()==kind::IMPLIES && i==0 ) ){
1848
        ch = atom[i].negate();
1849
      }
1850
      std::pair<bool, Node> chres = entailmentCheck(mode, ch);
1851
      if( chres.first ){
1852
        if( !is_conjunction ){
1853
          return chres;
1854
        }else{
1855
          children.push_back( chres.second );
1856
        }
1857
      }else if( !chres.first && is_conjunction ){
1858
        return std::pair<bool, Node>(false, Node::null());
1859
      }
1860
    }
1861
    if( is_conjunction ){
1862
      return std::pair<bool, Node>(true, NodeManager::currentNM()->mkNode(kind::AND, children));
1863
    }else{
1864
      return std::pair<bool, Node>(false, Node::null());
1865
    }
1866
8478
  }else if( atom.getKind()==kind::ITE || ( atom.getKind()==kind::EQUAL && atom[0].getType().isBoolean() ) ){
1867
    bool pol = (lit.getKind()!=kind::NOT);
1868
    for( unsigned r=0; r<2; r++ ){
1869
      Node ch = atom[0];
1870
      if( r==1 ){
1871
        ch = ch.negate();
1872
      }
1873
      std::pair<bool, Node> chres = entailmentCheck(mode, ch);
1874
      if( chres.first ){
1875
        Node ch2 = atom[ atom.getKind()==kind::ITE ? r+1 : 1 ];
1876
        if( pol==( atom.getKind()==kind::ITE ? true : r==1 ) ){
1877
          ch2 = ch2.negate();
1878
        }
1879
        std::pair<bool, Node> chres2 = entailmentCheck(mode, ch2);
1880
        if( chres2.first ){
1881
          return std::pair<bool, Node>(true, NodeManager::currentNM()->mkNode(kind::AND, chres.second, chres2.second));
1882
        }else{
1883
          break;
1884
        }
1885
      }
1886
    }
1887
    return std::pair<bool, Node>(false, Node::null());
1888
  }else{
1889
    //it is a theory atom
1890
8478
    theory::TheoryId tid = theory::Theory::theoryOf(mode, atom);
1891
8478
    theory::Theory* th = theoryOf(tid);
1892
1893
8478
    Assert(th != NULL);
1894
8478
    Trace("theory-engine-entc") << "Entailment check : " << lit << std::endl;
1895
1896
16956
    std::pair<bool, Node> chres = th->entailmentCheck(lit);
1897
8478
    return chres;
1898
  }
1899
}
1900
1901
11516878
void TheoryEngine::spendResource(Resource r)
1902
{
1903
11516878
  d_env.getResourceManager()->spendResource(r);
1904
11516878
}
1905
1906
7989
void TheoryEngine::initializeProofChecker(ProofChecker* pc)
1907
{
1908
111846
  for (theory::TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST;
1909
       ++id)
1910
  {
1911
103857
    ProofRuleChecker* prc = d_theoryTable[id]->getProofChecker();
1912
103857
    if (prc)
1913
    {
1914
71882
      prc->registerTo(pc);
1915
    }
1916
  }
1917
7989
}
1918
1919
198585
theory::Rewriter* TheoryEngine::getRewriter() { return d_env.getRewriter(); }
1920
1921
31137
}  // namespace cvc5