1 /******************************************************************************
2 * Top contributors (to current version):
3 * Andrew Reynolds, Aina Niemetz, Gereon Kremer
5 * This file is part of the cvc5 project.
7 * Copyright (c) 2009-2022 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 * ****************************************************************************
13 * The main entry point into the cvc5 library's SMT interface.
16 #include "smt/solver_engine.h"
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 "expr/node_algorithm.h"
26 #include "options/base_options.h"
27 #include "options/expr_options.h"
28 #include "options/language.h"
29 #include "options/main_options.h"
30 #include "options/option_exception.h"
31 #include "options/options_public.h"
32 #include "options/parser_options.h"
33 #include "options/printer_options.h"
34 #include "options/quantifiers_options.h"
35 #include "options/proof_options.h"
36 #include "options/smt_options.h"
37 #include "options/theory_options.h"
38 #include "printer/printer.h"
39 #include "proof/unsat_core.h"
40 #include "prop/prop_engine.h"
41 #include "smt/abduction_solver.h"
42 #include "smt/abstract_values.h"
43 #include "smt/assertions.h"
44 #include "smt/check_models.h"
46 #include "smt/interpolation_solver.h"
47 #include "smt/listeners.h"
48 #include "smt/logic_exception.h"
49 #include "smt/model_blocker.h"
50 #include "smt/model_core_builder.h"
51 #include "smt/preprocessor.h"
52 #include "smt/proof_manager.h"
53 #include "smt/quant_elim_solver.h"
54 #include "smt/set_defaults.h"
55 #include "smt/smt_solver.h"
56 #include "smt/solver_engine_scope.h"
57 #include "smt/solver_engine_state.h"
58 #include "smt/solver_engine_stats.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/oracle_engine.h"
63 #include "theory/quantifiers/quantifiers_attributes.h"
64 #include "theory/quantifiers_engine.h"
65 #include "theory/rewriter.h"
66 #include "theory/smt_engine_subsolver.h"
67 #include "theory/theory_engine.h"
68 #include "util/random.h"
69 #include "util/rational.h"
70 #include "util/resource_manager.h"
71 #include "util/sexpr.h"
72 #include "util/statistics_registry.h"
74 // required for hacks related to old proofs for unsat cores
75 #include "base/configuration.h"
76 #include "base/configuration_private.h"
79 using namespace cvc5::internal::smt
;
80 using namespace cvc5::internal::preprocessing
;
81 using namespace cvc5::internal::prop
;
82 using namespace cvc5::context
;
83 using namespace cvc5::internal::theory
;
85 namespace cvc5::internal
{
87 SolverEngine::SolverEngine(NodeManager
* nm
, const Options
* optr
)
88 : d_env(new Env(nm
, optr
)),
89 d_state(new SolverEngineState(*d_env
.get(), *this)),
90 d_absValues(new AbstractValues
),
91 d_asserts(new Assertions(*d_env
.get(), *d_absValues
.get())),
92 d_routListener(new ResourceOutListener(*this)),
94 d_checkModels(nullptr),
97 d_sygusSolver(nullptr),
98 d_abductSolver(nullptr),
99 d_interpolSolver(nullptr),
100 d_quantElimSolver(nullptr),
101 d_isInternalSubsolver(false),
105 // !!!!!!!!!!!!!!!!!!!!!! temporary hack: this makes the current SolverEngine
106 // we are constructing the current SolverEngine in scope for the lifetime of
107 // this SolverEngine, or until another SolverEngine is constructed (that
108 // SolverEngine is then in scope during its lifetime). This is mostly to
109 // ensure that options are always in scope, for e.g. printing expressions,
110 // which rely on knowing the output language. Notice that the SolverEngine may
111 // spawn new SolverEngine "subsolvers" internally. These are created, used,
112 // and deleted in a modular fashion while not interleaving calls to the master
113 // SolverEngine. Thus the hack here does not break this use case. On the other
114 // hand, this hack breaks use cases where multiple SolverEngine objects are
115 // created by the user.
116 d_scope
.reset(new SolverEngineScope(this));
117 // listen to resource out
118 getResourceManager()->registerListener(d_routListener
.get());
120 d_stats
.reset(new SolverEngineStatistics());
121 // make the SMT solver
122 d_smtSolver
.reset(new SmtSolver(*d_env
, *d_absValues
, *d_stats
));
123 // make the SyGuS solver
124 d_sygusSolver
.reset(new SygusSolver(*d_env
.get(), *d_smtSolver
));
125 // make the quantifier elimination solver
126 d_quantElimSolver
.reset(new QuantElimSolver(*d_env
.get(), *d_smtSolver
));
129 bool SolverEngine::isFullyInited() const { return d_state
->isFullyInited(); }
130 bool SolverEngine::isQueryMade() const { return d_state
->isQueryMade(); }
131 size_t SolverEngine::getNumUserLevels() const
133 return d_state
->getNumUserLevels();
135 SmtMode
SolverEngine::getSmtMode() const { return d_state
->getMode(); }
136 bool SolverEngine::isSmtModeSat() const
138 SmtMode mode
= getSmtMode();
139 return mode
== SmtMode::SAT
|| mode
== SmtMode::SAT_UNKNOWN
;
141 Result
SolverEngine::getStatusOfLastCommand() const
143 return d_state
->getStatus();
145 UserContext
* SolverEngine::getUserContext()
147 return d_env
->getUserContext();
149 Context
* SolverEngine::getContext()
151 return d_env
->getContext();
154 TheoryEngine
* SolverEngine::getTheoryEngine()
156 return d_smtSolver
->getTheoryEngine();
159 prop::PropEngine
* SolverEngine::getPropEngine()
161 return d_smtSolver
->getPropEngine();
164 void SolverEngine::finishInit()
166 if (d_state
->isFullyInited())
168 // already initialized, return
172 // Notice that finishInitInternal is called when options are finalized. If we
173 // are parsing smt2, this occurs at the moment we enter "Assert mode", page 52
174 // of SMT-LIB 2.6 standard.
177 const LogicInfo
& logic
= getLogicInfo();
178 if (!logic
.isLocked())
183 // set the random seed
184 Random::getRandom().setSeed(d_env
->getOptions().driver
.seed
);
186 // Call finish init on the set defaults module. This inializes the logic
187 // and the best default options based on our heuristics.
188 SetDefaults
sdefaults(*d_env
, d_isInternalSubsolver
);
189 sdefaults
.setDefaults(d_env
->d_logic
, getOptions());
191 if (d_env
->getOptions().smt
.produceProofs
)
193 // ensure bound variable uses canonical bound variables
194 getNodeManager()->getBoundVarManager()->enableKeepCacheValues();
195 // make the proof manager
196 d_pfManager
.reset(new PfManager(*d_env
.get()));
197 PreprocessProofGenerator
* pppg
= d_pfManager
->getPreprocessProofGenerator();
198 // start the unsat core manager
199 d_ucManager
.reset(new UnsatCoreManager());
200 // enable it in the assertions pipeline
201 d_asserts
->enableProofs(pppg
);
202 // enabled proofs in the preprocessor
203 d_smtSolver
->getPreprocessor()->enableProofs(pppg
);
206 Trace("smt-debug") << "SolverEngine::finishInit" << std::endl
;
207 d_smtSolver
->finishInit();
209 // now can construct the SMT-level model object
210 TheoryEngine
* te
= d_smtSolver
->getTheoryEngine();
211 Assert(te
!= nullptr);
212 TheoryModel
* tm
= te
->getModel();
215 // make the check models utility
216 d_checkModels
.reset(new CheckModels(*d_env
.get()));
219 // global push/pop around everything, to ensure proper destruction
220 // of context-dependent data structures
224 if (d_env
->getOptions().smt
.produceAbducts
)
226 d_abductSolver
.reset(new AbductionSolver(*d_env
.get()));
228 if (d_env
->getOptions().smt
.interpolants
)
230 d_interpolSolver
.reset(new InterpolationSolver(*d_env
));
233 AlwaysAssert(getPropEngine()->getAssertionLevel() == 0)
234 << "The PropEngine has pushed but the SolverEngine "
235 "hasn't finished initializing!";
237 Assert(getLogicInfo().isLocked());
239 // store that we are finished initializing
240 d_state
->finishInit();
241 Trace("smt-debug") << "SolverEngine::finishInit done" << std::endl
;
244 void SolverEngine::shutdown()
250 SolverEngine::~SolverEngine()
252 SolverEngineScope
smts(this);
258 // global push/pop around everything, to ensure proper destruction
259 // of context-dependent data structures
262 // destroy all passes before destroying things that they refer to
263 d_smtSolver
->getPreprocessor()->cleanup();
265 d_pfManager
.reset(nullptr);
266 d_ucManager
.reset(nullptr);
268 d_absValues
.reset(nullptr);
269 d_asserts
.reset(nullptr);
271 d_abductSolver
.reset(nullptr);
272 d_interpolSolver
.reset(nullptr);
273 d_quantElimSolver
.reset(nullptr);
274 d_sygusSolver
.reset(nullptr);
275 d_smtSolver
.reset(nullptr);
277 d_stats
.reset(nullptr);
278 d_routListener
.reset(nullptr);
280 d_state
.reset(nullptr);
281 // destroy the environment
282 d_env
.reset(nullptr);
286 d_env
->warning() << "cvc5 threw an exception during cleanup." << std::endl
<< e
<< std::endl
;
290 void SolverEngine::setLogic(const LogicInfo
& logic
)
292 SolverEngineScope
smts(this);
293 if (d_state
->isFullyInited())
295 throw ModalException(
296 "Cannot set logic in SolverEngine after the engine has "
297 "finished initializing.");
299 d_env
->d_logic
= logic
;
304 void SolverEngine::setLogic(const std::string
& s
)
306 SolverEngineScope
smts(this);
309 setLogic(LogicInfo(s
));
311 catch (IllegalArgumentException
& e
)
313 throw LogicException(e
.what());
317 void SolverEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
319 const LogicInfo
& SolverEngine::getLogicInfo() const
321 return d_env
->getLogicInfo();
324 LogicInfo
SolverEngine::getUserLogicInfo() const
326 // Lock the logic to make sure that this logic can be queried. We create a
327 // copy of the user logic here to keep this method const.
328 LogicInfo res
= d_userLogic
;
333 void SolverEngine::setLogicInternal()
335 Assert(!d_state
->isFullyInited())
336 << "setting logic in SolverEngine but the engine has already"
337 " finished initializing for this run";
338 d_env
->d_logic
.lock();
342 void SolverEngine::setInfo(const std::string
& key
, const std::string
& value
)
344 SolverEngineScope
smts(this);
346 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
348 if (key
== "filename")
350 d_env
->d_options
.writeDriver().filename
= value
;
351 d_env
->getStatisticsRegistry().registerValue
<std::string
>(
352 "driver::filename", value
);
354 else if (key
== "smt-lib-version"
355 && !getOptions().base
.inputLanguageWasSetByUser
)
357 if (value
!= "2" && value
!= "2.6")
359 d_env
->warning() << "SMT-LIB version " << value
360 << " unsupported, defaulting to language (and semantics of) "
363 getOptions().writeBase().inputLanguage
= Language::LANG_SMTLIB_V2_6
;
364 // also update the output language
365 if (!getOptions().printer
.outputLanguageWasSetByUser
)
367 setOption("output-language", "smtlib2.6");
368 getOptions().writePrinter().outputLanguageWasSetByUser
= false;
371 else if (key
== "status")
373 d_state
->notifyExpectedStatus(value
);
377 bool SolverEngine::isValidGetInfoFlag(const std::string
& key
) const
379 if (key
== "all-statistics" || key
== "error-behavior" || key
== "filename"
380 || key
== "name" || key
== "version" || key
== "authors"
381 || key
== "status" || key
== "time" || key
== "reason-unknown"
382 || key
== "assertion-stack-levels" || key
== "all-options")
389 std::string
SolverEngine::getInfo(const std::string
& key
) const
391 SolverEngineScope
smts(this);
393 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
394 if (key
== "all-statistics")
396 return toSExpr(d_env
->getStatisticsRegistry().begin(),
397 d_env
->getStatisticsRegistry().end());
399 if (key
== "error-behavior")
401 return "immediate-exit";
403 if (key
== "filename")
405 return d_env
->getOptions().driver
.filename
;
409 return toSExpr(Configuration::getName());
411 if (key
== "version")
413 return toSExpr(Configuration::getVersionString());
415 if (key
== "authors")
417 return toSExpr("the " + Configuration::getName() + " authors");
421 // sat | unsat | unknown
422 Result status
= d_state
->getStatus();
423 switch (status
.getStatus())
425 case Result::SAT
: return "sat";
426 case Result::UNSAT
: return "unsat";
427 default: return "unknown";
432 return toSExpr(std::clock());
434 if (key
== "reason-unknown")
436 Result status
= d_state
->getStatus();
437 if (!status
.isNull() && status
.isUnknown())
439 std::stringstream ss
;
440 ss
<< status
.getUnknownExplanation();
441 std::string s
= ss
.str();
442 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
447 throw RecoverableModalException(
448 "Can't get-info :reason-unknown when the "
449 "last result wasn't unknown!");
452 if (key
== "assertion-stack-levels")
454 size_t ulevel
= d_state
->getNumUserLevels();
455 AlwaysAssert(ulevel
<= std::numeric_limits
<unsigned long int>::max());
456 return toSExpr(ulevel
);
458 Assert(key
== "all-options");
459 // get the options, like all-statistics
460 std::vector
<std::vector
<std::string
>> res
;
461 for (const auto& opt
: options::getNames())
464 std::vector
<std::string
>{opt
, options::get(getOptions(), opt
)});
469 void SolverEngine::debugCheckFormals(const std::vector
<Node
>& formals
,
472 for (std::vector
<Node
>::const_iterator i
= formals
.begin();
476 if ((*i
).getKind() != kind::BOUND_VARIABLE
)
479 ss
<< "All formal arguments to defined functions must be "
480 "BOUND_VARIABLEs, but in the\n"
481 << "definition of function " << func
<< ", formal\n"
483 << "has kind " << (*i
).getKind();
484 throw TypeCheckingExceptionPrivate(func
, ss
.str());
489 void SolverEngine::debugCheckFunctionBody(Node formula
,
490 const std::vector
<Node
>& formals
,
493 TypeNode formulaType
= formula
.getType(d_env
->getOptions().expr
.typeChecking
);
494 TypeNode funcType
= func
.getType();
495 // We distinguish here between definitions of constants and functions,
496 // because the type checking for them is subtly different. Perhaps we
497 // should instead have SolverEngine::defineFunction() and
498 // SolverEngine::defineConstant() for better clarity, although then that
499 // doesn't match the SMT-LIBv2 standard...
500 if (formals
.size() > 0)
502 TypeNode rangeType
= funcType
.getRangeType();
503 if (formulaType
!= rangeType
)
506 ss
<< "Type of defined function does not match its declaration\n"
507 << "The function : " << func
<< "\n"
508 << "Declared type : " << rangeType
<< "\n"
509 << "The body : " << formula
<< "\n"
510 << "Body type : " << formulaType
;
511 throw TypeCheckingExceptionPrivate(func
, ss
.str());
516 if (formulaType
!= funcType
)
519 ss
<< "Declared type of defined constant does not match its definition\n"
520 << "The constant : " << func
<< "\n"
521 << "Declared type : " << funcType
<< "\n"
522 << "The definition : " << formula
<< "\n"
523 << "Definition type: " << formulaType
;
524 throw TypeCheckingExceptionPrivate(func
, ss
.str());
529 void SolverEngine::defineFunction(Node func
,
530 const std::vector
<Node
>& formals
,
534 SolverEngineScope
smts(this);
536 d_state
->doPendingPops();
537 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
538 debugCheckFormals(formals
, func
);
541 debugCheckFunctionBody(formula
, formals
, func
);
543 // Substitute out any abstract values in formula
544 Node def
= d_absValues
->substituteAbstractValues(formula
);
545 if (!formals
.empty())
547 NodeManager
* nm
= NodeManager::currentNM();
549 kind::LAMBDA
, nm
->mkNode(kind::BOUND_VAR_LIST
, formals
), def
);
551 // A define-fun is treated as a (higher-order) assertion. It is provided
552 // to the assertions object. It will be added as a top-level substitution
553 // within this class, possibly multiple times if global is true.
554 Node feq
= func
.eqNode(def
);
555 d_asserts
->addDefineFunDefinition(feq
, global
);
558 void SolverEngine::defineFunctionsRec(
559 const std::vector
<Node
>& funcs
,
560 const std::vector
<std::vector
<Node
>>& formals
,
561 const std::vector
<Node
>& formulas
,
564 SolverEngineScope
smts(this);
566 d_state
->doPendingPops();
567 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
569 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
572 ss
<< "Number of functions, formals, and function bodies passed to "
573 "defineFunctionsRec do not match:"
575 << " #functions : " << funcs
.size() << "\n"
576 << " #arg lists : " << formals
.size() << "\n"
577 << " #function bodies : " << formulas
.size() << "\n";
578 throw ModalException(ss
.str());
580 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
582 // check formal argument list
583 debugCheckFormals(formals
[i
], funcs
[i
]);
585 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
588 NodeManager
* nm
= getNodeManager();
589 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
591 // we assert a quantified formula
593 // make the function application
594 if (formals
[i
].empty())
596 // it has no arguments
601 std::vector
<Node
> children
;
602 children
.push_back(funcs
[i
]);
603 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
604 func_app
= nm
->mkNode(kind::APPLY_UF
, children
);
606 Node lem
= nm
->mkNode(kind::EQUAL
, func_app
, formulas
[i
]);
607 if (!formals
[i
].empty())
609 // set the attribute to denote this is a function definition
610 Node aexpr
= nm
->mkNode(kind::INST_ATTRIBUTE
, func_app
);
611 aexpr
= nm
->mkNode(kind::INST_PATTERN_LIST
, aexpr
);
613 func_app
.setAttribute(fda
, true);
614 // make the quantified formula
615 Node boundVars
= nm
->mkNode(kind::BOUND_VAR_LIST
, formals
[i
]);
616 lem
= nm
->mkNode(kind::FORALL
, boundVars
, lem
, aexpr
);
618 // Assert the quantified formula. Notice we don't call assertFormula
619 // directly, since we should call a private member method since we have
620 // already ensuring this SolverEngine is initialized above.
621 // add define recursive definition to the assertions
622 d_asserts
->addDefineFunDefinition(lem
, global
);
626 void SolverEngine::defineFunctionRec(Node func
,
627 const std::vector
<Node
>& formals
,
631 std::vector
<Node
> funcs
;
632 funcs
.push_back(func
);
633 std::vector
<std::vector
<Node
>> formals_multi
;
634 formals_multi
.push_back(formals
);
635 std::vector
<Node
> formulas
;
636 formulas
.push_back(formula
);
637 defineFunctionsRec(funcs
, formals_multi
, formulas
, global
);
640 TheoryModel
* SolverEngine::getAvailableModel(const char* c
) const
642 if (!d_env
->getOptions().theory
.assignFunctionValues
)
644 std::stringstream ss
;
645 ss
<< "Cannot " << c
<< " when --assign-function-values is false.";
646 throw RecoverableModalException(ss
.str().c_str());
649 if (d_state
->getMode() != SmtMode::SAT
650 && d_state
->getMode() != SmtMode::SAT_UNKNOWN
)
652 std::stringstream ss
;
654 << " unless immediately preceded by SAT/NOT_ENTAILED or UNKNOWN "
656 throw RecoverableModalException(ss
.str().c_str());
659 if (!d_env
->getOptions().smt
.produceModels
)
661 std::stringstream ss
;
662 ss
<< "Cannot " << c
<< " when produce-models options is off.";
663 throw ModalException(ss
.str().c_str());
666 TheoryEngine
* te
= d_smtSolver
->getTheoryEngine();
667 Assert(te
!= nullptr);
668 TheoryModel
* m
= te
->getBuiltModel();
672 std::stringstream ss
;
674 << " since model is not available. Perhaps the most recent call to "
675 "check-sat was interrupted?";
676 throw RecoverableModalException(ss
.str().c_str());
678 // compute the model core if necessary and not done so already
679 const Options
& opts
= d_env
->getOptions();
680 if (opts
.smt
.modelCoresMode
!= options::ModelCoresMode::NONE
681 && !m
->isUsingModelCore())
683 // If we enabled model cores, we compute a model core for m based on our
684 // (expanded) assertions using the model core builder utility. Notice that
685 // we get the assertions using the getAssertionsInternal, which does not
686 // impact whether we are in "sat" mode
687 std::vector
<Node
> asserts
= getAssertionsInternal();
688 d_smtSolver
->getPreprocessor()->expandDefinitions(asserts
);
689 ModelCoreBuilder
mcb(*d_env
.get());
690 mcb
.setModelCore(asserts
, m
, opts
.smt
.modelCoresMode
);
696 QuantifiersEngine
* SolverEngine::getAvailableQuantifiersEngine(
699 QuantifiersEngine
* qe
= d_smtSolver
->getQuantifiersEngine();
702 std::stringstream ss
;
703 ss
<< "Cannot " << c
<< " when quantifiers are not present.";
704 throw ModalException(ss
.str().c_str());
709 void SolverEngine::notifyPushPre()
711 d_smtSolver
->processAssertions(*d_asserts
);
714 void SolverEngine::notifyPushPost()
716 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
717 Assert(getPropEngine() != nullptr);
718 getPropEngine()->push();
721 void SolverEngine::notifyPopPre()
723 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
724 PropEngine
* pe
= getPropEngine();
725 Assert(pe
!= nullptr);
729 void SolverEngine::notifyPostSolvePre()
731 PropEngine
* pe
= getPropEngine();
732 Assert(pe
!= nullptr);
736 void SolverEngine::notifyPostSolvePost()
738 TheoryEngine
* te
= getTheoryEngine();
739 Assert(te
!= nullptr);
743 Result
SolverEngine::checkSat()
746 return checkSat(nullNode
);
749 Result
SolverEngine::checkSat(const Node
& assumption
)
751 ensureWellFormedTerm(assumption
, "checkSat");
752 std::vector
<Node
> assump
;
753 if (!assumption
.isNull())
755 assump
.push_back(assumption
);
757 return checkSatInternal(assump
);
760 Result
SolverEngine::checkSat(const std::vector
<Node
>& assumptions
)
762 ensureWellFormedTerms(assumptions
, "checkSat");
763 return checkSatInternal(assumptions
);
766 Result
SolverEngine::checkSatInternal(const std::vector
<Node
>& assumptions
)
768 SolverEngineScope
smts(this);
771 Trace("smt") << "SolverEngine::checkSat(" << assumptions
<< ")" << endl
;
772 // update the state to indicate we are about to run a check-sat
773 bool hasAssumptions
= !assumptions
.empty();
774 d_state
->notifyCheckSat(hasAssumptions
);
776 // state should be fully ready now
777 Assert(d_state
->isFullyReady());
779 // check the satisfiability with the solver object
780 Assertions
& as
= *d_asserts
.get();
781 Result r
= d_smtSolver
->checkSatisfiability(as
, assumptions
);
783 // If the result is unknown, we may optionally do a "deep restart" where
784 // the members of the SMT solver are reconstructed and given the
785 // preprocessed input formulas (plus additional learned formulas). Notice
786 // that assumptions are pushed to the preprocessed input in the above call, so
787 // any additional satisfiability checks use an empty set of assumptions.
788 while (r
.getStatus() == Result::UNKNOWN
&& deepRestart())
790 Trace("smt") << "SolverEngine::checkSat after deep restart" << std::endl
;
791 r
= d_smtSolver
->checkSatisfiability(as
, {});
794 Trace("smt") << "SolverEngine::checkSat(" << assumptions
<< ") => " << r
796 // notify our state of the check-sat result
797 d_state
->notifyCheckSatResult(hasAssumptions
, r
);
799 // Check that SAT results generate a model correctly.
800 if (d_env
->getOptions().smt
.checkModels
)
802 if (r
.getStatus() == Result::SAT
)
807 // Check that UNSAT results generate a proof correctly.
808 if (d_env
->getOptions().smt
.checkProofs
)
810 if (r
.getStatus() == Result::UNSAT
)
815 // Check that UNSAT results generate an unsat core correctly.
816 if (d_env
->getOptions().smt
.checkUnsatCores
)
818 if (r
.getStatus() == Result::UNSAT
)
820 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
825 if (d_env
->getOptions().base
.statisticsEveryQuery
)
827 printStatisticsDiff();
832 std::vector
<Node
> SolverEngine::getUnsatAssumptions(void)
834 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
835 SolverEngineScope
smts(this);
836 if (!d_env
->getOptions().smt
.unsatAssumptions
)
838 throw ModalException(
839 "Cannot get unsat assumptions when produce-unsat-assumptions option "
842 if (d_state
->getMode() != SmtMode::UNSAT
)
844 throw RecoverableModalException(
845 "Cannot get unsat assumptions unless immediately preceded by "
849 UnsatCore core
= getUnsatCoreInternal();
850 std::vector
<Node
> res
;
851 std::vector
<Node
>& assumps
= d_asserts
->getAssumptions();
852 for (const Node
& e
: assumps
)
854 if (std::find(core
.begin(), core
.end(), e
) != core
.end())
862 void SolverEngine::assertFormula(const Node
& formula
)
864 SolverEngineScope
smts(this);
866 d_state
->doPendingPops();
867 ensureWellFormedTerm(formula
, "assertFormula");
868 assertFormulaInternal(formula
);
871 void SolverEngine::assertFormulaInternal(const Node
& formula
)
873 // as an optimization we do not check whether formula is well-formed here, and
874 // defer this check for certain cases within the assertions module.
875 Trace("smt") << "SolverEngine::assertFormula(" << formula
<< ")" << endl
;
877 // Substitute out any abstract values in ex
878 Node n
= d_absValues
->substituteAbstractValues(formula
);
880 d_asserts
->assertFormula(n
);
884 --------------------------------------------------------------------------
885 Handling SyGuS commands
886 --------------------------------------------------------------------------
889 void SolverEngine::declareSygusVar(Node var
)
891 SolverEngineScope
smts(this);
892 d_sygusSolver
->declareSygusVar(var
);
895 void SolverEngine::declareSynthFun(Node func
,
898 const std::vector
<Node
>& vars
)
900 SolverEngineScope
smts(this);
902 d_state
->doPendingPops();
903 d_sygusSolver
->declareSynthFun(func
, sygusType
, isInv
, vars
);
905 void SolverEngine::declareSynthFun(Node func
,
907 const std::vector
<Node
>& vars
)
909 // use a null sygus type
911 declareSynthFun(func
, sygusType
, isInv
, vars
);
914 void SolverEngine::assertSygusConstraint(Node n
, bool isAssume
)
916 SolverEngineScope
smts(this);
918 d_sygusSolver
->assertSygusConstraint(n
, isAssume
);
921 void SolverEngine::assertSygusInvConstraint(Node inv
,
926 SolverEngineScope
smts(this);
928 d_sygusSolver
->assertSygusInvConstraint(inv
, pre
, trans
, post
);
931 SynthResult
SolverEngine::checkSynth(bool isNext
)
933 SolverEngineScope
smts(this);
935 if (isNext
&& d_state
->getMode() != SmtMode::SYNTH
)
937 throw RecoverableModalException(
938 "Cannot check-synth-next unless immediately preceded by a successful "
939 "call to check-synth(-next).");
941 SynthResult r
= d_sygusSolver
->checkSynth(*d_asserts
, isNext
);
942 d_state
->notifyCheckSynthResult(r
);
947 --------------------------------------------------------------------------
948 End of Handling SyGuS commands
949 --------------------------------------------------------------------------
952 void SolverEngine::declarePool(const Node
& p
,
953 const std::vector
<Node
>& initValue
)
955 Assert(p
.isVar() && p
.getType().isSet());
957 QuantifiersEngine
* qe
= getAvailableQuantifiersEngine("declareTermPool");
958 qe
->declarePool(p
, initValue
);
961 void SolverEngine::declareOracleFun(
962 Node var
, std::function
<std::vector
<Node
>(const std::vector
<Node
>&)> fn
)
965 d_state
->doPendingPops();
966 QuantifiersEngine
* qe
= getAvailableQuantifiersEngine("declareOracleFun");
967 qe
->declareOracleFun(var
);
968 NodeManager
* nm
= NodeManager::currentNM();
969 std::vector
<Node
> inputs
;
970 std::vector
<Node
> outputs
;
971 TypeNode tn
= var
.getType();
975 const std::vector
<TypeNode
>& argTypes
= tn
.getArgTypes();
976 for (const TypeNode
& t
: argTypes
)
978 inputs
.push_back(nm
->mkBoundVar(t
));
980 outputs
.push_back(nm
->mkBoundVar(tn
.getRangeType()));
981 std::vector
<Node
> appc
;
983 appc
.insert(appc
.end(), inputs
.begin(), inputs
.end());
984 app
= nm
->mkNode(kind::APPLY_UF
, appc
);
988 outputs
.push_back(nm
->mkBoundVar(tn
.getRangeType()));
991 // makes equality assumption
992 Node assume
= nm
->mkNode(kind::EQUAL
, app
, outputs
[0]);
994 Node constraint
= nm
->mkConst(true);
995 // make the oracle constant which carries the method implementation
997 Node o
= NodeManager::currentNM()->mkOracle(oracle
);
998 // set the attribute, which ensures we remember the method implementation for
999 // the oracle function
1000 var
.setAttribute(theory::OracleInterfaceAttribute(), o
);
1001 // define the oracle interface
1002 Node q
= quantifiers::OracleEngine::mkOracleInterface(
1003 inputs
, outputs
, assume
, constraint
, o
);
1008 Node
SolverEngine::simplify(const Node
& ex
)
1010 SolverEngineScope
smts(this);
1012 d_state
->doPendingPops();
1013 // ensure we've processed assertions
1014 d_smtSolver
->processAssertions(*d_asserts
);
1015 return d_smtSolver
->getPreprocessor()->simplify(ex
);
1018 Node
SolverEngine::expandDefinitions(const Node
& ex
)
1020 getResourceManager()->spendResource(Resource::PreprocessStep
);
1021 SolverEngineScope
smts(this);
1023 d_state
->doPendingPops();
1024 return d_smtSolver
->getPreprocessor()->expandDefinitions(ex
);
1027 // TODO(#1108): Simplify the error reporting of this method.
1028 Node
SolverEngine::getValue(const Node
& ex
) const
1030 SolverEngineScope
smts(this);
1032 ensureWellFormedTerm(ex
, "get value");
1033 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
1034 TypeNode expectedType
= ex
.getType();
1036 // Substitute out any abstract values in ex and expand
1037 Node n
= d_smtSolver
->getPreprocessor()->expandDefinitions(ex
);
1039 Trace("smt") << "--- getting value of " << n
<< endl
;
1040 // There are two ways model values for terms are computed (for historical
1041 // reasons). One way is that used in check-model; the other is that
1042 // used by the Model classes. It's not clear to me exactly how these
1043 // two are different, but they need to be unified. This ugly hack here
1044 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
1047 if (!n
.getType().isFunction())
1049 n
= d_env
->getRewriter()->rewrite(n
);
1052 Trace("smt") << "--- getting value of " << n
<< endl
;
1053 TheoryModel
* m
= getAvailableModel("get-value");
1054 Assert(m
!= nullptr);
1055 Node resultNode
= m
->getValue(n
);
1056 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
1057 Trace("smt") << "--- type " << resultNode
.getType() << endl
;
1058 Trace("smt") << "--- expected type " << expectedType
<< endl
;
1060 // type-check the result we got
1061 Assert(resultNode
.isNull() || resultNode
.getType() == expectedType
)
1062 << "Run with -t smt for details.";
1064 // Ensure it's a value (constant or const-ish like real algebraic
1065 // numbers), or a lambda (for uninterpreted functions). This assertion only
1066 // holds for models that do not have approximate values.
1067 if (!m
->isValue(resultNode
))
1069 d_env
->warning() << "Could not evaluate " << resultNode
1070 << " in getValue." << std::endl
;
1073 if (d_env
->getOptions().smt
.abstractValues
&& resultNode
.getType().isArray())
1075 resultNode
= d_absValues
->mkAbstractValue(resultNode
);
1076 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
1082 std::vector
<Node
> SolverEngine::getValues(const std::vector
<Node
>& exprs
) const
1084 std::vector
<Node
> result
;
1085 for (const Node
& e
: exprs
)
1087 result
.push_back(getValue(e
));
1092 std::vector
<Node
> SolverEngine::getModelDomainElements(TypeNode tn
) const
1094 Assert(tn
.isUninterpretedSort());
1095 TheoryModel
* m
= getAvailableModel("getModelDomainElements");
1096 return m
->getDomainElements(tn
);
1099 bool SolverEngine::isModelCoreSymbol(Node n
)
1101 SolverEngineScope
smts(this);
1103 const Options
& opts
= d_env
->getOptions();
1104 if (opts
.smt
.modelCoresMode
== options::ModelCoresMode::NONE
)
1106 // if the model core mode is none, we are always a model core symbol
1109 TheoryModel
* tm
= getAvailableModel("isModelCoreSymbol");
1110 return tm
->isModelCoreSymbol(n
);
1113 std::string
SolverEngine::getModel(const std::vector
<TypeNode
>& declaredSorts
,
1114 const std::vector
<Node
>& declaredFuns
)
1116 SolverEngineScope
smts(this);
1117 // !!! Note that all methods called here should have a version at the API
1118 // level. This is to ensure that the information associated with a model is
1119 // completely accessible by the user. This is currently not rigorously
1120 // enforced. An alternative design would be to have this method implemented
1121 // at the API level, but this makes exceptions in the text interface less
1123 TheoryModel
* tm
= getAvailableModel("get model");
1124 // use the smt::Model model utility for printing
1125 const Options
& opts
= d_env
->getOptions();
1126 bool isKnownSat
= (d_state
->getMode() == SmtMode::SAT
);
1127 Model
m(isKnownSat
, opts
.driver
.filename
);
1128 // set the model declarations, which determines what is printed in the model
1129 for (const TypeNode
& tn
: declaredSorts
)
1131 m
.addDeclarationSort(tn
, getModelDomainElements(tn
));
1133 bool usingModelCores
=
1134 (opts
.smt
.modelCoresMode
!= options::ModelCoresMode::NONE
);
1135 for (const Node
& n
: declaredFuns
)
1137 if (usingModelCores
&& !tm
->isModelCoreSymbol(n
))
1139 // skip if not in model core
1142 Node value
= tm
->getValue(n
);
1143 m
.addDeclarationTerm(n
, value
);
1145 // for separation logic
1146 TypeNode locT
, dataT
;
1147 if (getSepHeapTypes(locT
, dataT
))
1149 std::pair
<Node
, Node
> sh
= getSepHeapAndNilExpr();
1150 m
.setHeapModel(sh
.first
, sh
.second
);
1153 std::stringstream ssm
;
1158 void SolverEngine::blockModel(modes::BlockModelsMode mode
)
1160 Trace("smt") << "SMT blockModel()" << endl
;
1161 SolverEngineScope
smts(this);
1165 TheoryModel
* m
= getAvailableModel("block model");
1167 // get expanded assertions
1168 std::vector
<Node
> eassertsProc
= getExpandedAssertions();
1169 ModelBlocker
mb(*d_env
.get());
1170 Node eblocker
= mb
.getModelBlocker(eassertsProc
, m
, mode
);
1171 Trace("smt") << "Block formula: " << eblocker
<< std::endl
;
1172 assertFormulaInternal(eblocker
);
1175 void SolverEngine::blockModelValues(const std::vector
<Node
>& exprs
)
1177 Trace("smt") << "SMT blockModelValues()" << endl
;
1178 SolverEngineScope
smts(this);
1182 for (const Node
& e
: exprs
)
1184 ensureWellFormedTerm(e
, "block model values");
1187 TheoryModel
* m
= getAvailableModel("block model values");
1189 // get expanded assertions
1190 std::vector
<Node
> eassertsProc
= getExpandedAssertions();
1191 // we always do block model values mode here
1192 ModelBlocker
mb(*d_env
.get());
1193 Node eblocker
= mb
.getModelBlocker(
1194 eassertsProc
, m
, modes::BlockModelsMode::VALUES
, exprs
);
1195 assertFormulaInternal(eblocker
);
1198 std::pair
<Node
, Node
> SolverEngine::getSepHeapAndNilExpr(void)
1200 if (!getLogicInfo().isTheoryEnabled(THEORY_SEP
))
1203 "Cannot obtain separation logic expressions if not using the "
1204 "separation logic theory.";
1205 throw RecoverableModalException(msg
);
1209 TheoryModel
* tm
= getAvailableModel("get separation logic heap and nil");
1210 if (!tm
->getHeapModel(heap
, nil
))
1213 "Failed to obtain heap/nil "
1214 "expressions from theory model.";
1215 throw RecoverableModalException(msg
);
1217 return std::make_pair(heap
, nil
);
1220 std::vector
<Node
> SolverEngine::getAssertionsInternal() const
1222 Assert(d_state
->isFullyInited());
1223 const CDList
<Node
>& al
= d_asserts
->getAssertionList();
1224 std::vector
<Node
> res
;
1225 for (const Node
& n
: al
)
1227 res
.emplace_back(n
);
1232 const Options
& SolverEngine::options() const { return d_env
->getOptions(); }
1234 void SolverEngine::ensureWellFormedTerm(const Node
& n
,
1235 const std::string
& src
) const
1237 if (Configuration::isAssertionBuild())
1239 bool wasShadow
= false;
1240 if (expr::hasFreeOrShadowedVar(n
, wasShadow
))
1242 std::string
varType(wasShadow
? "shadowed" : "free");
1243 std::stringstream se
;
1244 se
<< "Cannot process term with " << varType
<< " variable in " << src
1246 throw ModalException(se
.str().c_str());
1251 void SolverEngine::ensureWellFormedTerms(const std::vector
<Node
>& ns
,
1252 const std::string
& src
) const
1254 if (Configuration::isAssertionBuild())
1256 for (const Node
& n
: ns
)
1258 ensureWellFormedTerm(n
, src
);
1263 std::vector
<Node
> SolverEngine::getExpandedAssertions()
1265 std::vector
<Node
> easserts
= getAssertions();
1266 // must expand definitions
1267 d_smtSolver
->getPreprocessor()->expandDefinitions(easserts
);
1270 Env
& SolverEngine::getEnv() { return *d_env
.get(); }
1272 void SolverEngine::declareSepHeap(TypeNode locT
, TypeNode dataT
)
1274 if (d_state
->isFullyInited())
1276 throw ModalException(
1277 "Cannot set logic in SolverEngine after the engine has "
1278 "finished initializing.");
1280 if (!getLogicInfo().isTheoryEnabled(THEORY_SEP
))
1283 "Cannot declare heap if not using the separation logic theory.";
1284 throw RecoverableModalException(msg
);
1286 TypeNode locT2
, dataT2
;
1287 if (d_env
->getSepHeapTypes(locT2
, dataT2
))
1289 std::stringstream ss
;
1290 ss
<< "ERROR: cannot declare heap types for separation logic more than "
1291 "once. We are declaring heap of type ";
1292 ss
<< locT
<< " -> " << dataT
<< ", but we already have ";
1293 ss
<< locT2
<< " -> " << dataT2
;
1294 throw LogicException(ss
.str());
1296 d_env
->declareSepHeap(locT
, dataT
);
1299 bool SolverEngine::getSepHeapTypes(TypeNode
& locT
, TypeNode
& dataT
)
1301 return d_env
->getSepHeapTypes(locT
, dataT
);
1304 Node
SolverEngine::getSepHeapExpr() { return getSepHeapAndNilExpr().first
; }
1306 Node
SolverEngine::getSepNilExpr() { return getSepHeapAndNilExpr().second
; }
1308 std::vector
<Node
> SolverEngine::getLearnedLiterals()
1310 Trace("smt") << "SMT getLearnedLiterals()" << std::endl
;
1311 SolverEngineScope
smts(this);
1312 // note that the default mode for learned literals is via the prop engine,
1313 // although other modes could use the preprocessor
1314 PropEngine
* pe
= getPropEngine();
1315 Assert(pe
!= nullptr);
1316 return pe
->getLearnedZeroLevelLiterals(modes::LearnedLitType::INPUT
);
1319 void SolverEngine::checkProof()
1321 Assert(d_env
->getOptions().smt
.produceProofs
);
1322 // internal check the proof
1323 PropEngine
* pe
= getPropEngine();
1324 Assert(pe
!= nullptr);
1325 if (d_env
->getOptions().proof
.proofCheck
== options::ProofCheckMode::EAGER
)
1327 pe
->checkProof(d_asserts
->getAssertionList());
1329 Assert(pe
->getProof() != nullptr);
1330 std::shared_ptr
<ProofNode
> pePfn
= pe
->getProof();
1331 if (d_env
->getOptions().smt
.checkProofs
)
1333 d_pfManager
->checkProof(pePfn
, *d_asserts
);
1337 StatisticsRegistry
& SolverEngine::getStatisticsRegistry()
1339 return d_env
->getStatisticsRegistry();
1342 UnsatCore
SolverEngine::getUnsatCoreInternal()
1344 if (!d_env
->getOptions().smt
.produceUnsatCores
)
1346 throw ModalException(
1347 "Cannot get an unsat core when produce-unsat-cores or produce-proofs "
1350 if (d_state
->getMode() != SmtMode::UNSAT
)
1352 throw RecoverableModalException(
1353 "Cannot get an unsat core unless immediately preceded by "
1354 "UNSAT/ENTAILED response.");
1356 // generate with new proofs
1357 PropEngine
* pe
= getPropEngine();
1358 Assert(pe
!= nullptr);
1360 std::shared_ptr
<ProofNode
> pepf
;
1361 if (options().smt
.unsatCoresMode
== options::UnsatCoresMode::ASSUMPTIONS
)
1363 pepf
= pe
->getRefutation();
1367 pepf
= pe
->getProof();
1369 Assert(pepf
!= nullptr);
1370 std::shared_ptr
<ProofNode
> pfn
= d_pfManager
->getFinalProof(pepf
, *d_asserts
);
1371 std::vector
<Node
> core
;
1372 d_ucManager
->getUnsatCore(pfn
, *d_asserts
, core
);
1373 if (options().smt
.minimalUnsatCores
)
1375 core
= reduceUnsatCore(core
);
1377 return UnsatCore(core
);
1380 std::vector
<Node
> SolverEngine::reduceUnsatCore(const std::vector
<Node
>& core
)
1382 Assert(options().smt
.produceUnsatCores
)
1383 << "cannot reduce unsat core if unsat cores are turned off";
1385 d_env
->verbose(1) << "SolverEngine::reduceUnsatCore(): reducing unsat core"
1387 std::unordered_set
<Node
> removed
;
1388 for (const Node
& skip
: core
)
1390 std::unique_ptr
<SolverEngine
> coreChecker
;
1391 initializeSubsolver(coreChecker
, *d_env
.get());
1392 coreChecker
->setLogic(getLogicInfo());
1393 coreChecker
->getOptions().writeSmt().checkUnsatCores
= false;
1394 // disable all proof options
1395 coreChecker
->getOptions().writeSmt().produceProofs
= false;
1396 coreChecker
->getOptions().writeSmt().checkProofs
= false;
1398 for (const Node
& ucAssertion
: core
)
1400 if (ucAssertion
!= skip
&& removed
.find(ucAssertion
) == removed
.end())
1402 Node assertionAfterExpansion
= expandDefinitions(ucAssertion
);
1403 coreChecker
->assertFormula(assertionAfterExpansion
);
1409 r
= coreChecker
->checkSat();
1416 if (r
.getStatus() == Result::UNSAT
)
1418 removed
.insert(skip
);
1420 else if (r
.isUnknown())
1423 << "SolverEngine::reduceUnsatCore(): could not reduce unsat core "
1429 if (removed
.empty())
1435 std::vector
<Node
> newUcAssertions
;
1436 for (const Node
& n
: core
)
1438 if (removed
.find(n
) == removed
.end())
1440 newUcAssertions
.push_back(n
);
1444 return newUcAssertions
;
1448 void SolverEngine::checkUnsatCore()
1450 Assert(d_env
->getOptions().smt
.produceUnsatCores
)
1451 << "cannot check unsat core if unsat cores are turned off";
1453 d_env
->verbose(1) << "SolverEngine::checkUnsatCore(): generating unsat core"
1455 UnsatCore core
= getUnsatCore();
1457 // initialize the core checker
1458 std::unique_ptr
<SolverEngine
> coreChecker
;
1459 initializeSubsolver(coreChecker
, *d_env
.get());
1460 coreChecker
->getOptions().writeSmt().checkUnsatCores
= false;
1461 // disable all proof options
1462 coreChecker
->getOptions().writeSmt().produceProofs
= false;
1463 coreChecker
->getOptions().writeSmt().checkProofs
= false;
1465 d_env
->verbose(1) << "SolverEngine::checkUnsatCore(): pushing core assertions"
1467 theory::TrustSubstitutionMap
& tls
= d_env
->getTopLevelSubstitutions();
1468 for (UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
)
1470 Node assertionAfterExpansion
= tls
.apply(*i
);
1471 d_env
->verbose(1) << "SolverEngine::checkUnsatCore(): pushing core member "
1472 << *i
<< ", expanded to " << assertionAfterExpansion
1474 coreChecker
->assertFormula(assertionAfterExpansion
);
1479 r
= coreChecker
->checkSat();
1485 d_env
->verbose(1) << "SolverEngine::checkUnsatCore(): result is " << r
1489 d_env
->warning() << "SolverEngine::checkUnsatCore(): could not check core result "
1493 else if (r
.getStatus() == Result::SAT
)
1496 << "SolverEngine::checkUnsatCore(): produced core was satisfiable.";
1500 void SolverEngine::checkModel(bool hardFailure
)
1502 const CDList
<Node
>& al
= d_asserts
->getAssertionList();
1503 // we always enable the assertion list, so it is able to be checked
1505 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
1507 d_env
->verbose(1) << "SolverEngine::checkModel(): generating model"
1509 TheoryModel
* m
= getAvailableModel("check model");
1510 Assert(m
!= nullptr);
1512 // check the model with the theory engine for debugging
1513 if (options().smt
.debugCheckModels
)
1515 TheoryEngine
* te
= getTheoryEngine();
1516 Assert(te
!= nullptr);
1517 te
->checkTheoryAssertionsWithModel(hardFailure
);
1520 // check the model with the check models utility
1521 Assert(d_checkModels
!= nullptr);
1522 d_checkModels
->checkModel(m
, al
, hardFailure
);
1525 UnsatCore
SolverEngine::getUnsatCore()
1527 Trace("smt") << "SMT getUnsatCore()" << std::endl
;
1528 SolverEngineScope
smts(this);
1530 return getUnsatCoreInternal();
1533 void SolverEngine::getRelevantInstantiationTermVectors(
1534 std::map
<Node
, InstantiationList
>& insts
, bool getDebugInfo
)
1536 Assert(d_state
->getMode() == SmtMode::UNSAT
);
1537 // generate with new proofs
1538 PropEngine
* pe
= getPropEngine();
1539 Assert(pe
!= nullptr);
1540 Assert(pe
->getProof() != nullptr);
1541 std::shared_ptr
<ProofNode
> pfn
=
1542 d_pfManager
->getFinalProof(pe
->getProof(), *d_asserts
);
1543 d_ucManager
->getRelevantInstantiations(pfn
, insts
, getDebugInfo
);
1546 std::string
SolverEngine::getProof()
1548 Trace("smt") << "SMT getProof()\n";
1549 SolverEngineScope
smts(this);
1551 if (!d_env
->getOptions().smt
.produceProofs
)
1553 throw ModalException("Cannot get a proof when proof option is off.");
1555 if (d_state
->getMode() != SmtMode::UNSAT
)
1557 throw RecoverableModalException(
1558 "Cannot get a proof unless immediately preceded by "
1559 "UNSAT/ENTAILED response.");
1561 // the prop engine has the proof of false
1562 PropEngine
* pe
= getPropEngine();
1563 Assert(pe
!= nullptr);
1564 Assert(pe
->getProof() != nullptr);
1565 Assert(d_pfManager
);
1566 std::ostringstream ss
;
1567 d_pfManager
->printProof(ss
, pe
->getProof(), *d_asserts
);
1571 void SolverEngine::printInstantiations(std::ostream
& out
)
1573 SolverEngineScope
smts(this);
1575 QuantifiersEngine
* qe
= getAvailableQuantifiersEngine("printInstantiations");
1577 // First, extract and print the skolemizations
1578 bool printed
= false;
1579 bool reqNames
= !d_env
->getOptions().quantifiers
.printInstFull
;
1580 // only print when in list mode
1581 if (d_env
->getOptions().quantifiers
.printInstMode
== options::PrintInstMode::LIST
)
1583 std::map
<Node
, std::vector
<Node
>> sks
;
1584 qe
->getSkolemTermVectors(sks
);
1585 for (const std::pair
<const Node
, std::vector
<Node
>>& s
: sks
)
1588 if (!qe
->getNameForQuant(s
.first
, name
, reqNames
))
1590 // did not have a name and we are only printing formulas with names
1593 SkolemList
slist(name
, s
.second
);
1599 // Second, extract and print the instantiations
1600 std::map
<Node
, InstantiationList
> rinsts
;
1601 if ((d_env
->getOptions().smt
.produceProofs
1602 && d_env
->getOptions().smt
.proofMode
== options::ProofMode::FULL
)
1603 && getSmtMode() == SmtMode::UNSAT
)
1605 // minimize instantiations based on proof manager
1606 getRelevantInstantiationTermVectors(
1607 rinsts
, options().driver
.dumpInstantiationsDebug
);
1611 std::map
<Node
, std::vector
<std::vector
<Node
>>> insts
;
1612 getInstantiationTermVectors(insts
);
1613 for (const std::pair
<const Node
, std::vector
<std::vector
<Node
>>>& i
: insts
)
1615 // convert to instantiation list
1617 InstantiationList
& ilq
= rinsts
[q
];
1619 for (const std::vector
<Node
>& ii
: i
.second
)
1621 ilq
.d_inst
.push_back(InstantiationVec(ii
));
1625 for (std::pair
<const Node
, InstantiationList
>& i
: rinsts
)
1627 if (i
.second
.d_inst
.empty())
1629 // no instantiations, skip
1633 if (!qe
->getNameForQuant(i
.first
, name
, reqNames
))
1635 // did not have a name and we are only printing formulas with names
1639 if (d_env
->getOptions().quantifiers
.printInstMode
1640 == options::PrintInstMode::NUM
)
1642 out
<< "(num-instantiations " << name
<< " " << i
.second
.d_inst
.size()
1643 << ")" << std::endl
;
1648 i
.second
.d_quant
= name
;
1649 Assert(d_env
->getOptions().quantifiers
.printInstMode
1650 == options::PrintInstMode::LIST
);
1655 // if we did not print anything, we indicate this
1658 out
<< "none" << std::endl
;
1662 void SolverEngine::getInstantiationTermVectors(
1663 std::map
<Node
, std::vector
<std::vector
<Node
>>>& insts
)
1665 SolverEngineScope
smts(this);
1667 QuantifiersEngine
* qe
=
1668 getAvailableQuantifiersEngine("getInstantiationTermVectors");
1669 // get the list of all instantiations
1670 qe
->getInstantiationTermVectors(insts
);
1673 bool SolverEngine::getSynthSolutions(std::map
<Node
, Node
>& solMap
)
1675 SolverEngineScope
smts(this);
1677 return d_sygusSolver
->getSynthSolutions(solMap
);
1680 bool SolverEngine::getSubsolverSynthSolutions(std::map
<Node
, Node
>& solMap
)
1682 SolverEngineScope
smts(this);
1684 return d_sygusSolver
->getSubsolverSynthSolutions(solMap
);
1687 Node
SolverEngine::getQuantifierElimination(Node q
, bool doFull
)
1689 SolverEngineScope
smts(this);
1691 return d_quantElimSolver
->getQuantifierElimination(
1692 *d_asserts
, q
, doFull
, d_isInternalSubsolver
);
1695 Node
SolverEngine::getInterpolant(const Node
& conj
, const TypeNode
& grammarType
)
1697 SolverEngineScope
smts(this);
1699 std::vector
<Node
> axioms
= getExpandedAssertions();
1702 d_interpolSolver
->getInterpolant(axioms
, conj
, grammarType
, interpol
);
1703 // notify the state of whether the get-interpolant call was successfuly, which
1704 // impacts the SMT mode.
1705 d_state
->notifyGetInterpol(success
);
1706 Assert(success
== !interpol
.isNull());
1710 Node
SolverEngine::getInterpolantNext()
1712 SolverEngineScope
smts(this);
1714 if (d_state
->getMode() != SmtMode::INTERPOL
)
1716 throw RecoverableModalException(
1717 "Cannot get-interpolant-next unless immediately preceded by a "
1719 "call to get-interpolant(-next).");
1722 bool success
= d_interpolSolver
->getInterpolantNext(interpol
);
1723 // notify the state of whether the get-interpolantant-next call was successful
1724 d_state
->notifyGetInterpol(success
);
1725 Assert(success
== !interpol
.isNull());
1729 Node
SolverEngine::getAbduct(const Node
& conj
, const TypeNode
& grammarType
)
1731 SolverEngineScope
smts(this);
1733 std::vector
<Node
> axioms
= getExpandedAssertions();
1735 bool success
= d_abductSolver
->getAbduct(axioms
, conj
, grammarType
, abd
);
1736 // notify the state of whether the get-abduct call was successful, which
1737 // impacts the SMT mode.
1738 d_state
->notifyGetAbduct(success
);
1739 Assert(success
== !abd
.isNull());
1743 Node
SolverEngine::getAbductNext()
1745 SolverEngineScope
smts(this);
1747 if (d_state
->getMode() != SmtMode::ABDUCT
)
1749 throw RecoverableModalException(
1750 "Cannot get-abduct-next unless immediately preceded by a successful "
1751 "call to get-abduct(-next).");
1754 bool success
= d_abductSolver
->getAbductNext(abd
);
1755 // notify the state of whether the get-abduct-next call was successful
1756 d_state
->notifyGetAbduct(success
);
1757 Assert(success
== !abd
.isNull());
1761 void SolverEngine::getInstantiatedQuantifiedFormulas(std::vector
<Node
>& qs
)
1763 SolverEngineScope
smts(this);
1764 QuantifiersEngine
* qe
=
1765 getAvailableQuantifiersEngine("getInstantiatedQuantifiedFormulas");
1766 qe
->getInstantiatedQuantifiedFormulas(qs
);
1769 void SolverEngine::getInstantiationTermVectors(
1770 Node q
, std::vector
<std::vector
<Node
>>& tvecs
)
1772 SolverEngineScope
smts(this);
1773 QuantifiersEngine
* qe
=
1774 getAvailableQuantifiersEngine("getInstantiationTermVectors");
1775 qe
->getInstantiationTermVectors(q
, tvecs
);
1778 std::vector
<Node
> SolverEngine::getAssertions()
1780 SolverEngineScope
smts(this);
1782 d_state
->doPendingPops();
1783 Trace("smt") << "SMT getAssertions()" << endl
;
1784 // note we always enable assertions, so it is available here
1785 return getAssertionsInternal();
1788 void SolverEngine::getDifficultyMap(std::map
<Node
, Node
>& dmap
)
1790 Trace("smt") << "SMT getDifficultyMap()\n";
1791 SolverEngineScope
smts(this);
1793 if (!d_env
->getOptions().smt
.produceDifficulty
)
1795 throw ModalException(
1796 "Cannot get difficulty when difficulty option is off.");
1798 // the prop engine has the proof of false
1799 Assert(d_pfManager
);
1800 // get difficulty map from theory engine first
1801 TheoryEngine
* te
= getTheoryEngine();
1802 te
->getDifficultyMap(dmap
);
1803 // then ask proof manager to translate dmap in terms of the input
1804 d_pfManager
->translateDifficultyMap(dmap
, *d_asserts
);
1807 void SolverEngine::push()
1809 SolverEngineScope
smts(this);
1811 d_state
->doPendingPops();
1812 Trace("smt") << "SMT push()" << endl
;
1813 d_smtSolver
->processAssertions(*d_asserts
);
1814 d_state
->userPush();
1817 void SolverEngine::pop()
1819 SolverEngineScope
smts(this);
1821 Trace("smt") << "SMT pop()" << endl
;
1824 // Clear out assertion queues etc., in case anything is still in there
1825 d_asserts
->clearCurrent();
1826 // clear the learned literals from the preprocessor
1827 d_smtSolver
->getPreprocessor()->clearLearnedLiterals();
1829 Trace("userpushpop") << "SolverEngine: popped to level "
1830 << getUserContext()->getLevel() << endl
;
1831 // should we reset d_status here?
1832 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
1835 void SolverEngine::resetAssertions()
1837 SolverEngineScope
smts(this);
1839 if (!d_state
->isFullyInited())
1841 // We're still in Start Mode, nothing asserted yet, do nothing.
1842 // (see solver execution modes in the SMT-LIB standard)
1843 Assert(getContext()->getLevel() == 0);
1844 Assert(getUserContext()->getLevel() == 0);
1848 Trace("smt") << "SMT resetAssertions()" << endl
;
1850 d_asserts
->clearCurrent();
1851 d_state
->notifyResetAssertions();
1852 // push the state to maintain global context around everything
1855 // reset SmtSolver, which will construct a new prop engine
1856 d_smtSolver
->resetAssertions();
1859 bool SolverEngine::deepRestart()
1861 SolverEngineScope
smts(this);
1862 if (options().smt
.deepRestartMode
== options::DeepRestartMode::NONE
)
1864 // deep restarts not enabled
1867 Trace("smt") << "SMT deepRestart()" << endl
;
1869 Assert(d_state
->isFullyInited());
1871 // get the zero-level learned literals now, before resetting the context
1872 std::vector
<Node
> zll
=
1873 getPropEngine()->getLearnedZeroLevelLiteralsForRestart();
1877 // not worthwhile to restart if we didn't learn anything
1878 Trace("deep-restart") << "No learned literals" << std::endl
;
1882 d_asserts
->clearCurrent();
1883 d_state
->notifyResetAssertions();
1884 // deep restart the SMT solver, which reconstructs the theory engine and
1886 d_smtSolver
->deepRestart(*d_asserts
.get(), zll
);
1887 // push the state to maintain global context around everything
1892 void SolverEngine::interrupt()
1894 if (!d_state
->isFullyInited())
1898 d_smtSolver
->interrupt();
1901 void SolverEngine::setResourceLimit(uint64_t units
, bool cumulative
)
1905 d_env
->d_options
.writeBase().cumulativeResourceLimit
= units
;
1909 d_env
->d_options
.writeBase().perCallResourceLimit
= units
;
1912 void SolverEngine::setTimeLimit(uint64_t millis
)
1914 d_env
->d_options
.writeBase().perCallMillisecondLimit
= millis
;
1917 unsigned long SolverEngine::getResourceUsage() const
1919 return getResourceManager()->getResourceUsage();
1922 unsigned long SolverEngine::getTimeUsage() const
1924 return getResourceManager()->getTimeUsage();
1927 unsigned long SolverEngine::getResourceRemaining() const
1929 return getResourceManager()->getResourceRemaining();
1932 NodeManager
* SolverEngine::getNodeManager() const
1934 return d_env
->getNodeManager();
1937 void SolverEngine::printStatisticsSafe(int fd
) const
1939 d_env
->getStatisticsRegistry().printSafe(fd
);
1942 void SolverEngine::printStatisticsDiff() const
1944 d_env
->getStatisticsRegistry().printDiff(*d_env
->getOptions().base
.err
);
1945 d_env
->getStatisticsRegistry().storeSnapshot();
1948 void SolverEngine::setOption(const std::string
& key
, const std::string
& value
)
1950 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
1951 options::set(getOptions(), key
, value
);
1954 void SolverEngine::setIsInternalSubsolver() { d_isInternalSubsolver
= true; }
1956 bool SolverEngine::isInternalSubsolver() const { return d_isInternalSubsolver
; }
1958 std::string
SolverEngine::getOption(const std::string
& key
) const
1960 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
1961 return options::get(getOptions(), key
);
1964 Options
& SolverEngine::getOptions() { return d_env
->d_options
; }
1966 const Options
& SolverEngine::getOptions() const { return d_env
->getOptions(); }
1968 ResourceManager
* SolverEngine::getResourceManager() const
1970 return d_env
->getResourceManager();
1973 theory::Rewriter
* SolverEngine::getRewriter() { return d_env
->getRewriter(); }
1975 } // namespace cvc5::internal