GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/smt/smt_engine.cpp Lines: 824 999 82.5 %
Date: 2021-05-22 Branches: 1236 3303 37.4 %

Line Exec Source
1
/******************************************************************************
2
 * Top contributors (to current version):
3
 *   Andrew Reynolds, Morgan Deters, Abdalrhman Mohamed
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 main entry point into the cvc5 library's SMT interface.
14
 */
15
16
#include "smt/smt_engine.h"
17
18
#include "base/check.h"
19
#include "base/exception.h"
20
#include "base/modal_exception.h"
21
#include "base/output.h"
22
#include "decision/decision_engine.h"
23
#include "expr/bound_var_manager.h"
24
#include "expr/node.h"
25
#include "options/base_options.h"
26
#include "options/expr_options.h"
27
#include "options/language.h"
28
#include "options/main_options.h"
29
#include "options/option_exception.h"
30
#include "options/printer_options.h"
31
#include "options/proof_options.h"
32
#include "options/resource_manager_options.h"
33
#include "options/smt_options.h"
34
#include "options/theory_options.h"
35
#include "printer/printer.h"
36
#include "proof/unsat_core.h"
37
#include "prop/prop_engine.h"
38
#include "smt/abduction_solver.h"
39
#include "smt/abstract_values.h"
40
#include "smt/assertions.h"
41
#include "smt/check_models.h"
42
#include "smt/dump.h"
43
#include "smt/dump_manager.h"
44
#include "smt/env.h"
45
#include "smt/interpolation_solver.h"
46
#include "smt/listeners.h"
47
#include "smt/logic_exception.h"
48
#include "smt/model_blocker.h"
49
#include "smt/model_core_builder.h"
50
#include "smt/node_command.h"
51
#include "smt/options_manager.h"
52
#include "smt/preprocessor.h"
53
#include "smt/proof_manager.h"
54
#include "smt/quant_elim_solver.h"
55
#include "smt/smt_engine_scope.h"
56
#include "smt/smt_engine_state.h"
57
#include "smt/smt_engine_stats.h"
58
#include "smt/smt_solver.h"
59
#include "smt/sygus_solver.h"
60
#include "smt/unsat_core_manager.h"
61
#include "theory/quantifiers/instantiation_list.h"
62
#include "theory/quantifiers/quantifiers_attributes.h"
63
#include "theory/quantifiers_engine.h"
64
#include "theory/rewriter.h"
65
#include "theory/smt_engine_subsolver.h"
66
#include "theory/theory_engine.h"
67
#include "util/random.h"
68
#include "util/resource_manager.h"
69
#include "util/sexpr.h"
70
#include "util/statistics_registry.h"
71
72
// required for hacks related to old proofs for unsat cores
73
#include "base/configuration.h"
74
#include "base/configuration_private.h"
75
76
using namespace std;
77
using namespace cvc5::smt;
78
using namespace cvc5::preprocessing;
79
using namespace cvc5::prop;
80
using namespace cvc5::context;
81
using namespace cvc5::theory;
82
83
namespace cvc5 {
84
85
10093
SmtEngine::SmtEngine(NodeManager* nm, Options* optr)
86
10093
    : d_env(new Env(nm, optr)),
87
10093
      d_state(new SmtEngineState(getContext(), getUserContext(), *this)),
88
10093
      d_absValues(new AbstractValues(getNodeManager())),
89
10093
      d_asserts(new Assertions(*d_env.get(), *d_absValues.get())),
90
10093
      d_routListener(new ResourceOutListener(*this)),
91
10093
      d_snmListener(new SmtNodeManagerListener(*getDumpManager(), d_outMgr)),
92
      d_smtSolver(nullptr),
93
      d_model(nullptr),
94
      d_checkModels(nullptr),
95
      d_pfManager(nullptr),
96
      d_ucManager(nullptr),
97
      d_sygusSolver(nullptr),
98
      d_abductSolver(nullptr),
99
      d_interpolSolver(nullptr),
100
      d_quantElimSolver(nullptr),
101
      d_isInternalSubsolver(false),
102
      d_stats(nullptr),
103
      d_outMgr(this),
104
      d_optm(nullptr),
105
      d_pp(nullptr),
106
70652
      d_scope(nullptr)
107
{
108
  // !!!!!!!!!!!!!!!!!!!!!! temporary hack: this makes the current SmtEngine
109
  // we are constructing the current SmtEngine in scope for the lifetime of
110
  // this SmtEngine, or until another SmtEngine is constructed (that SmtEngine
111
  // is then in scope during its lifetime). This is mostly to ensure that
112
  // options are always in scope, for e.g. printing expressions, which rely
113
  // on knowing the output language.
114
  // Notice that the SmtEngine may spawn new SmtEngine "subsolvers" internally.
115
  // These are created, used, and deleted in a modular fashion while not
116
  // interleaving calls to the master SmtEngine. Thus the hack here does not
117
  // break this use case.
118
  // On the other hand, this hack breaks use cases where multiple SmtEngine
119
  // objects are created by the user.
120
10093
  d_scope.reset(new SmtScope(this));
121
  // set the options manager
122
10094
  d_optm.reset(new smt::OptionsManager(&getOptions()));
123
  // listen to node manager events
124
10092
  getNodeManager()->subscribeEvents(d_snmListener.get());
125
  // listen to resource out
126
10092
  getResourceManager()->registerListener(d_routListener.get());
127
  // make statistics
128
10092
  d_stats.reset(new SmtEngineStatistics());
129
  // reset the preprocessor
130
30276
  d_pp.reset(
131
20184
      new smt::Preprocessor(*this, *d_env.get(), *d_absValues.get(), *d_stats));
132
  // make the SMT solver
133
50460
  d_smtSolver.reset(
134
40368
      new SmtSolver(*this, *d_env.get(), *d_state, *d_pp, *d_stats));
135
  // make the SyGuS solver
136
40368
  d_sygusSolver.reset(
137
30276
      new SygusSolver(*d_smtSolver, *d_pp, getUserContext(), d_outMgr));
138
  // make the quantifier elimination solver
139
10092
  d_quantElimSolver.reset(new QuantElimSolver(*d_smtSolver));
140
141
10092
}
142
143
27010
bool SmtEngine::isFullyInited() const { return d_state->isFullyInited(); }
144
10603
bool SmtEngine::isQueryMade() const { return d_state->isQueryMade(); }
145
2752
size_t SmtEngine::getNumUserLevels() const
146
{
147
2752
  return d_state->getNumUserLevels();
148
}
149
164
SmtMode SmtEngine::getSmtMode() const { return d_state->getMode(); }
150
128
bool SmtEngine::isSmtModeSat() const
151
{
152
128
  SmtMode mode = getSmtMode();
153
128
  return mode == SmtMode::SAT || mode == SmtMode::SAT_UNKNOWN;
154
}
155
Result SmtEngine::getStatusOfLastCommand() const
156
{
157
  return d_state->getStatus();
158
}
159
26801
context::UserContext* SmtEngine::getUserContext()
160
{
161
26801
  return d_env->getUserContext();
162
}
163
10111
context::Context* SmtEngine::getContext() { return d_env->getContext(); }
164
165
339803
TheoryEngine* SmtEngine::getTheoryEngine()
166
{
167
339803
  return d_smtSolver->getTheoryEngine();
168
}
169
170
52409
prop::PropEngine* SmtEngine::getPropEngine()
171
{
172
52409
  return d_smtSolver->getPropEngine();
173
}
174
175
118934
void SmtEngine::finishInit()
176
{
177
118934
  if (d_state->isFullyInited())
178
  {
179
    // already initialized, return
180
109474
    return;
181
  }
182
183
  // Notice that finishInitInternal is called when options are finalized. If we
184
  // are parsing smt2, this occurs at the moment we enter "Assert mode", page 52
185
  // of SMT-LIB 2.6 standard.
186
187
  // set the logic
188
9460
  const LogicInfo& logic = getLogicInfo();
189
9460
  if (!logic.isLocked())
190
  {
191
1550
    setLogicInternal();
192
  }
193
194
  // set the random seed
195
9460
  Random::getRandom().setSeed(d_env->getOption(options::seed));
196
197
  // Call finish init on the options manager. This inializes the resource
198
  // manager based on the options, and sets up the best default options
199
  // based on our heuristics.
200
9460
  d_optm->finishInit(d_env->d_logic, d_isInternalSubsolver);
201
202
9459
  ProofNodeManager* pnm = nullptr;
203
9459
  if (d_env->getOption(options::produceProofs))
204
  {
205
    // ensure bound variable uses canonical bound variables
206
3600
    getNodeManager()->getBoundVarManager()->enableKeepCacheValues();
207
    // make the proof manager
208
3600
    d_pfManager.reset(new PfManager(getUserContext(), this));
209
3600
    PreprocessProofGenerator* pppg = d_pfManager->getPreprocessProofGenerator();
210
    // start the unsat core manager
211
3600
    d_ucManager.reset(new UnsatCoreManager());
212
    // use this proof node manager
213
3600
    pnm = d_pfManager->getProofNodeManager();
214
    // enable proof support in the environment/rewriter
215
3600
    d_env->setProofNodeManager(pnm);
216
    // enable it in the assertions pipeline
217
3600
    d_asserts->setProofGenerator(pppg);
218
    // enable it in the SmtSolver
219
3600
    d_smtSolver->setProofNodeManager(pnm);
220
    // enabled proofs in the preprocessor
221
3600
    d_pp->setProofGenerator(pppg);
222
  }
223
224
9459
  Trace("smt-debug") << "SmtEngine::finishInit" << std::endl;
225
9459
  d_smtSolver->finishInit(logic);
226
227
  // now can construct the SMT-level model object
228
9459
  TheoryEngine* te = d_smtSolver->getTheoryEngine();
229
9459
  Assert(te != nullptr);
230
9459
  TheoryModel* tm = te->getModel();
231
9459
  if (tm != nullptr)
232
  {
233
9459
    d_model.reset(new Model(tm));
234
    // make the check models utility
235
9459
    d_checkModels.reset(new CheckModels(*d_env.get()));
236
  }
237
238
  // global push/pop around everything, to ensure proper destruction
239
  // of context-dependent data structures
240
9459
  d_state->setup();
241
242
9459
  Trace("smt-debug") << "Set up assertions..." << std::endl;
243
9459
  d_asserts->finishInit();
244
245
  // dump out a set-logic command only when raw-benchmark is disabled to avoid
246
  // dumping the command twice.
247
9459
  if (Dump.isOn("benchmark") && !Dump.isOn("raw-benchmark"))
248
  {
249
2
      LogicInfo everything;
250
1
      everything.lock();
251
3
      getPrinter().toStreamCmdComment(
252
1
          getOutputManager().getDumpOut(),
253
          "cvc5 always dumps the most general, all-supported logic (below), as "
254
          "some internals might require the use of a logic more general than "
255
1
          "the input.");
256
2
      getPrinter().toStreamCmdSetBenchmarkLogic(getOutputManager().getDumpOut(),
257
2
                                                everything.getLogicString());
258
  }
259
260
  // initialize the dump manager
261
9459
  getDumpManager()->finishInit();
262
263
  // subsolvers
264
9459
  if (d_env->getOption(options::produceAbducts))
265
  {
266
322
    d_abductSolver.reset(new AbductionSolver(this));
267
  }
268
18918
  if (d_env->getOption(options::produceInterpols)
269
9459
      != options::ProduceInterpols::NONE)
270
  {
271
115
    d_interpolSolver.reset(new InterpolationSolver(this));
272
  }
273
274
9459
  d_pp->finishInit();
275
276
9459
  AlwaysAssert(getPropEngine()->getAssertionLevel() == 0)
277
      << "The PropEngine has pushed but the SmtEngine "
278
         "hasn't finished initializing!";
279
280
9459
  Assert(getLogicInfo().isLocked());
281
282
  // store that we are finished initializing
283
9459
  d_state->finishInit();
284
9459
  Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl;
285
}
286
287
10092
void SmtEngine::shutdown() {
288
10092
  d_state->shutdown();
289
290
10092
  d_smtSolver->shutdown();
291
292
10092
  d_env->shutdown();
293
10092
}
294
295
20184
SmtEngine::~SmtEngine()
296
{
297
20184
  SmtScope smts(this);
298
299
  try {
300
10092
    shutdown();
301
302
    // global push/pop around everything, to ensure proper destruction
303
    // of context-dependent data structures
304
10092
    d_state->cleanup();
305
306
    //destroy all passes before destroying things that they refer to
307
10092
    d_pp->cleanup();
308
309
10092
    d_pfManager.reset(nullptr);
310
10092
    d_ucManager.reset(nullptr);
311
312
10092
    d_absValues.reset(nullptr);
313
10092
    d_asserts.reset(nullptr);
314
10092
    d_model.reset(nullptr);
315
316
10092
    d_abductSolver.reset(nullptr);
317
10092
    d_interpolSolver.reset(nullptr);
318
10092
    d_quantElimSolver.reset(nullptr);
319
10092
    d_sygusSolver.reset(nullptr);
320
10092
    d_smtSolver.reset(nullptr);
321
322
10092
    d_stats.reset(nullptr);
323
10092
    getNodeManager()->unsubscribeEvents(d_snmListener.get());
324
10092
    d_snmListener.reset(nullptr);
325
10092
    d_routListener.reset(nullptr);
326
10092
    d_optm.reset(nullptr);
327
10092
    d_pp.reset(nullptr);
328
    // destroy the state
329
10092
    d_state.reset(nullptr);
330
    // destroy the environment
331
10092
    d_env.reset(nullptr);
332
  } catch(Exception& e) {
333
    Warning() << "cvc5 threw an exception during cleanup." << endl << e << endl;
334
  }
335
10092
}
336
337
7958
void SmtEngine::setLogic(const LogicInfo& logic)
338
{
339
15916
  SmtScope smts(this);
340
7958
  if (d_state->isFullyInited())
341
  {
342
    throw ModalException("Cannot set logic in SmtEngine after the engine has "
343
                         "finished initializing.");
344
  }
345
7958
  d_env->d_logic = logic;
346
7958
  d_userLogic = logic;
347
7958
  setLogicInternal();
348
7958
}
349
350
2
void SmtEngine::setLogic(const std::string& s)
351
{
352
4
  SmtScope smts(this);
353
  try
354
  {
355
2
    setLogic(LogicInfo(s));
356
    // dump out a set-logic command
357
2
    if (Dump.isOn("raw-benchmark"))
358
    {
359
      getPrinter().toStreamCmdSetBenchmarkLogic(
360
          getOutputManager().getDumpOut(), getLogicInfo().getLogicString());
361
    }
362
  }
363
  catch (IllegalArgumentException& e)
364
  {
365
    throw LogicException(e.what());
366
  }
367
2
}
368
369
2
void SmtEngine::setLogic(const char* logic) { setLogic(string(logic)); }
370
371
44343
const LogicInfo& SmtEngine::getLogicInfo() const
372
{
373
44343
  return d_env->getLogicInfo();
374
}
375
376
393
LogicInfo SmtEngine::getUserLogicInfo() const
377
{
378
  // Lock the logic to make sure that this logic can be queried. We create a
379
  // copy of the user logic here to keep this method const.
380
393
  LogicInfo res = d_userLogic;
381
393
  res.lock();
382
393
  return res;
383
}
384
385
5877
void SmtEngine::notifyStartParsing(const std::string& filename)
386
{
387
5877
  d_state->setFilename(filename);
388
11754
  d_env->getStatisticsRegistry().registerValue<std::string>("driver::filename",
389
11754
                                                            filename);
390
  // Copy the original options. This is called prior to beginning parsing.
391
  // Hence reset should revert to these options, which note is after reading
392
  // the command line.
393
5877
}
394
395
const std::string& SmtEngine::getFilename() const
396
{
397
  return d_state->getFilename();
398
}
399
400
void SmtEngine::setResultStatistic(const std::string& result) {
401
  d_env->getStatisticsRegistry().registerValue<std::string>("driver::sat/unsat",
402
                                                            result);
403
}
404
5877
void SmtEngine::setTotalTimeStatistic(double seconds) {
405
11754
  d_env->getStatisticsRegistry().registerValue<double>("driver::totalTime",
406
11754
                                                       seconds);
407
5877
}
408
409
9508
void SmtEngine::setLogicInternal()
410
{
411
9508
  Assert(!d_state->isFullyInited())
412
      << "setting logic in SmtEngine but the engine has already"
413
         " finished initializing for this run";
414
9508
  d_env->d_logic.lock();
415
9508
  d_userLogic.lock();
416
9508
}
417
418
5575
void SmtEngine::setInfo(const std::string& key, const std::string& value)
419
{
420
11150
  SmtScope smts(this);
421
422
5575
  Trace("smt") << "SMT setInfo(" << key << ", " << value << ")" << endl;
423
424
5575
  if (Dump.isOn("benchmark"))
425
  {
426
    if (key == "status")
427
    {
428
      Result::Sat status =
429
          (value == "sat")
430
              ? Result::SAT
431
              : ((value == "unsat") ? Result::UNSAT : Result::SAT_UNKNOWN);
432
      getPrinter().toStreamCmdSetBenchmarkStatus(
433
          getOutputManager().getDumpOut(), status);
434
    }
435
    else
436
    {
437
      getPrinter().toStreamCmdSetInfo(
438
          getOutputManager().getDumpOut(), key, value);
439
    }
440
  }
441
442
5575
  if (key == "filename")
443
  {
444
56
    d_state->setFilename(value);
445
  }
446
5519
  else if (key == "smt-lib-version" && !Options::current().wasSetByUser(options::inputLanguage))
447
  {
448
707
    language::input::Language ilang = language::input::LANG_SMTLIB_V2_6;
449
450
707
    if (value != "2" && value != "2.6")
451
    {
452
8
      Warning() << "SMT-LIB version " << value
453
                << " unsupported, defaulting to language (and semantics of) "
454
4
                   "SMT-LIB 2.6\n";
455
    }
456
707
    Options::current().set(options::inputLanguage, ilang);
457
    // also update the output language
458
707
    if (!Options::current().wasSetByUser(options::outputLanguage))
459
    {
460
707
      language::output::Language olang = language::toOutputLanguage(ilang);
461
707
      if (d_env->getOption(options::outputLanguage) != olang)
462
      {
463
2
        Options::current().set(options::outputLanguage, olang);
464
2
        *d_env->getOption(options::out) << language::SetLanguage(olang);
465
      }
466
    }
467
  }
468
4812
  else if (key == "status")
469
  {
470
3500
    d_state->notifyExpectedStatus(value);
471
  }
472
5575
}
473
474
24
bool SmtEngine::isValidGetInfoFlag(const std::string& key) const
475
{
476
71
  if (key == "all-statistics" || key == "error-behavior" || key == "name"
477
19
      || key == "version" || key == "authors" || key == "status"
478
15
      || key == "reason-unknown" || key == "assertion-stack-levels"
479
30
      || key == "all-options" || key == "time")
480
  {
481
18
    return true;
482
  }
483
6
  return false;
484
}
485
486
18
std::string SmtEngine::getInfo(const std::string& key) const
487
{
488
36
  SmtScope smts(this);
489
490
18
  Trace("smt") << "SMT getInfo(" << key << ")" << endl;
491
18
  if (key == "all-statistics")
492
  {
493
1
    return toSExpr(d_env->getStatisticsRegistry().begin(), d_env->getStatisticsRegistry().end());
494
  }
495
17
  if (key == "error-behavior")
496
  {
497
1
    return "immediate-exit";
498
  }
499
16
  if (key == "name")
500
  {
501
3
    return toSExpr(Configuration::getName());
502
  }
503
13
  if (key == "version")
504
  {
505
1
    return toSExpr(Configuration::getVersionString());
506
  }
507
12
  if (key == "authors")
508
  {
509
1
    return toSExpr(Configuration::about());
510
  }
511
11
  if (key == "status")
512
  {
513
    // sat | unsat | unknown
514
4
    Result status = d_state->getStatus();
515
2
    switch (status.asSatisfiabilityResult().isSat())
516
    {
517
      case Result::SAT: return "sat";
518
      case Result::UNSAT: return "unsat";
519
2
      default: return "unknown";
520
    }
521
  }
522
9
  if (key == "time")
523
  {
524
    return toSExpr(std::clock());
525
  }
526
9
  if (key == "reason-unknown")
527
  {
528
18
    Result status = d_state->getStatus();
529
9
    if (!status.isNull() && status.isUnknown())
530
    {
531
12
      std::stringstream ss;
532
6
      ss << status.whyUnknown();
533
12
      std::string s = ss.str();
534
6
      transform(s.begin(), s.end(), s.begin(), ::tolower);
535
6
      return s;
536
    }
537
    else
538
    {
539
      throw RecoverableModalException(
540
          "Can't get-info :reason-unknown when the "
541
3
          "last result wasn't unknown!");
542
    }
543
  }
544
  if (key == "assertion-stack-levels")
545
  {
546
    size_t ulevel = d_state->getNumUserLevels();
547
    AlwaysAssert(ulevel <= std::numeric_limits<unsigned long int>::max());
548
    return toSExpr(ulevel);
549
  }
550
  Assert(key == "all-options");
551
  // get the options, like all-statistics
552
  return toSExpr(Options::current().getOptions());
553
}
554
555
2443
void SmtEngine::debugCheckFormals(const std::vector<Node>& formals, Node func)
556
{
557
5269
  for (std::vector<Node>::const_iterator i = formals.begin();
558
5269
       i != formals.end();
559
       ++i)
560
  {
561
2826
    if((*i).getKind() != kind::BOUND_VARIABLE) {
562
      stringstream ss;
563
      ss << "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
564
         << "definition of function " << func << ", formal\n"
565
         << "  " << *i << "\n"
566
         << "has kind " << (*i).getKind();
567
      throw TypeCheckingExceptionPrivate(func, ss.str());
568
    }
569
  }
570
2443
}
571
572
2443
void SmtEngine::debugCheckFunctionBody(Node formula,
573
                                       const std::vector<Node>& formals,
574
                                       Node func)
575
{
576
  TypeNode formulaType =
577
4886
      formula.getType(d_env->getOption(options::typeChecking));
578
4886
  TypeNode funcType = func.getType();
579
  // We distinguish here between definitions of constants and functions,
580
  // because the type checking for them is subtly different.  Perhaps we
581
  // should instead have SmtEngine::defineFunction() and
582
  // SmtEngine::defineConstant() for better clarity, although then that
583
  // doesn't match the SMT-LIBv2 standard...
584
2443
  if(formals.size() > 0) {
585
2736
    TypeNode rangeType = funcType.getRangeType();
586
1368
    if(! formulaType.isComparableTo(rangeType)) {
587
      stringstream ss;
588
      ss << "Type of defined function does not match its declaration\n"
589
         << "The function  : " << func << "\n"
590
         << "Declared type : " << rangeType << "\n"
591
         << "The body      : " << formula << "\n"
592
         << "Body type     : " << formulaType;
593
      throw TypeCheckingExceptionPrivate(func, ss.str());
594
    }
595
  } else {
596
1075
    if(! formulaType.isComparableTo(funcType)) {
597
      stringstream ss;
598
      ss << "Declared type of defined constant does not match its definition\n"
599
         << "The constant   : " << func << "\n"
600
         << "Declared type  : " << funcType << "\n"
601
         << "The definition : " << formula << "\n"
602
         << "Definition type: " << formulaType;
603
      throw TypeCheckingExceptionPrivate(func, ss.str());
604
    }
605
  }
606
2443
}
607
608
2252
void SmtEngine::defineFunction(Node func,
609
                               const std::vector<Node>& formals,
610
                               Node formula,
611
                               bool global)
612
{
613
4504
  SmtScope smts(this);
614
2252
  finishInit();
615
2252
  d_state->doPendingPops();
616
2252
  Trace("smt") << "SMT defineFunction(" << func << ")" << endl;
617
2252
  debugCheckFormals(formals, func);
618
619
4504
  stringstream ss;
620
  ss << language::SetLanguage(
621
            language::SetLanguage::getLanguage(Dump.getStream()))
622
2252
     << func;
623
624
4504
  DefineFunctionNodeCommand nc(ss.str(), func, formals, formula);
625
2252
  getDumpManager()->addToDump(nc, "declarations");
626
627
  // type check body
628
2252
  debugCheckFunctionBody(formula, formals, func);
629
630
  // Substitute out any abstract values in formula
631
4504
  Node def = d_absValues->substituteAbstractValues(formula);
632
2252
  if (!formals.empty())
633
  {
634
1198
    NodeManager* nm = NodeManager::currentNM();
635
3594
    def = nm->mkNode(
636
2396
        kind::LAMBDA, nm->mkNode(kind::BOUND_VAR_LIST, formals), def);
637
  }
638
  // A define-fun is treated as a (higher-order) assertion. It is provided
639
  // to the assertions object. It will be added as a top-level substitution
640
  // within this class, possibly multiple times if global is true.
641
4504
  Node feq = func.eqNode(def);
642
2252
  d_asserts->addDefineFunDefinition(feq, global);
643
2252
}
644
645
140
void SmtEngine::defineFunctionsRec(
646
    const std::vector<Node>& funcs,
647
    const std::vector<std::vector<Node>>& formals,
648
    const std::vector<Node>& formulas,
649
    bool global)
650
{
651
280
  SmtScope smts(this);
652
140
  finishInit();
653
140
  d_state->doPendingPops();
654
140
  Trace("smt") << "SMT defineFunctionsRec(...)" << endl;
655
656
140
  if (funcs.size() != formals.size() && funcs.size() != formulas.size())
657
  {
658
    stringstream ss;
659
    ss << "Number of functions, formals, and function bodies passed to "
660
          "defineFunctionsRec do not match:"
661
       << "\n"
662
       << "        #functions : " << funcs.size() << "\n"
663
       << "        #arg lists : " << formals.size() << "\n"
664
       << "  #function bodies : " << formulas.size() << "\n";
665
    throw ModalException(ss.str());
666
  }
667
331
  for (unsigned i = 0, size = funcs.size(); i < size; i++)
668
  {
669
    // check formal argument list
670
191
    debugCheckFormals(formals[i], funcs[i]);
671
    // type check body
672
191
    debugCheckFunctionBody(formulas[i], formals[i], funcs[i]);
673
  }
674
675
140
  if (Dump.isOn("raw-benchmark"))
676
  {
677
    getPrinter().toStreamCmdDefineFunctionRec(
678
        getOutputManager().getDumpOut(), funcs, formals, formulas);
679
  }
680
681
140
  NodeManager* nm = getNodeManager();
682
331
  for (unsigned i = 0, size = funcs.size(); i < size; i++)
683
  {
684
    // we assert a quantified formula
685
382
    Node func_app;
686
    // make the function application
687
191
    if (formals[i].empty())
688
    {
689
      // it has no arguments
690
21
      func_app = funcs[i];
691
    }
692
    else
693
    {
694
340
      std::vector<Node> children;
695
170
      children.push_back(funcs[i]);
696
170
      children.insert(children.end(), formals[i].begin(), formals[i].end());
697
170
      func_app = nm->mkNode(kind::APPLY_UF, children);
698
    }
699
382
    Node lem = nm->mkNode(kind::EQUAL, func_app, formulas[i]);
700
191
    if (!formals[i].empty())
701
    {
702
      // set the attribute to denote this is a function definition
703
340
      Node aexpr = nm->mkNode(kind::INST_ATTRIBUTE, func_app);
704
170
      aexpr = nm->mkNode(kind::INST_PATTERN_LIST, aexpr);
705
      FunDefAttribute fda;
706
170
      func_app.setAttribute(fda, true);
707
      // make the quantified formula
708
340
      Node boundVars = nm->mkNode(kind::BOUND_VAR_LIST, formals[i]);
709
170
      lem = nm->mkNode(kind::FORALL, boundVars, lem, aexpr);
710
    }
711
    // assert the quantified formula
712
    //   notice we don't call assertFormula directly, since this would
713
    //   duplicate the output on raw-benchmark.
714
    // add define recursive definition to the assertions
715
191
    d_asserts->addDefineFunDefinition(lem, global);
716
  }
717
140
}
718
719
16
void SmtEngine::defineFunctionRec(Node func,
720
                                  const std::vector<Node>& formals,
721
                                  Node formula,
722
                                  bool global)
723
{
724
32
  std::vector<Node> funcs;
725
16
  funcs.push_back(func);
726
32
  std::vector<std::vector<Node>> formals_multi;
727
16
  formals_multi.push_back(formals);
728
32
  std::vector<Node> formulas;
729
16
  formulas.push_back(formula);
730
16
  defineFunctionsRec(funcs, formals_multi, formulas, global);
731
16
}
732
733
89066
Result SmtEngine::quickCheck() {
734
89066
  Assert(d_state->isFullyInited());
735
89066
  Trace("smt") << "SMT quickCheck()" << endl;
736
89066
  const std::string& filename = d_state->getFilename();
737
  return Result(
738
89066
      Result::ENTAILMENT_UNKNOWN, Result::REQUIRES_FULL_CHECK, filename);
739
}
740
741
4205
Model* SmtEngine::getAvailableModel(const char* c) const
742
{
743
4205
  if (!d_env->getOption(options::assignFunctionValues))
744
  {
745
    std::stringstream ss;
746
    ss << "Cannot " << c << " when --assign-function-values is false.";
747
    throw RecoverableModalException(ss.str().c_str());
748
  }
749
750
8410
  if (d_state->getMode() != SmtMode::SAT
751
4205
      && d_state->getMode() != SmtMode::SAT_UNKNOWN)
752
  {
753
18
    std::stringstream ss;
754
    ss << "Cannot " << c
755
9
       << " unless immediately preceded by SAT/NOT_ENTAILED or UNKNOWN "
756
9
          "response.";
757
9
    throw RecoverableModalException(ss.str().c_str());
758
  }
759
760
4196
  if (!d_env->getOption(options::produceModels))
761
  {
762
4
    std::stringstream ss;
763
2
    ss << "Cannot " << c << " when produce-models options is off.";
764
2
    throw ModalException(ss.str().c_str());
765
  }
766
767
4194
  TheoryEngine* te = d_smtSolver->getTheoryEngine();
768
4194
  Assert(te != nullptr);
769
4194
  TheoryModel* m = te->getBuiltModel();
770
771
4193
  if (m == nullptr)
772
  {
773
    std::stringstream ss;
774
    ss << "Cannot " << c
775
       << " since model is not available. Perhaps the most recent call to "
776
          "check-sat was interrupted?";
777
    throw RecoverableModalException(ss.str().c_str());
778
  }
779
780
4193
  return d_model.get();
781
}
782
783
117
QuantifiersEngine* SmtEngine::getAvailableQuantifiersEngine(const char* c) const
784
{
785
117
  QuantifiersEngine* qe = d_smtSolver->getQuantifiersEngine();
786
117
  if (qe == nullptr)
787
  {
788
    std::stringstream ss;
789
    ss << "Cannot " << c << " when quantifiers are not present.";
790
    throw ModalException(ss.str().c_str());
791
  }
792
117
  return qe;
793
}
794
795
4361
void SmtEngine::notifyPushPre() { d_smtSolver->processAssertions(*d_asserts); }
796
797
4361
void SmtEngine::notifyPushPost()
798
{
799
8722
  TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
800
4361
  Assert(getPropEngine() != nullptr);
801
4361
  getPropEngine()->push();
802
4361
}
803
804
4361
void SmtEngine::notifyPopPre()
805
{
806
8722
  TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
807
4361
  PropEngine* pe = getPropEngine();
808
4361
  Assert(pe != nullptr);
809
4361
  pe->pop();
810
4361
}
811
812
14294
void SmtEngine::notifyPostSolvePre()
813
{
814
14294
  PropEngine* pe = getPropEngine();
815
14294
  Assert(pe != nullptr);
816
14294
  pe->resetTrail();
817
14294
}
818
819
14294
void SmtEngine::notifyPostSolvePost()
820
{
821
14294
  TheoryEngine* te = getTheoryEngine();
822
14294
  Assert(te != nullptr);
823
14294
  te->postsolve();
824
14294
}
825
826
11873
Result SmtEngine::checkSat()
827
{
828
23746
  Node nullNode;
829
23729
  return checkSat(nullNode);
830
}
831
832
12460
Result SmtEngine::checkSat(const Node& assumption, bool inUnsatCore)
833
{
834
12460
  if (Dump.isOn("benchmark"))
835
  {
836
4
    getPrinter().toStreamCmdCheckSat(getOutputManager().getDumpOut(),
837
2
                                     assumption);
838
  }
839
24920
  std::vector<Node> assump;
840
12460
  if (!assumption.isNull())
841
  {
842
587
    assump.push_back(assumption);
843
  }
844
24902
  return checkSatInternal(assump, inUnsatCore, false);
845
}
846
847
994
Result SmtEngine::checkSat(const std::vector<Node>& assumptions,
848
                           bool inUnsatCore)
849
{
850
994
  if (Dump.isOn("benchmark"))
851
  {
852
    if (assumptions.empty())
853
    {
854
      getPrinter().toStreamCmdCheckSat(getOutputManager().getDumpOut());
855
    }
856
    else
857
    {
858
      getPrinter().toStreamCmdCheckSatAssuming(getOutputManager().getDumpOut(),
859
                                               assumptions);
860
    }
861
  }
862
994
  return checkSatInternal(assumptions, inUnsatCore, false);
863
}
864
865
634
Result SmtEngine::checkEntailed(const Node& node, bool inUnsatCore)
866
{
867
634
  if (Dump.isOn("benchmark"))
868
  {
869
    getPrinter().toStreamCmdQuery(getOutputManager().getDumpOut(), node);
870
  }
871
1898
  return checkSatInternal(
872
1268
             node.isNull() ? std::vector<Node>() : std::vector<Node>{node},
873
             inUnsatCore,
874
             true)
875
1260
      .asEntailmentResult();
876
}
877
878
2
Result SmtEngine::checkEntailed(const std::vector<Node>& nodes,
879
                                bool inUnsatCore)
880
{
881
2
  return checkSatInternal(nodes, inUnsatCore, true).asEntailmentResult();
882
}
883
884
14090
Result SmtEngine::checkSatInternal(const std::vector<Node>& assumptions,
885
                                   bool inUnsatCore,
886
                                   bool isEntailmentCheck)
887
{
888
  try
889
  {
890
28180
    SmtScope smts(this);
891
14090
    finishInit();
892
893
28180
    Trace("smt") << "SmtEngine::"
894
28180
                 << (isEntailmentCheck ? "checkEntailed" : "checkSat") << "("
895
14090
                 << assumptions << ")" << endl;
896
    // check the satisfiability with the solver object
897
    Result r = d_smtSolver->checkSatisfiability(
898
28160
        *d_asserts.get(), assumptions, inUnsatCore, isEntailmentCheck);
899
900
28140
    Trace("smt") << "SmtEngine::" << (isEntailmentCheck ? "query" : "checkSat")
901
14070
                 << "(" << assumptions << ") => " << r << endl;
902
903
    // Check that SAT results generate a model correctly.
904
14070
    if (d_env->getOption(options::checkModels))
905
    {
906
2468
      if (r.asSatisfiabilityResult().isSat() == Result::SAT)
907
      {
908
2075
        checkModel();
909
      }
910
    }
911
    // Check that UNSAT results generate a proof correctly.
912
28136
    if (d_env->getOption(options::checkProofs)
913
14068
        || d_env->getOption(options::proofEagerChecking))
914
    {
915
2202
      if (r.asSatisfiabilityResult().isSat() == Result::UNSAT)
916
      {
917
2636
        if ((d_env->getOption(options::checkProofs)
918
             || d_env->getOption(options::proofEagerChecking))
919
2636
            && !d_env->getOption(options::produceProofs))
920
        {
921
          throw ModalException(
922
              "Cannot check-proofs because proofs were disabled.");
923
        }
924
1318
        checkProof();
925
      }
926
    }
927
    // Check that UNSAT results generate an unsat core correctly.
928
14068
    if (d_env->getOption(options::checkUnsatCores))
929
    {
930
2281
      if (r.asSatisfiabilityResult().isSat() == Result::UNSAT)
931
      {
932
2620
        TimerStat::CodeTimer checkUnsatCoreTimer(d_stats->d_checkUnsatCoreTime);
933
1310
        checkUnsatCore();
934
      }
935
    }
936
937
14068
    return r;
938
  }
939
  catch (UnsafeInterruptException& e)
940
  {
941
    AlwaysAssert(getResourceManager()->out());
942
    // Notice that we do not notify the state of this result. If we wanted to
943
    // make the solver resume a working state after an interupt, then we would
944
    // implement a different callback and use it here, e.g.
945
    // d_state.notifyCheckSatInterupt.
946
    Result::UnknownExplanation why = getResourceManager()->outOfResources()
947
                                         ? Result::RESOURCEOUT
948
                                         : Result::TIMEOUT;
949
    return Result(Result::SAT_UNKNOWN, why, d_state->getFilename());
950
  }
951
}
952
953
13
std::vector<Node> SmtEngine::getUnsatAssumptions(void)
954
{
955
13
  Trace("smt") << "SMT getUnsatAssumptions()" << endl;
956
26
  SmtScope smts(this);
957
13
  if (!d_env->getOption(options::unsatAssumptions))
958
  {
959
    throw ModalException(
960
        "Cannot get unsat assumptions when produce-unsat-assumptions option "
961
        "is off.");
962
  }
963
13
  if (d_state->getMode() != SmtMode::UNSAT)
964
  {
965
    throw RecoverableModalException(
966
        "Cannot get unsat assumptions unless immediately preceded by "
967
        "UNSAT/ENTAILED.");
968
  }
969
13
  finishInit();
970
13
  if (Dump.isOn("benchmark"))
971
  {
972
    getPrinter().toStreamCmdGetUnsatAssumptions(
973
        getOutputManager().getDumpOut());
974
  }
975
26
  UnsatCore core = getUnsatCoreInternal();
976
13
  std::vector<Node> res;
977
13
  std::vector<Node>& assumps = d_asserts->getAssumptions();
978
37
  for (const Node& e : assumps)
979
  {
980
24
    if (std::find(core.begin(), core.end(), e) != core.end())
981
    {
982
16
      res.push_back(e);
983
    }
984
  }
985
26
  return res;
986
}
987
988
89067
Result SmtEngine::assertFormula(const Node& formula, bool inUnsatCore)
989
{
990
178134
  SmtScope smts(this);
991
89067
  finishInit();
992
89066
  d_state->doPendingPops();
993
994
89066
  Trace("smt") << "SmtEngine::assertFormula(" << formula << ")" << endl;
995
996
89066
  if (Dump.isOn("raw-benchmark"))
997
  {
998
3
    getPrinter().toStreamCmdAssert(getOutputManager().getDumpOut(), formula);
999
  }
1000
1001
  // Substitute out any abstract values in ex
1002
178132
  Node n = d_absValues->substituteAbstractValues(formula);
1003
1004
89066
  d_asserts->assertFormula(n, inUnsatCore);
1005
178132
  return quickCheck().asEntailmentResult();
1006
}/* SmtEngine::assertFormula() */
1007
1008
/*
1009
   --------------------------------------------------------------------------
1010
    Handling SyGuS commands
1011
   --------------------------------------------------------------------------
1012
*/
1013
1014
373
void SmtEngine::declareSygusVar(Node var)
1015
{
1016
746
  SmtScope smts(this);
1017
373
  d_sygusSolver->declareSygusVar(var);
1018
373
  if (Dump.isOn("raw-benchmark"))
1019
  {
1020
    getPrinter().toStreamCmdDeclareVar(
1021
        getOutputManager().getDumpOut(), var, var.getType());
1022
  }
1023
  // don't need to set that the conjecture is stale
1024
373
}
1025
1026
318
void SmtEngine::declareSynthFun(Node func,
1027
                                TypeNode sygusType,
1028
                                bool isInv,
1029
                                const std::vector<Node>& vars)
1030
{
1031
636
  SmtScope smts(this);
1032
318
  d_state->doPendingPops();
1033
318
  d_sygusSolver->declareSynthFun(func, sygusType, isInv, vars);
1034
1035
  // !!! TEMPORARY: We cannot construct a SynthFunCommand since we cannot
1036
  // construct a Term-level Grammar from a Node-level sygus TypeNode. Thus we
1037
  // must print the command using the Node-level utility method for now.
1038
1039
318
  if (Dump.isOn("raw-benchmark"))
1040
  {
1041
    getPrinter().toStreamCmdSynthFun(
1042
        getOutputManager().getDumpOut(), func, vars, isInv, sygusType);
1043
  }
1044
318
}
1045
void SmtEngine::declareSynthFun(Node func,
1046
                                bool isInv,
1047
                                const std::vector<Node>& vars)
1048
{
1049
  // use a null sygus type
1050
  TypeNode sygusType;
1051
  declareSynthFun(func, sygusType, isInv, vars);
1052
}
1053
1054
610
void SmtEngine::assertSygusConstraint(Node constraint)
1055
{
1056
1220
  SmtScope smts(this);
1057
610
  finishInit();
1058
610
  d_sygusSolver->assertSygusConstraint(constraint);
1059
610
  if (Dump.isOn("raw-benchmark"))
1060
  {
1061
    getPrinter().toStreamCmdConstraint(getOutputManager().getDumpOut(),
1062
                                       constraint);
1063
  }
1064
610
}
1065
1066
17
void SmtEngine::assertSygusInvConstraint(Node inv,
1067
                                         Node pre,
1068
                                         Node trans,
1069
                                         Node post)
1070
{
1071
34
  SmtScope smts(this);
1072
17
  finishInit();
1073
17
  d_sygusSolver->assertSygusInvConstraint(inv, pre, trans, post);
1074
17
  if (Dump.isOn("raw-benchmark"))
1075
  {
1076
    getPrinter().toStreamCmdInvConstraint(
1077
        getOutputManager().getDumpOut(), inv, pre, trans, post);
1078
  }
1079
17
}
1080
1081
203
Result SmtEngine::checkSynth()
1082
{
1083
406
  SmtScope smts(this);
1084
203
  finishInit();
1085
397
  return d_sygusSolver->checkSynth(*d_asserts);
1086
}
1087
1088
/*
1089
   --------------------------------------------------------------------------
1090
    End of Handling SyGuS commands
1091
   --------------------------------------------------------------------------
1092
*/
1093
1094
5
void SmtEngine::declarePool(const Node& p, const std::vector<Node>& initValue)
1095
{
1096
5
  Assert(p.isVar() && p.getType().isSet());
1097
5
  finishInit();
1098
5
  QuantifiersEngine* qe = getAvailableQuantifiersEngine("declareTermPool");
1099
5
  qe->declarePool(p, initValue);
1100
5
}
1101
1102
68
Node SmtEngine::simplify(const Node& ex)
1103
{
1104
136
  SmtScope smts(this);
1105
68
  finishInit();
1106
68
  d_state->doPendingPops();
1107
  // ensure we've processed assertions
1108
68
  d_smtSolver->processAssertions(*d_asserts);
1109
136
  return d_pp->simplify(ex);
1110
}
1111
1112
1804
Node SmtEngine::expandDefinitions(const Node& ex)
1113
{
1114
1804
  getResourceManager()->spendResource(Resource::PreprocessStep);
1115
3608
  SmtScope smts(this);
1116
1804
  finishInit();
1117
1804
  d_state->doPendingPops();
1118
3608
  return d_pp->expandDefinitions(ex);
1119
}
1120
1121
// TODO(#1108): Simplify the error reporting of this method.
1122
2060
Node SmtEngine::getValue(const Node& ex) const
1123
{
1124
4120
  SmtScope smts(this);
1125
1126
2060
  Trace("smt") << "SMT getValue(" << ex << ")" << endl;
1127
2060
  if (Dump.isOn("benchmark"))
1128
  {
1129
    getPrinter().toStreamCmdGetValue(d_outMgr.getDumpOut(), {ex});
1130
  }
1131
4120
  TypeNode expectedType = ex.getType();
1132
1133
  // Substitute out any abstract values in ex and expand
1134
4120
  Node n = d_pp->expandDefinitions(ex);
1135
1136
2060
  Trace("smt") << "--- getting value of " << n << endl;
1137
  // There are two ways model values for terms are computed (for historical
1138
  // reasons).  One way is that used in check-model; the other is that
1139
  // used by the Model classes.  It's not clear to me exactly how these
1140
  // two are different, but they need to be unified.  This ugly hack here
1141
  // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
1142
1143
  //AJR : necessary?
1144
2060
  if(!n.getType().isFunction()) {
1145
2053
    n = Rewriter::rewrite(n);
1146
  }
1147
1148
2060
  Trace("smt") << "--- getting value of " << n << endl;
1149
2060
  Model* m = getAvailableModel("get-value");
1150
2054
  Assert(m != nullptr);
1151
2054
  Node resultNode = m->getValue(n);
1152
2054
  Trace("smt") << "--- got value " << n << " = " << resultNode << endl;
1153
2054
  Trace("smt") << "--- type " << resultNode.getType() << endl;
1154
2054
  Trace("smt") << "--- expected type " << expectedType << endl;
1155
1156
  // type-check the result we got
1157
  // Notice that lambdas have function type, which does not respect the subtype
1158
  // relation, so we ignore them here.
1159
2054
  Assert(resultNode.isNull() || resultNode.getKind() == kind::LAMBDA
1160
         || resultNode.getType().isSubtypeOf(expectedType))
1161
      << "Run with -t smt for details.";
1162
1163
  // Ensure it's a constant, or a lambda (for uninterpreted functions). This
1164
  // assertion only holds for models that do not have approximate values.
1165
2054
  Assert(m->hasApproximations() || resultNode.getKind() == kind::LAMBDA
1166
         || resultNode.isConst());
1167
1168
4108
  if (d_env->getOption(options::abstractValues)
1169
4108
      && resultNode.getType().isArray())
1170
  {
1171
8
    resultNode = d_absValues->mkAbstractValue(resultNode);
1172
8
    Trace("smt") << "--- abstract value >> " << resultNode << endl;
1173
  }
1174
1175
4108
  return resultNode;
1176
}
1177
1178
std::vector<Node> SmtEngine::getValues(const std::vector<Node>& exprs)
1179
{
1180
  std::vector<Node> result;
1181
  for (const Node& e : exprs)
1182
  {
1183
    result.push_back(getValue(e));
1184
  }
1185
  return result;
1186
}
1187
1188
// TODO(#1108): Simplify the error reporting of this method.
1189
30
Model* SmtEngine::getModel() {
1190
30
  Trace("smt") << "SMT getModel()" << endl;
1191
60
  SmtScope smts(this);
1192
1193
30
  finishInit();
1194
1195
30
  if (Dump.isOn("benchmark"))
1196
  {
1197
    getPrinter().toStreamCmdGetModel(getOutputManager().getDumpOut());
1198
  }
1199
1200
30
  Model* m = getAvailableModel("get model");
1201
1202
  // Since model m is being returned to the user, we must ensure that this
1203
  // model object remains valid with future check-sat calls. Hence, we set
1204
  // the theory engine into "eager model building" mode. TODO #2648: revisit.
1205
25
  TheoryEngine* te = getTheoryEngine();
1206
25
  Assert(te != nullptr);
1207
25
  te->setEagerModelBuilding();
1208
1209
50
  if (d_env->getOption(options::modelCoresMode)
1210
25
      != options::ModelCoresMode::NONE)
1211
  {
1212
    // If we enabled model cores, we compute a model core for m based on our
1213
    // (expanded) assertions using the model core builder utility
1214
    std::vector<Node> eassertsProc = getExpandedAssertions();
1215
    ModelCoreBuilder::setModelCore(eassertsProc,
1216
                                   m->getTheoryModel(),
1217
                                   d_env->getOption(options::modelCoresMode));
1218
  }
1219
  // set the information on the SMT-level model
1220
25
  Assert(m != nullptr);
1221
25
  m->d_inputName = d_state->getFilename();
1222
25
  m->d_isKnownSat = (d_state->getMode() == SmtMode::SAT);
1223
50
  return m;
1224
}
1225
1226
18
Result SmtEngine::blockModel()
1227
{
1228
18
  Trace("smt") << "SMT blockModel()" << endl;
1229
36
  SmtScope smts(this);
1230
1231
18
  finishInit();
1232
1233
18
  if (Dump.isOn("benchmark"))
1234
  {
1235
    getPrinter().toStreamCmdBlockModel(getOutputManager().getDumpOut());
1236
  }
1237
1238
18
  Model* m = getAvailableModel("block model");
1239
1240
36
  if (d_env->getOption(options::blockModelsMode)
1241
18
      == options::BlockModelsMode::NONE)
1242
  {
1243
4
    std::stringstream ss;
1244
2
    ss << "Cannot block model when block-models is set to none.";
1245
2
    throw RecoverableModalException(ss.str().c_str());
1246
  }
1247
1248
  // get expanded assertions
1249
32
  std::vector<Node> eassertsProc = getExpandedAssertions();
1250
  Node eblocker =
1251
      ModelBlocker::getModelBlocker(eassertsProc,
1252
                                    m->getTheoryModel(),
1253
32
                                    d_env->getOption(options::blockModelsMode));
1254
16
  Trace("smt") << "Block formula: " << eblocker << std::endl;
1255
32
  return assertFormula(eblocker);
1256
}
1257
1258
12
Result SmtEngine::blockModelValues(const std::vector<Node>& exprs)
1259
{
1260
12
  Trace("smt") << "SMT blockModelValues()" << endl;
1261
24
  SmtScope smts(this);
1262
1263
12
  finishInit();
1264
1265
12
  if (Dump.isOn("benchmark"))
1266
  {
1267
    getPrinter().toStreamCmdBlockModelValues(getOutputManager().getDumpOut(),
1268
                                             exprs);
1269
  }
1270
1271
12
  Model* m = getAvailableModel("block model values");
1272
1273
  // get expanded assertions
1274
22
  std::vector<Node> eassertsProc = getExpandedAssertions();
1275
  // we always do block model values mode here
1276
  Node eblocker =
1277
      ModelBlocker::getModelBlocker(eassertsProc,
1278
                                    m->getTheoryModel(),
1279
                                    options::BlockModelsMode::VALUES,
1280
20
                                    exprs);
1281
20
  return assertFormula(eblocker);
1282
}
1283
1284
10
std::pair<Node, Node> SmtEngine::getSepHeapAndNilExpr(void)
1285
{
1286
10
  if (!getLogicInfo().isTheoryEnabled(THEORY_SEP))
1287
  {
1288
    const char* msg =
1289
        "Cannot obtain separation logic expressions if not using the "
1290
        "separation logic theory.";
1291
    throw RecoverableModalException(msg);
1292
  }
1293
20
  NodeManagerScope nms(getNodeManager());
1294
20
  Node heap;
1295
20
  Node nil;
1296
10
  Model* m = getAvailableModel("get separation logic heap and nil");
1297
10
  TheoryModel* tm = m->getTheoryModel();
1298
10
  if (!tm->getHeapModel(heap, nil))
1299
  {
1300
4
    const char* msg =
1301
        "Failed to obtain heap/nil "
1302
        "expressions from theory model.";
1303
4
    throw RecoverableModalException(msg);
1304
  }
1305
12
  return std::make_pair(heap, nil);
1306
}
1307
1308
80
std::vector<Node> SmtEngine::getExpandedAssertions()
1309
{
1310
158
  std::vector<Node> easserts = getAssertions();
1311
  // must expand definitions
1312
78
  std::vector<Node> eassertsProc;
1313
156
  std::unordered_map<Node, Node> cache;
1314
350
  for (const Node& e : easserts)
1315
  {
1316
544
    Node eae = d_pp->expandDefinitions(e, cache);
1317
272
    eassertsProc.push_back(eae);
1318
  }
1319
156
  return eassertsProc;
1320
}
1321
25
Env& SmtEngine::getEnv() { return *d_env.get(); }
1322
1323
121
void SmtEngine::declareSepHeap(TypeNode locT, TypeNode dataT)
1324
{
1325
121
  if (!getLogicInfo().isTheoryEnabled(THEORY_SEP))
1326
  {
1327
    const char* msg =
1328
        "Cannot declare heap if not using the separation logic theory.";
1329
    throw RecoverableModalException(msg);
1330
  }
1331
242
  SmtScope smts(this);
1332
121
  finishInit();
1333
121
  TheoryEngine* te = getTheoryEngine();
1334
123
  te->declareSepHeap(locT, dataT);
1335
119
}
1336
1337
1310
bool SmtEngine::getSepHeapTypes(TypeNode& locT, TypeNode& dataT)
1338
{
1339
2620
  SmtScope smts(this);
1340
1310
  finishInit();
1341
1310
  TheoryEngine* te = getTheoryEngine();
1342
2620
  return te->getSepHeapTypes(locT, dataT);
1343
}
1344
1345
5
Node SmtEngine::getSepHeapExpr() { return getSepHeapAndNilExpr().first; }
1346
1347
5
Node SmtEngine::getSepNilExpr() { return getSepHeapAndNilExpr().second; }
1348
1349
1318
void SmtEngine::checkProof()
1350
{
1351
1318
  Assert(d_env->getOption(options::produceProofs));
1352
  // internal check the proof
1353
1318
  PropEngine* pe = getPropEngine();
1354
1318
  Assert(pe != nullptr);
1355
1318
  if (d_env->getOption(options::proofEagerChecking))
1356
  {
1357
    pe->checkProof(d_asserts->getAssertionList());
1358
  }
1359
1318
  Assert(pe->getProof() != nullptr);
1360
2636
  std::shared_ptr<ProofNode> pePfn = pe->getProof();
1361
1318
  if (d_env->getOption(options::checkProofs))
1362
  {
1363
1318
    d_pfManager->checkProof(pePfn, *d_asserts);
1364
  }
1365
1318
}
1366
1367
4621920
StatisticsRegistry& SmtEngine::getStatisticsRegistry()
1368
{
1369
4621920
  return d_env->getStatisticsRegistry();
1370
}
1371
1372
1364
UnsatCore SmtEngine::getUnsatCoreInternal()
1373
{
1374
1364
  if (!d_env->getOption(options::unsatCores))
1375
  {
1376
    throw ModalException(
1377
        "Cannot get an unsat core when produce-unsat-cores or produce-proofs "
1378
        "option is off.");
1379
  }
1380
1364
  if (d_state->getMode() != SmtMode::UNSAT)
1381
  {
1382
    throw RecoverableModalException(
1383
        "Cannot get an unsat core unless immediately preceded by "
1384
        "UNSAT/ENTAILED response.");
1385
  }
1386
  // generate with new proofs
1387
1364
  PropEngine* pe = getPropEngine();
1388
1364
  Assert(pe != nullptr);
1389
1390
2728
  std::shared_ptr<ProofNode> pepf;
1391
1364
  if (options::unsatCoresMode() == options::UnsatCoresMode::ASSUMPTIONS)
1392
  {
1393
1318
    pepf = pe->getRefutation();
1394
  }
1395
  else
1396
  {
1397
46
    pepf = pe->getProof();
1398
  }
1399
1364
  Assert(pepf != nullptr);
1400
2728
  std::shared_ptr<ProofNode> pfn = d_pfManager->getFinalProof(pepf, *d_asserts);
1401
2728
  std::vector<Node> core;
1402
1364
  d_ucManager->getUnsatCore(pfn, *d_asserts, core);
1403
2728
  return UnsatCore(core);
1404
}
1405
1406
1310
void SmtEngine::checkUnsatCore() {
1407
1310
  Assert(d_env->getOption(options::unsatCores))
1408
      << "cannot check unsat core if unsat cores are turned off";
1409
1410
1310
  Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl;
1411
2620
  UnsatCore core = getUnsatCore();
1412
1413
  // initialize the core checker
1414
2620
  std::unique_ptr<SmtEngine> coreChecker;
1415
1310
  initializeSubsolver(coreChecker);
1416
1310
  coreChecker->getOptions().set(options::checkUnsatCores, false);
1417
  // disable all proof options
1418
1310
  coreChecker->getOptions().set(options::produceProofs, false);
1419
1310
  coreChecker->getOptions().set(options::checkProofs, false);
1420
1310
  coreChecker->getOptions().set(options::proofEagerChecking, false);
1421
1422
  // set up separation logic heap if necessary
1423
2620
  TypeNode sepLocType, sepDataType;
1424
1310
  if (getSepHeapTypes(sepLocType, sepDataType))
1425
  {
1426
21
    coreChecker->declareSepHeap(sepLocType, sepDataType);
1427
  }
1428
1429
1310
  Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions"
1430
           << std::endl;
1431
1310
  theory::TrustSubstitutionMap& tls = d_env->getTopLevelSubstitutions();
1432
7158
  for(UnsatCore::iterator i = core.begin(); i != core.end(); ++i) {
1433
11696
    Node assertionAfterExpansion = tls.apply(*i, false);
1434
5848
    Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
1435
             << ", expanded to " << assertionAfterExpansion << "\n";
1436
5848
    coreChecker->assertFormula(assertionAfterExpansion);
1437
  }
1438
2620
  Result r;
1439
  try {
1440
1310
    r = coreChecker->checkSat();
1441
  } catch(...) {
1442
    throw;
1443
  }
1444
1310
  Notice() << "SmtEngine::checkUnsatCore(): result is " << r << endl;
1445
1310
  if(r.asSatisfiabilityResult().isUnknown()) {
1446
1
    Warning()
1447
        << "SmtEngine::checkUnsatCore(): could not check core result unknown."
1448
        << std::endl;
1449
  }
1450
1309
  else if (r.asSatisfiabilityResult().isSat())
1451
  {
1452
    InternalError()
1453
        << "SmtEngine::checkUnsatCore(): produced core was satisfiable.";
1454
  }
1455
1310
}
1456
1457
2075
void SmtEngine::checkModel(bool hardFailure) {
1458
2075
  context::CDList<Node>* al = d_asserts->getAssertionList();
1459
  // --check-model implies --produce-assertions, which enables the
1460
  // assertion list, so we should be ok.
1461
2075
  Assert(al != nullptr)
1462
      << "don't have an assertion list to check in SmtEngine::checkModel()";
1463
1464
4150
  TimerStat::CodeTimer checkModelTimer(d_stats->d_checkModelTime);
1465
1466
2075
  Notice() << "SmtEngine::checkModel(): generating model" << endl;
1467
2075
  Model* m = getAvailableModel("check model");
1468
2074
  Assert(m != nullptr);
1469
1470
  // check the model with the theory engine for debugging
1471
2074
  if (options::debugCheckModels())
1472
  {
1473
2064
    TheoryEngine* te = getTheoryEngine();
1474
2064
    Assert(te != nullptr);
1475
2064
    te->checkTheoryAssertionsWithModel(hardFailure);
1476
  }
1477
1478
  // check the model with the check models utility
1479
2074
  Assert(d_checkModels != nullptr);
1480
2074
  d_checkModels->checkModel(m, al, hardFailure);
1481
2073
}
1482
1483
1351
UnsatCore SmtEngine::getUnsatCore() {
1484
1351
  Trace("smt") << "SMT getUnsatCore()" << std::endl;
1485
2702
  SmtScope smts(this);
1486
1351
  finishInit();
1487
1351
  if (Dump.isOn("benchmark"))
1488
  {
1489
    getPrinter().toStreamCmdGetUnsatCore(getOutputManager().getDumpOut());
1490
  }
1491
2702
  return getUnsatCoreInternal();
1492
}
1493
1494
7
void SmtEngine::getRelevantInstantiationTermVectors(
1495
    std::map<Node, std::vector<std::vector<Node>>>& insts)
1496
{
1497
7
  Assert(d_state->getMode() == SmtMode::UNSAT);
1498
  // generate with new proofs
1499
7
  PropEngine* pe = getPropEngine();
1500
7
  Assert(pe != nullptr);
1501
7
  Assert(pe->getProof() != nullptr);
1502
  std::shared_ptr<ProofNode> pfn =
1503
14
      d_pfManager->getFinalProof(pe->getProof(), *d_asserts);
1504
7
  d_ucManager->getRelevantInstantiations(pfn, insts);
1505
7
}
1506
1507
1
std::string SmtEngine::getProof()
1508
{
1509
1
  Trace("smt") << "SMT getProof()\n";
1510
2
  SmtScope smts(this);
1511
1
  finishInit();
1512
1
  if (Dump.isOn("benchmark"))
1513
  {
1514
    getPrinter().toStreamCmdGetProof(getOutputManager().getDumpOut());
1515
  }
1516
1
  if (!d_env->getOption(options::produceProofs))
1517
  {
1518
    throw ModalException("Cannot get a proof when proof option is off.");
1519
  }
1520
1
  if (d_state->getMode() != SmtMode::UNSAT)
1521
  {
1522
    throw RecoverableModalException(
1523
        "Cannot get a proof unless immediately preceded by "
1524
        "UNSAT/ENTAILED response.");
1525
  }
1526
  // the prop engine has the proof of false
1527
1
  PropEngine* pe = getPropEngine();
1528
1
  Assert(pe != nullptr);
1529
1
  Assert(pe->getProof() != nullptr);
1530
1
  Assert(d_pfManager);
1531
2
  std::ostringstream ss;
1532
1
  d_pfManager->printProof(ss, pe->getProof(), *d_asserts);
1533
2
  return ss.str();
1534
}
1535
1536
15
void SmtEngine::printInstantiations( std::ostream& out ) {
1537
30
  SmtScope smts(this);
1538
15
  finishInit();
1539
198
  if (d_env->getOption(options::instFormatMode) == options::InstFormatMode::SZS)
1540
  {
1541
    out << "% SZS output start Proof for " << d_state->getFilename()
1542
        << std::endl;
1543
  }
1544
15
  QuantifiersEngine* qe = getAvailableQuantifiersEngine("printInstantiations");
1545
1546
  // First, extract and print the skolemizations
1547
15
  bool printed = false;
1548
44
  bool reqNames = !d_env->getOption(options::printInstFull);
1549
  // only print when in list mode
1550
69
  if (d_env->getOption(options::printInstMode) == options::PrintInstMode::LIST)
1551
  {
1552
24
    std::map<Node, std::vector<Node>> sks;
1553
12
    qe->getSkolemTermVectors(sks);
1554
21
    for (const std::pair<const Node, std::vector<Node>>& s : sks)
1555
    {
1556
18
      Node name;
1557
9
      if (!qe->getNameForQuant(s.first, name, reqNames))
1558
      {
1559
        // did not have a name and we are only printing formulas with names
1560
        continue;
1561
      }
1562
18
      SkolemList slist(name, s.second);
1563
9
      out << slist;
1564
9
      printed = true;
1565
    }
1566
  }
1567
1568
  // Second, extract and print the instantiations
1569
30
  std::map<Node, std::vector<std::vector<Node>>> insts;
1570
15
  getInstantiationTermVectors(insts);
1571
36
  for (const std::pair<const Node, std::vector<std::vector<Node>>>& i : insts)
1572
  {
1573
21
    if (i.second.empty())
1574
    {
1575
      // no instantiations, skip
1576
      continue;
1577
    }
1578
42
    Node name;
1579
21
    if (!qe->getNameForQuant(i.first, name, reqNames))
1580
    {
1581
      // did not have a name and we are only printing formulas with names
1582
      continue;
1583
    }
1584
    // must have a name
1585
21
    if (d_env->getOption(options::printInstMode) == options::PrintInstMode::NUM)
1586
    {
1587
12
      out << "(num-instantiations " << name << " " << i.second.size() << ")"
1588
6
          << std::endl;
1589
    }
1590
    else
1591
    {
1592
15
      Assert(d_env->getOption(options::printInstMode)
1593
             == options::PrintInstMode::LIST);
1594
30
      InstantiationList ilist(name, i.second);
1595
15
      out << ilist;
1596
    }
1597
21
    printed = true;
1598
  }
1599
  // if we did not print anything, we indicate this
1600
15
  if (!printed)
1601
  {
1602
    out << "No instantiations" << std::endl;
1603
  }
1604
15
  if (d_env->getOption(options::instFormatMode) == options::InstFormatMode::SZS)
1605
  {
1606
    out << "% SZS output end Proof for " << d_state->getFilename() << std::endl;
1607
  }
1608
15
}
1609
1610
15
void SmtEngine::getInstantiationTermVectors(
1611
    std::map<Node, std::vector<std::vector<Node>>>& insts)
1612
{
1613
30
  SmtScope smts(this);
1614
15
  finishInit();
1615
30
  if (d_env->getOption(options::produceProofs)
1616
11
      && (!d_env->getOption(options::unsatCores)
1617
11
          || d_env->getOption(options::unsatCoresMode) == options::UnsatCoresMode::FULL_PROOF)
1618
22
      && getSmtMode() == SmtMode::UNSAT)
1619
  {
1620
    // minimize instantiations based on proof manager
1621
7
    getRelevantInstantiationTermVectors(insts);
1622
  }
1623
  else
1624
  {
1625
    QuantifiersEngine* qe =
1626
8
        getAvailableQuantifiersEngine("getInstantiationTermVectors");
1627
    // otherwise, just get the list of all instantiations
1628
8
    qe->getInstantiationTermVectors(insts);
1629
  }
1630
15
}
1631
1632
85
bool SmtEngine::getSynthSolutions(std::map<Node, Node>& solMap)
1633
{
1634
170
  SmtScope smts(this);
1635
85
  finishInit();
1636
170
  return d_sygusSolver->getSynthSolutions(solMap);
1637
}
1638
1639
30
Node SmtEngine::getQuantifierElimination(Node q, bool doFull, bool strict)
1640
{
1641
60
  SmtScope smts(this);
1642
30
  finishInit();
1643
30
  const LogicInfo& logic = getLogicInfo();
1644
30
  if (!logic.isPure(THEORY_ARITH) && strict)
1645
  {
1646
10
    Warning() << "Unexpected logic for quantifier elimination " << logic
1647
4
              << endl;
1648
  }
1649
  return d_quantElimSolver->getQuantifierElimination(
1650
60
      *d_asserts, q, doFull, d_isInternalSubsolver);
1651
}
1652
1653
10
bool SmtEngine::getInterpol(const Node& conj,
1654
                            const TypeNode& grammarType,
1655
                            Node& interpol)
1656
{
1657
20
  SmtScope smts(this);
1658
10
  finishInit();
1659
10
  bool success = d_interpolSolver->getInterpol(conj, grammarType, interpol);
1660
  // notify the state of whether the get-interpol call was successfuly, which
1661
  // impacts the SMT mode.
1662
10
  d_state->notifyGetInterpol(success);
1663
20
  return success;
1664
}
1665
1666
9
bool SmtEngine::getInterpol(const Node& conj, Node& interpol)
1667
{
1668
18
  TypeNode grammarType;
1669
18
  return getInterpol(conj, grammarType, interpol);
1670
}
1671
1672
15
bool SmtEngine::getAbduct(const Node& conj,
1673
                          const TypeNode& grammarType,
1674
                          Node& abd)
1675
{
1676
30
  SmtScope smts(this);
1677
15
  finishInit();
1678
15
  bool success = d_abductSolver->getAbduct(conj, grammarType, abd);
1679
  // notify the state of whether the get-abduct call was successfuly, which
1680
  // impacts the SMT mode.
1681
13
  d_state->notifyGetAbduct(success);
1682
26
  return success;
1683
}
1684
1685
9
bool SmtEngine::getAbduct(const Node& conj, Node& abd)
1686
{
1687
18
  TypeNode grammarType;
1688
17
  return getAbduct(conj, grammarType, abd);
1689
}
1690
1691
47
void SmtEngine::getInstantiatedQuantifiedFormulas(std::vector<Node>& qs)
1692
{
1693
94
  SmtScope smts(this);
1694
  QuantifiersEngine* qe =
1695
47
      getAvailableQuantifiersEngine("getInstantiatedQuantifiedFormulas");
1696
47
  qe->getInstantiatedQuantifiedFormulas(qs);
1697
47
}
1698
1699
42
void SmtEngine::getInstantiationTermVectors(
1700
    Node q, std::vector<std::vector<Node>>& tvecs)
1701
{
1702
84
  SmtScope smts(this);
1703
  QuantifiersEngine* qe =
1704
42
      getAvailableQuantifiersEngine("getInstantiationTermVectors");
1705
42
  qe->getInstantiationTermVectors(q, tvecs);
1706
42
}
1707
1708
80
std::vector<Node> SmtEngine::getAssertions()
1709
{
1710
160
  SmtScope smts(this);
1711
80
  finishInit();
1712
80
  d_state->doPendingPops();
1713
80
  if (Dump.isOn("benchmark"))
1714
  {
1715
    getPrinter().toStreamCmdGetAssertions(getOutputManager().getDumpOut());
1716
  }
1717
80
  Trace("smt") << "SMT getAssertions()" << endl;
1718
80
  if (!d_env->getOption(options::produceAssertions))
1719
  {
1720
2
    const char* msg =
1721
      "Cannot query the current assertion list when not in produce-assertions mode.";
1722
2
    throw ModalException(msg);
1723
  }
1724
78
  context::CDList<Node>* al = d_asserts->getAssertionList();
1725
78
  Assert(al != nullptr);
1726
78
  std::vector<Node> res;
1727
350
  for (const Node& n : *al)
1728
  {
1729
272
    res.emplace_back(n);
1730
  }
1731
  // copy the result out
1732
156
  return res;
1733
}
1734
1735
3534
void SmtEngine::push()
1736
{
1737
7068
  SmtScope smts(this);
1738
3534
  finishInit();
1739
3534
  d_state->doPendingPops();
1740
3534
  Trace("smt") << "SMT push()" << endl;
1741
3534
  d_smtSolver->processAssertions(*d_asserts);
1742
3534
  if(Dump.isOn("benchmark")) {
1743
    getPrinter().toStreamCmdPush(getOutputManager().getDumpOut());
1744
  }
1745
3534
  d_state->userPush();
1746
3534
}
1747
1748
3000
void SmtEngine::pop() {
1749
6000
  SmtScope smts(this);
1750
3000
  finishInit();
1751
3000
  Trace("smt") << "SMT pop()" << endl;
1752
3000
  if (Dump.isOn("benchmark"))
1753
  {
1754
    getPrinter().toStreamCmdPop(getOutputManager().getDumpOut());
1755
  }
1756
3000
  d_state->userPop();
1757
1758
  // Clear out assertion queues etc., in case anything is still in there
1759
3000
  d_asserts->clearCurrent();
1760
  // clear the learned literals from the preprocessor
1761
3000
  d_pp->clearLearnedLiterals();
1762
1763
6000
  Trace("userpushpop") << "SmtEngine: popped to level "
1764
3000
                       << getUserContext()->getLevel() << endl;
1765
  // should we reset d_status here?
1766
  // SMT-LIBv2 spec seems to imply no, but it would make sense to..
1767
3000
}
1768
1769
39
void SmtEngine::resetAssertions()
1770
{
1771
74
  SmtScope smts(this);
1772
1773
39
  if (!d_state->isFullyInited())
1774
  {
1775
    // We're still in Start Mode, nothing asserted yet, do nothing.
1776
    // (see solver execution modes in the SMT-LIB standard)
1777
4
    Assert(getContext()->getLevel() == 0);
1778
4
    Assert(getUserContext()->getLevel() == 0);
1779
4
    getDumpManager()->resetAssertions();
1780
4
    return;
1781
  }
1782
1783
1784
35
  Trace("smt") << "SMT resetAssertions()" << endl;
1785
35
  if (Dump.isOn("benchmark"))
1786
  {
1787
    getPrinter().toStreamCmdResetAssertions(getOutputManager().getDumpOut());
1788
  }
1789
1790
35
  d_asserts->clearCurrent();
1791
35
  d_state->notifyResetAssertions();
1792
35
  getDumpManager()->resetAssertions();
1793
  // push the state to maintain global context around everything
1794
35
  d_state->setup();
1795
1796
  // reset SmtSolver, which will construct a new prop engine
1797
35
  d_smtSolver->resetAssertions();
1798
}
1799
1800
void SmtEngine::interrupt()
1801
{
1802
  if (!d_state->isFullyInited())
1803
  {
1804
    return;
1805
  }
1806
  d_smtSolver->interrupt();
1807
}
1808
1809
void SmtEngine::setResourceLimit(uint64_t units, bool cumulative)
1810
{
1811
  if (cumulative)
1812
  {
1813
    d_env->d_options.set(options::cumulativeResourceLimit__option_t(), units);
1814
  }
1815
  else
1816
  {
1817
    d_env->d_options.set(options::perCallResourceLimit__option_t(), units);
1818
  }
1819
}
1820
void SmtEngine::setTimeLimit(uint64_t millis)
1821
{
1822
  d_env->d_options.set(options::perCallMillisecondLimit__option_t(), millis);
1823
}
1824
1825
unsigned long SmtEngine::getResourceUsage() const
1826
{
1827
  return getResourceManager()->getResourceUsage();
1828
}
1829
1830
unsigned long SmtEngine::getTimeUsage() const
1831
{
1832
  return getResourceManager()->getTimeUsage();
1833
}
1834
1835
unsigned long SmtEngine::getResourceRemaining() const
1836
{
1837
  return getResourceManager()->getResourceRemaining();
1838
}
1839
1840
794835
NodeManager* SmtEngine::getNodeManager() const
1841
{
1842
794835
  return d_env->getNodeManager();
1843
}
1844
1845
void SmtEngine::printStatistics(std::ostream& out) const
1846
{
1847
  d_env->getStatisticsRegistry().print(out);
1848
}
1849
1850
void SmtEngine::printStatisticsSafe(int fd) const
1851
{
1852
  d_env->getStatisticsRegistry().printSafe(fd);
1853
}
1854
1855
void SmtEngine::printStatisticsDiff(std::ostream& out) const
1856
{
1857
  d_env->getStatisticsRegistry().printDiff(out);
1858
  d_env->getStatisticsRegistry().storeSnapshot();
1859
}
1860
1861
202
void SmtEngine::setUserAttribute(const std::string& attr,
1862
                                 Node expr,
1863
                                 const std::vector<Node>& expr_values,
1864
                                 const std::string& str_value)
1865
{
1866
404
  SmtScope smts(this);
1867
202
  finishInit();
1868
202
  TheoryEngine* te = getTheoryEngine();
1869
202
  Assert(te != nullptr);
1870
202
  te->setUserAttribute(attr, expr, expr_values, str_value);
1871
202
}
1872
1873
9281
void SmtEngine::setOption(const std::string& key, const std::string& value)
1874
{
1875
18558
  NodeManagerScope nms(getNodeManager());
1876
9281
  Trace("smt") << "SMT setOption(" << key << ", " << value << ")" << endl;
1877
1878
9281
  if (Dump.isOn("benchmark"))
1879
  {
1880
4
    getPrinter().toStreamCmdSetOption(
1881
2
        getOutputManager().getDumpOut(), key, value);
1882
  }
1883
1884
9281
  if (key == "command-verbosity")
1885
  {
1886
4
    size_t fstIndex = value.find(" ");
1887
4
    size_t sndIndex = value.find(" ", fstIndex + 1);
1888
4
    if (sndIndex == std::string::npos)
1889
    {
1890
8
      string c = value.substr(1, fstIndex - 1);
1891
      int v =
1892
4
          std::stoi(value.substr(fstIndex + 1, value.length() - fstIndex - 1));
1893
4
      if (v < 0 || v > 2)
1894
      {
1895
        throw OptionException("command-verbosity must be 0, 1, or 2");
1896
      }
1897
4
      d_commandVerbosity[c] = v;
1898
4
      return;
1899
    }
1900
    throw OptionException(
1901
        "command-verbosity value must be a tuple (command-name integer)");
1902
  }
1903
1904
9277
  if (value.find(" ") != std::string::npos)
1905
  {
1906
    throw OptionException("bad value for :" + key);
1907
  }
1908
1909
18554
  std::string optionarg = value;
1910
9277
  getOptions().setOption(key, optionarg);
1911
}
1912
1913
2575
void SmtEngine::setIsInternalSubsolver() { d_isInternalSubsolver = true; }
1914
1915
12881
bool SmtEngine::isInternalSubsolver() const { return d_isInternalSubsolver; }
1916
1917
596799
std::string SmtEngine::getOption(const std::string& key) const
1918
{
1919
1193598
  NodeManagerScope nms(getNodeManager());
1920
596799
  NodeManager* nm = d_env->getNodeManager();
1921
1922
596799
  Trace("smt") << "SMT getOption(" << key << ")" << endl;
1923
1924
596799
  if (key.find("command-verbosity:") == 0)
1925
  {
1926
596767
    auto it = d_commandVerbosity.find(key.substr(std::strlen("command-verbosity:")));
1927
596767
    if (it != d_commandVerbosity.end())
1928
    {
1929
      return std::to_string(it->second);
1930
    }
1931
596767
    it = d_commandVerbosity.find("*");
1932
596767
    if (it != d_commandVerbosity.end())
1933
    {
1934
32
      return std::to_string(it->second);
1935
    }
1936
596735
    return "2";
1937
  }
1938
1939
32
  if (Dump.isOn("benchmark"))
1940
  {
1941
    getPrinter().toStreamCmdGetOption(d_outMgr.getDumpOut(), key);
1942
  }
1943
1944
32
  if (key == "command-verbosity")
1945
  {
1946
6
    vector<Node> result;
1947
6
    Node defaultVerbosity;
1948
7
    for (const auto& verb: d_commandVerbosity)
1949
    {
1950
      // treat the command name as a variable name as opposed to a string
1951
      // constant to avoid printing double quotes around the name
1952
8
      Node name = nm->mkBoundVar(verb.first, nm->integerType());
1953
8
      Node value = nm->mkConst(Rational(verb.second));
1954
4
      if (verb.first == "*")
1955
      {
1956
        // put the default at the end of the SExpr
1957
2
        defaultVerbosity = nm->mkNode(Kind::SEXPR, name, value);
1958
      }
1959
      else
1960
      {
1961
2
        result.push_back(nm->mkNode(Kind::SEXPR, name, value));
1962
      }
1963
    }
1964
    // ensure the default is always listed
1965
3
    if (defaultVerbosity.isNull())
1966
    {
1967
3
      defaultVerbosity = nm->mkNode(Kind::SEXPR,
1968
2
                                    nm->mkBoundVar("*", nm->integerType()),
1969
2
                                    nm->mkConst(Rational(2)));
1970
    }
1971
3
    result.push_back(defaultVerbosity);
1972
3
    return nm->mkNode(Kind::SEXPR, result).toString();
1973
  }
1974
1975
56
  std::string atom = getOptions().getOption(key);
1976
1977
27
  if (atom != "true" && atom != "false")
1978
  {
1979
    try
1980
    {
1981
3
      Integer z(atom);
1982
    }
1983
4
    catch (std::invalid_argument&)
1984
    {
1985
2
      atom = "\"" + atom + "\"";
1986
    }
1987
  }
1988
1989
27
  return atom;
1990
}
1991
1992
4335632
Options& SmtEngine::getOptions() { return d_env->d_options; }
1993
1994
29
const Options& SmtEngine::getOptions() const { return d_env->getOptions(); }
1995
1996
6469887
ResourceManager* SmtEngine::getResourceManager() const
1997
{
1998
6469887
  return d_env->getResourceManager();
1999
}
2000
2001
21863
DumpManager* SmtEngine::getDumpManager() { return d_env->getDumpManager(); }
2002
2003
10
const Printer& SmtEngine::getPrinter() const { return d_env->getPrinter(); }
2004
2005
18985
OutputManager& SmtEngine::getOutputManager() { return d_outMgr; }
2006
2007
27836183
theory::Rewriter* SmtEngine::getRewriter() { return d_env->getRewriter(); }
2008
2009
28191
}  // namespace cvc5