Fix compiler warnings. (#2601)
[cvc5.git] / src / smt / smt_engine.cpp
1 /********************* */
2 /*! \file smt_engine.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Andrew Reynolds, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief The main entry point into the CVC4 library's SMT interface
13 **
14 ** The main entry point into the CVC4 library's SMT interface.
15 **/
16
17 #include "smt/smt_engine.h"
18
19 #include <algorithm>
20 #include <cctype>
21 #include <iterator>
22 #include <memory>
23 #include <sstream>
24 #include <stack>
25 #include <string>
26 #include <tuple>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <utility>
30 #include <vector>
31
32 #include "base/configuration.h"
33 #include "base/configuration_private.h"
34 #include "base/exception.h"
35 #include "base/listener.h"
36 #include "base/modal_exception.h"
37 #include "base/output.h"
38 #include "context/cdhashmap.h"
39 #include "context/cdhashset.h"
40 #include "context/cdlist.h"
41 #include "context/context.h"
42 #include "decision/decision_engine.h"
43 #include "expr/attribute.h"
44 #include "expr/expr.h"
45 #include "expr/kind.h"
46 #include "expr/metakind.h"
47 #include "expr/node.h"
48 #include "expr/node_algorithm.h"
49 #include "expr/node_builder.h"
50 #include "expr/node_self_iterator.h"
51 #include "options/arith_options.h"
52 #include "options/arrays_options.h"
53 #include "options/base_options.h"
54 #include "options/booleans_options.h"
55 #include "options/bv_options.h"
56 #include "options/datatypes_options.h"
57 #include "options/decision_mode.h"
58 #include "options/decision_options.h"
59 #include "options/language.h"
60 #include "options/main_options.h"
61 #include "options/open_ostream.h"
62 #include "options/option_exception.h"
63 #include "options/printer_options.h"
64 #include "options/proof_options.h"
65 #include "options/prop_options.h"
66 #include "options/quantifiers_options.h"
67 #include "options/sep_options.h"
68 #include "options/set_language.h"
69 #include "options/smt_options.h"
70 #include "options/strings_options.h"
71 #include "options/theory_options.h"
72 #include "options/uf_options.h"
73 #include "preprocessing/preprocessing_pass.h"
74 #include "preprocessing/preprocessing_pass_context.h"
75 #include "preprocessing/preprocessing_pass_registry.h"
76 #include "printer/printer.h"
77 #include "proof/proof.h"
78 #include "proof/proof_manager.h"
79 #include "proof/theory_proof.h"
80 #include "proof/unsat_core.h"
81 #include "prop/prop_engine.h"
82 #include "smt/command.h"
83 #include "smt/command_list.h"
84 #include "smt/logic_request.h"
85 #include "smt/managed_ostreams.h"
86 #include "smt/model_core_builder.h"
87 #include "smt/smt_engine_scope.h"
88 #include "smt/term_formula_removal.h"
89 #include "smt/update_ostream.h"
90 #include "smt_util/boolean_simplification.h"
91 #include "smt_util/nary_builder.h"
92 #include "smt_util/node_visitor.h"
93 #include "theory/booleans/circuit_propagator.h"
94 #include "theory/bv/theory_bv_rewriter.h"
95 #include "theory/logic_info.h"
96 #include "theory/quantifiers/fun_def_process.h"
97 #include "theory/quantifiers/quantifiers_rewriter.h"
98 #include "theory/quantifiers/single_inv_partition.h"
99 #include "theory/quantifiers/sygus/synth_engine.h"
100 #include "theory/quantifiers/term_util.h"
101 #include "theory/rewriter.h"
102 #include "theory/sort_inference.h"
103 #include "theory/strings/theory_strings.h"
104 #include "theory/substitutions.h"
105 #include "theory/theory_engine.h"
106 #include "theory/theory_model.h"
107 #include "theory/theory_traits.h"
108 #include "util/hash.h"
109 #include "util/proof.h"
110 #include "util/random.h"
111 #include "util/resource_manager.h"
112
113 using namespace std;
114 using namespace CVC4;
115 using namespace CVC4::smt;
116 using namespace CVC4::preprocessing;
117 using namespace CVC4::prop;
118 using namespace CVC4::context;
119 using namespace CVC4::theory;
120
121 namespace CVC4 {
122 namespace smt {
123
124 struct DeleteCommandFunction : public std::unary_function<const Command*, void>
125 {
126 void operator()(const Command* command) { delete command; }
127 };
128
129 void DeleteAndClearCommandVector(std::vector<Command*>& commands) {
130 std::for_each(commands.begin(), commands.end(), DeleteCommandFunction());
131 commands.clear();
132 }
133
134 /** Useful for counting the number of recursive calls. */
135 class ScopeCounter {
136 private:
137 unsigned& d_depth;
138 public:
139 ScopeCounter(unsigned& d) : d_depth(d) {
140 ++d_depth;
141 }
142 ~ScopeCounter(){
143 --d_depth;
144 }
145 };
146
147 /**
148 * Representation of a defined function. We keep these around in
149 * SmtEngine to permit expanding definitions late (and lazily), to
150 * support getValue() over defined functions, to support user output
151 * in terms of defined functions, etc.
152 */
153 class DefinedFunction {
154 Node d_func;
155 vector<Node> d_formals;
156 Node d_formula;
157 public:
158 DefinedFunction() {}
159 DefinedFunction(Node func, vector<Node> formals, Node formula) :
160 d_func(func),
161 d_formals(formals),
162 d_formula(formula) {
163 }
164 Node getFunction() const { return d_func; }
165 vector<Node> getFormals() const { return d_formals; }
166 Node getFormula() const { return d_formula; }
167 };/* class DefinedFunction */
168
169 struct SmtEngineStatistics {
170 /** time spent in definition-expansion */
171 TimerStat d_definitionExpansionTime;
172 /** number of constant propagations found during nonclausal simp */
173 IntStat d_numConstantProps;
174 /** time spent converting to CNF */
175 TimerStat d_cnfConversionTime;
176 /** Num of assertions before ite removal */
177 IntStat d_numAssertionsPre;
178 /** Num of assertions after ite removal */
179 IntStat d_numAssertionsPost;
180 /** time spent in checkModel() */
181 TimerStat d_checkModelTime;
182 /** time spent in checkProof() */
183 TimerStat d_checkProofTime;
184 /** time spent in checkUnsatCore() */
185 TimerStat d_checkUnsatCoreTime;
186 /** time spent in PropEngine::checkSat() */
187 TimerStat d_solveTime;
188 /** time spent in pushing/popping */
189 TimerStat d_pushPopTime;
190 /** time spent in processAssertions() */
191 TimerStat d_processAssertionsTime;
192
193 /** Has something simplified to false? */
194 IntStat d_simplifiedToFalse;
195 /** Number of resource units spent. */
196 ReferenceStat<uint64_t> d_resourceUnitsUsed;
197
198 SmtEngineStatistics() :
199 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
200 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
201 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
202 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
203 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
204 d_checkModelTime("smt::SmtEngine::checkModelTime"),
205 d_checkProofTime("smt::SmtEngine::checkProofTime"),
206 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
207 d_solveTime("smt::SmtEngine::solveTime"),
208 d_pushPopTime("smt::SmtEngine::pushPopTime"),
209 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
210 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
211 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
212 {
213 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime);
214 smtStatisticsRegistry()->registerStat(&d_numConstantProps);
215 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime);
216 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre);
217 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost);
218 smtStatisticsRegistry()->registerStat(&d_checkModelTime);
219 smtStatisticsRegistry()->registerStat(&d_checkProofTime);
220 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime);
221 smtStatisticsRegistry()->registerStat(&d_solveTime);
222 smtStatisticsRegistry()->registerStat(&d_pushPopTime);
223 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime);
224 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse);
225 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed);
226 }
227
228 ~SmtEngineStatistics() {
229 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime);
230 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps);
231 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime);
232 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre);
233 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost);
234 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime);
235 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime);
236 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime);
237 smtStatisticsRegistry()->unregisterStat(&d_solveTime);
238 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime);
239 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime);
240 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse);
241 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed);
242 }
243 };/* struct SmtEngineStatistics */
244
245
246 class SoftResourceOutListener : public Listener {
247 public:
248 SoftResourceOutListener(SmtEngine& smt) : d_smt(&smt) {}
249 void notify() override
250 {
251 SmtScope scope(d_smt);
252 Assert(smt::smtEngineInScope());
253 d_smt->interrupt();
254 }
255 private:
256 SmtEngine* d_smt;
257 }; /* class SoftResourceOutListener */
258
259
260 class HardResourceOutListener : public Listener {
261 public:
262 HardResourceOutListener(SmtEngine& smt) : d_smt(&smt) {}
263 void notify() override
264 {
265 SmtScope scope(d_smt);
266 theory::Rewriter::clearCaches();
267 }
268 private:
269 SmtEngine* d_smt;
270 }; /* class HardResourceOutListener */
271
272 class SetLogicListener : public Listener {
273 public:
274 SetLogicListener(SmtEngine& smt) : d_smt(&smt) {}
275 void notify() override
276 {
277 LogicInfo inOptions(options::forceLogicString());
278 d_smt->setLogic(inOptions);
279 }
280 private:
281 SmtEngine* d_smt;
282 }; /* class SetLogicListener */
283
284 class BeforeSearchListener : public Listener {
285 public:
286 BeforeSearchListener(SmtEngine& smt) : d_smt(&smt) {}
287 void notify() override { d_smt->beforeSearch(); }
288
289 private:
290 SmtEngine* d_smt;
291 }; /* class BeforeSearchListener */
292
293 class UseTheoryListListener : public Listener {
294 public:
295 UseTheoryListListener(TheoryEngine* theoryEngine)
296 : d_theoryEngine(theoryEngine)
297 {}
298
299 void notify() override
300 {
301 std::stringstream commaList(options::useTheoryList());
302 std::string token;
303
304 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
305 << options::useTheoryList() << std::endl;
306
307 while(std::getline(commaList, token, ',')){
308 if(token == "help") {
309 puts(theory::useTheoryHelp);
310 exit(1);
311 }
312 if(theory::useTheoryValidate(token)) {
313 d_theoryEngine->enableTheoryAlternative(token);
314 } else {
315 throw OptionException(
316 std::string("unknown option for --use-theory : `") + token +
317 "'. Try --use-theory=help.");
318 }
319 }
320 }
321
322 private:
323 TheoryEngine* d_theoryEngine;
324 }; /* class UseTheoryListListener */
325
326
327 class SetDefaultExprDepthListener : public Listener {
328 public:
329 void notify() override
330 {
331 int depth = options::defaultExprDepth();
332 Debug.getStream() << expr::ExprSetDepth(depth);
333 Trace.getStream() << expr::ExprSetDepth(depth);
334 Notice.getStream() << expr::ExprSetDepth(depth);
335 Chat.getStream() << expr::ExprSetDepth(depth);
336 Message.getStream() << expr::ExprSetDepth(depth);
337 Warning.getStream() << expr::ExprSetDepth(depth);
338 // intentionally exclude Dump stream from this list
339 }
340 };
341
342 class SetDefaultExprDagListener : public Listener {
343 public:
344 void notify() override
345 {
346 int dag = options::defaultDagThresh();
347 Debug.getStream() << expr::ExprDag(dag);
348 Trace.getStream() << expr::ExprDag(dag);
349 Notice.getStream() << expr::ExprDag(dag);
350 Chat.getStream() << expr::ExprDag(dag);
351 Message.getStream() << expr::ExprDag(dag);
352 Warning.getStream() << expr::ExprDag(dag);
353 Dump.getStream() << expr::ExprDag(dag);
354 }
355 };
356
357 class SetPrintExprTypesListener : public Listener {
358 public:
359 void notify() override
360 {
361 bool value = options::printExprTypes();
362 Debug.getStream() << expr::ExprPrintTypes(value);
363 Trace.getStream() << expr::ExprPrintTypes(value);
364 Notice.getStream() << expr::ExprPrintTypes(value);
365 Chat.getStream() << expr::ExprPrintTypes(value);
366 Message.getStream() << expr::ExprPrintTypes(value);
367 Warning.getStream() << expr::ExprPrintTypes(value);
368 // intentionally exclude Dump stream from this list
369 }
370 };
371
372 class DumpModeListener : public Listener {
373 public:
374 void notify() override
375 {
376 const std::string& value = options::dumpModeString();
377 Dump.setDumpFromString(value);
378 }
379 };
380
381 class PrintSuccessListener : public Listener {
382 public:
383 void notify() override
384 {
385 bool value = options::printSuccess();
386 Debug.getStream() << Command::printsuccess(value);
387 Trace.getStream() << Command::printsuccess(value);
388 Notice.getStream() << Command::printsuccess(value);
389 Chat.getStream() << Command::printsuccess(value);
390 Message.getStream() << Command::printsuccess(value);
391 Warning.getStream() << Command::printsuccess(value);
392 *options::out() << Command::printsuccess(value);
393 }
394 };
395
396
397
398 /**
399 * This is an inelegant solution, but for the present, it will work.
400 * The point of this is to separate the public and private portions of
401 * the SmtEngine class, so that smt_engine.h doesn't
402 * include "expr/node.h", which is a private CVC4 header (and can lead
403 * to linking errors due to the improper inlining of non-visible symbols
404 * into user code!).
405 *
406 * The "real" solution (that which is usually implemented) is to move
407 * ALL the implementation to SmtEnginePrivate and maintain a
408 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
409 * one) becomes an "interface shell" which simply acts as a forwarder
410 * of method calls.
411 */
412 class SmtEnginePrivate : public NodeManagerListener {
413 SmtEngine& d_smt;
414
415 typedef unordered_map<Node, Node, NodeHashFunction> NodeToNodeHashMap;
416 typedef unordered_map<Node, bool, NodeHashFunction> NodeToBoolHashMap;
417
418 /**
419 * Manager for limiting time and abstract resource usage.
420 */
421 ResourceManager* d_resourceManager;
422
423 /** Manager for the memory of regular-output-channel. */
424 ManagedRegularOutputChannel d_managedRegularChannel;
425
426 /** Manager for the memory of diagnostic-output-channel. */
427 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel;
428
429 /** Manager for the memory of --dump-to. */
430 ManagedDumpOStream d_managedDumpChannel;
431
432 /** Manager for --replay-log. */
433 ManagedReplayLogOstream d_managedReplayLog;
434
435 /**
436 * This list contains:
437 * softResourceOut
438 * hardResourceOut
439 * setForceLogic
440 * beforeSearchListener
441 * UseTheoryListListener
442 *
443 * This needs to be deleted before both NodeManager's Options,
444 * SmtEngine, d_resourceManager, and TheoryEngine.
445 */
446 ListenerRegistrationList* d_listenerRegistrations;
447
448 /** A circuit propagator for non-clausal propositional deduction */
449 booleans::CircuitPropagator d_propagator;
450
451 /** Assertions in the preprocessing pipeline */
452 AssertionPipeline d_assertions;
453
454 /** Whether any assertions have been processed */
455 CDO<bool> d_assertionsProcessed;
456
457 // Cached true value
458 Node d_true;
459
460 /**
461 * A context that never pushes/pops, for use by CD structures (like
462 * SubstitutionMaps) that should be "global".
463 */
464 context::Context d_fakeContext;
465
466 /**
467 * A map of AbsractValues to their actual constants. Only used if
468 * options::abstractValues() is on.
469 */
470 SubstitutionMap d_abstractValueMap;
471
472 /**
473 * A mapping of all abstract values (actual value |-> abstract) that
474 * we've handed out. This is necessary to ensure that we give the
475 * same AbstractValues for the same real constants. Only used if
476 * options::abstractValues() is on.
477 */
478 NodeToNodeHashMap d_abstractValues;
479
480 /** Number of calls of simplify assertions active.
481 */
482 unsigned d_simplifyAssertionsDepth;
483
484 /** TODO: whether certain preprocess steps are necessary */
485 //bool d_needsExpandDefs;
486
487 //------------------------------- expression names
488 /** mapping from expressions to name */
489 context::CDHashMap< Node, std::string, NodeHashFunction > d_exprNames;
490 //------------------------------- end expression names
491 public:
492 IteSkolemMap& getIteSkolemMap() { return d_assertions.getIteSkolemMap(); }
493
494 /** Instance of the ITE remover */
495 RemoveTermFormulas d_iteRemover;
496
497 /* Finishes the initialization of the private portion of SMTEngine. */
498 void finishInit();
499
500 private:
501 std::unique_ptr<PreprocessingPassContext> d_preprocessingPassContext;
502
503 /**
504 * Map of preprocessing pass instances, mapping from names to preprocessing
505 * pass instance
506 */
507 std::unordered_map<std::string, std::unique_ptr<PreprocessingPass>> d_passes;
508
509 /**
510 * Helper function to fix up assertion list to restore invariants needed after
511 * ite removal.
512 */
513 void collectSkolems(TNode n, set<TNode>& skolemSet, NodeToBoolHashMap& cache);
514
515 /**
516 * Helper function to fix up assertion list to restore invariants needed after
517 * ite removal.
518 */
519 bool checkForBadSkolems(TNode n, TNode skolem, NodeToBoolHashMap& cache);
520
521 /**
522 * Perform non-clausal simplification of a Node. This involves
523 * Theory implementations, but does NOT involve the SAT solver in
524 * any way.
525 *
526 * Returns false if the formula simplifies to "false"
527 */
528 bool simplifyAssertions();
529
530 public:
531 SmtEnginePrivate(SmtEngine& smt)
532 : d_smt(smt),
533 d_managedRegularChannel(),
534 d_managedDiagnosticChannel(),
535 d_managedDumpChannel(),
536 d_managedReplayLog(),
537 d_listenerRegistrations(new ListenerRegistrationList()),
538 d_propagator(true, true),
539 d_assertions(),
540 d_assertionsProcessed(smt.d_userContext, false),
541 d_fakeContext(),
542 d_abstractValueMap(&d_fakeContext),
543 d_abstractValues(),
544 d_simplifyAssertionsDepth(0),
545 // d_needsExpandDefs(true), //TODO?
546 d_exprNames(smt.d_userContext),
547 d_iteRemover(smt.d_userContext)
548 {
549 d_smt.d_nodeManager->subscribeEvents(this);
550 d_true = NodeManager::currentNM()->mkConst(true);
551 d_resourceManager = NodeManager::currentResourceManager();
552
553 d_listenerRegistrations->add(d_resourceManager->registerSoftListener(
554 new SoftResourceOutListener(d_smt)));
555
556 d_listenerRegistrations->add(d_resourceManager->registerHardListener(
557 new HardResourceOutListener(d_smt)));
558
559 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
560 d_listenerRegistrations->add(
561 nodeManagerOptions.registerForceLogicListener(
562 new SetLogicListener(d_smt), true));
563
564 // Multiple options reuse BeforeSearchListener so registration requires an
565 // extra bit of care.
566 // We can safely not call notify on this before search listener at
567 // registration time. This d_smt cannot be beforeSearch at construction
568 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
569 // not have to be called.
570 d_listenerRegistrations->add(
571 nodeManagerOptions.registerBeforeSearchListener(
572 new BeforeSearchListener(d_smt)));
573
574 // These do need registration calls.
575 d_listenerRegistrations->add(
576 nodeManagerOptions.registerSetDefaultExprDepthListener(
577 new SetDefaultExprDepthListener(), true));
578 d_listenerRegistrations->add(
579 nodeManagerOptions.registerSetDefaultExprDagListener(
580 new SetDefaultExprDagListener(), true));
581 d_listenerRegistrations->add(
582 nodeManagerOptions.registerSetPrintExprTypesListener(
583 new SetPrintExprTypesListener(), true));
584 d_listenerRegistrations->add(
585 nodeManagerOptions.registerSetDumpModeListener(
586 new DumpModeListener(), true));
587 d_listenerRegistrations->add(
588 nodeManagerOptions.registerSetPrintSuccessListener(
589 new PrintSuccessListener(), true));
590 d_listenerRegistrations->add(
591 nodeManagerOptions.registerSetRegularOutputChannelListener(
592 new SetToDefaultSourceListener(&d_managedRegularChannel), true));
593 d_listenerRegistrations->add(
594 nodeManagerOptions.registerSetDiagnosticOutputChannelListener(
595 new SetToDefaultSourceListener(&d_managedDiagnosticChannel), true));
596 d_listenerRegistrations->add(
597 nodeManagerOptions.registerDumpToFileNameListener(
598 new SetToDefaultSourceListener(&d_managedDumpChannel), true));
599 d_listenerRegistrations->add(
600 nodeManagerOptions.registerSetReplayLogFilename(
601 new SetToDefaultSourceListener(&d_managedReplayLog), true));
602 }
603
604 ~SmtEnginePrivate()
605 {
606 delete d_listenerRegistrations;
607
608 if(d_propagator.getNeedsFinish()) {
609 d_propagator.finish();
610 d_propagator.setNeedsFinish(false);
611 }
612 d_smt.d_nodeManager->unsubscribeEvents(this);
613 }
614
615 void cleanupPreprocessingPasses() { d_passes.clear(); }
616
617 ResourceManager* getResourceManager() { return d_resourceManager; }
618 void spendResource(unsigned amount)
619 {
620 d_resourceManager->spendResource(amount);
621 }
622
623 void nmNotifyNewSort(TypeNode tn, uint32_t flags) override
624 {
625 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
626 0,
627 tn.toType());
628 if((flags & ExprManager::SORT_FLAG_PLACEHOLDER) == 0) {
629 d_smt.addToModelCommandAndDump(c, flags);
630 }
631 }
632
633 void nmNotifyNewSortConstructor(TypeNode tn, uint32_t flags) override
634 {
635 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
636 tn.getAttribute(expr::SortArityAttr()),
637 tn.toType());
638 if ((flags & ExprManager::SORT_FLAG_PLACEHOLDER) == 0)
639 {
640 d_smt.addToModelCommandAndDump(c);
641 }
642 }
643
644 void nmNotifyNewDatatypes(const std::vector<DatatypeType>& dtts,
645 uint32_t flags) override
646 {
647 if ((flags & ExprManager::DATATYPE_FLAG_PLACEHOLDER) == 0)
648 {
649 DatatypeDeclarationCommand c(dtts);
650 d_smt.addToModelCommandAndDump(c);
651 }
652 }
653
654 void nmNotifyNewVar(TNode n, uint32_t flags) override
655 {
656 DeclareFunctionCommand c(n.getAttribute(expr::VarNameAttr()),
657 n.toExpr(),
658 n.getType().toType());
659 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
660 d_smt.addToModelCommandAndDump(c, flags);
661 }
662 }
663
664 void nmNotifyNewSkolem(TNode n,
665 const std::string& comment,
666 uint32_t flags) override
667 {
668 string id = n.getAttribute(expr::VarNameAttr());
669 DeclareFunctionCommand c(id, n.toExpr(), n.getType().toType());
670 if(Dump.isOn("skolems") && comment != "") {
671 Dump("skolems") << CommentCommand(id + " is " + comment);
672 }
673 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
674 d_smt.addToModelCommandAndDump(c, flags, false, "skolems");
675 }
676 }
677
678 void nmNotifyDeleteNode(TNode n) override {}
679
680 Node applySubstitutions(TNode node)
681 {
682 return Rewriter::rewrite(
683 d_preprocessingPassContext->getTopLevelSubstitutions().apply(node));
684 }
685
686 /**
687 * Process the assertions that have been asserted.
688 */
689 void processAssertions();
690
691 /** Process a user push.
692 */
693 void notifyPush() {
694
695 }
696
697 /**
698 * Process a user pop. Clears out the non-context-dependent stuff in this
699 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
700 * someone does a push-assert-pop without a check-sat. It also pops the
701 * last map of expression names from notifyPush.
702 */
703 void notifyPop() {
704 d_assertions.clear();
705 d_propagator.getLearnedLiterals().clear();
706 getIteSkolemMap().clear();
707 }
708
709 /**
710 * Adds a formula to the current context. Action here depends on
711 * the SimplificationMode (in the current Options scope); the
712 * formula might be pushed out to the propositional layer
713 * immediately, or it might be simplified and kept, or it might not
714 * even be simplified.
715 * the 2nd and 3rd arguments added for bookkeeping for proofs
716 */
717 void addFormula(TNode n, bool inUnsatCore, bool inInput = true);
718
719 /** Expand definitions in n. */
720 Node expandDefinitions(TNode n,
721 NodeToNodeHashMap& cache,
722 bool expandOnly = false);
723
724 /**
725 * Simplify node "in" by expanding definitions and applying any
726 * substitutions learned from preprocessing.
727 */
728 Node simplify(TNode in) {
729 // Substitute out any abstract values in ex.
730 // Expand definitions.
731 NodeToNodeHashMap cache;
732 Node n = expandDefinitions(in, cache).toExpr();
733 // Make sure we've done all preprocessing, etc.
734 Assert(d_assertions.size() == 0);
735 return applySubstitutions(n).toExpr();
736 }
737
738 /**
739 * Substitute away all AbstractValues in a node.
740 */
741 Node substituteAbstractValues(TNode n) {
742 // We need to do this even if options::abstractValues() is off,
743 // since the setting might have changed after we already gave out
744 // some abstract values.
745 return d_abstractValueMap.apply(n);
746 }
747
748 /**
749 * Make a new (or return an existing) abstract value for a node.
750 * Can only use this if options::abstractValues() is on.
751 */
752 Node mkAbstractValue(TNode n) {
753 Assert(options::abstractValues());
754 Node& val = d_abstractValues[n];
755 if(val.isNull()) {
756 val = d_smt.d_nodeManager->mkAbstractValue(n.getType());
757 d_abstractValueMap.addSubstitution(val, n);
758 }
759 // We are supposed to ascribe types to all abstract values that go out.
760 NodeManager* current = d_smt.d_nodeManager;
761 Node ascription = current->mkConst(AscriptionType(n.getType().toType()));
762 Node retval = current->mkNode(kind::APPLY_TYPE_ASCRIPTION, ascription, val);
763 return retval;
764 }
765
766 void addUseTheoryListListener(TheoryEngine* theoryEngine){
767 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
768 d_listenerRegistrations->add(
769 nodeManagerOptions.registerUseTheoryListListener(
770 new UseTheoryListListener(theoryEngine), true));
771 }
772
773 std::ostream* getReplayLog() const {
774 return d_managedReplayLog.getReplayLog();
775 }
776
777 //------------------------------- expression names
778 // implements setExpressionName, as described in smt_engine.h
779 void setExpressionName(Expr e, std::string name) {
780 d_exprNames[Node::fromExpr(e)] = name;
781 }
782
783 // implements getExpressionName, as described in smt_engine.h
784 bool getExpressionName(Expr e, std::string& name) const {
785 context::CDHashMap< Node, std::string, NodeHashFunction >::const_iterator it = d_exprNames.find(e);
786 if(it!=d_exprNames.end()) {
787 name = (*it).second;
788 return true;
789 }else{
790 return false;
791 }
792 }
793 //------------------------------- end expression names
794 };/* class SmtEnginePrivate */
795
796 }/* namespace CVC4::smt */
797
798 SmtEngine::SmtEngine(ExprManager* em)
799 : d_context(new Context()),
800 d_userLevels(),
801 d_userContext(new UserContext()),
802 d_exprManager(em),
803 d_nodeManager(d_exprManager->getNodeManager()),
804 d_decisionEngine(NULL),
805 d_theoryEngine(NULL),
806 d_propEngine(NULL),
807 d_proofManager(NULL),
808 d_definedFunctions(NULL),
809 d_fmfRecFunctionsDefined(NULL),
810 d_assertionList(NULL),
811 d_assignments(NULL),
812 d_modelGlobalCommands(),
813 d_modelCommands(NULL),
814 d_dumpCommands(),
815 d_defineCommands(),
816 d_logic(),
817 d_originalOptions(),
818 d_pendingPops(0),
819 d_fullyInited(false),
820 d_problemExtended(false),
821 d_queryMade(false),
822 d_needPostsolve(false),
823 d_earlyTheoryPP(true),
824 d_globalNegation(false),
825 d_status(),
826 d_replayStream(NULL),
827 d_private(NULL),
828 d_statisticsRegistry(NULL),
829 d_stats(NULL),
830 d_channels(new LemmaChannels())
831 {
832 SmtScope smts(this);
833 d_originalOptions.copyValues(em->getOptions());
834 d_private = new smt::SmtEnginePrivate(*this);
835 d_statisticsRegistry = new StatisticsRegistry();
836 d_stats = new SmtEngineStatistics();
837 d_stats->d_resourceUnitsUsed.setData(
838 d_private->getResourceManager()->getResourceUsage());
839
840 // The ProofManager is constructed before any other proof objects such as
841 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
842 // initialized in TheoryEngine and PropEngine respectively.
843 Assert(d_proofManager == NULL);
844
845 // d_proofManager must be created before Options has been finished
846 // being parsed from the input file. Because of this, we cannot trust
847 // that options::proof() is set correctly yet.
848 #ifdef CVC4_PROOF
849 d_proofManager = new ProofManager(d_userContext);
850 #endif
851
852 // We have mutual dependency here, so we add the prop engine to the theory
853 // engine later (it is non-essential there)
854 d_theoryEngine = new TheoryEngine(d_context,
855 d_userContext,
856 d_private->d_iteRemover,
857 const_cast<const LogicInfo&>(d_logic),
858 d_channels);
859
860 // Add the theories
861 for(TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST; ++id) {
862 TheoryConstructor::addTheory(d_theoryEngine, id);
863 //register with proof engine if applicable
864 #ifdef CVC4_PROOF
865 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine->theoryOf(id));
866 #endif
867 }
868
869 d_private->addUseTheoryListListener(d_theoryEngine);
870
871 // global push/pop around everything, to ensure proper destruction
872 // of context-dependent data structures
873 d_userContext->push();
874 d_context->push();
875
876 d_definedFunctions = new(true) DefinedFunctionMap(d_userContext);
877 d_fmfRecFunctionsDefined = new(true) NodeList(d_userContext);
878 d_modelCommands = new(true) smt::CommandList(d_userContext);
879 }
880
881 void SmtEngine::finishInit() {
882 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl;
883 // ensure that our heuristics are properly set up
884 setDefaults();
885
886 Trace("smt-debug") << "Making decision engine..." << std::endl;
887
888 d_decisionEngine = new DecisionEngine(d_context, d_userContext);
889 d_decisionEngine->init(); // enable appropriate strategies
890
891 Trace("smt-debug") << "Making prop engine..." << std::endl;
892 d_propEngine = new PropEngine(d_theoryEngine, d_decisionEngine, d_context,
893 d_userContext, d_private->getReplayLog(),
894 d_replayStream, d_channels);
895
896 Trace("smt-debug") << "Setting up theory engine..." << std::endl;
897 d_theoryEngine->setPropEngine(d_propEngine);
898 d_theoryEngine->setDecisionEngine(d_decisionEngine);
899 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl;
900 d_theoryEngine->finishInit();
901
902 Trace("smt-debug") << "Set up assertion list..." << std::endl;
903 // [MGD 10/20/2011] keep around in incremental mode, due to a
904 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
905 // first, some user-context-dependent TNodes might still exist
906 // with rc == 0.
907 if(options::produceAssertions() ||
908 options::incrementalSolving()) {
909 // In the case of incremental solving, we appear to need these to
910 // ensure the relevant Nodes remain live.
911 d_assertionList = new(true) AssertionList(d_userContext);
912 }
913
914 // dump out a set-logic command
915 if(Dump.isOn("benchmark")) {
916 if (Dump.isOn("raw-benchmark")) {
917 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic.getLogicString());
918 } else {
919 LogicInfo everything;
920 everything.lock();
921 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, all-supported logic (below), as some internals might require the use of a logic more general than the input.")
922 << SetBenchmarkLogicCommand(everything.getLogicString());
923 }
924 }
925
926 Trace("smt-debug") << "Dump declaration commands..." << std::endl;
927 // dump out any pending declaration commands
928 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
929 Dump("declarations") << *d_dumpCommands[i];
930 delete d_dumpCommands[i];
931 }
932 d_dumpCommands.clear();
933
934 PROOF( ProofManager::currentPM()->setLogic(d_logic); );
935 PROOF({
936 for(TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST; ++id) {
937 ProofManager::currentPM()->getTheoryProofEngine()->
938 finishRegisterTheory(d_theoryEngine->theoryOf(id));
939 }
940 });
941 d_private->finishInit();
942 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl;
943 }
944
945 void SmtEngine::finalOptionsAreSet() {
946 if(d_fullyInited) {
947 return;
948 }
949
950 if(! d_logic.isLocked()) {
951 setLogicInternal();
952 }
953
954 // finish initialization, create the prop engine, etc.
955 finishInit();
956
957 AlwaysAssert( d_propEngine->getAssertionLevel() == 0,
958 "The PropEngine has pushed but the SmtEngine "
959 "hasn't finished initializing!" );
960
961 d_fullyInited = true;
962 Assert(d_logic.isLocked());
963
964 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(true));
965 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(false).notNode());
966 }
967
968 void SmtEngine::shutdown() {
969 doPendingPops();
970
971 while(options::incrementalSolving() && d_userContext->getLevel() > 1) {
972 internalPop(true);
973 }
974
975 // check to see if a postsolve() is pending
976 if(d_needPostsolve) {
977 d_theoryEngine->postsolve();
978 d_needPostsolve = false;
979 }
980
981 if(d_propEngine != NULL) {
982 d_propEngine->shutdown();
983 }
984 if(d_theoryEngine != NULL) {
985 d_theoryEngine->shutdown();
986 }
987 if(d_decisionEngine != NULL) {
988 d_decisionEngine->shutdown();
989 }
990 }
991
992 SmtEngine::~SmtEngine()
993 {
994 SmtScope smts(this);
995
996 try {
997 shutdown();
998
999 // global push/pop around everything, to ensure proper destruction
1000 // of context-dependent data structures
1001 d_context->popto(0);
1002 d_userContext->popto(0);
1003
1004 if(d_assignments != NULL) {
1005 d_assignments->deleteSelf();
1006 }
1007
1008 if(d_assertionList != NULL) {
1009 d_assertionList->deleteSelf();
1010 }
1011
1012 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
1013 delete d_dumpCommands[i];
1014 d_dumpCommands[i] = NULL;
1015 }
1016 d_dumpCommands.clear();
1017
1018 DeleteAndClearCommandVector(d_modelGlobalCommands);
1019
1020 if(d_modelCommands != NULL) {
1021 d_modelCommands->deleteSelf();
1022 }
1023
1024 d_definedFunctions->deleteSelf();
1025 d_fmfRecFunctionsDefined->deleteSelf();
1026
1027 //destroy all passes before destroying things that they refer to
1028 d_private->cleanupPreprocessingPasses();
1029
1030 delete d_theoryEngine;
1031 d_theoryEngine = NULL;
1032 delete d_propEngine;
1033 d_propEngine = NULL;
1034 delete d_decisionEngine;
1035 d_decisionEngine = NULL;
1036
1037
1038 // d_proofManager is always created when proofs are enabled at configure time.
1039 // Becuase of this, this code should not be wrapped in PROOF() which
1040 // additionally checks flags such as options::proof().
1041 #ifdef CVC4_PROOF
1042 delete d_proofManager;
1043 d_proofManager = NULL;
1044 #endif
1045
1046 delete d_stats;
1047 d_stats = NULL;
1048 delete d_statisticsRegistry;
1049 d_statisticsRegistry = NULL;
1050
1051 delete d_private;
1052 d_private = NULL;
1053
1054 delete d_userContext;
1055 d_userContext = NULL;
1056 delete d_context;
1057 d_context = NULL;
1058
1059 delete d_channels;
1060 d_channels = NULL;
1061
1062 } catch(Exception& e) {
1063 Warning() << "CVC4 threw an exception during cleanup." << endl
1064 << e << endl;
1065 }
1066 }
1067
1068 void SmtEngine::setLogic(const LogicInfo& logic)
1069 {
1070 SmtScope smts(this);
1071 if(d_fullyInited) {
1072 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1073 "finished initializing.");
1074 }
1075 d_logic = logic;
1076 setLogicInternal();
1077 }
1078
1079 void SmtEngine::setLogic(const std::string& s)
1080 {
1081 SmtScope smts(this);
1082 try {
1083 setLogic(LogicInfo(s));
1084 } catch(IllegalArgumentException& e) {
1085 throw LogicException(e.what());
1086 }
1087 }
1088
1089 void SmtEngine::setLogic(const char* logic) { setLogic(string(logic)); }
1090 LogicInfo SmtEngine::getLogicInfo() const {
1091 return d_logic;
1092 }
1093 void SmtEngine::setFilename(std::string filename) { d_filename = filename; }
1094 std::string SmtEngine::getFilename() const { return d_filename; }
1095 void SmtEngine::setLogicInternal()
1096 {
1097 Assert(!d_fullyInited, "setting logic in SmtEngine but the engine has already"
1098 " finished initializing for this run");
1099 d_logic.lock();
1100 }
1101
1102 void SmtEngine::setDefaults() {
1103 Random::getRandom().setSeed(options::seed());
1104 // Language-based defaults
1105 if (!options::bitvectorDivByZeroConst.wasSetByUser())
1106 {
1107 // Bitvector-divide-by-zero changed semantics in SMT LIB 2.6, thus we
1108 // set this option if the input format is SMT LIB 2.6. We also set this
1109 // option if we are sygus, since we assume SMT LIB 2.6 semantics for sygus.
1110 options::bitvectorDivByZeroConst.set(
1111 language::isInputLang_smt2_6(options::inputLanguage())
1112 || options::inputLanguage() == language::input::LANG_SYGUS);
1113 }
1114 bool is_sygus = false;
1115 if (options::inputLanguage() == language::input::LANG_SYGUS)
1116 {
1117 is_sygus = true;
1118 if (!options::ceGuidedInst.wasSetByUser())
1119 {
1120 options::ceGuidedInst.set(true);
1121 }
1122 // must use Ferrante/Rackoff for real arithmetic
1123 if (!options::cbqiMidpoint.wasSetByUser())
1124 {
1125 options::cbqiMidpoint.set(true);
1126 }
1127 if (options::sygusRepairConst())
1128 {
1129 if (!options::cbqi.wasSetByUser())
1130 {
1131 options::cbqi.set(true);
1132 }
1133 }
1134 }
1135
1136 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER)
1137 {
1138 if (options::produceModels()
1139 && (d_logic.isTheoryEnabled(THEORY_ARRAYS)
1140 || d_logic.isTheoryEnabled(THEORY_UF)))
1141 {
1142 if (options::bitblastMode.wasSetByUser()
1143 || options::produceModels.wasSetByUser())
1144 {
1145 throw OptionException(std::string(
1146 "Eager bit-blasting currently does not support model generation "
1147 "for the combination of bit-vectors with arrays or uinterpreted "
1148 "functions. Try --bitblast=lazy"));
1149 }
1150 Notice() << "SmtEngine: setting bit-blast mode to lazy to support model"
1151 << "generation" << endl;
1152 setOption("bitblastMode", SExpr("lazy"));
1153 }
1154
1155 if (options::incrementalSolving() && !d_logic.isPure(THEORY_BV))
1156 {
1157 throw OptionException(
1158 "Incremental eager bit-blasting is currently "
1159 "only supported for QF_BV. Try --bitblast=lazy.");
1160 }
1161 }
1162
1163 if(options::forceLogicString.wasSetByUser()) {
1164 d_logic = LogicInfo(options::forceLogicString());
1165 }else if (options::solveIntAsBV() > 0) {
1166 d_logic = LogicInfo("QF_BV");
1167 }else if (d_logic.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1168 d_logic = LogicInfo("QF_NIA");
1169 } else if ((d_logic.getLogicString() == "QF_UFBV" ||
1170 d_logic.getLogicString() == "QF_ABV") &&
1171 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
1172 d_logic = LogicInfo("QF_BV");
1173 }
1174
1175 // set strings-exp
1176 /* - disabled for 1.4 release [MGD 2014.06.25]
1177 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1178 if(! options::stringExp.wasSetByUser()) {
1179 options::stringExp.set( true );
1180 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1181 }
1182 }
1183 */
1184 // for strings
1185 if(options::stringExp()) {
1186 if( !d_logic.isQuantified() ) {
1187 d_logic = d_logic.getUnlockedCopy();
1188 d_logic.enableQuantifiers();
1189 d_logic.lock();
1190 Trace("smt") << "turning on quantifier logic, for strings-exp"
1191 << std::endl;
1192 }
1193 if(! options::fmfBound.wasSetByUser()) {
1194 options::fmfBound.set( true );
1195 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl;
1196 }
1197 if(! options::fmfInstEngine.wasSetByUser()) {
1198 options::fmfInstEngine.set( true );
1199 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl;
1200 }
1201 /*
1202 if(! options::rewriteDivk.wasSetByUser()) {
1203 options::rewriteDivk.set( true );
1204 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1205 }*/
1206 /*
1207 if(! options::stringFMF.wasSetByUser()) {
1208 options::stringFMF.set( true );
1209 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1210 }
1211 */
1212 }
1213
1214 // sygus inference may require datatypes
1215 if (options::sygusInference())
1216 {
1217 d_logic = d_logic.getUnlockedCopy();
1218 d_logic.enableTheory(THEORY_DATATYPES);
1219 d_logic.lock();
1220 // since we are trying to recast as sygus, we assume the input is sygus
1221 is_sygus = true;
1222 }
1223
1224 if ((options::checkModels() || options::checkSynthSol()
1225 || options::produceModelCores())
1226 && !options::produceAssertions())
1227 {
1228 Notice() << "SmtEngine: turning on produce-assertions to support "
1229 << "check-models, check-synth-sol or produce-model-cores." << endl;
1230 setOption("produce-assertions", SExpr("true"));
1231 }
1232
1233 // Disable options incompatible with incremental solving, unsat cores, and
1234 // proofs or output an error if enabled explicitly
1235 if (options::incrementalSolving() || options::unsatCores()
1236 || options::proof())
1237 {
1238 if (options::unconstrainedSimp())
1239 {
1240 if (options::unconstrainedSimp.wasSetByUser())
1241 {
1242 throw OptionException(
1243 "unconstrained simplification not supported with unsat "
1244 "cores/proofs/incremental solving");
1245 }
1246 Notice() << "SmtEngine: turning off unconstrained simplification to "
1247 "support unsat cores/proofs/incremental solving"
1248 << endl;
1249 options::unconstrainedSimp.set(false);
1250 }
1251 }
1252 else
1253 {
1254 // Turn on unconstrained simplification for QF_AUFBV
1255 if (!options::unconstrainedSimp.wasSetByUser())
1256 {
1257 // bool qf_sat = d_logic.isPure(THEORY_BOOL) &&
1258 // !d_logic.isQuantified(); bool uncSimp = false && !qf_sat &&
1259 // !options::incrementalSolving();
1260 bool uncSimp = !d_logic.isQuantified() && !options::produceModels()
1261 && !options::produceAssignments()
1262 && !options::checkModels()
1263 && (d_logic.isTheoryEnabled(THEORY_ARRAYS)
1264 && d_logic.isTheoryEnabled(THEORY_BV));
1265 Trace("smt") << "setting unconstrained simplification to " << uncSimp
1266 << endl;
1267 options::unconstrainedSimp.set(uncSimp);
1268 }
1269 }
1270
1271 // Disable options incompatible with unsat cores and proofs or output an
1272 // error if enabled explicitly
1273 if (options::unsatCores() || options::proof())
1274 {
1275 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE)
1276 {
1277 if (options::simplificationMode.wasSetByUser())
1278 {
1279 throw OptionException(
1280 "simplification not supported with unsat cores/proofs");
1281 }
1282 Notice() << "SmtEngine: turning off simplification to support unsat "
1283 "cores/proofs"
1284 << endl;
1285 options::simplificationMode.set(SIMPLIFICATION_MODE_NONE);
1286 }
1287
1288 if (options::pbRewrites())
1289 {
1290 if (options::pbRewrites.wasSetByUser())
1291 {
1292 throw OptionException(
1293 "pseudoboolean rewrites not supported with unsat cores/proofs");
1294 }
1295 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support "
1296 "unsat cores/proofs"
1297 << endl;
1298 setOption("pb-rewrites", false);
1299 }
1300
1301 if (options::sortInference())
1302 {
1303 if (options::sortInference.wasSetByUser())
1304 {
1305 throw OptionException(
1306 "sort inference not supported with unsat cores/proofs");
1307 }
1308 Notice() << "SmtEngine: turning off sort inference to support unsat "
1309 "cores/proofs"
1310 << endl;
1311 options::sortInference.set(false);
1312 }
1313
1314 if (options::preSkolemQuant())
1315 {
1316 if (options::preSkolemQuant.wasSetByUser())
1317 {
1318 throw OptionException(
1319 "pre-skolemization not supported with unsat cores/proofs");
1320 }
1321 Notice() << "SmtEngine: turning off pre-skolemization to support unsat "
1322 "cores/proofs"
1323 << endl;
1324 options::preSkolemQuant.set(false);
1325 }
1326
1327 if (options::bitvectorToBool())
1328 {
1329 if (options::bitvectorToBool.wasSetByUser())
1330 {
1331 throw OptionException(
1332 "bv-to-bool not supported with unsat cores/proofs");
1333 }
1334 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat "
1335 "cores/proofs"
1336 << endl;
1337 options::bitvectorToBool.set(false);
1338 }
1339
1340 if (options::boolToBitvector())
1341 {
1342 if (options::boolToBitvector.wasSetByUser())
1343 {
1344 throw OptionException(
1345 "bool-to-bv not supported with unsat cores/proofs");
1346 }
1347 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat "
1348 "cores/proofs"
1349 << endl;
1350 options::boolToBitvector.set(false);
1351 }
1352
1353 if (options::bvIntroducePow2())
1354 {
1355 if (options::bvIntroducePow2.wasSetByUser())
1356 {
1357 throw OptionException(
1358 "bv-intro-pow2 not supported with unsat cores/proofs");
1359 }
1360 Notice() << "SmtEngine: turning off bv-intro-pow2 to support "
1361 "unsat-cores/proofs"
1362 << endl;
1363 setOption("bv-intro-pow2", false);
1364 }
1365
1366 if (options::repeatSimp())
1367 {
1368 if (options::repeatSimp.wasSetByUser())
1369 {
1370 throw OptionException(
1371 "repeat-simp not supported with unsat cores/proofs");
1372 }
1373 Notice() << "SmtEngine: turning off repeat-simp to support unsat "
1374 "cores/proofs"
1375 << endl;
1376 setOption("repeat-simp", false);
1377 }
1378
1379 if (options::globalNegate())
1380 {
1381 if (options::globalNegate.wasSetByUser())
1382 {
1383 throw OptionException(
1384 "global-negate not supported with unsat cores/proofs");
1385 }
1386 Notice() << "SmtEngine: turning off global-negate to support unsat "
1387 "cores/proofs"
1388 << endl;
1389 setOption("global-negate", false);
1390 }
1391 }
1392 else
1393 {
1394 // by default, nonclausal simplification is off for QF_SAT
1395 if (!options::simplificationMode.wasSetByUser())
1396 {
1397 bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1398 Trace("smt") << "setting simplification mode to <"
1399 << d_logic.getLogicString() << "> " << (!qf_sat) << endl;
1400 // simplification=none works better for SMT LIB benchmarks with
1401 // quantifiers, not others options::simplificationMode.set(qf_sat ||
1402 // quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1403 options::simplificationMode.set(qf_sat ? SIMPLIFICATION_MODE_NONE
1404 : SIMPLIFICATION_MODE_BATCH);
1405 }
1406 }
1407
1408 if (options::cbqiBv() && d_logic.isQuantified())
1409 {
1410 if(options::boolToBitvector.wasSetByUser()) {
1411 throw OptionException(
1412 "bool-to-bv not supported with CBQI BV for quantified logics");
1413 }
1414 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1415 << endl;
1416 options::boolToBitvector.set(false);
1417 }
1418
1419 // cases where we need produce models
1420 if (!options::produceModels()
1421 && (options::produceAssignments() || options::sygusRewSynthCheck()
1422 || options::produceModelCores() || is_sygus))
1423 {
1424 Notice() << "SmtEngine: turning on produce-models" << endl;
1425 setOption("produce-models", SExpr("true"));
1426 }
1427
1428 // Set the options for the theoryOf
1429 if(!options::theoryOfMode.wasSetByUser()) {
1430 if(d_logic.isSharingEnabled() &&
1431 !d_logic.isTheoryEnabled(THEORY_BV) &&
1432 !d_logic.isTheoryEnabled(THEORY_STRINGS) &&
1433 !d_logic.isTheoryEnabled(THEORY_SETS) ) {
1434 Trace("smt") << "setting theoryof-mode to term-based" << endl;
1435 options::theoryOfMode.set(THEORY_OF_TERM_BASED);
1436 }
1437 }
1438
1439 // strings require LIA, UF; widen the logic
1440 if(d_logic.isTheoryEnabled(THEORY_STRINGS)) {
1441 LogicInfo log(d_logic.getUnlockedCopy());
1442 // Strings requires arith for length constraints, and also UF
1443 if(!d_logic.isTheoryEnabled(THEORY_UF)) {
1444 Trace("smt") << "because strings are enabled, also enabling UF" << endl;
1445 log.enableTheory(THEORY_UF);
1446 }
1447 if(!d_logic.isTheoryEnabled(THEORY_ARITH) || d_logic.isDifferenceLogic() || !d_logic.areIntegersUsed()) {
1448 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl;
1449 log.enableTheory(THEORY_ARITH);
1450 log.enableIntegers();
1451 log.arithOnlyLinear();
1452 }
1453 d_logic = log;
1454 d_logic.lock();
1455 }
1456 if(d_logic.isTheoryEnabled(THEORY_ARRAYS) || d_logic.isTheoryEnabled(THEORY_DATATYPES) || d_logic.isTheoryEnabled(THEORY_SETS)) {
1457 if(!d_logic.isTheoryEnabled(THEORY_UF)) {
1458 LogicInfo log(d_logic.getUnlockedCopy());
1459 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl;
1460 log.enableTheory(THEORY_UF);
1461 d_logic = log;
1462 d_logic.lock();
1463 }
1464 }
1465
1466 // by default, symmetry breaker is on only for non-incremental QF_UF
1467 if(! options::ufSymmetryBreaker.wasSetByUser()) {
1468 bool qf_uf_noinc = d_logic.isPure(THEORY_UF) && !d_logic.isQuantified()
1469 && !options::incrementalSolving() && !options::proof()
1470 && !options::unsatCores();
1471 Trace("smt") << "setting uf symmetry breaker to " << qf_uf_noinc << endl;
1472 options::ufSymmetryBreaker.set(qf_uf_noinc);
1473 }
1474
1475 // If in arrays, set the UF handler to arrays
1476 if(d_logic.isTheoryEnabled(THEORY_ARRAYS) && ( !d_logic.isQuantified() ||
1477 (d_logic.isQuantified() && !d_logic.isTheoryEnabled(THEORY_UF)))) {
1478 Theory::setUninterpretedSortOwner(THEORY_ARRAYS);
1479 } else {
1480 Theory::setUninterpretedSortOwner(THEORY_UF);
1481 }
1482
1483 // Turn on ite simplification for QF_LIA and QF_AUFBV
1484 // WARNING: These checks match much more than just QF_AUFBV and
1485 // QF_LIA logics. --K [2014/10/15]
1486 if(! options::doITESimp.wasSetByUser()) {
1487 bool qf_aufbv = !d_logic.isQuantified() &&
1488 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1489 d_logic.isTheoryEnabled(THEORY_UF) &&
1490 d_logic.isTheoryEnabled(THEORY_BV);
1491 bool qf_lia = !d_logic.isQuantified() &&
1492 d_logic.isPure(THEORY_ARITH) &&
1493 d_logic.isLinear() &&
1494 !d_logic.isDifferenceLogic() &&
1495 !d_logic.areRealsUsed();
1496
1497 bool iteSimp = (qf_aufbv || qf_lia);
1498 Trace("smt") << "setting ite simplification to " << iteSimp << endl;
1499 options::doITESimp.set(iteSimp);
1500 }
1501 if(! options::compressItes.wasSetByUser() ){
1502 bool qf_lia = !d_logic.isQuantified() &&
1503 d_logic.isPure(THEORY_ARITH) &&
1504 d_logic.isLinear() &&
1505 !d_logic.isDifferenceLogic() &&
1506 !d_logic.areRealsUsed();
1507
1508 bool compressIte = qf_lia;
1509 Trace("smt") << "setting ite compression to " << compressIte << endl;
1510 options::compressItes.set(compressIte);
1511 }
1512 if(! options::simplifyWithCareEnabled.wasSetByUser() ){
1513 bool qf_aufbv = !d_logic.isQuantified() &&
1514 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1515 d_logic.isTheoryEnabled(THEORY_UF) &&
1516 d_logic.isTheoryEnabled(THEORY_BV);
1517
1518 bool withCare = qf_aufbv;
1519 Trace("smt") << "setting ite simplify with care to " << withCare << endl;
1520 options::simplifyWithCareEnabled.set(withCare);
1521 }
1522 // Turn off array eager index splitting for QF_AUFLIA
1523 if(! options::arraysEagerIndexSplitting.wasSetByUser()) {
1524 if (not d_logic.isQuantified() &&
1525 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1526 d_logic.isTheoryEnabled(THEORY_UF) &&
1527 d_logic.isTheoryEnabled(THEORY_ARITH)) {
1528 Trace("smt") << "setting array eager index splitting to false" << endl;
1529 options::arraysEagerIndexSplitting.set(false);
1530 }
1531 }
1532 // Turn on model-based arrays for QF_AX (unless models are enabled)
1533 // if(! options::arraysModelBased.wasSetByUser()) {
1534 // if (not d_logic.isQuantified() &&
1535 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1536 // d_logic.isPure(THEORY_ARRAYS) &&
1537 // !options::produceModels() &&
1538 // !options::checkModels()) {
1539 // Trace("smt") << "turning on model-based array solver" << endl;
1540 // options::arraysModelBased.set(true);
1541 // }
1542 // }
1543 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1544 if(! options::repeatSimp.wasSetByUser()) {
1545 bool repeatSimp = !d_logic.isQuantified() &&
1546 (d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1547 d_logic.isTheoryEnabled(THEORY_UF) &&
1548 d_logic.isTheoryEnabled(THEORY_BV)) &&
1549 !options::unsatCores();
1550 Trace("smt") << "setting repeat simplification to " << repeatSimp << endl;
1551 options::repeatSimp.set(repeatSimp);
1552 }
1553 // Unconstrained simp currently does *not* support model generation
1554 if (options::unconstrainedSimp.wasSetByUser() && options::unconstrainedSimp()) {
1555 if (options::produceModels()) {
1556 if (options::produceModels.wasSetByUser()) {
1557 throw OptionException("Cannot use unconstrained-simp with model generation.");
1558 }
1559 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl;
1560 setOption("produce-models", SExpr("false"));
1561 }
1562 if (options::produceAssignments()) {
1563 if (options::produceAssignments.wasSetByUser()) {
1564 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1565 }
1566 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl;
1567 setOption("produce-assignments", SExpr("false"));
1568 }
1569 if (options::checkModels()) {
1570 if (options::checkModels.wasSetByUser()) {
1571 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1572 }
1573 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl;
1574 setOption("check-models", SExpr("false"));
1575 }
1576 }
1577
1578 if (! options::bvEagerExplanations.wasSetByUser() &&
1579 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1580 d_logic.isTheoryEnabled(THEORY_BV)) {
1581 Trace("smt") << "enabling eager bit-vector explanations " << endl;
1582 options::bvEagerExplanations.set(true);
1583 }
1584
1585 // Turn on arith rewrite equalities only for pure arithmetic
1586 if(! options::arithRewriteEq.wasSetByUser()) {
1587 bool arithRewriteEq = d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isQuantified();
1588 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq << endl;
1589 options::arithRewriteEq.set(arithRewriteEq);
1590 }
1591 if(! options::arithHeuristicPivots.wasSetByUser()) {
1592 int16_t heuristicPivots = 5;
1593 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()) {
1594 if(d_logic.isDifferenceLogic()) {
1595 heuristicPivots = -1;
1596 } else if(!d_logic.areIntegersUsed()) {
1597 heuristicPivots = 0;
1598 }
1599 }
1600 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots << endl;
1601 options::arithHeuristicPivots.set(heuristicPivots);
1602 }
1603 if(! options::arithPivotThreshold.wasSetByUser()){
1604 uint16_t pivotThreshold = 2;
1605 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1606 if(d_logic.isDifferenceLogic()){
1607 pivotThreshold = 16;
1608 }
1609 }
1610 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold << endl;
1611 options::arithPivotThreshold.set(pivotThreshold);
1612 }
1613 if(! options::arithStandardCheckVarOrderPivots.wasSetByUser()){
1614 int16_t varOrderPivots = -1;
1615 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1616 varOrderPivots = 200;
1617 }
1618 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots << endl;
1619 options::arithStandardCheckVarOrderPivots.set(varOrderPivots);
1620 }
1621 // Turn off early theory preprocessing if arithRewriteEq is on
1622 if (options::arithRewriteEq()) {
1623 d_earlyTheoryPP = false;
1624 }
1625 if (d_logic.isPure(THEORY_ARITH) && !d_logic.areRealsUsed())
1626 {
1627 if (!options::nlExtTangentPlanesInterleave.wasSetByUser())
1628 {
1629 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl;
1630 options::nlExtTangentPlanesInterleave.set(true);
1631 }
1632 }
1633
1634 // Set decision mode based on logic (if not set by user)
1635 if(!options::decisionMode.wasSetByUser()) {
1636 decision::DecisionMode decMode =
1637 // sygus uses internal
1638 is_sygus ? decision::DECISION_STRATEGY_INTERNAL :
1639 // ALL
1640 d_logic.hasEverything()
1641 ? decision::DECISION_STRATEGY_JUSTIFICATION
1642 : ( // QF_BV
1643 (not d_logic.isQuantified() && d_logic.isPure(THEORY_BV))
1644 ||
1645 // QF_AUFBV or QF_ABV or QF_UFBV
1646 (not d_logic.isQuantified()
1647 && (d_logic.isTheoryEnabled(THEORY_ARRAYS)
1648 || d_logic.isTheoryEnabled(THEORY_UF))
1649 && d_logic.isTheoryEnabled(THEORY_BV))
1650 ||
1651 // QF_AUFLIA (and may be ends up enabling
1652 // QF_AUFLRA?)
1653 (not d_logic.isQuantified()
1654 && d_logic.isTheoryEnabled(THEORY_ARRAYS)
1655 && d_logic.isTheoryEnabled(THEORY_UF)
1656 && d_logic.isTheoryEnabled(THEORY_ARITH))
1657 ||
1658 // QF_LRA
1659 (not d_logic.isQuantified()
1660 && d_logic.isPure(THEORY_ARITH)
1661 && d_logic.isLinear()
1662 && !d_logic.isDifferenceLogic()
1663 && !d_logic.areIntegersUsed())
1664 ||
1665 // Quantifiers
1666 d_logic.isQuantified() ||
1667 // Strings
1668 d_logic.isTheoryEnabled(THEORY_STRINGS)
1669 ? decision::DECISION_STRATEGY_JUSTIFICATION
1670 : decision::DECISION_STRATEGY_INTERNAL);
1671
1672 bool stoponly =
1673 // ALL
1674 d_logic.hasEverything() || d_logic.isTheoryEnabled(THEORY_STRINGS) ? false :
1675 ( // QF_AUFLIA
1676 (not d_logic.isQuantified() &&
1677 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1678 d_logic.isTheoryEnabled(THEORY_UF) &&
1679 d_logic.isTheoryEnabled(THEORY_ARITH)
1680 ) ||
1681 // QF_LRA
1682 (not d_logic.isQuantified() &&
1683 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
1684 )
1685 ? true : false
1686 );
1687
1688 Trace("smt") << "setting decision mode to " << decMode << endl;
1689 options::decisionMode.set(decMode);
1690 options::decisionStopOnly.set(stoponly);
1691 }
1692 if( options::incrementalSolving() ){
1693 //disable modes not supported by incremental
1694 options::sortInference.set( false );
1695 options::ufssFairnessMonotone.set( false );
1696 options::quantEpr.set( false );
1697 options::globalNegate.set(false);
1698 }
1699 if( d_logic.hasCardinalityConstraints() ){
1700 //must have finite model finding on
1701 options::finiteModelFind.set( true );
1702 }
1703
1704 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1705 if( d_logic.isTheoryEnabled(THEORY_STRINGS) || (d_logic.isTheoryEnabled(THEORY_ARITH) && !d_logic.isLinear()) ){
1706 if( !options::instWhenStrictInterleave.wasSetByUser() ){
1707 options::instWhenStrictInterleave.set( false );
1708 }
1709 }
1710
1711 //local theory extensions
1712 if( options::localTheoryExt() ){
1713 if( !options::instMaxLevel.wasSetByUser() ){
1714 options::instMaxLevel.set( 0 );
1715 }
1716 }
1717 if( options::instMaxLevel()!=-1 ){
1718 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl;
1719 options::cbqi.set(false);
1720 }
1721 //track instantiations?
1722 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas.wasSetByUser() ) ){
1723 options::trackInstLemmas.set( true );
1724 }
1725
1726 if( ( options::fmfBoundLazy.wasSetByUser() && options::fmfBoundLazy() ) ||
1727 ( options::fmfBoundInt.wasSetByUser() && options::fmfBoundInt() ) ) {
1728 options::fmfBound.set( true );
1729 }
1730 //now have determined whether fmfBoundInt is on/off
1731 //apply fmfBoundInt options
1732 if( options::fmfBound() ){
1733 //must have finite model finding on
1734 options::finiteModelFind.set( true );
1735 if (!options::mbqiMode.wasSetByUser()
1736 || (options::mbqiMode() != quantifiers::MBQI_NONE
1737 && options::mbqiMode() != quantifiers::MBQI_FMC))
1738 {
1739 //if bounded integers are set, use no MBQI by default
1740 options::mbqiMode.set( quantifiers::MBQI_NONE );
1741 }
1742 if( ! options::prenexQuant.wasSetByUser() ){
1743 options::prenexQuant.set( quantifiers::PRENEX_QUANT_NONE );
1744 }
1745 }
1746 if( options::ufHo() ){
1747 //if higher-order, then current variants of model-based instantiation cannot be used
1748 if( options::mbqiMode()!=quantifiers::MBQI_NONE ){
1749 options::mbqiMode.set( quantifiers::MBQI_NONE );
1750 }
1751 }
1752 if( options::mbqiMode()==quantifiers::MBQI_ABS ){
1753 if( !d_logic.isPure(THEORY_UF) ){
1754 //MBQI_ABS is only supported in pure quantified UF
1755 options::mbqiMode.set( quantifiers::MBQI_FMC );
1756 }
1757 }
1758 if( options::fmfFunWellDefinedRelevant() ){
1759 if( !options::fmfFunWellDefined.wasSetByUser() ){
1760 options::fmfFunWellDefined.set( true );
1761 }
1762 }
1763 if( options::fmfFunWellDefined() ){
1764 if( !options::finiteModelFind.wasSetByUser() ){
1765 options::finiteModelFind.set( true );
1766 }
1767 }
1768 //EPR
1769 if( options::quantEpr() ){
1770 if( !options::preSkolemQuant.wasSetByUser() ){
1771 options::preSkolemQuant.set( true );
1772 }
1773 }
1774
1775 //now, have determined whether finite model find is on/off
1776 //apply finite model finding options
1777 if( options::finiteModelFind() ){
1778 //apply conservative quantifiers splitting
1779 if( !options::quantDynamicSplit.wasSetByUser() ){
1780 options::quantDynamicSplit.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT );
1781 }
1782 //do not eliminate extended arithmetic symbols from quantified formulas
1783 if( !options::elimExtArithQuant.wasSetByUser() ){
1784 options::elimExtArithQuant.set( false );
1785 }
1786 if( !options::eMatching.wasSetByUser() ){
1787 options::eMatching.set( options::fmfInstEngine() );
1788 }
1789 if( !options::instWhenMode.wasSetByUser() ){
1790 //instantiate only on last call
1791 if( options::eMatching() ){
1792 options::instWhenMode.set( quantifiers::INST_WHEN_LAST_CALL );
1793 }
1794 }
1795 if( options::mbqiMode()==quantifiers::MBQI_ABS ){
1796 if( !options::preSkolemQuant.wasSetByUser() ){
1797 options::preSkolemQuant.set( true );
1798 }
1799 if( !options::preSkolemQuantNested.wasSetByUser() ){
1800 options::preSkolemQuantNested.set( true );
1801 }
1802 if( !options::fmfOneInstPerRound.wasSetByUser() ){
1803 options::fmfOneInstPerRound.set( true );
1804 }
1805 }
1806 }
1807
1808 //apply counterexample guided instantiation options
1809 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1810 if (options::sygusInference())
1811 {
1812 if (!options::ceGuidedInst.wasSetByUser())
1813 {
1814 options::ceGuidedInst.set(true);
1815 }
1816 // optimization: apply preskolemization, makes it succeed more often
1817 if (!options::preSkolemQuant.wasSetByUser())
1818 {
1819 options::preSkolemQuant.set(true);
1820 }
1821 if (!options::preSkolemQuantNested.wasSetByUser())
1822 {
1823 options::preSkolemQuantNested.set(true);
1824 }
1825 }
1826 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE ){
1827 if( !options::ceGuidedInst.wasSetByUser() ){
1828 options::ceGuidedInst.set( true );
1829 }
1830 }
1831 // if sygus is enabled, set the defaults for sygus
1832 if( options::ceGuidedInst() ){
1833 //counterexample-guided instantiation for sygus
1834 if( !options::cegqiSingleInvMode.wasSetByUser() ){
1835 options::cegqiSingleInvMode.set( quantifiers::CEGQI_SI_MODE_USE );
1836 }
1837 if( !options::quantConflictFind.wasSetByUser() ){
1838 options::quantConflictFind.set( false );
1839 }
1840 if( !options::instNoEntail.wasSetByUser() ){
1841 options::instNoEntail.set( false );
1842 }
1843 if (!options::cbqiFullEffort.wasSetByUser())
1844 {
1845 // should use full effort cbqi for single invocation and repair const
1846 options::cbqiFullEffort.set(true);
1847 }
1848 if (options::sygusRew())
1849 {
1850 options::sygusRewSynth.set(true);
1851 options::sygusRewVerify.set(true);
1852 }
1853 if (options::sygusRewSynth() || options::sygusRewVerify())
1854 {
1855 // rewrite rule synthesis implies that sygus stream must be true
1856 options::sygusStream.set(true);
1857 }
1858 if (options::sygusStream())
1859 {
1860 // PBE and streaming modes are incompatible
1861 if (!options::sygusSymBreakPbe.wasSetByUser())
1862 {
1863 options::sygusSymBreakPbe.set(false);
1864 }
1865 if (!options::sygusUnifPbe.wasSetByUser())
1866 {
1867 options::sygusUnifPbe.set(false);
1868 }
1869 }
1870 //do not allow partial functions
1871 if( !options::bitvectorDivByZeroConst.wasSetByUser() ){
1872 options::bitvectorDivByZeroConst.set( true );
1873 }
1874 if( !options::dtRewriteErrorSel.wasSetByUser() ){
1875 options::dtRewriteErrorSel.set( true );
1876 }
1877 //do not miniscope
1878 if( !options::miniscopeQuant.wasSetByUser() ){
1879 options::miniscopeQuant.set( false );
1880 }
1881 if( !options::miniscopeQuantFreeVar.wasSetByUser() ){
1882 options::miniscopeQuantFreeVar.set( false );
1883 }
1884 if (!options::quantSplit.wasSetByUser())
1885 {
1886 options::quantSplit.set(false);
1887 }
1888 //rewrite divk
1889 if( !options::rewriteDivk.wasSetByUser()) {
1890 options::rewriteDivk.set( true );
1891 }
1892 //do not do macros
1893 if( !options::macrosQuant.wasSetByUser()) {
1894 options::macrosQuant.set( false );
1895 }
1896 if( !options::cbqiPreRegInst.wasSetByUser()) {
1897 options::cbqiPreRegInst.set( true );
1898 }
1899 }
1900 //counterexample-guided instantiation for non-sygus
1901 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
1902 if ((d_logic.isQuantified()
1903 && (d_logic.isTheoryEnabled(THEORY_ARITH)
1904 || d_logic.isTheoryEnabled(THEORY_DATATYPES)
1905 || d_logic.isTheoryEnabled(THEORY_BV)
1906 || d_logic.isTheoryEnabled(THEORY_FP)))
1907 || options::cbqiAll())
1908 {
1909 if( !options::cbqi.wasSetByUser() ){
1910 options::cbqi.set( true );
1911 }
1912 // check whether we should apply full cbqi
1913 if (d_logic.isPure(THEORY_BV))
1914 {
1915 if (!options::cbqiFullEffort.wasSetByUser())
1916 {
1917 options::cbqiFullEffort.set(true);
1918 }
1919 }
1920 }
1921 if( options::cbqi() ){
1922 //must rewrite divk
1923 if( !options::rewriteDivk.wasSetByUser()) {
1924 options::rewriteDivk.set( true );
1925 }
1926 if (options::incrementalSolving())
1927 {
1928 // cannot do nested quantifier elimination in incremental mode
1929 options::cbqiNestedQE.set(false);
1930 }
1931 if (d_logic.isPure(THEORY_ARITH) || d_logic.isPure(THEORY_BV))
1932 {
1933 if( !options::quantConflictFind.wasSetByUser() ){
1934 options::quantConflictFind.set( false );
1935 }
1936 if( !options::instNoEntail.wasSetByUser() ){
1937 options::instNoEntail.set( false );
1938 }
1939 if( !options::instWhenMode.wasSetByUser() && options::cbqiModel() ){
1940 //only instantiation should happen at last call when model is avaiable
1941 options::instWhenMode.set( quantifiers::INST_WHEN_LAST_CALL );
1942 }
1943 }else{
1944 // only supported in pure arithmetic or pure BV
1945 options::cbqiNestedQE.set(false);
1946 }
1947 // prenexing
1948 if (options::cbqiNestedQE())
1949 {
1950 // only complete with prenex = disj_normal or normal
1951 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL)
1952 {
1953 options::prenexQuant.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL);
1954 }
1955 }
1956 else if (options::globalNegate())
1957 {
1958 if (!options::prenexQuant.wasSetByUser())
1959 {
1960 options::prenexQuant.set(quantifiers::PRENEX_QUANT_NONE);
1961 }
1962 }
1963 }
1964 //implied options...
1965 if( options::strictTriggers() ){
1966 if( !options::userPatternsQuant.wasSetByUser() ){
1967 options::userPatternsQuant.set( quantifiers::USER_PAT_MODE_TRUST );
1968 }
1969 }
1970 if( options::qcfMode.wasSetByUser() || options::qcfTConstraint() ){
1971 options::quantConflictFind.set( true );
1972 }
1973 if( options::cbqiNestedQE() ){
1974 options::prenexQuantUser.set( true );
1975 if( !options::preSkolemQuant.wasSetByUser() ){
1976 options::preSkolemQuant.set( true );
1977 }
1978 }
1979 //for induction techniques
1980 if( options::quantInduction() ){
1981 if( !options::dtStcInduction.wasSetByUser() ){
1982 options::dtStcInduction.set( true );
1983 }
1984 if( !options::intWfInduction.wasSetByUser() ){
1985 options::intWfInduction.set( true );
1986 }
1987 }
1988 if( options::dtStcInduction() ){
1989 //try to remove ITEs from quantified formulas
1990 if( !options::iteDtTesterSplitQuant.wasSetByUser() ){
1991 options::iteDtTesterSplitQuant.set( true );
1992 }
1993 if( !options::iteLiftQuant.wasSetByUser() ){
1994 options::iteLiftQuant.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL );
1995 }
1996 }
1997 if( options::intWfInduction() ){
1998 if( !options::purifyTriggers.wasSetByUser() ){
1999 options::purifyTriggers.set( true );
2000 }
2001 }
2002 if( options::conjectureNoFilter() ){
2003 if( !options::conjectureFilterActiveTerms.wasSetByUser() ){
2004 options::conjectureFilterActiveTerms.set( false );
2005 }
2006 if( !options::conjectureFilterCanonical.wasSetByUser() ){
2007 options::conjectureFilterCanonical.set( false );
2008 }
2009 if( !options::conjectureFilterModel.wasSetByUser() ){
2010 options::conjectureFilterModel.set( false );
2011 }
2012 }
2013 if( options::conjectureGenPerRound.wasSetByUser() ){
2014 if( options::conjectureGenPerRound()>0 ){
2015 options::conjectureGen.set( true );
2016 }else{
2017 options::conjectureGen.set( false );
2018 }
2019 }
2020 //can't pre-skolemize nested quantifiers without UF theory
2021 if( !d_logic.isTheoryEnabled(THEORY_UF) && options::preSkolemQuant() ){
2022 if( !options::preSkolemQuantNested.wasSetByUser() ){
2023 options::preSkolemQuantNested.set( false );
2024 }
2025 }
2026 if( !d_logic.isTheoryEnabled(THEORY_DATATYPES) ){
2027 options::quantDynamicSplit.set( quantifiers::QUANT_DSPLIT_MODE_NONE );
2028 }
2029
2030 //until bugs 371,431 are fixed
2031 if( ! options::minisatUseElim.wasSetByUser()){
2032 // cannot use minisat elimination for logics where a theory solver
2033 // introduces new literals into the search. This includes quantifiers
2034 // (quantifier instantiation), and the lemma schemas used in non-linear
2035 // and sets. We also can't use it if models are enabled.
2036 if (d_logic.isTheoryEnabled(THEORY_SETS) || d_logic.isQuantified()
2037 || options::produceModels() || options::produceAssignments()
2038 || options::checkModels()
2039 || (d_logic.isTheoryEnabled(THEORY_ARITH) && !d_logic.isLinear()))
2040 {
2041 options::minisatUseElim.set( false );
2042 }
2043 }
2044 else if (options::minisatUseElim()) {
2045 if (options::produceModels()) {
2046 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl;
2047 setOption("produce-models", SExpr("false"));
2048 }
2049 if (options::produceAssignments()) {
2050 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl;
2051 setOption("produce-assignments", SExpr("false"));
2052 }
2053 if (options::checkModels()) {
2054 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl;
2055 setOption("check-models", SExpr("false"));
2056 }
2057 }
2058
2059 // For now, these array theory optimizations do not support model-building
2060 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2061 options::arraysOptimizeLinear.set(false);
2062 options::arraysLazyRIntro1.set(false);
2063 }
2064
2065 // Non-linear arithmetic does not support models unless nlExt is enabled
2066 if ((d_logic.isTheoryEnabled(THEORY_ARITH) && !d_logic.isLinear()
2067 && !options::nlExt())
2068 || options::globalNegate())
2069 {
2070 std::string reason =
2071 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2072 if (options::produceModels()) {
2073 if(options::produceModels.wasSetByUser()) {
2074 throw OptionException(
2075 std::string("produce-model not supported with " + reason));
2076 }
2077 Warning()
2078 << "SmtEngine: turning off produce-models because unsupported for "
2079 << reason << endl;
2080 setOption("produce-models", SExpr("false"));
2081 }
2082 if (options::produceAssignments()) {
2083 if(options::produceAssignments.wasSetByUser()) {
2084 throw OptionException(
2085 std::string("produce-assignments not supported with " + reason));
2086 }
2087 Warning() << "SmtEngine: turning off produce-assignments because "
2088 "unsupported for "
2089 << reason << endl;
2090 setOption("produce-assignments", SExpr("false"));
2091 }
2092 if (options::checkModels()) {
2093 if(options::checkModels.wasSetByUser()) {
2094 throw OptionException(
2095 std::string("check-models not supported with " + reason));
2096 }
2097 Warning()
2098 << "SmtEngine: turning off check-models because unsupported for "
2099 << reason << endl;
2100 setOption("check-models", SExpr("false"));
2101 }
2102 }
2103
2104 if(options::incrementalSolving() && options::proof()) {
2105 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl;
2106 setOption("incremental", SExpr("false"));
2107 }
2108
2109 if (options::proof())
2110 {
2111 if (options::bitvectorAlgebraicSolver())
2112 {
2113 if (options::bitvectorAlgebraicSolver.wasSetByUser())
2114 {
2115 throw OptionException(
2116 "--bv-algebraic-solver is not supported with proofs");
2117 }
2118 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2119 << std::endl;
2120 options::bitvectorAlgebraicSolver.set(false);
2121 }
2122 if (options::bitvectorEqualitySolver())
2123 {
2124 if (options::bitvectorEqualitySolver.wasSetByUser())
2125 {
2126 throw OptionException("--bv-eq-solver is not supported with proofs");
2127 }
2128 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2129 << std::endl;
2130 options::bitvectorEqualitySolver.set(false);
2131 }
2132 if (options::bitvectorInequalitySolver())
2133 {
2134 if (options::bitvectorInequalitySolver.wasSetByUser())
2135 {
2136 throw OptionException(
2137 "--bv-inequality-solver is not supported with proofs");
2138 }
2139 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2140 << std::endl;
2141 options::bitvectorInequalitySolver.set(false);
2142 }
2143 }
2144
2145 if (!options::bitvectorEqualitySolver())
2146 {
2147 if (options::bvLazyRewriteExtf())
2148 {
2149 if (options::bvLazyRewriteExtf.wasSetByUser())
2150 {
2151 throw OptionException(
2152 "--bv-lazy-rewrite-extf requires --bv-eq-solver to be set");
2153 }
2154 }
2155 Trace("smt")
2156 << "disabling bvLazyRewriteExtf since equality solver is disabled"
2157 << endl;
2158 options::bvLazyRewriteExtf.set(false);
2159 }
2160 }
2161
2162 void SmtEngine::setProblemExtended(bool value)
2163 {
2164 d_problemExtended = value;
2165 if (value) { d_assumptions.clear(); }
2166 }
2167
2168 void SmtEngine::setInfo(const std::string& key, const CVC4::SExpr& value)
2169 {
2170 SmtScope smts(this);
2171
2172 Trace("smt") << "SMT setInfo(" << key << ", " << value << ")" << endl;
2173
2174 if(Dump.isOn("benchmark")) {
2175 if(key == "status") {
2176 string s = value.getValue();
2177 BenchmarkStatus status =
2178 (s == "sat") ? SMT_SATISFIABLE :
2179 ((s == "unsat") ? SMT_UNSATISFIABLE : SMT_UNKNOWN);
2180 Dump("benchmark") << SetBenchmarkStatusCommand(status);
2181 } else {
2182 Dump("benchmark") << SetInfoCommand(key, value);
2183 }
2184 }
2185
2186 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2187 if(key.length() > 5) {
2188 string prefix = key.substr(0, 5);
2189 if(prefix == "cvc4-" || prefix == "cvc4_") {
2190 string cvc4key = key.substr(5);
2191 if(cvc4key == "logic") {
2192 if(! value.isAtom()) {
2193 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2194 }
2195 SmtScope smts(this);
2196 d_logic = value.getValue();
2197 setLogicInternal();
2198 return;
2199 } else {
2200 throw UnrecognizedOptionException();
2201 }
2202 }
2203 }
2204
2205 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2206 if (key == "source" || key == "category" || key == "difficulty"
2207 || key == "notes" || key == "name" || key == "license")
2208 {
2209 // ignore these
2210 return;
2211 }
2212 else if (key == "filename")
2213 {
2214 d_filename = value.getValue();
2215 return;
2216 }
2217 else if (key == "smt-lib-version" && !options::inputLanguage.wasSetByUser())
2218 {
2219 language::input::Language ilang = language::input::LANG_AUTO;
2220 if( (value.isInteger() && value.getIntegerValue() == Integer(2)) ||
2221 (value.isRational() && value.getRationalValue() == Rational(2)) ||
2222 value.getValue() == "2" ||
2223 value.getValue() == "2.0" ) {
2224 ilang = language::input::LANG_SMTLIB_V2_0;
2225 } else if( (value.isRational() && value.getRationalValue() == Rational(5, 2)) ||
2226 value.getValue() == "2.5" ) {
2227 ilang = language::input::LANG_SMTLIB_V2_5;
2228 } else if( (value.isRational() && value.getRationalValue() == Rational(13, 5)) ||
2229 value.getValue() == "2.6" ) {
2230 ilang = language::input::LANG_SMTLIB_V2_6;
2231 }
2232 else if (value.getValue() == "2.6.1")
2233 {
2234 ilang = language::input::LANG_SMTLIB_V2_6_1;
2235 }
2236 else
2237 {
2238 Warning() << "Warning: unsupported smt-lib-version: " << value << endl;
2239 throw UnrecognizedOptionException();
2240 }
2241 options::inputLanguage.set(ilang);
2242 // also update the output language
2243 if (!options::outputLanguage.wasSetByUser())
2244 {
2245 language::output::Language olang = language::toOutputLanguage(ilang);
2246 if (options::outputLanguage() != olang)
2247 {
2248 options::outputLanguage.set(olang);
2249 *options::out() << language::SetLanguage(olang);
2250 }
2251 }
2252 return;
2253 } else if(key == "status") {
2254 string s;
2255 if(value.isAtom()) {
2256 s = value.getValue();
2257 }
2258 if(s != "sat" && s != "unsat" && s != "unknown") {
2259 throw OptionException("argument to (set-info :status ..) must be "
2260 "`sat' or `unsat' or `unknown'");
2261 }
2262 d_status = Result(s, d_filename);
2263 return;
2264 }
2265 throw UnrecognizedOptionException();
2266 }
2267
2268 CVC4::SExpr SmtEngine::getInfo(const std::string& key) const {
2269
2270 SmtScope smts(this);
2271
2272 Trace("smt") << "SMT getInfo(" << key << ")" << endl;
2273 if(key == "all-statistics") {
2274 vector<SExpr> stats;
2275 for(StatisticsRegistry::const_iterator i = NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->begin();
2276 i != NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->end();
2277 ++i) {
2278 vector<SExpr> v;
2279 v.push_back((*i).first);
2280 v.push_back((*i).second);
2281 stats.push_back(v);
2282 }
2283 for(StatisticsRegistry::const_iterator i = d_statisticsRegistry->begin();
2284 i != d_statisticsRegistry->end();
2285 ++i) {
2286 vector<SExpr> v;
2287 v.push_back((*i).first);
2288 v.push_back((*i).second);
2289 stats.push_back(v);
2290 }
2291 return SExpr(stats);
2292 } else if(key == "error-behavior") {
2293 // immediate-exit | continued-execution
2294 if( options::continuedExecution() || options::interactive() ) {
2295 return SExpr(SExpr::Keyword("continued-execution"));
2296 } else {
2297 return SExpr(SExpr::Keyword("immediate-exit"));
2298 }
2299 } else if(key == "name") {
2300 return SExpr(Configuration::getName());
2301 } else if(key == "version") {
2302 return SExpr(Configuration::getVersionString());
2303 } else if(key == "authors") {
2304 return SExpr(Configuration::about());
2305 } else if(key == "status") {
2306 // sat | unsat | unknown
2307 switch(d_status.asSatisfiabilityResult().isSat()) {
2308 case Result::SAT:
2309 return SExpr(SExpr::Keyword("sat"));
2310 case Result::UNSAT:
2311 return SExpr(SExpr::Keyword("unsat"));
2312 default:
2313 return SExpr(SExpr::Keyword("unknown"));
2314 }
2315 } else if(key == "reason-unknown") {
2316 if(!d_status.isNull() && d_status.isUnknown()) {
2317 stringstream ss;
2318 ss << d_status.whyUnknown();
2319 string s = ss.str();
2320 transform(s.begin(), s.end(), s.begin(), ::tolower);
2321 return SExpr(SExpr::Keyword(s));
2322 } else {
2323 throw ModalException("Can't get-info :reason-unknown when the "
2324 "last result wasn't unknown!");
2325 }
2326 } else if(key == "assertion-stack-levels") {
2327 AlwaysAssert(d_userLevels.size() <=
2328 std::numeric_limits<unsigned long int>::max());
2329 return SExpr(static_cast<unsigned long int>(d_userLevels.size()));
2330 } else if(key == "all-options") {
2331 // get the options, like all-statistics
2332 std::vector< std::vector<std::string> > current_options =
2333 Options::current()->getOptions();
2334 return SExpr::parseListOfListOfAtoms(current_options);
2335 } else {
2336 throw UnrecognizedOptionException();
2337 }
2338 }
2339
2340 void SmtEngine::debugCheckFormals(const std::vector<Expr>& formals, Expr func)
2341 {
2342 for(std::vector<Expr>::const_iterator i = formals.begin(); i != formals.end(); ++i) {
2343 if((*i).getKind() != kind::BOUND_VARIABLE) {
2344 stringstream ss;
2345 ss << "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2346 << "definition of function " << func << ", formal\n"
2347 << " " << *i << "\n"
2348 << "has kind " << (*i).getKind();
2349 throw TypeCheckingException(func, ss.str());
2350 }
2351 }
2352 }
2353
2354 void SmtEngine::debugCheckFunctionBody(Expr formula,
2355 const std::vector<Expr>& formals,
2356 Expr func)
2357 {
2358 Type formulaType = formula.getType(options::typeChecking());
2359 Type funcType = func.getType();
2360 // We distinguish here between definitions of constants and functions,
2361 // because the type checking for them is subtly different. Perhaps we
2362 // should instead have SmtEngine::defineFunction() and
2363 // SmtEngine::defineConstant() for better clarity, although then that
2364 // doesn't match the SMT-LIBv2 standard...
2365 if(formals.size() > 0) {
2366 Type rangeType = FunctionType(funcType).getRangeType();
2367 if(! formulaType.isComparableTo(rangeType)) {
2368 stringstream ss;
2369 ss << "Type of defined function does not match its declaration\n"
2370 << "The function : " << func << "\n"
2371 << "Declared type : " << rangeType << "\n"
2372 << "The body : " << formula << "\n"
2373 << "Body type : " << formulaType;
2374 throw TypeCheckingException(func, ss.str());
2375 }
2376 } else {
2377 if(! formulaType.isComparableTo(funcType)) {
2378 stringstream ss;
2379 ss << "Declared type of defined constant does not match its definition\n"
2380 << "The constant : " << func << "\n"
2381 << "Declared type : " << funcType << " " << Type::getTypeNode(funcType)->getId() << "\n"
2382 << "The definition : " << formula << "\n"
2383 << "Definition type: " << formulaType << " " << Type::getTypeNode(formulaType)->getId();
2384 throw TypeCheckingException(func, ss.str());
2385 }
2386 }
2387 }
2388
2389 void SmtEngine::defineFunction(Expr func,
2390 const std::vector<Expr>& formals,
2391 Expr formula)
2392 {
2393 SmtScope smts(this);
2394 doPendingPops();
2395 Trace("smt") << "SMT defineFunction(" << func << ")" << endl;
2396 debugCheckFormals(formals, func);
2397
2398 stringstream ss;
2399 ss << language::SetLanguage(
2400 language::SetLanguage::getLanguage(Dump.getStream()))
2401 << func;
2402 DefineFunctionCommand c(ss.str(), func, formals, formula);
2403 addToModelCommandAndDump(
2404 c, ExprManager::VAR_FLAG_DEFINED, true, "declarations");
2405
2406 PROOF(if (options::checkUnsatCores()) {
2407 d_defineCommands.push_back(c.clone());
2408 });
2409
2410 // type check body
2411 debugCheckFunctionBody(formula, formals, func);
2412
2413 // Substitute out any abstract values in formula
2414 Expr form =
2415 d_private->substituteAbstractValues(Node::fromExpr(formula)).toExpr();
2416
2417 TNode funcNode = func.getTNode();
2418 vector<Node> formalsNodes;
2419 for(vector<Expr>::const_iterator i = formals.begin(),
2420 iend = formals.end();
2421 i != iend;
2422 ++i) {
2423 formalsNodes.push_back((*i).getNode());
2424 }
2425 TNode formNode = form.getTNode();
2426 DefinedFunction def(funcNode, formalsNodes, formNode);
2427 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2428 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2429 // d_haveAdditions = true;
2430 Debug("smt") << "definedFunctions insert " << funcNode << " " << formNode << endl;
2431 d_definedFunctions->insert(funcNode, def);
2432 }
2433
2434 void SmtEngine::defineFunctionsRec(
2435 const std::vector<Expr>& funcs,
2436 const std::vector<std::vector<Expr> >& formals,
2437 const std::vector<Expr>& formulas)
2438 {
2439 SmtScope smts(this);
2440 finalOptionsAreSet();
2441 doPendingPops();
2442 Trace("smt") << "SMT defineFunctionsRec(...)" << endl;
2443
2444 if (funcs.size() != formals.size() && funcs.size() != formulas.size())
2445 {
2446 stringstream ss;
2447 ss << "Number of functions, formals, and function bodies passed to "
2448 "defineFunctionsRec do not match:"
2449 << "\n"
2450 << " #functions : " << funcs.size() << "\n"
2451 << " #arg lists : " << formals.size() << "\n"
2452 << " #function bodies : " << formulas.size() << "\n";
2453 throw ModalException(ss.str());
2454 }
2455 for (unsigned i = 0, size = funcs.size(); i < size; i++)
2456 {
2457 // check formal argument list
2458 debugCheckFormals(formals[i], funcs[i]);
2459 // type check body
2460 debugCheckFunctionBody(formulas[i], formals[i], funcs[i]);
2461 }
2462
2463 if (Dump.isOn("raw-benchmark"))
2464 {
2465 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs, formals, formulas);
2466 }
2467
2468 ExprManager* em = getExprManager();
2469 for (unsigned i = 0, size = funcs.size(); i < size; i++)
2470 {
2471 // we assert a quantified formula
2472 Expr func_app;
2473 // make the function application
2474 if (formals[i].empty())
2475 {
2476 // it has no arguments
2477 func_app = funcs[i];
2478 }
2479 else
2480 {
2481 std::vector<Expr> children;
2482 children.push_back(funcs[i]);
2483 children.insert(children.end(), formals[i].begin(), formals[i].end());
2484 func_app = em->mkExpr(kind::APPLY_UF, children);
2485 }
2486 Expr lem = em->mkExpr(kind::EQUAL, func_app, formulas[i]);
2487 if (!formals[i].empty())
2488 {
2489 // set the attribute to denote this is a function definition
2490 std::string attr_name("fun-def");
2491 Expr aexpr = em->mkExpr(kind::INST_ATTRIBUTE, func_app);
2492 aexpr = em->mkExpr(kind::INST_PATTERN_LIST, aexpr);
2493 std::vector<Expr> expr_values;
2494 std::string str_value;
2495 setUserAttribute(attr_name, func_app, expr_values, str_value);
2496 // make the quantified formula
2497 Expr boundVars = em->mkExpr(kind::BOUND_VAR_LIST, formals[i]);
2498 lem = em->mkExpr(kind::FORALL, boundVars, lem, aexpr);
2499 }
2500 // assert the quantified formula
2501 // notice we don't call assertFormula directly, since this would
2502 // duplicate the output on raw-benchmark.
2503 Expr e = d_private->substituteAbstractValues(Node::fromExpr(lem)).toExpr();
2504 if (d_assertionList != NULL)
2505 {
2506 d_assertionList->push_back(e);
2507 }
2508 d_private->addFormula(e.getNode(), false);
2509 }
2510 }
2511
2512 void SmtEngine::defineFunctionRec(Expr func,
2513 const std::vector<Expr>& formals,
2514 Expr formula)
2515 {
2516 std::vector<Expr> funcs;
2517 funcs.push_back(func);
2518 std::vector<std::vector<Expr> > formals_multi;
2519 formals_multi.push_back(formals);
2520 std::vector<Expr> formulas;
2521 formulas.push_back(formula);
2522 defineFunctionsRec(funcs, formals_multi, formulas);
2523 }
2524
2525 bool SmtEngine::isDefinedFunction( Expr func ){
2526 Node nf = Node::fromExpr( func );
2527 Debug("smt") << "isDefined function " << nf << "?" << std::endl;
2528 return d_definedFunctions->find(nf) != d_definedFunctions->end();
2529 }
2530
2531 void SmtEnginePrivate::finishInit()
2532 {
2533 PreprocessingPassRegistry& ppReg = PreprocessingPassRegistry::getInstance();
2534 d_preprocessingPassContext.reset(new PreprocessingPassContext(
2535 &d_smt, d_resourceManager, &d_iteRemover, &d_propagator));
2536
2537 // TODO: this will likely change when we add support for actually assembling
2538 // preprocessing pipelines. For now, we just create an instance of each
2539 // available preprocessing pass.
2540 std::vector<std::string> passNames = ppReg.getAvailablePasses();
2541 for (const std::string& passName : passNames)
2542 {
2543 d_passes[passName].reset(
2544 ppReg.createPass(d_preprocessingPassContext.get(), passName));
2545 }
2546 }
2547
2548 Node SmtEnginePrivate::expandDefinitions(TNode n, unordered_map<Node, Node, NodeHashFunction>& cache, bool expandOnly)
2549 {
2550 stack<std::tuple<Node, Node, bool>> worklist;
2551 stack<Node> result;
2552 worklist.push(std::make_tuple(Node(n), Node(n), false));
2553 // The worklist is made of triples, each is input / original node then the output / rewritten node
2554 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2555 // or upward pass).
2556
2557 do {
2558 spendResource(options::preprocessStep());
2559
2560 // n is the input / original
2561 // node is the output / result
2562 Node node;
2563 bool childrenPushed;
2564 std::tie(n, node, childrenPushed) = worklist.top();
2565 worklist.pop();
2566
2567 // Working downwards
2568 if(!childrenPushed) {
2569 Kind k = n.getKind();
2570
2571 // we can short circuit (variable) leaves
2572 if(n.isVar()) {
2573 SmtEngine::DefinedFunctionMap::const_iterator i = d_smt.d_definedFunctions->find(n);
2574 if(i != d_smt.d_definedFunctions->end()) {
2575 // replacement must be closed
2576 if((*i).second.getFormals().size() > 0) {
2577 result.push(d_smt.d_nodeManager->mkNode(kind::LAMBDA, d_smt.d_nodeManager->mkNode(kind::BOUND_VAR_LIST, (*i).second.getFormals()), (*i).second.getFormula()));
2578 continue;
2579 }
2580 // don't bother putting in the cache
2581 result.push((*i).second.getFormula());
2582 continue;
2583 }
2584 // don't bother putting in the cache
2585 result.push(n);
2586 continue;
2587 }
2588
2589 // maybe it's in the cache
2590 unordered_map<Node, Node, NodeHashFunction>::iterator cacheHit = cache.find(n);
2591 if(cacheHit != cache.end()) {
2592 TNode ret = (*cacheHit).second;
2593 result.push(ret.isNull() ? n : ret);
2594 continue;
2595 }
2596
2597 // otherwise expand it
2598 bool doExpand = false;
2599 if (k == kind::APPLY)
2600 {
2601 doExpand = true;
2602 }
2603 else if (k == kind::APPLY_UF)
2604 {
2605 // Always do beta-reduction here. The reason is that there may be
2606 // operators such as INTS_MODULUS in the body of the lambda that would
2607 // otherwise be introduced by beta-reduction via the rewriter, but are
2608 // not expanded here since the traversal in this function does not
2609 // traverse the operators of nodes. Hence, we beta-reduce here to
2610 // ensure terms in the body of the lambda are expanded during this
2611 // call.
2612 if (n.getOperator().getKind() == kind::LAMBDA)
2613 {
2614 doExpand = true;
2615 }
2616 else if (options::macrosQuant() || options::sygusInference())
2617 {
2618 // The above options assign substitutions to APPLY_UF, thus we check
2619 // here and expand if this operator corresponds to a defined function.
2620 doExpand = d_smt.isDefinedFunction(n.getOperator().toExpr());
2621 }
2622 }
2623 if (doExpand) {
2624 vector<Node> formals;
2625 TNode fm;
2626 if( n.getOperator().getKind() == kind::LAMBDA ){
2627 TNode op = n.getOperator();
2628 // lambda
2629 for( unsigned i=0; i<op[0].getNumChildren(); i++ ){
2630 formals.push_back( op[0][i] );
2631 }
2632 fm = op[1];
2633 }else{
2634 // application of a user-defined symbol
2635 TNode func = n.getOperator();
2636 SmtEngine::DefinedFunctionMap::const_iterator i = d_smt.d_definedFunctions->find(func);
2637 if(i == d_smt.d_definedFunctions->end()) {
2638 throw TypeCheckingException(n.toExpr(), string("Undefined function: `") + func.toString() + "'");
2639 }
2640 DefinedFunction def = (*i).second;
2641 formals = def.getFormals();
2642
2643 if(Debug.isOn("expand")) {
2644 Debug("expand") << "found: " << n << endl;
2645 Debug("expand") << " func: " << func << endl;
2646 string name = func.getAttribute(expr::VarNameAttr());
2647 Debug("expand") << " : \"" << name << "\"" << endl;
2648 }
2649 if(Debug.isOn("expand")) {
2650 Debug("expand") << " defn: " << def.getFunction() << endl
2651 << " [";
2652 if(formals.size() > 0) {
2653 copy( formals.begin(), formals.end() - 1,
2654 ostream_iterator<Node>(Debug("expand"), ", ") );
2655 Debug("expand") << formals.back();
2656 }
2657 Debug("expand") << "]" << endl
2658 << " " << def.getFunction().getType() << endl
2659 << " " << def.getFormula() << endl;
2660 }
2661
2662 fm = def.getFormula();
2663 }
2664
2665 Node instance = fm.substitute(formals.begin(),
2666 formals.end(),
2667 n.begin(),
2668 n.begin() + formals.size());
2669 Debug("expand") << "made : " << instance << endl;
2670
2671 Node expanded = expandDefinitions(instance, cache, expandOnly);
2672 cache[n] = (n == expanded ? Node::null() : expanded);
2673 result.push(expanded);
2674 continue;
2675
2676 } else if(! expandOnly) {
2677 // do not do any theory stuff if expandOnly is true
2678
2679 theory::Theory* t = d_smt.d_theoryEngine->theoryOf(node);
2680
2681 Assert(t != NULL);
2682 LogicRequest req(d_smt);
2683 node = t->expandDefinition(req, n);
2684 }
2685
2686 // the partial functions can fall through, in which case we still
2687 // consider their children
2688 worklist.push(std::make_tuple(
2689 Node(n), node, true)); // Original and rewritten result
2690
2691 for(size_t i = 0; i < node.getNumChildren(); ++i) {
2692 worklist.push(
2693 std::make_tuple(node[i],
2694 node[i],
2695 false)); // Rewrite the children of the result only
2696 }
2697
2698 } else {
2699 // Working upwards
2700 // Reconstruct the node from it's (now rewritten) children on the stack
2701
2702 Debug("expand") << "cons : " << node << endl;
2703 if(node.getNumChildren()>0) {
2704 //cout << "cons : " << node << endl;
2705 NodeBuilder<> nb(node.getKind());
2706 if(node.getMetaKind() == kind::metakind::PARAMETERIZED) {
2707 Debug("expand") << "op : " << node.getOperator() << endl;
2708 //cout << "op : " << node.getOperator() << endl;
2709 nb << node.getOperator();
2710 }
2711 for(size_t i = 0; i < node.getNumChildren(); ++i) {
2712 Assert(!result.empty());
2713 Node expanded = result.top();
2714 result.pop();
2715 //cout << "exchld : " << expanded << endl;
2716 Debug("expand") << "exchld : " << expanded << endl;
2717 nb << expanded;
2718 }
2719 node = nb;
2720 }
2721 cache[n] = n == node ? Node::null() : node; // Only cache once all subterms are expanded
2722 result.push(node);
2723 }
2724 } while(!worklist.empty());
2725
2726 AlwaysAssert(result.size() == 1);
2727
2728 return result.top();
2729 }
2730
2731 // do dumping (before/after any preprocessing pass)
2732 static void dumpAssertions(const char* key,
2733 const AssertionPipeline& assertionList) {
2734 if( Dump.isOn("assertions") &&
2735 Dump.isOn(string("assertions:") + key) ) {
2736 // Push the simplified assertions to the dump output stream
2737 for(unsigned i = 0; i < assertionList.size(); ++ i) {
2738 TNode n = assertionList[i];
2739 Dump("assertions") << AssertCommand(Expr(n.toExpr()));
2740 }
2741 }
2742 }
2743
2744 // returns false if simplification led to "false"
2745 bool SmtEnginePrivate::simplifyAssertions()
2746 {
2747 spendResource(options::preprocessStep());
2748 Assert(d_smt.d_pendingPops == 0);
2749 try {
2750 ScopeCounter depth(d_simplifyAssertionsDepth);
2751
2752 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl;
2753
2754 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE)
2755 {
2756 if (!options::unsatCores() && !options::fewerPreprocessingHoles())
2757 {
2758 // Perform non-clausal simplification
2759 PreprocessingPassResult res =
2760 d_passes["non-clausal-simp"]->apply(&d_assertions);
2761 if (res == PreprocessingPassResult::CONFLICT)
2762 {
2763 return false;
2764 }
2765 }
2766
2767 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
2768 // do the miplib trick.
2769 if ( // check that option is on
2770 options::arithMLTrick() &&
2771 // miplib rewrites aren't safe in incremental mode
2772 !options::incrementalSolving() &&
2773 // only useful in arith
2774 d_smt.d_logic.isTheoryEnabled(THEORY_ARITH) &&
2775 // we add new assertions and need this (in practice, this
2776 // restriction only disables miplib processing during
2777 // re-simplification, which we don't expect to be useful anyway)
2778 d_assertions.getRealAssertionsEnd() == d_assertions.size())
2779 {
2780 d_passes["miplib-trick"]->apply(&d_assertions);
2781 } else {
2782 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2783 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl;
2784 }
2785 }
2786
2787 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2788
2789 // before ppRewrite check if only core theory for BV theory
2790 d_smt.d_theoryEngine->staticInitializeBVOptions(d_assertions.ref());
2791
2792 // Theory preprocessing
2793 if (d_smt.d_earlyTheoryPP)
2794 {
2795 d_passes["theory-preprocess"]->apply(&d_assertions);
2796 }
2797
2798 // ITE simplification
2799 if (options::doITESimp()
2800 && (d_simplifyAssertionsDepth <= 1 || options::doITESimpOnRepeat()))
2801 {
2802 PreprocessingPassResult res = d_passes["ite-simp"]->apply(&d_assertions);
2803 if (res == PreprocessingPassResult::CONFLICT)
2804 {
2805 Chat() << "...ITE simplification found unsat..." << endl;
2806 return false;
2807 }
2808 }
2809
2810 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2811
2812 // Unconstrained simplification
2813 if(options::unconstrainedSimp()) {
2814 d_passes["unconstrained-simplifier"]->apply(&d_assertions);
2815 }
2816
2817 if (options::repeatSimp()
2818 && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
2819 && !options::unsatCores() && !options::fewerPreprocessingHoles())
2820 {
2821 PreprocessingPassResult res =
2822 d_passes["non-clausal-simp"]->apply(&d_assertions);
2823 if (res == PreprocessingPassResult::CONFLICT)
2824 {
2825 return false;
2826 }
2827 }
2828
2829 dumpAssertions("post-repeatsimp", d_assertions);
2830 Trace("smt") << "POST repeatSimp" << endl;
2831 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2832
2833 } catch(TypeCheckingExceptionPrivate& tcep) {
2834 // Calls to this function should have already weeded out any
2835 // typechecking exceptions via (e.g.) ensureBoolean(). But a
2836 // theory could still create a new expression that isn't
2837 // well-typed, and we don't want the C++ runtime to abort our
2838 // process without any error notice.
2839 stringstream ss;
2840 ss << "A bad expression was produced. Original exception follows:\n"
2841 << tcep;
2842 InternalError(ss.str().c_str());
2843 }
2844 return true;
2845 }
2846
2847 Result SmtEngine::check() {
2848 Assert(d_fullyInited);
2849 Assert(d_pendingPops == 0);
2850
2851 Trace("smt") << "SmtEngine::check()" << endl;
2852
2853 ResourceManager* resourceManager = d_private->getResourceManager();
2854
2855 resourceManager->beginCall();
2856
2857 // Only way we can be out of resource is if cumulative budget is on
2858 if (resourceManager->cumulativeLimitOn() &&
2859 resourceManager->out()) {
2860 Result::UnknownExplanation why = resourceManager->outOfResources() ?
2861 Result::RESOURCEOUT : Result::TIMEOUT;
2862 return Result(Result::VALIDITY_UNKNOWN, why, d_filename);
2863 }
2864
2865 // Make sure the prop layer has all of the assertions
2866 Trace("smt") << "SmtEngine::check(): processing assertions" << endl;
2867 d_private->processAssertions();
2868 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl;
2869
2870 // Turn off stop only for QF_LRA
2871 // TODO: Bring up in a meeting where to put this
2872 if(options::decisionStopOnly() && !options::decisionMode.wasSetByUser() ){
2873 if( // QF_LRA
2874 (not d_logic.isQuantified() &&
2875 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
2876 )){
2877 if (d_private->getIteSkolemMap().empty())
2878 {
2879 options::decisionStopOnly.set(false);
2880 d_decisionEngine->clearStrategies();
2881 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl;
2882 }
2883 }
2884 }
2885
2886 TimerStat::CodeTimer solveTimer(d_stats->d_solveTime);
2887
2888 Chat() << "solving..." << endl;
2889 Trace("smt") << "SmtEngine::check(): running check" << endl;
2890 Result result = d_propEngine->checkSat();
2891
2892 resourceManager->endCall();
2893 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager->getTimeUsage()
2894 << ", resources " << resourceManager->getResourceUsage() << endl;
2895
2896
2897 return Result(result, d_filename);
2898 }
2899
2900 Result SmtEngine::quickCheck() {
2901 Assert(d_fullyInited);
2902 Trace("smt") << "SMT quickCheck()" << endl;
2903 return Result(Result::VALIDITY_UNKNOWN, Result::REQUIRES_FULL_CHECK, d_filename);
2904 }
2905
2906
2907 void SmtEnginePrivate::collectSkolems(TNode n, set<TNode>& skolemSet, unordered_map<Node, bool, NodeHashFunction>& cache)
2908 {
2909 unordered_map<Node, bool, NodeHashFunction>::iterator it;
2910 it = cache.find(n);
2911 if (it != cache.end()) {
2912 return;
2913 }
2914
2915 size_t sz = n.getNumChildren();
2916 if (sz == 0) {
2917 IteSkolemMap::iterator it = getIteSkolemMap().find(n);
2918 if (it != getIteSkolemMap().end())
2919 {
2920 skolemSet.insert(n);
2921 }
2922 cache[n] = true;
2923 return;
2924 }
2925
2926 size_t k = 0;
2927 for (; k < sz; ++k) {
2928 collectSkolems(n[k], skolemSet, cache);
2929 }
2930 cache[n] = true;
2931 }
2932
2933 bool SmtEnginePrivate::checkForBadSkolems(TNode n, TNode skolem, unordered_map<Node, bool, NodeHashFunction>& cache)
2934 {
2935 unordered_map<Node, bool, NodeHashFunction>::iterator it;
2936 it = cache.find(n);
2937 if (it != cache.end()) {
2938 return (*it).second;
2939 }
2940
2941 size_t sz = n.getNumChildren();
2942 if (sz == 0) {
2943 IteSkolemMap::iterator it = getIteSkolemMap().find(n);
2944 bool bad = false;
2945 if (it != getIteSkolemMap().end())
2946 {
2947 if (!((*it).first < n)) {
2948 bad = true;
2949 }
2950 }
2951 cache[n] = bad;
2952 return bad;
2953 }
2954
2955 size_t k = 0;
2956 for (; k < sz; ++k) {
2957 if (checkForBadSkolems(n[k], skolem, cache)) {
2958 cache[n] = true;
2959 return true;
2960 }
2961 }
2962
2963 cache[n] = false;
2964 return false;
2965 }
2966
2967 void SmtEnginePrivate::processAssertions() {
2968 TimerStat::CodeTimer paTimer(d_smt.d_stats->d_processAssertionsTime);
2969 spendResource(options::preprocessStep());
2970 Assert(d_smt.d_fullyInited);
2971 Assert(d_smt.d_pendingPops == 0);
2972 SubstitutionMap& top_level_substs =
2973 d_preprocessingPassContext->getTopLevelSubstitutions();
2974
2975 // Dump the assertions
2976 dumpAssertions("pre-everything", d_assertions);
2977
2978 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl;
2979 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl;
2980
2981 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2982
2983 if (d_assertions.size() == 0) {
2984 // nothing to do
2985 return;
2986 }
2987
2988 if (options::bvGaussElim())
2989 {
2990 d_passes["bv-gauss"]->apply(&d_assertions);
2991 }
2992
2993 if (d_assertionsProcessed && options::incrementalSolving()) {
2994 // TODO(b/1255): Substitutions in incremental mode should be managed with a
2995 // proper data structure.
2996
2997 // Placeholder for storing substitutions
2998 d_preprocessingPassContext->setSubstitutionsIndex(d_assertions.size());
2999 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
3000 }
3001
3002 // Add dummy assertion in last position - to be used as a
3003 // placeholder for any new assertions to get added
3004 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
3005 // any assertions added beyond realAssertionsEnd must NOT affect the
3006 // equisatisfiability
3007 d_assertions.updateRealAssertionsEnd();
3008
3009 // Assertions are NOT guaranteed to be rewritten by this point
3010
3011 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl;
3012 dumpAssertions("pre-definition-expansion", d_assertions);
3013 {
3014 Chat() << "expanding definitions..." << endl;
3015 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl;
3016 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_definitionExpansionTime);
3017 unordered_map<Node, Node, NodeHashFunction> cache;
3018 for(unsigned i = 0; i < d_assertions.size(); ++ i) {
3019 d_assertions.replace(i, expandDefinitions(d_assertions[i], cache));
3020 }
3021 }
3022 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl;
3023 dumpAssertions("post-definition-expansion", d_assertions);
3024
3025 // save the assertions now
3026 THEORY_PROOF
3027 (
3028 for (unsigned i = 0; i < d_assertions.size(); ++i) {
3029 ProofManager::currentPM()->addAssertion(d_assertions[i].toExpr());
3030 }
3031 );
3032
3033 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3034
3035 if (options::globalNegate())
3036 {
3037 // global negation of the formula
3038 d_passes["global-negate"]->apply(&d_assertions);
3039 d_smt.d_globalNegation = !d_smt.d_globalNegation;
3040 }
3041
3042 if( options::nlExtPurify() ){
3043 d_passes["nl-ext-purify"]->apply(&d_assertions);
3044 }
3045
3046 if( options::ceGuidedInst() ){
3047 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
3048 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3049 d_smt.d_theoryEngine->getQuantifiersEngine()
3050 ->getSynthEngine()
3051 ->preregisterAssertion(d_assertions[i]);
3052 }
3053 }
3054
3055 if (options::solveRealAsInt()) {
3056 d_passes["real-to-int"]->apply(&d_assertions);
3057 }
3058
3059 if (options::solveIntAsBV() > 0)
3060 {
3061 d_passes["int-to-bv"]->apply(&d_assertions);
3062 }
3063
3064 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
3065 !d_smt.d_logic.isPure(THEORY_BV) &&
3066 d_smt.d_logic.getLogicString() != "QF_UFBV" &&
3067 d_smt.d_logic.getLogicString() != "QF_ABV") {
3068 throw ModalException("Eager bit-blasting does not currently support theory combination. "
3069 "Note that in a QF_BV problem UF symbols can be introduced for division. "
3070 "Try --bv-div-zero-const to interpret division by zero as a constant.");
3071 }
3072
3073 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
3074 && !options::incrementalSolving())
3075 {
3076 d_passes["bv-ackermann"]->apply(&d_assertions);
3077 }
3078
3079 if (options::bvAbstraction() && !options::incrementalSolving())
3080 {
3081 d_passes["bv-abstraction"]->apply(&d_assertions);
3082 }
3083
3084 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3085
3086 bool noConflict = true;
3087
3088 if (options::extRewPrep())
3089 {
3090 d_passes["ext-rew-pre"]->apply(&d_assertions);
3091 }
3092
3093 // Unconstrained simplification
3094 if(options::unconstrainedSimp()) {
3095 d_passes["rewrite"]->apply(&d_assertions);
3096 d_passes["unconstrained-simplifier"]->apply(&d_assertions);
3097 }
3098
3099 if(options::bvIntroducePow2())
3100 {
3101 d_passes["bv-intro-pow2"]->apply(&d_assertions);
3102 }
3103
3104 if (options::unsatCores())
3105 {
3106 // special rewriting pass for unsat cores, since many of the passes below
3107 // are skipped
3108 d_passes["rewrite"]->apply(&d_assertions);
3109 }
3110 else
3111 {
3112 d_passes["apply-substs"]->apply(&d_assertions);
3113 }
3114
3115 // Assertions ARE guaranteed to be rewritten by this point
3116 #ifdef CVC4_ASSERTIONS
3117 for (unsigned i = 0; i < d_assertions.size(); ++i)
3118 {
3119 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
3120 }
3121 #endif
3122
3123 // Lift bit-vectors of size 1 to bool
3124 if (options::bitvectorToBool())
3125 {
3126 d_passes["bv-to-bool"]->apply(&d_assertions);
3127 }
3128 // Convert non-top-level Booleans to bit-vectors of size 1
3129 if (options::boolToBitvector())
3130 {
3131 d_passes["bool-to-bv"]->apply(&d_assertions);
3132 }
3133 if(options::sepPreSkolemEmp()) {
3134 d_passes["sep-skolem-emp"]->apply(&d_assertions);
3135 }
3136
3137 if( d_smt.d_logic.isQuantified() ){
3138 //remove rewrite rules, apply pre-skolemization to existential quantifiers
3139 d_passes["quantifiers-preprocess"]->apply(&d_assertions);
3140 if( options::macrosQuant() ){
3141 //quantifiers macro expansion
3142 d_passes["quantifier-macros"]->apply(&d_assertions);
3143 }
3144
3145 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
3146 if( options::fmfFunWellDefined() ){
3147 quantifiers::FunDefFmf fdf;
3148 Assert( d_smt.d_fmfRecFunctionsDefined!=NULL );
3149 //must carry over current definitions (for incremental)
3150 for( context::CDList<Node>::const_iterator fit = d_smt.d_fmfRecFunctionsDefined->begin();
3151 fit != d_smt.d_fmfRecFunctionsDefined->end(); ++fit ) {
3152 Node f = (*fit);
3153 Assert( d_smt.d_fmfRecFunctionsAbs.find( f )!=d_smt.d_fmfRecFunctionsAbs.end() );
3154 TypeNode ft = d_smt.d_fmfRecFunctionsAbs[f];
3155 fdf.d_sorts[f] = ft;
3156 std::map< Node, std::vector< Node > >::iterator fcit = d_smt.d_fmfRecFunctionsConcrete.find( f );
3157 Assert( fcit!=d_smt.d_fmfRecFunctionsConcrete.end() );
3158 for( unsigned j=0; j<fcit->second.size(); j++ ){
3159 fdf.d_input_arg_inj[f].push_back( fcit->second[j] );
3160 }
3161 }
3162 fdf.simplify( d_assertions.ref() );
3163 //must store new definitions (for incremental)
3164 for( unsigned i=0; i<fdf.d_funcs.size(); i++ ){
3165 Node f = fdf.d_funcs[i];
3166 d_smt.d_fmfRecFunctionsAbs[f] = fdf.d_sorts[f];
3167 d_smt.d_fmfRecFunctionsConcrete[f].clear();
3168 for( unsigned j=0; j<fdf.d_input_arg_inj[f].size(); j++ ){
3169 d_smt.d_fmfRecFunctionsConcrete[f].push_back( fdf.d_input_arg_inj[f][j] );
3170 }
3171 d_smt.d_fmfRecFunctionsDefined->push_back( f );
3172 }
3173 }
3174 if (options::sygusInference())
3175 {
3176 d_passes["sygus-infer"]->apply(&d_assertions);
3177 }
3178 }
3179
3180 if( options::sortInference() || options::ufssFairnessMonotone() ){
3181 d_passes["sort-inference"]->apply(&d_assertions);
3182 }
3183
3184 if( options::pbRewrites() ){
3185 d_passes["pseudo-boolean-processor"]->apply(&d_assertions);
3186 }
3187
3188 if (options::synthRrPrep())
3189 {
3190 // do candidate rewrite rule synthesis
3191 d_passes["synth-rr"]->apply(&d_assertions);
3192 }
3193
3194 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl;
3195 dumpAssertions("pre-simplify", d_assertions);
3196 Chat() << "simplifying assertions..." << endl;
3197 noConflict = simplifyAssertions();
3198 if(!noConflict){
3199 ++(d_smt.d_stats->d_simplifiedToFalse);
3200 }
3201 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl;
3202 dumpAssertions("post-simplify", d_assertions);
3203
3204 if (options::symmetryBreakerExp() && !options::incrementalSolving())
3205 {
3206 // apply symmetry breaking if not in incremental mode
3207 d_passes["sym-break"]->apply(&d_assertions);
3208 }
3209
3210 if(options::doStaticLearning()) {
3211 d_passes["static-learning"]->apply(&d_assertions);
3212 }
3213 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3214
3215 {
3216 d_smt.d_stats->d_numAssertionsPre += d_assertions.size();
3217 d_passes["ite-removal"]->apply(&d_assertions);
3218 // This is needed because when solving incrementally, removeITEs may introduce
3219 // skolems that were solved for earlier and thus appear in the substitution
3220 // map.
3221 d_passes["apply-substs"]->apply(&d_assertions);
3222 d_smt.d_stats->d_numAssertionsPost += d_assertions.size();
3223 }
3224
3225 dumpAssertions("pre-repeat-simplify", d_assertions);
3226 if(options::repeatSimp()) {
3227 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl;
3228 Chat() << "re-simplifying assertions..." << endl;
3229 ScopeCounter depth(d_simplifyAssertionsDepth);
3230 noConflict &= simplifyAssertions();
3231 if (noConflict) {
3232 // Need to fix up assertion list to maintain invariants:
3233 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
3234 // during ite removal.
3235 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
3236
3237 // cache for expression traversal
3238 unordered_map<Node, bool, NodeHashFunction> cache;
3239
3240 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
3241 // to be moved to the main assertion set
3242 set<TNode> skolemSet;
3243 SubstitutionMap::iterator pos = top_level_substs.begin();
3244 for (; pos != top_level_substs.end(); ++pos)
3245 {
3246 collectSkolems((*pos).first, skolemSet, cache);
3247 collectSkolems((*pos).second, skolemSet, cache);
3248 }
3249
3250 // We need to ensure:
3251 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
3252 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
3253 // If either of these is violated, we must add iteExpr as a proper assertion
3254 IteSkolemMap::iterator it = getIteSkolemMap().begin();
3255 IteSkolemMap::iterator iend = getIteSkolemMap().end();
3256 NodeBuilder<> builder(kind::AND);
3257 builder << d_assertions[d_assertions.getRealAssertionsEnd() - 1];
3258 vector<TNode> toErase;
3259 for (; it != iend; ++it) {
3260 if (skolemSet.find((*it).first) == skolemSet.end()) {
3261 TNode iteExpr = d_assertions[(*it).second];
3262 if (iteExpr.getKind() == kind::ITE &&
3263 iteExpr[1].getKind() == kind::EQUAL &&
3264 iteExpr[1][0] == (*it).first &&
3265 iteExpr[2].getKind() == kind::EQUAL &&
3266 iteExpr[2][0] == (*it).first) {
3267 cache.clear();
3268 bool bad = checkForBadSkolems(iteExpr[0], (*it).first, cache);
3269 bad = bad || checkForBadSkolems(iteExpr[1][1], (*it).first, cache);
3270 bad = bad || checkForBadSkolems(iteExpr[2][1], (*it).first, cache);
3271 if (!bad) {
3272 continue;
3273 }
3274 }
3275 }
3276 // Move this iteExpr into the main assertions
3277 builder << d_assertions[(*it).second];
3278 d_assertions[(*it).second] = NodeManager::currentNM()->mkConst<bool>(true);
3279 toErase.push_back((*it).first);
3280 }
3281 if(builder.getNumChildren() > 1) {
3282 while (!toErase.empty()) {
3283 getIteSkolemMap().erase(toErase.back());
3284 toErase.pop_back();
3285 }
3286 d_assertions[d_assertions.getRealAssertionsEnd() - 1] =
3287 Rewriter::rewrite(Node(builder));
3288 }
3289 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
3290 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
3291 d_passes["ite-removal"]->apply(&d_assertions);
3292 d_passes["apply-substs"]->apply(&d_assertions);
3293 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
3294 }
3295 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl;
3296 }
3297 dumpAssertions("post-repeat-simplify", d_assertions);
3298
3299 if (options::rewriteApplyToConst())
3300 {
3301 d_passes["apply-to-const"]->apply(&d_assertions);
3302 }
3303
3304 // begin: INVARIANT to maintain: no reordering of assertions or
3305 // introducing new ones
3306 #ifdef CVC4_ASSERTIONS
3307 unsigned iteRewriteAssertionsEnd = d_assertions.size();
3308 #endif
3309
3310 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3311
3312 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl;
3313 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3314
3315 d_passes["theory-preprocess"]->apply(&d_assertions);
3316
3317 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER)
3318 {
3319 d_passes["bv-eager-atoms"]->apply(&d_assertions);
3320 }
3321
3322 //notify theory engine new preprocessed assertions
3323 d_smt.d_theoryEngine->notifyPreprocessedAssertions( d_assertions.ref() );
3324
3325 // Push the formula to decision engine
3326 if(noConflict) {
3327 Chat() << "pushing to decision engine..." << endl;
3328 Assert(iteRewriteAssertionsEnd == d_assertions.size());
3329 d_smt.d_decisionEngine->addAssertions(d_assertions);
3330 }
3331
3332 // end: INVARIANT to maintain: no reordering of assertions or
3333 // introducing new ones
3334
3335 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl;
3336 dumpAssertions("post-everything", d_assertions);
3337
3338 // if incremental, compute which variables are assigned
3339 if (options::incrementalSolving())
3340 {
3341 d_preprocessingPassContext->recordSymbolsInAssertions(d_assertions.ref());
3342 }
3343
3344 // Push the formula to SAT
3345 {
3346 Chat() << "converting to CNF..." << endl;
3347 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_cnfConversionTime);
3348 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3349 Chat() << "+ " << d_assertions[i] << std::endl;
3350 d_smt.d_propEngine->assertFormula(d_assertions[i]);
3351 }
3352 }
3353
3354 d_assertionsProcessed = true;
3355
3356 d_assertions.clear();
3357 getIteSkolemMap().clear();
3358 }
3359
3360 void SmtEnginePrivate::addFormula(TNode n, bool inUnsatCore, bool inInput)
3361 {
3362 if (n == d_true) {
3363 // nothing to do
3364 return;
3365 }
3366
3367 Trace("smt") << "SmtEnginePrivate::addFormula(" << n << "), inUnsatCore = " << inUnsatCore << ", inInput = " << inInput << endl;
3368
3369 // Give it to proof manager
3370 PROOF(
3371 if( inInput ){
3372 // n is an input assertion
3373 if (inUnsatCore || options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
3374
3375 ProofManager::currentPM()->addCoreAssertion(n.toExpr());
3376 }
3377 }else{
3378 // n is the result of an unknown preprocessing step, add it to dependency map to null
3379 ProofManager::currentPM()->addDependence(n, Node::null());
3380 }
3381 // rewrite rules are by default in the unsat core because
3382 // they need to be applied until saturation
3383 if(options::unsatCores() &&
3384 n.getKind() == kind::REWRITE_RULE ){
3385 ProofManager::currentPM()->addUnsatCore(n.toExpr());
3386 }
3387 );
3388
3389 // Add the normalized formula to the queue
3390 d_assertions.push_back(n);
3391 //d_assertions.push_back(Rewriter::rewrite(n));
3392 }
3393
3394 void SmtEngine::ensureBoolean(const Expr& e)
3395 {
3396 Type type = e.getType(options::typeChecking());
3397 Type boolType = d_exprManager->booleanType();
3398 if(type != boolType) {
3399 stringstream ss;
3400 ss << "Expected " << boolType << "\n"
3401 << "The assertion : " << e << "\n"
3402 << "Its type : " << type;
3403 throw TypeCheckingException(e, ss.str());
3404 }
3405 }
3406
3407 Result SmtEngine::checkSat(const Expr& assumption, bool inUnsatCore)
3408 {
3409 return checkSatisfiability(assumption, inUnsatCore, false);
3410 }
3411
3412 Result SmtEngine::checkSat(const vector<Expr>& assumptions, bool inUnsatCore)
3413 {
3414 return checkSatisfiability(assumptions, inUnsatCore, false);
3415 }
3416
3417 Result SmtEngine::query(const Expr& assumption, bool inUnsatCore)
3418 {
3419 Assert(!assumption.isNull());
3420 return checkSatisfiability(assumption, inUnsatCore, true);
3421 }
3422
3423 Result SmtEngine::query(const vector<Expr>& assumptions, bool inUnsatCore)
3424 {
3425 return checkSatisfiability(assumptions, inUnsatCore, true);
3426 }
3427
3428 Result SmtEngine::checkSatisfiability(const Expr& expr,
3429 bool inUnsatCore,
3430 bool isQuery)
3431 {
3432 return checkSatisfiability(
3433 expr.isNull() ? vector<Expr>() : vector<Expr>{expr},
3434 inUnsatCore,
3435 isQuery);
3436 }
3437
3438 Result SmtEngine::checkSatisfiability(const vector<Expr>& assumptions,
3439 bool inUnsatCore,
3440 bool isQuery)
3441 {
3442 try
3443 {
3444 SmtScope smts(this);
3445 finalOptionsAreSet();
3446 doPendingPops();
3447
3448 Trace("smt") << "SmtEngine::" << (isQuery ? "query" : "checkSat") << "("
3449 << assumptions << ")" << endl;
3450
3451 if(d_queryMade && !options::incrementalSolving()) {
3452 throw ModalException("Cannot make multiple queries unless "
3453 "incremental solving is enabled "
3454 "(try --incremental)");
3455 }
3456
3457 // check to see if a postsolve() is pending
3458 if(d_needPostsolve) {
3459 d_theoryEngine->postsolve();
3460 d_needPostsolve = false;
3461 }
3462 // Note that a query has been made
3463 d_queryMade = true;
3464 // reset global negation
3465 d_globalNegation = false;
3466
3467 bool didInternalPush = false;
3468
3469 setProblemExtended(true);
3470
3471 if (isQuery)
3472 {
3473 size_t size = assumptions.size();
3474 if (size > 1)
3475 {
3476 /* Assume: not (BIGAND assumptions) */
3477 d_assumptions.push_back(
3478 d_exprManager->mkExpr(kind::AND, assumptions).notExpr());
3479 }
3480 else if (size == 1)
3481 {
3482 /* Assume: not expr */
3483 d_assumptions.push_back(assumptions[0].notExpr());
3484 }
3485 }
3486 else
3487 {
3488 /* Assume: BIGAND assumptions */
3489 d_assumptions = assumptions;
3490 }
3491
3492 if (!d_assumptions.empty())
3493 {
3494 internalPush();
3495 didInternalPush = true;
3496 }
3497
3498 Result r(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
3499 for (Expr e : d_assumptions)
3500 {
3501 // Substitute out any abstract values in ex.
3502 e = d_private->substituteAbstractValues(Node::fromExpr(e)).toExpr();
3503 Assert(e.getExprManager() == d_exprManager);
3504 // Ensure expr is type-checked at this point.
3505 ensureBoolean(e);
3506
3507 /* Add assumption */
3508 if (d_assertionList != NULL)
3509 {
3510 d_assertionList->push_back(e);
3511 }
3512 d_private->addFormula(e.getNode(), inUnsatCore);
3513 }
3514
3515 r = isQuery ? check().asValidityResult() : check().asSatisfiabilityResult();
3516
3517 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
3518 && r.asSatisfiabilityResult().isSat() == Result::UNSAT)
3519 {
3520 r = Result(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
3521 }
3522 // flipped if we did a global negation
3523 if (d_globalNegation)
3524 {
3525 Trace("smt") << "SmtEngine::process global negate " << r << std::endl;
3526 if (r.asSatisfiabilityResult().isSat() == Result::UNSAT)
3527 {
3528 r = Result(Result::SAT);
3529 }
3530 else if (r.asSatisfiabilityResult().isSat() == Result::SAT)
3531 {
3532 // only if satisfaction complete
3533 if (d_logic.isPure(THEORY_ARITH) || d_logic.isPure(THEORY_BV))
3534 {
3535 r = Result(Result::UNSAT);
3536 }
3537 else
3538 {
3539 r = Result(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
3540 }
3541 }
3542 Trace("smt") << "SmtEngine::global negate returned " << r << std::endl;
3543 }
3544
3545 d_needPostsolve = true;
3546
3547 // Dump the query if requested
3548 if (Dump.isOn("benchmark"))
3549 {
3550 size_t size = assumptions.size();
3551 // the expr already got dumped out if assertion-dumping is on
3552 if (isQuery && size == 1)
3553 {
3554 Dump("benchmark") << QueryCommand(assumptions[0]);
3555 }
3556 else if (size == 0)
3557 {
3558 Dump("benchmark") << CheckSatCommand();
3559 }
3560 else
3561 {
3562 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions);
3563 }
3564 }
3565
3566 d_propEngine->resetTrail();
3567
3568 // Pop the context
3569 if (didInternalPush)
3570 {
3571 internalPop();
3572 }
3573
3574 // Remember the status
3575 d_status = r;
3576
3577 setProblemExtended(false);
3578
3579 Trace("smt") << "SmtEngine::" << (isQuery ? "query" : "checkSat") << "("
3580 << assumptions << ") => " << r << endl;
3581
3582 // Check that SAT results generate a model correctly.
3583 if(options::checkModels()) {
3584 // TODO (#1693) check model when unknown result?
3585 if (r.asSatisfiabilityResult().isSat() == Result::SAT)
3586 {
3587 checkModel();
3588 }
3589 }
3590 // Check that UNSAT results generate a proof correctly.
3591 if(options::checkProofs()) {
3592 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
3593 TimerStat::CodeTimer checkProofTimer(d_stats->d_checkProofTime);
3594 checkProof();
3595 }
3596 }
3597 // Check that UNSAT results generate an unsat core correctly.
3598 if(options::checkUnsatCores()) {
3599 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
3600 TimerStat::CodeTimer checkUnsatCoreTimer(d_stats->d_checkUnsatCoreTime);
3601 checkUnsatCore();
3602 }
3603 }
3604 // Check that synthesis solutions satisfy the conjecture
3605 if (options::checkSynthSol()
3606 && r.asSatisfiabilityResult().isSat() == Result::UNSAT)
3607 {
3608 checkSynthSolution();
3609 }
3610
3611 return r;
3612 } catch (UnsafeInterruptException& e) {
3613 AlwaysAssert(d_private->getResourceManager()->out());
3614 Result::UnknownExplanation why = d_private->getResourceManager()->outOfResources() ?
3615 Result::RESOURCEOUT : Result::TIMEOUT;
3616 return Result(Result::SAT_UNKNOWN, why, d_filename);
3617 }
3618 }
3619
3620 vector<Expr> SmtEngine::getUnsatAssumptions(void)
3621 {
3622 Trace("smt") << "SMT getUnsatAssumptions()" << endl;
3623 SmtScope smts(this);
3624 if (!options::unsatAssumptions())
3625 {
3626 throw ModalException(
3627 "Cannot get unsat assumptions when produce-unsat-assumptions option "
3628 "is off.");
3629 }
3630 if (d_status.isNull()
3631 || d_status.asSatisfiabilityResult() != Result::UNSAT
3632 || d_problemExtended)
3633 {
3634 throw RecoverableModalException(
3635 "Cannot get unsat assumptions unless immediately preceded by "
3636 "UNSAT/VALID response.");
3637 }
3638 finalOptionsAreSet();
3639 if (Dump.isOn("benchmark"))
3640 {
3641 Dump("benchmark") << GetUnsatAssumptionsCommand();
3642 }
3643 UnsatCore core = getUnsatCoreInternal();
3644 vector<Expr> res;
3645 for (const Expr& e : d_assumptions)
3646 {
3647 if (find(core.begin(), core.end(), e) != core.end()) { res.push_back(e); }
3648 }
3649 return res;
3650 }
3651
3652 Result SmtEngine::checkSynth(const Expr& e)
3653 {
3654 SmtScope smts(this);
3655 Trace("smt") << "Check synth: " << e << std::endl;
3656 Trace("smt-synth") << "Check synthesis conjecture: " << e << std::endl;
3657 return checkSatisfiability(e, true, false);
3658 }
3659
3660 Result SmtEngine::assertFormula(const Expr& ex, bool inUnsatCore)
3661 {
3662 Assert(ex.getExprManager() == d_exprManager);
3663 SmtScope smts(this);
3664 finalOptionsAreSet();
3665 doPendingPops();
3666
3667 Trace("smt") << "SmtEngine::assertFormula(" << ex << ")" << endl;
3668
3669 if (Dump.isOn("raw-benchmark")) {
3670 Dump("raw-benchmark") << AssertCommand(ex);
3671 }
3672
3673 // Substitute out any abstract values in ex
3674 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3675
3676 ensureBoolean(e);
3677 if(d_assertionList != NULL) {
3678 d_assertionList->push_back(e);
3679 }
3680 d_private->addFormula(e.getNode(), inUnsatCore);
3681 return quickCheck().asValidityResult();
3682 }/* SmtEngine::assertFormula() */
3683
3684 Node SmtEngine::postprocess(TNode node, TypeNode expectedType) const {
3685 return node;
3686 }
3687
3688 Expr SmtEngine::simplify(const Expr& ex)
3689 {
3690 Assert(ex.getExprManager() == d_exprManager);
3691 SmtScope smts(this);
3692 finalOptionsAreSet();
3693 doPendingPops();
3694 Trace("smt") << "SMT simplify(" << ex << ")" << endl;
3695
3696 if(Dump.isOn("benchmark")) {
3697 Dump("benchmark") << SimplifyCommand(ex);
3698 }
3699
3700 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3701 if( options::typeChecking() ) {
3702 e.getType(true); // ensure expr is type-checked at this point
3703 }
3704
3705 // Make sure all preprocessing is done
3706 d_private->processAssertions();
3707 Node n = d_private->simplify(Node::fromExpr(e));
3708 n = postprocess(n, TypeNode::fromType(e.getType()));
3709 return n.toExpr();
3710 }
3711
3712 Expr SmtEngine::expandDefinitions(const Expr& ex)
3713 {
3714 d_private->spendResource(options::preprocessStep());
3715
3716 Assert(ex.getExprManager() == d_exprManager);
3717 SmtScope smts(this);
3718 finalOptionsAreSet();
3719 doPendingPops();
3720 Trace("smt") << "SMT expandDefinitions(" << ex << ")" << endl;
3721
3722 // Substitute out any abstract values in ex.
3723 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3724 if(options::typeChecking()) {
3725 // Ensure expr is type-checked at this point.
3726 e.getType(true);
3727 }
3728 if(Dump.isOn("benchmark")) {
3729 Dump("benchmark") << ExpandDefinitionsCommand(e);
3730 }
3731 unordered_map<Node, Node, NodeHashFunction> cache;
3732 Node n = d_private->expandDefinitions(Node::fromExpr(e), cache, /* expandOnly = */ true);
3733 n = postprocess(n, TypeNode::fromType(e.getType()));
3734
3735 return n.toExpr();
3736 }
3737
3738 // TODO(#1108): Simplify the error reporting of this method.
3739 Expr SmtEngine::getValue(const Expr& ex) const
3740 {
3741 Assert(ex.getExprManager() == d_exprManager);
3742 SmtScope smts(this);
3743
3744 Trace("smt") << "SMT getValue(" << ex << ")" << endl;
3745 if(Dump.isOn("benchmark")) {
3746 Dump("benchmark") << GetValueCommand(ex);
3747 }
3748
3749 if(!options::produceModels()) {
3750 const char* msg =
3751 "Cannot get value when produce-models options is off.";
3752 throw ModalException(msg);
3753 }
3754 if(d_status.isNull() ||
3755 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3756 d_problemExtended) {
3757 const char* msg =
3758 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
3759 throw RecoverableModalException(msg);
3760 }
3761
3762 // Substitute out any abstract values in ex.
3763 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3764
3765 // Ensure expr is type-checked at this point.
3766 e.getType(options::typeChecking());
3767
3768 // do not need to apply preprocessing substitutions (should be recorded
3769 // in model already)
3770
3771 Node n = Node::fromExpr(e);
3772 Trace("smt") << "--- getting value of " << n << endl;
3773 TypeNode expectedType = n.getType();
3774
3775 // Expand, then normalize
3776 unordered_map<Node, Node, NodeHashFunction> cache;
3777 n = d_private->expandDefinitions(n, cache);
3778 // There are two ways model values for terms are computed (for historical
3779 // reasons). One way is that used in check-model; the other is that
3780 // used by the Model classes. It's not clear to me exactly how these
3781 // two are different, but they need to be unified. This ugly hack here
3782 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
3783
3784 //AJR : necessary?
3785 if(!n.getType().isFunction()) {
3786 n = Rewriter::rewrite(n);
3787 }
3788
3789 Trace("smt") << "--- getting value of " << n << endl;
3790 TheoryModel* m = d_theoryEngine->getModel();
3791 Node resultNode;
3792 if(m != NULL) {
3793 resultNode = m->getValue(n);
3794 }
3795 Trace("smt") << "--- got value " << n << " = " << resultNode << endl;
3796 resultNode = postprocess(resultNode, expectedType);
3797 Trace("smt") << "--- model-post returned " << resultNode << endl;
3798 Trace("smt") << "--- model-post returned " << resultNode.getType() << endl;
3799 Trace("smt") << "--- model-post expected " << expectedType << endl;
3800
3801 // type-check the result we got
3802 Assert(resultNode.isNull() || resultNode.getType().isSubtypeOf(expectedType),
3803 "Run with -t smt for details.");
3804
3805 // ensure it's a constant
3806 Assert(resultNode.getKind() == kind::LAMBDA || resultNode.isConst());
3807
3808 if(options::abstractValues() && resultNode.getType().isArray()) {
3809 resultNode = d_private->mkAbstractValue(resultNode);
3810 Trace("smt") << "--- abstract value >> " << resultNode << endl;
3811 }
3812
3813 return resultNode.toExpr();
3814 }
3815
3816 bool SmtEngine::addToAssignment(const Expr& ex) {
3817 SmtScope smts(this);
3818 finalOptionsAreSet();
3819 doPendingPops();
3820 // Substitute out any abstract values in ex
3821 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3822 Type type = e.getType(options::typeChecking());
3823 // must be Boolean
3824 PrettyCheckArgument(
3825 type.isBoolean(), e,
3826 "expected Boolean-typed variable or function application "
3827 "in addToAssignment()" );
3828 Node n = e.getNode();
3829 // must be an APPLY of a zero-ary defined function, or a variable
3830 PrettyCheckArgument(
3831 ( ( n.getKind() == kind::APPLY &&
3832 ( d_definedFunctions->find(n.getOperator()) !=
3833 d_definedFunctions->end() ) &&
3834 n.getNumChildren() == 0 ) ||
3835 n.isVar() ), e,
3836 "expected variable or defined-function application "
3837 "in addToAssignment(),\ngot %s", e.toString().c_str() );
3838 if(!options::produceAssignments()) {
3839 return false;
3840 }
3841 if(d_assignments == NULL) {
3842 d_assignments = new(true) AssignmentSet(d_context);
3843 }
3844 d_assignments->insert(n);
3845
3846 return true;
3847 }
3848
3849 // TODO(#1108): Simplify the error reporting of this method.
3850 vector<pair<Expr, Expr>> SmtEngine::getAssignment()
3851 {
3852 Trace("smt") << "SMT getAssignment()" << endl;
3853 SmtScope smts(this);
3854 finalOptionsAreSet();
3855 if(Dump.isOn("benchmark")) {
3856 Dump("benchmark") << GetAssignmentCommand();
3857 }
3858 if(!options::produceAssignments()) {
3859 const char* msg =
3860 "Cannot get the current assignment when "
3861 "produce-assignments option is off.";
3862 throw ModalException(msg);
3863 }
3864 if(d_status.isNull() ||
3865 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3866 d_problemExtended) {
3867 const char* msg =
3868 "Cannot get the current assignment unless immediately "
3869 "preceded by SAT/INVALID or UNKNOWN response.";
3870 throw RecoverableModalException(msg);
3871 }
3872
3873 vector<pair<Expr,Expr>> res;
3874 if (d_assignments != nullptr)
3875 {
3876 TypeNode boolType = d_nodeManager->booleanType();
3877 TheoryModel* m = d_theoryEngine->getModel();
3878 for (AssignmentSet::key_iterator i = d_assignments->key_begin(),
3879 iend = d_assignments->key_end();
3880 i != iend;
3881 ++i)
3882 {
3883 Node as = *i;
3884 Assert(as.getType() == boolType);
3885
3886 Trace("smt") << "--- getting value of " << as << endl;
3887
3888 // Expand, then normalize
3889 unordered_map<Node, Node, NodeHashFunction> cache;
3890 Node n = d_private->expandDefinitions(as, cache);
3891 n = Rewriter::rewrite(n);
3892
3893 Trace("smt") << "--- getting value of " << n << endl;
3894 Node resultNode;
3895 if (m != nullptr)
3896 {
3897 resultNode = m->getValue(n);
3898 }
3899
3900 // type-check the result we got
3901 Assert(resultNode.isNull() || resultNode.getType() == boolType);
3902
3903 // ensure it's a constant
3904 Assert(resultNode.isConst());
3905
3906 Assert(as.getKind() == kind::APPLY || as.isVar());
3907 Assert(as.getKind() != kind::APPLY || as.getNumChildren() == 0);
3908 res.emplace_back(as.toExpr(), resultNode.toExpr());
3909 }
3910 }
3911 return res;
3912 }
3913
3914 void SmtEngine::addToModelCommandAndDump(const Command& c, uint32_t flags, bool userVisible, const char* dumpTag) {
3915 Trace("smt") << "SMT addToModelCommandAndDump(" << c << ")" << endl;
3916 SmtScope smts(this);
3917 // If we aren't yet fully inited, the user might still turn on
3918 // produce-models. So let's keep any commands around just in
3919 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
3920 // sort "U" in QF_UF before setLogic() is run and we still want to
3921 // support finding card(U) with --finite-model-find, and (2) to
3922 // decouple SmtEngine and ExprManager if the user does a few
3923 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
3924 // and expects to find their cardinalities in the model.
3925 if(/* userVisible && */
3926 (!d_fullyInited || options::produceModels()) &&
3927 (flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
3928 doPendingPops();
3929 if(flags & ExprManager::VAR_FLAG_GLOBAL) {
3930 d_modelGlobalCommands.push_back(c.clone());
3931 } else {
3932 d_modelCommands->push_back(c.clone());
3933 }
3934 }
3935 if(Dump.isOn(dumpTag)) {
3936 if(d_fullyInited) {
3937 Dump(dumpTag) << c;
3938 } else {
3939 d_dumpCommands.push_back(c.clone());
3940 }
3941 }
3942 }
3943
3944 // TODO(#1108): Simplify the error reporting of this method.
3945 Model* SmtEngine::getModel() {
3946 Trace("smt") << "SMT getModel()" << endl;
3947 SmtScope smts(this);
3948
3949 finalOptionsAreSet();
3950
3951 if(Dump.isOn("benchmark")) {
3952 Dump("benchmark") << GetModelCommand();
3953 }
3954
3955 if (!options::assignFunctionValues())
3956 {
3957 const char* msg =
3958 "Cannot get the model when --assign-function-values is false.";
3959 throw RecoverableModalException(msg);
3960 }
3961
3962 if(d_status.isNull() ||
3963 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3964 d_problemExtended) {
3965 const char* msg =
3966 "Cannot get the current model unless immediately "
3967 "preceded by SAT/INVALID or UNKNOWN response.";
3968 throw RecoverableModalException(msg);
3969 }
3970 if(!options::produceModels()) {
3971 const char* msg =
3972 "Cannot get model when produce-models options is off.";
3973 throw ModalException(msg);
3974 }
3975 TheoryModel* m = d_theoryEngine->getModel();
3976
3977 if (options::produceModelCores())
3978 {
3979 // If we enabled model cores, we compute a model core for m based on our
3980 // assertions using the model core builder utility
3981 std::vector<Expr> easserts = getAssertions();
3982 ModelCoreBuilder::setModelCore(easserts, m);
3983 }
3984 m->d_inputName = d_filename;
3985 return m;
3986 }
3987
3988 std::pair<Expr, Expr> SmtEngine::getSepHeapAndNilExpr(void)
3989 {
3990 if (!d_logic.isTheoryEnabled(THEORY_SEP))
3991 {
3992 const char* msg =
3993 "Cannot obtain separation logic expressions if not using the "
3994 "separation logic theory.";
3995 throw RecoverableModalException(msg);
3996 }
3997 NodeManagerScope nms(d_nodeManager);
3998 Expr heap;
3999 Expr nil;
4000 Model* m = getModel();
4001 if (m->getHeapModel(heap, nil))
4002 {
4003 return std::make_pair(heap, nil);
4004 }
4005 InternalError(
4006 "SmtEngine::getSepHeapAndNilExpr(): failed to obtain heap/nil "
4007 "expressions from theory model.");
4008 }
4009
4010 Expr SmtEngine::getSepHeapExpr() { return getSepHeapAndNilExpr().first; }
4011
4012 Expr SmtEngine::getSepNilExpr() { return getSepHeapAndNilExpr().second; }
4013
4014 UnsatCore SmtEngine::getUnsatCoreInternal()
4015 {
4016 #if IS_PROOFS_BUILD
4017 if (!options::unsatCores())
4018 {
4019 throw ModalException(
4020 "Cannot get an unsat core when produce-unsat-cores option is off.");
4021 }
4022 if (d_status.isNull() || d_status.asSatisfiabilityResult() != Result::UNSAT
4023 || d_problemExtended)
4024 {
4025 throw RecoverableModalException(
4026 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
4027 "response.");
4028 }
4029
4030 d_proofManager->traceUnsatCore(); // just to trigger core creation
4031 return UnsatCore(this, d_proofManager->extractUnsatCore());
4032 #else /* IS_PROOFS_BUILD */
4033 throw ModalException(
4034 "This build of CVC4 doesn't have proof support (required for unsat "
4035 "cores).");
4036 #endif /* IS_PROOFS_BUILD */
4037 }
4038
4039 void SmtEngine::checkUnsatCore() {
4040 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
4041
4042 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl;
4043 UnsatCore core = getUnsatCore();
4044
4045 SmtEngine coreChecker(d_exprManager);
4046 coreChecker.setLogic(getLogicInfo());
4047
4048 PROOF(
4049 std::vector<Command*>::const_iterator itg = d_defineCommands.begin();
4050 for (; itg != d_defineCommands.end(); ++itg) {
4051 (*itg)->invoke(&coreChecker);
4052 }
4053 );
4054
4055 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core.size() << ")" << endl;
4056 for(UnsatCore::iterator i = core.begin(); i != core.end(); ++i) {
4057 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i << endl;
4058 coreChecker.assertFormula(*i);
4059 }
4060 const bool checkUnsatCores = options::checkUnsatCores();
4061 Result r;
4062 try {
4063 options::checkUnsatCores.set(false);
4064 options::checkProofs.set(false);
4065 r = coreChecker.checkSat();
4066 } catch(...) {
4067 options::checkUnsatCores.set(checkUnsatCores);
4068 throw;
4069 }
4070 Notice() << "SmtEngine::checkUnsatCore(): result is " << r << endl;
4071 if(r.asSatisfiabilityResult().isUnknown()) {
4072 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
4073 }
4074
4075 if(r.asSatisfiabilityResult().isSat()) {
4076 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
4077 }
4078 }
4079
4080 void SmtEngine::checkModel(bool hardFailure) {
4081 // --check-model implies --produce-assertions, which enables the
4082 // assertion list, so we should be ok.
4083 Assert(d_assertionList != NULL, "don't have an assertion list to check in SmtEngine::checkModel()");
4084
4085 TimerStat::CodeTimer checkModelTimer(d_stats->d_checkModelTime);
4086
4087 // Throughout, we use Notice() to give diagnostic output.
4088 //
4089 // If this function is running, the user gave --check-model (or equivalent),
4090 // and if Notice() is on, the user gave --verbose (or equivalent).
4091
4092 Notice() << "SmtEngine::checkModel(): generating model" << endl;
4093 TheoryModel* m = d_theoryEngine->getModel();
4094
4095 // check-model is not guaranteed to succeed if approximate values were used
4096 if (m->hasApproximations())
4097 {
4098 Warning()
4099 << "WARNING: running check-model on a model with approximate values..."
4100 << endl;
4101 }
4102
4103 // Check individual theory assertions
4104 d_theoryEngine->checkTheoryAssertionsWithModel(hardFailure);
4105
4106 // Output the model
4107 Notice() << *m;
4108
4109 // We have a "fake context" for the substitution map (we don't need it
4110 // to be context-dependent)
4111 context::Context fakeContext;
4112 SubstitutionMap substitutions(&fakeContext, /* substituteUnderQuantifiers = */ false);
4113
4114 for(size_t k = 0; k < m->getNumCommands(); ++k) {
4115 const DeclareFunctionCommand* c = dynamic_cast<const DeclareFunctionCommand*>(m->getCommand(k));
4116 Notice() << "SmtEngine::checkModel(): model command " << k << " : " << m->getCommand(k) << endl;
4117 if(c == NULL) {
4118 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
4119 Notice() << "SmtEngine::checkModel(): skipping..." << endl;
4120 } else {
4121 // We have a DECLARE-FUN:
4122 //
4123 // We'll first do some checks, then add to our substitution map
4124 // the mapping: function symbol |-> value
4125
4126 Expr func = c->getFunction();
4127 Node val = m->getValue(func);
4128
4129 Notice() << "SmtEngine::checkModel(): adding substitution: " << func << " |-> " << val << endl;
4130
4131 // (1) if the value is a lambda, ensure the lambda doesn't contain the
4132 // function symbol (since then the definition is recursive)
4133 if (val.getKind() == kind::LAMBDA) {
4134 // first apply the model substitutions we have so far
4135 Debug("boolean-terms") << "applying subses to " << val[1] << endl;
4136 Node n = substitutions.apply(val[1]);
4137 Debug("boolean-terms") << "++ got " << n << endl;
4138 // now check if n contains func by doing a substitution
4139 // [func->func2] and checking equality of the Nodes.
4140 // (this just a way to check if func is in n.)
4141 SubstitutionMap subs(&fakeContext);
4142 Node func2 = NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func.getType()), "", NodeManager::SKOLEM_NO_NOTIFY);
4143 subs.addSubstitution(func, func2);
4144 if(subs.apply(n) != n) {
4145 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl;
4146 stringstream ss;
4147 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4148 << "considering model value for " << func << endl
4149 << "body of lambda is: " << val << endl;
4150 if(n != val[1]) {
4151 ss << "body substitutes to: " << n << endl;
4152 }
4153 ss << "so " << func << " is defined in terms of itself." << endl
4154 << "Run with `--check-models -v' for additional diagnostics.";
4155 InternalError(ss.str());
4156 }
4157 }
4158
4159 // (2) check that the value is actually a value
4160 else if (!val.isConst()) {
4161 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl;
4162 stringstream ss;
4163 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4164 << "model value for " << func << endl
4165 << " is " << val << endl
4166 << "and that is not a constant (.isConst() == false)." << endl
4167 << "Run with `--check-models -v' for additional diagnostics.";
4168 InternalError(ss.str());
4169 }
4170
4171 // (3) check that it's the correct (sub)type
4172 // This was intended to be a more general check, but for now we can't do that because
4173 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
4174 else if(func.getType().isInteger() && !val.getType().isInteger()) {
4175 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl;
4176 stringstream ss;
4177 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4178 << "model value for " << func << endl
4179 << " is " << val << endl
4180 << "value type is " << val.getType() << endl
4181 << "should be of type " << func.getType() << endl
4182 << "Run with `--check-models -v' for additional diagnostics.";
4183 InternalError(ss.str());
4184 }
4185
4186 // (4) checks complete, add the substitution
4187 Debug("boolean-terms") << "cm: adding subs " << func << " :=> " << val << endl;
4188 substitutions.addSubstitution(func, val);
4189 }
4190 }
4191
4192 // Now go through all our user assertions checking if they're satisfied.
4193 for(AssertionList::const_iterator i = d_assertionList->begin(); i != d_assertionList->end(); ++i) {
4194 Notice() << "SmtEngine::checkModel(): checking assertion " << *i << endl;
4195 Node n = Node::fromExpr(*i);
4196
4197 // Apply any define-funs from the problem.
4198 {
4199 unordered_map<Node, Node, NodeHashFunction> cache;
4200 n = d_private->expandDefinitions(n, cache);
4201 }
4202 Notice() << "SmtEngine::checkModel(): -- expands to " << n << endl;
4203
4204 // Apply our model value substitutions.
4205 Debug("boolean-terms") << "applying subses to " << n << endl;
4206 n = substitutions.apply(n);
4207 Debug("boolean-terms") << "++ got " << n << endl;
4208 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n << endl;
4209
4210 if( n.getKind() != kind::REWRITE_RULE ){
4211 // In case it's a quantifier (or contains one), look up its value before
4212 // simplifying, or the quantifier might be irreparably altered.
4213 n = m->getValue(n);
4214 Notice() << "SmtEngine::checkModel(): -- get value : " << n << std::endl;
4215 } else {
4216 // Note this "skip" is done here, rather than above. This is
4217 // because (1) the quantifier could in principle simplify to false,
4218 // which should be reported, and (2) checking for the quantifier
4219 // above, before simplification, doesn't catch buried quantifiers
4220 // anyway (those not at the top-level).
4221 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
4222 << endl;
4223 continue;
4224 }
4225
4226 // Simplify the result.
4227 n = d_private->simplify(n);
4228 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n << endl;
4229
4230 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
4231 n = d_private->d_iteRemover.replace(n);
4232 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n << endl;
4233
4234 // Apply our model value substitutions (again), as things may have been simplified.
4235 Debug("boolean-terms") << "applying subses to " << n << endl;
4236 n = substitutions.apply(n);
4237 Debug("boolean-terms") << "++ got " << n << endl;
4238 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n << endl;
4239
4240 // As a last-ditch effort, ask model to simplify it.
4241 // Presently, this is only an issue for quantifiers, which can have a value
4242 // but don't show up in our substitution map above.
4243 n = m->getValue(n);
4244 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n << endl;
4245
4246 if( d_logic.isQuantified() ){
4247 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
4248 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
4249 // hence we use a relaxed version of check model here.
4250 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
4251 if( hardFailure && !n.isConst() && n.getKind() != kind::LAMBDA ){
4252 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl;
4253 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n ) );
4254 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n << endl;
4255 continue;
4256 }
4257 }else{
4258 AlwaysAssert(!hardFailure || n.isConst() || n.getKind() == kind::LAMBDA);
4259 }
4260 // The result should be == true.
4261 if(n != NodeManager::currentNM()->mkConst(true)) {
4262 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
4263 << endl;
4264 stringstream ss;
4265 ss << "SmtEngine::checkModel(): "
4266 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4267 << "assertion: " << *i << endl
4268 << "simplifies to: " << n << endl
4269 << "expected `true'." << endl
4270 << "Run with `--check-models -v' for additional diagnostics.";
4271 if(hardFailure) {
4272 InternalError(ss.str());
4273 } else {
4274 Warning() << ss.str() << endl;
4275 }
4276 }
4277 }
4278 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl;
4279 }
4280
4281 void SmtEngine::checkSynthSolution()
4282 {
4283 NodeManager* nm = NodeManager::currentNM();
4284 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl;
4285 map<Node, Node> sol_map;
4286 /* Get solutions and build auxiliary vectors for substituting */
4287 d_theoryEngine->getSynthSolutions(sol_map);
4288 if (sol_map.empty())
4289 {
4290 Trace("check-synth-sol") << "No solution to check!\n";
4291 return;
4292 }
4293 Trace("check-synth-sol") << "Got solution map:\n";
4294 std::vector<Node> function_vars, function_sols;
4295 for (const auto& pair : sol_map)
4296 {
4297 Trace("check-synth-sol") << pair.first << " --> " << pair.second << "\n";
4298 function_vars.push_back(pair.first);
4299 function_sols.push_back(pair.second);
4300 }
4301 Trace("check-synth-sol") << "Starting new SMT Engine\n";
4302 /* Start new SMT engine to check solutions */
4303 SmtEngine solChecker(d_exprManager);
4304 solChecker.setLogic(getLogicInfo());
4305 setOption("check-synth-sol", SExpr("false"));
4306
4307 Trace("check-synth-sol") << "Retrieving assertions\n";
4308 // Build conjecture from original assertions
4309 if (d_assertionList == NULL)
4310 {
4311 Trace("check-synth-sol") << "No assertions to check\n";
4312 return;
4313 }
4314 for (AssertionList::const_iterator i = d_assertionList->begin();
4315 i != d_assertionList->end();
4316 ++i)
4317 {
4318 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i << endl;
4319 Trace("check-synth-sol") << "Retrieving assertion " << *i << "\n";
4320 Node conj = Node::fromExpr(*i);
4321 // Apply any define-funs from the problem.
4322 {
4323 unordered_map<Node, Node, NodeHashFunction> cache;
4324 conj = d_private->expandDefinitions(conj, cache);
4325 }
4326 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj << endl;
4327 Trace("check-synth-sol") << "Expanded assertion " << conj << "\n";
4328 if (conj.getKind() != kind::FORALL)
4329 {
4330 Trace("check-synth-sol") << "Not a checkable assertion.\n";
4331 continue;
4332 }
4333
4334 // Apply solution map to conjecture body
4335 Node conjBody;
4336 /* Whether property is quantifier free */
4337 if (conj[1].getKind() != kind::EXISTS)
4338 {
4339 conjBody = conj[1].substitute(function_vars.begin(),
4340 function_vars.end(),
4341 function_sols.begin(),
4342 function_sols.end());
4343 }
4344 else
4345 {
4346 conjBody = conj[1][1].substitute(function_vars.begin(),
4347 function_vars.end(),
4348 function_sols.begin(),
4349 function_sols.end());
4350
4351 /* Skolemize property */
4352 std::vector<Node> vars, skos;
4353 for (unsigned j = 0, size = conj[1][0].getNumChildren(); j < size; ++j)
4354 {
4355 vars.push_back(conj[1][0][j]);
4356 std::stringstream ss;
4357 ss << "sk_" << j;
4358 skos.push_back(nm->mkSkolem(ss.str(), conj[1][0][j].getType()));
4359 Trace("check-synth-sol") << "\tSkolemizing " << conj[1][0][j] << " to "
4360 << skos.back() << "\n";
4361 }
4362 conjBody = conjBody.substitute(
4363 vars.begin(), vars.end(), skos.begin(), skos.end());
4364 }
4365 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
4366 << conjBody << endl;
4367 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
4368 << "\n";
4369 solChecker.assertFormula(conjBody.toExpr());
4370 Result r = solChecker.checkSat();
4371 Notice() << "SmtEngine::checkSynthSolution(): result is " << r << endl;
4372 Trace("check-synth-sol") << "Satsifiability check: " << r << "\n";
4373 if (r.asSatisfiabilityResult().isUnknown())
4374 {
4375 InternalError(
4376 "SmtEngine::checkSynthSolution(): could not check solution, result "
4377 "unknown.");
4378 }
4379 else if (r.asSatisfiabilityResult().isSat())
4380 {
4381 InternalError(
4382 "SmtEngine::checkSynthSolution(): produced solution leads to "
4383 "satisfiable negated conjecture.");
4384 }
4385 solChecker.resetAssertions();
4386 }
4387 }
4388
4389 // TODO(#1108): Simplify the error reporting of this method.
4390 UnsatCore SmtEngine::getUnsatCore() {
4391 Trace("smt") << "SMT getUnsatCore()" << endl;
4392 SmtScope smts(this);
4393 finalOptionsAreSet();
4394 if(Dump.isOn("benchmark")) {
4395 Dump("benchmark") << GetUnsatCoreCommand();
4396 }
4397 return getUnsatCoreInternal();
4398 }
4399
4400 // TODO(#1108): Simplify the error reporting of this method.
4401 const Proof& SmtEngine::getProof()
4402 {
4403 Trace("smt") << "SMT getProof()" << endl;
4404 SmtScope smts(this);
4405 finalOptionsAreSet();
4406 if(Dump.isOn("benchmark")) {
4407 Dump("benchmark") << GetProofCommand();
4408 }
4409 #if IS_PROOFS_BUILD
4410 if(!options::proof()) {
4411 throw ModalException("Cannot get a proof when produce-proofs option is off.");
4412 }
4413 if(d_status.isNull() ||
4414 d_status.asSatisfiabilityResult() != Result::UNSAT ||
4415 d_problemExtended) {
4416 throw RecoverableModalException(
4417 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
4418 "response.");
4419 }
4420
4421 return ProofManager::getProof(this);
4422 #else /* IS_PROOFS_BUILD */
4423 throw ModalException("This build of CVC4 doesn't have proof support.");
4424 #endif /* IS_PROOFS_BUILD */
4425 }
4426
4427 void SmtEngine::printInstantiations( std::ostream& out ) {
4428 SmtScope smts(this);
4429 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
4430 out << "% SZS output start Proof for " << d_filename.c_str() << std::endl;
4431 }
4432 if( d_theoryEngine ){
4433 d_theoryEngine->printInstantiations( out );
4434 }else{
4435 Assert( false );
4436 }
4437 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
4438 out << "% SZS output end Proof for " << d_filename.c_str() << std::endl;
4439 }
4440 }
4441
4442 void SmtEngine::printSynthSolution( std::ostream& out ) {
4443 SmtScope smts(this);
4444 if( d_theoryEngine ){
4445 d_theoryEngine->printSynthSolution( out );
4446 }else{
4447 Assert( false );
4448 }
4449 }
4450
4451 void SmtEngine::getSynthSolutions(std::map<Expr, Expr>& sol_map)
4452 {
4453 SmtScope smts(this);
4454 map<Node, Node> sol_mapn;
4455 Assert(d_theoryEngine != nullptr);
4456 d_theoryEngine->getSynthSolutions(sol_mapn);
4457 for (std::pair<const Node, Node>& s : sol_mapn)
4458 {
4459 sol_map[s.first.toExpr()] = s.second.toExpr();
4460 }
4461 }
4462
4463 Expr SmtEngine::doQuantifierElimination(const Expr& e, bool doFull, bool strict)
4464 {
4465 SmtScope smts(this);
4466 if(!d_logic.isPure(THEORY_ARITH) && strict){
4467 Warning() << "Unexpected logic for quantifier elimination " << d_logic << endl;
4468 }
4469 Trace("smt-qe") << "Do quantifier elimination " << e << std::endl;
4470 Node n_e = Node::fromExpr( e );
4471 if (n_e.getKind() != kind::EXISTS && n_e.getKind() != kind::FORALL)
4472 {
4473 throw ModalException(
4474 "Expecting a quantified formula as argument to get-qe.");
4475 }
4476 //tag the quantified formula with the quant-elim attribute
4477 TypeNode t = NodeManager::currentNM()->booleanType();
4478 Node n_attr = NodeManager::currentNM()->mkSkolem("qe", t, "Auxiliary variable for qe attr.");
4479 std::vector< Node > node_values;
4480 d_theoryEngine->setUserAttribute( doFull ? "quant-elim" : "quant-elim-partial", n_attr, node_values, "");
4481 n_attr = NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE, n_attr);
4482 n_attr = NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST, n_attr);
4483 std::vector< Node > e_children;
4484 e_children.push_back( n_e[0] );
4485 e_children.push_back(n_e.getKind() == kind::EXISTS ? n_e[1]
4486 : n_e[1].negate());
4487 e_children.push_back( n_attr );
4488 Node nn_e = NodeManager::currentNM()->mkNode( kind::EXISTS, e_children );
4489 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e << std::endl;
4490 Assert( nn_e.getNumChildren()==3 );
4491 Result r = checkSatisfiability(nn_e.toExpr(), true, true);
4492 Trace("smt-qe") << "Query returned " << r << std::endl;
4493 if(r.asSatisfiabilityResult().isSat() != Result::UNSAT ) {
4494 if( r.asSatisfiabilityResult().isSat() != Result::SAT && doFull ){
4495 stringstream ss;
4496 ss << "While performing quantifier elimination, unexpected result : " << r << " for query.";
4497 InternalError(ss.str().c_str());
4498 }
4499 std::vector< Node > inst_qs;
4500 d_theoryEngine->getInstantiatedQuantifiedFormulas( inst_qs );
4501 Assert( inst_qs.size()<=1 );
4502 Node ret_n;
4503 if( inst_qs.size()==1 ){
4504 Node top_q = inst_qs[0];
4505 //Node top_q = Rewriter::rewrite( nn_e ).negate();
4506 Assert( top_q.getKind()==kind::FORALL );
4507 Trace("smt-qe") << "Get qe for " << top_q << std::endl;
4508 ret_n = d_theoryEngine->getInstantiatedConjunction( top_q );
4509 Trace("smt-qe") << "Returned : " << ret_n << std::endl;
4510 if (n_e.getKind() == kind::EXISTS)
4511 {
4512 ret_n = Rewriter::rewrite(ret_n.negate());
4513 }
4514 }else{
4515 ret_n = NodeManager::currentNM()->mkConst(n_e.getKind() != kind::EXISTS);
4516 }
4517 // do extended rewrite to minimize the size of the formula aggressively
4518 theory::quantifiers::ExtendedRewriter extr(true);
4519 ret_n = extr.extendedRewrite(ret_n);
4520 return ret_n.toExpr();
4521 }else {
4522 return NodeManager::currentNM()
4523 ->mkConst(n_e.getKind() == kind::EXISTS)
4524 .toExpr();
4525 }
4526 }
4527
4528 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector< Expr >& qs ) {
4529 SmtScope smts(this);
4530 if( d_theoryEngine ){
4531 std::vector< Node > qs_n;
4532 d_theoryEngine->getInstantiatedQuantifiedFormulas( qs_n );
4533 for( unsigned i=0; i<qs_n.size(); i++ ){
4534 qs.push_back( qs_n[i].toExpr() );
4535 }
4536 }else{
4537 Assert( false );
4538 }
4539 }
4540
4541 void SmtEngine::getInstantiations( Expr q, std::vector< Expr >& insts ) {
4542 SmtScope smts(this);
4543 if( d_theoryEngine ){
4544 std::vector< Node > insts_n;
4545 d_theoryEngine->getInstantiations( Node::fromExpr( q ), insts_n );
4546 for( unsigned i=0; i<insts_n.size(); i++ ){
4547 insts.push_back( insts_n[i].toExpr() );
4548 }
4549 }else{
4550 Assert( false );
4551 }
4552 }
4553
4554 void SmtEngine::getInstantiationTermVectors( Expr q, std::vector< std::vector< Expr > >& tvecs ) {
4555 SmtScope smts(this);
4556 Assert(options::trackInstLemmas());
4557 if( d_theoryEngine ){
4558 std::vector< std::vector< Node > > tvecs_n;
4559 d_theoryEngine->getInstantiationTermVectors( Node::fromExpr( q ), tvecs_n );
4560 for( unsigned i=0; i<tvecs_n.size(); i++ ){
4561 std::vector< Expr > tvec;
4562 for( unsigned j=0; j<tvecs_n[i].size(); j++ ){
4563 tvec.push_back( tvecs_n[i][j].toExpr() );
4564 }
4565 tvecs.push_back( tvec );
4566 }
4567 }else{
4568 Assert( false );
4569 }
4570 }
4571
4572 vector<Expr> SmtEngine::getAssertions() {
4573 SmtScope smts(this);
4574 finalOptionsAreSet();
4575 doPendingPops();
4576 if(Dump.isOn("benchmark")) {
4577 Dump("benchmark") << GetAssertionsCommand();
4578 }
4579 Trace("smt") << "SMT getAssertions()" << endl;
4580 if(!options::produceAssertions()) {
4581 const char* msg =
4582 "Cannot query the current assertion list when not in produce-assertions mode.";
4583 throw ModalException(msg);
4584 }
4585 Assert(d_assertionList != NULL);
4586 // copy the result out
4587 return vector<Expr>(d_assertionList->begin(), d_assertionList->end());
4588 }
4589
4590 void SmtEngine::push()
4591 {
4592 SmtScope smts(this);
4593 finalOptionsAreSet();
4594 doPendingPops();
4595 Trace("smt") << "SMT push()" << endl;
4596 d_private->notifyPush();
4597 d_private->processAssertions();
4598 if(Dump.isOn("benchmark")) {
4599 Dump("benchmark") << PushCommand();
4600 }
4601 if(!options::incrementalSolving()) {
4602 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
4603 }
4604
4605 // check to see if a postsolve() is pending
4606 if(d_needPostsolve) {
4607 d_theoryEngine->postsolve();
4608 d_needPostsolve = false;
4609 }
4610
4611 // The problem isn't really "extended" yet, but this disallows
4612 // get-model after a push, simplifying our lives somewhat and
4613 // staying symmtric with pop.
4614 setProblemExtended(true);
4615
4616 d_userLevels.push_back(d_userContext->getLevel());
4617 internalPush();
4618 Trace("userpushpop") << "SmtEngine: pushed to level "
4619 << d_userContext->getLevel() << endl;
4620 }
4621
4622 void SmtEngine::pop() {
4623 SmtScope smts(this);
4624 finalOptionsAreSet();
4625 Trace("smt") << "SMT pop()" << endl;
4626 if(Dump.isOn("benchmark")) {
4627 Dump("benchmark") << PopCommand();
4628 }
4629 if(!options::incrementalSolving()) {
4630 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
4631 }
4632 if(d_userLevels.size() == 0) {
4633 throw ModalException("Cannot pop beyond the first user frame");
4634 }
4635
4636 // check to see if a postsolve() is pending
4637 if(d_needPostsolve) {
4638 d_theoryEngine->postsolve();
4639 d_needPostsolve = false;
4640 }
4641
4642 // The problem isn't really "extended" yet, but this disallows
4643 // get-model after a pop, simplifying our lives somewhat. It might
4644 // not be strictly necessary to do so, since the pops occur lazily,
4645 // but also it would be weird to have a legally-executed (get-model)
4646 // that only returns a subset of the assignment (because the rest
4647 // is no longer in scope!).
4648 setProblemExtended(true);
4649
4650 AlwaysAssert(d_userContext->getLevel() > 0);
4651 AlwaysAssert(d_userLevels.back() < d_userContext->getLevel());
4652 while (d_userLevels.back() < d_userContext->getLevel()) {
4653 internalPop(true);
4654 }
4655 d_userLevels.pop_back();
4656
4657 // Clear out assertion queues etc., in case anything is still in there
4658 d_private->notifyPop();
4659
4660 Trace("userpushpop") << "SmtEngine: popped to level "
4661 << d_userContext->getLevel() << endl;
4662 // FIXME: should we reset d_status here?
4663 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
4664 }
4665
4666 void SmtEngine::internalPush() {
4667 Assert(d_fullyInited);
4668 Trace("smt") << "SmtEngine::internalPush()" << endl;
4669 doPendingPops();
4670 if(options::incrementalSolving()) {
4671 d_private->processAssertions();
4672 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
4673 d_userContext->push();
4674 // the d_context push is done inside of the SAT solver
4675 d_propEngine->push();
4676 }
4677 }
4678
4679 void SmtEngine::internalPop(bool immediate) {
4680 Assert(d_fullyInited);
4681 Trace("smt") << "SmtEngine::internalPop()" << endl;
4682 if(options::incrementalSolving()) {
4683 ++d_pendingPops;
4684 }
4685 if(immediate) {
4686 doPendingPops();
4687 }
4688 }
4689
4690 void SmtEngine::doPendingPops() {
4691 Assert(d_pendingPops == 0 || options::incrementalSolving());
4692 while(d_pendingPops > 0) {
4693 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
4694 d_propEngine->pop();
4695 // the d_context pop is done inside of the SAT solver
4696 d_userContext->pop();
4697 --d_pendingPops;
4698 }
4699 }
4700
4701 void SmtEngine::reset()
4702 {
4703 SmtScope smts(this);
4704 ExprManager *em = d_exprManager;
4705 Trace("smt") << "SMT reset()" << endl;
4706 if(Dump.isOn("benchmark")) {
4707 Dump("benchmark") << ResetCommand();
4708 }
4709 Options opts;
4710 opts.copyValues(d_originalOptions);
4711 this->~SmtEngine();
4712 NodeManager::fromExprManager(em)->getOptions().copyValues(opts);
4713 new(this) SmtEngine(em);
4714 }
4715
4716 void SmtEngine::resetAssertions()
4717 {
4718 SmtScope smts(this);
4719 doPendingPops();
4720
4721 Trace("smt") << "SMT resetAssertions()" << endl;
4722 if(Dump.isOn("benchmark")) {
4723 Dump("benchmark") << ResetAssertionsCommand();
4724 }
4725
4726 while(!d_userLevels.empty()) {
4727 pop();
4728 }
4729
4730 // Also remember the global push/pop around everything.
4731 Assert(d_userLevels.size() == 0 && d_userContext->getLevel() == 1);
4732 d_context->popto(0);
4733 d_userContext->popto(0);
4734 DeleteAndClearCommandVector(d_modelGlobalCommands);
4735 d_userContext->push();
4736 d_context->push();
4737 }
4738
4739 void SmtEngine::interrupt()
4740 {
4741 if(!d_fullyInited) {
4742 return;
4743 }
4744 d_propEngine->interrupt();
4745 d_theoryEngine->interrupt();
4746 }
4747
4748 void SmtEngine::setResourceLimit(unsigned long units, bool cumulative) {
4749 d_private->getResourceManager()->setResourceLimit(units, cumulative);
4750 }
4751 void SmtEngine::setTimeLimit(unsigned long milis, bool cumulative) {
4752 d_private->getResourceManager()->setTimeLimit(milis, cumulative);
4753 }
4754
4755 unsigned long SmtEngine::getResourceUsage() const {
4756 return d_private->getResourceManager()->getResourceUsage();
4757 }
4758
4759 unsigned long SmtEngine::getTimeUsage() const {
4760 return d_private->getResourceManager()->getTimeUsage();
4761 }
4762
4763 unsigned long SmtEngine::getResourceRemaining() const
4764 {
4765 return d_private->getResourceManager()->getResourceRemaining();
4766 }
4767
4768 unsigned long SmtEngine::getTimeRemaining() const
4769 {
4770 return d_private->getResourceManager()->getTimeRemaining();
4771 }
4772
4773 Statistics SmtEngine::getStatistics() const
4774 {
4775 return Statistics(*d_statisticsRegistry);
4776 }
4777
4778 SExpr SmtEngine::getStatistic(std::string name) const
4779 {
4780 return d_statisticsRegistry->getStatistic(name);
4781 }
4782
4783 void SmtEngine::safeFlushStatistics(int fd) const {
4784 d_statisticsRegistry->safeFlushInformation(fd);
4785 }
4786
4787 void SmtEngine::setUserAttribute(const std::string& attr,
4788 Expr expr,
4789 const std::vector<Expr>& expr_values,
4790 const std::string& str_value)
4791 {
4792 SmtScope smts(this);
4793 std::vector<Node> node_values;
4794 for( unsigned i=0; i<expr_values.size(); i++ ){
4795 node_values.push_back( expr_values[i].getNode() );
4796 }
4797 d_theoryEngine->setUserAttribute(attr, expr.getNode(), node_values, str_value);
4798 }
4799
4800 void SmtEngine::setPrintFuncInModel(Expr f, bool p) {
4801 Trace("setp-model") << "Set printInModel " << f << " to " << p << std::endl;
4802 for( unsigned i=0; i<d_modelGlobalCommands.size(); i++ ){
4803 Command * c = d_modelGlobalCommands[i];
4804 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
4805 if(dfc != NULL) {
4806 if( dfc->getFunction()==f ){
4807 dfc->setPrintInModel( p );
4808 }
4809 }
4810 }
4811 for( unsigned i=0; i<d_modelCommands->size(); i++ ){
4812 Command * c = (*d_modelCommands)[i];
4813 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
4814 if(dfc != NULL) {
4815 if( dfc->getFunction()==f ){
4816 dfc->setPrintInModel( p );
4817 }
4818 }
4819 }
4820 }
4821
4822 void SmtEngine::beforeSearch()
4823 {
4824 if(d_fullyInited) {
4825 throw ModalException(
4826 "SmtEngine::beforeSearch called after initialization.");
4827 }
4828 }
4829
4830
4831 void SmtEngine::setOption(const std::string& key, const CVC4::SExpr& value)
4832 {
4833 NodeManagerScope nms(d_nodeManager);
4834 Trace("smt") << "SMT setOption(" << key << ", " << value << ")" << endl;
4835
4836 if(Dump.isOn("benchmark")) {
4837 Dump("benchmark") << SetOptionCommand(key, value);
4838 }
4839
4840 if(key == "command-verbosity") {
4841 if(!value.isAtom()) {
4842 const vector<SExpr>& cs = value.getChildren();
4843 if(cs.size() == 2 &&
4844 (cs[0].isKeyword() || cs[0].isString()) &&
4845 cs[1].isInteger()) {
4846 string c = cs[0].getValue();
4847 const Integer& v = cs[1].getIntegerValue();
4848 if(v < 0 || v > 2) {
4849 throw OptionException("command-verbosity must be 0, 1, or 2");
4850 }
4851 d_commandVerbosity[c] = v;
4852 return;
4853 }
4854 }
4855 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
4856 }
4857
4858 if(!value.isAtom()) {
4859 throw OptionException("bad value for :" + key);
4860 }
4861
4862 string optionarg = value.getValue();
4863 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
4864 nodeManagerOptions.setOption(key, optionarg);
4865 }
4866
4867 CVC4::SExpr SmtEngine::getOption(const std::string& key) const
4868 {
4869 NodeManagerScope nms(d_nodeManager);
4870
4871 Trace("smt") << "SMT getOption(" << key << ")" << endl;
4872
4873 if(key.length() >= 18 &&
4874 key.compare(0, 18, "command-verbosity:") == 0) {
4875 map<string, Integer>::const_iterator i = d_commandVerbosity.find(key.c_str() + 18);
4876 if(i != d_commandVerbosity.end()) {
4877 return SExpr((*i).second);
4878 }
4879 i = d_commandVerbosity.find("*");
4880 if(i != d_commandVerbosity.end()) {
4881 return SExpr((*i).second);
4882 }
4883 return SExpr(Integer(2));
4884 }
4885
4886 if(Dump.isOn("benchmark")) {
4887 Dump("benchmark") << GetOptionCommand(key);
4888 }
4889
4890 if(key == "command-verbosity") {
4891 vector<SExpr> result;
4892 SExpr defaultVerbosity;
4893 for(map<string, Integer>::const_iterator i = d_commandVerbosity.begin();
4894 i != d_commandVerbosity.end();
4895 ++i) {
4896 vector<SExpr> v;
4897 v.push_back(SExpr((*i).first));
4898 v.push_back(SExpr((*i).second));
4899 if((*i).first == "*") {
4900 // put the default at the end of the SExpr
4901 defaultVerbosity = SExpr(v);
4902 } else {
4903 result.push_back(SExpr(v));
4904 }
4905 }
4906 // put the default at the end of the SExpr
4907 if(!defaultVerbosity.isAtom()) {
4908 result.push_back(defaultVerbosity);
4909 } else {
4910 // ensure the default is always listed
4911 vector<SExpr> v;
4912 v.push_back(SExpr("*"));
4913 v.push_back(SExpr(Integer(2)));
4914 result.push_back(SExpr(v));
4915 }
4916 return SExpr(result);
4917 }
4918
4919 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
4920 return SExpr::parseAtom(nodeManagerOptions.getOption(key));
4921 }
4922
4923 void SmtEngine::setReplayStream(ExprStream* replayStream) {
4924 AlwaysAssert(!d_fullyInited,
4925 "Cannot set replay stream once fully initialized");
4926 d_replayStream = replayStream;
4927 }
4928
4929 bool SmtEngine::getExpressionName(Expr e, std::string& name) const {
4930 return d_private->getExpressionName(e, name);
4931 }
4932
4933 void SmtEngine::setExpressionName(Expr e, const std::string& name) {
4934 Trace("smt-debug") << "Set expression name " << e << " to " << name << std::endl;
4935 d_private->setExpressionName(e,name);
4936 }
4937
4938 }/* CVC4 namespace */