Renaming the class PtrCloser to not cause confusion with unique_ptr.
[cvc5.git] / src / main / driver_unified.cpp
1 /********************* */
2 /*! \file driver_unified.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Tim King, Liana Hadarean
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2016 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 Driver for CVC4 executable (cvc4) unified for both
13 ** sequential and portfolio versions
14 **/
15
16 #include <stdio.h>
17 #include <unistd.h>
18
19 #include <cstdlib>
20 #include <cstring>
21 #include <fstream>
22 #include <iostream>
23 #include <new>
24
25 // This must come before PORTFOLIO_BUILD.
26 #include "cvc4autoconfig.h"
27
28 #include "base/configuration.h"
29 #include "base/output.h"
30 #include "base/ptr_closer.h"
31 #include "expr/expr_iomanip.h"
32 #include "expr/expr_manager.h"
33 #include "main/command_executor.h"
34
35 #ifdef PORTFOLIO_BUILD
36 # include "main/command_executor_portfolio.h"
37 #endif
38
39 #include "main/interactive_shell.h"
40 #include "main/main.h"
41 #include "options/options.h"
42 #include "options/set_language.h"
43 #include "parser/parser.h"
44 #include "parser/parser_builder.h"
45 #include "parser/parser_exception.h"
46 #include "smt/command.h"
47 #include "util/result.h"
48 #include "util/statistics_registry.h"
49
50 using namespace std;
51 using namespace CVC4;
52 using namespace CVC4::parser;
53 using namespace CVC4::main;
54
55 namespace CVC4 {
56 namespace main {
57 /** Global options variable */
58 CVC4_THREADLOCAL(Options*) pOptions;
59
60 /** Full argv[0] */
61 const char *progPath;
62
63 /** Just the basename component of argv[0] */
64 const char *progName;
65
66 /** A pointer to the CommandExecutor (the signal handlers need it) */
67 CVC4::main::CommandExecutor* pExecutor = NULL;
68
69 /** A pointer to the totalTime driver stat (the signal handlers need it) */
70 CVC4::TimerStat* pTotalTime = NULL;
71
72 }/* CVC4::main namespace */
73 }/* CVC4 namespace */
74
75
76 void printUsage(Options& opts, bool full) {
77 stringstream ss;
78 ss << "usage: " << opts.getBinaryName() << " [options] [input-file]"
79 << endl << endl
80 << "Without an input file, or with `-', CVC4 reads from standard input."
81 << endl << endl
82 << "CVC4 options:" << endl;
83 if(full) {
84 Options::printUsage( ss.str(), *(opts.getOut()) );
85 } else {
86 Options::printShortUsage( ss.str(), *(opts.getOut()) );
87 }
88 }
89
90 int runCvc4(int argc, char* argv[], Options& opts) {
91
92 // Timer statistic
93 pTotalTime = new TimerStat("totalTime");
94 pTotalTime->start();
95
96 // For the signal handlers' benefit
97 pOptions = &opts;
98
99 // Initialize the signal handlers
100 cvc4_init();
101
102 progPath = argv[0];
103
104 // Parse the options
105 vector<string> filenames = Options::parseOptions(&opts, argc, argv);
106
107 # ifndef PORTFOLIO_BUILD
108 if( opts.wasSetByUserThreads() ||
109 opts.wasSetByUserThreadStackSize() ||
110 (! opts.getThreadArgv().empty()) ) {
111 throw OptionException("Thread options cannot be used with sequential CVC4. Please build and use the portfolio binary `pcvc4'.");
112 }
113 # endif
114
115 progName = opts.getBinaryName().c_str();
116
117 if( opts.getHelp() ) {
118 printUsage(opts, true);
119 exit(1);
120 } else if( opts.getLanguageHelp() ) {
121 Options::printLanguageHelp(*(opts.getOut()));
122 exit(1);
123 } else if( opts.getVersion() ) {
124 *(opts.getOut()) << Configuration::about().c_str() << flush;
125 exit(0);
126 }
127
128 segvSpin = opts.getSegvSpin();
129
130 // If in competition mode, set output stream option to flush immediately
131 #ifdef CVC4_COMPETITION_MODE
132 *(opts.getOut()) << unitbuf;
133 #endif /* CVC4_COMPETITION_MODE */
134
135 // We only accept one input file
136 if(filenames.size() > 1) {
137 throw Exception("Too many input files specified.");
138 }
139
140 // If no file supplied we will read from standard input
141 const bool inputFromStdin = filenames.empty() || filenames[0] == "-";
142
143 // if we're reading from stdin on a TTY, default to interactive mode
144 if(!opts.wasSetByUserInteractive()) {
145 opts.setInteractive(inputFromStdin && isatty(fileno(stdin)));
146 }
147
148 // Auto-detect input language by filename extension
149 const char* filename = inputFromStdin ? "<stdin>" : filenames[0].c_str();
150
151 if(opts.getInputLanguage() == language::input::LANG_AUTO) {
152 if( inputFromStdin ) {
153 // We can't do any fancy detection on stdin
154 opts.setInputLanguage(language::input::LANG_CVC4);
155 } else {
156 unsigned len = strlen(filename);
157 if(len >= 5 && !strcmp(".smt2", filename + len - 5)) {
158 opts.setInputLanguage(language::input::LANG_SMTLIB_V2_0);
159 } else if(len >= 4 && !strcmp(".smt", filename + len - 4)) {
160 opts.setInputLanguage(language::input::LANG_SMTLIB_V1);
161 } else if(len >= 5 && !strcmp(".smt1", filename + len - 5)) {
162 opts.setInputLanguage(language::input::LANG_SMTLIB_V1);
163 } else if((len >= 2 && !strcmp(".p", filename + len - 2))
164 || (len >= 5 && !strcmp(".tptp", filename + len - 5))) {
165 opts.setInputLanguage(language::input::LANG_TPTP);
166 } else if(( len >= 4 && !strcmp(".cvc", filename + len - 4) )
167 || ( len >= 5 && !strcmp(".cvc4", filename + len - 5) )) {
168 opts.setInputLanguage(language::input::LANG_CVC4);
169 } else if((len >= 3 && !strcmp(".sy", filename + len - 3))
170 || (len >= 3 && !strcmp(".sl", filename + len - 3))) {
171 opts.setInputLanguage(language::input::LANG_SYGUS);
172 //since there is no sygus output language, set this to SMT lib 2
173 //opts.setOutputLanguage(language::output::LANG_SMTLIB_V2_0);
174 }
175 }
176 }
177
178 if(opts.getOutputLanguage() == language::output::LANG_AUTO) {
179 opts.setOutputLanguage(language::toOutputLanguage(opts.getInputLanguage()));
180 }
181
182 // if doing sygus, turn on CEGQI by default
183 if(opts.getInputLanguage() == language::input::LANG_SYGUS ){
184 if( !opts.wasSetByUserCeGuidedInst()) {
185 opts.setCeGuidedInst(true);
186 }
187 if( !opts.wasSetByUserDumpSynth()) {
188 opts.setDumpSynth(true);
189 }
190 }
191
192 // Determine which messages to show based on smtcomp_mode and verbosity
193 if(Configuration::isMuzzledBuild()) {
194 DebugChannel.setStream(&CVC4::null_os);
195 TraceChannel.setStream(&CVC4::null_os);
196 NoticeChannel.setStream(&CVC4::null_os);
197 ChatChannel.setStream(&CVC4::null_os);
198 MessageChannel.setStream(&CVC4::null_os);
199 WarningChannel.setStream(&CVC4::null_os);
200 }
201
202 // important even for muzzled builds (to get result output right)
203 (*(opts.getOut())) << language::SetLanguage(opts.getOutputLanguage());
204
205 // Create the expression manager using appropriate options
206 ExprManager* exprMgr;
207 # ifndef PORTFOLIO_BUILD
208 exprMgr = new ExprManager(opts);
209 pExecutor = new CommandExecutor(*exprMgr, opts);
210 # else
211 OptionsList threadOpts;
212 parseThreadSpecificOptions(threadOpts, opts);
213
214 bool useParallelExecutor = true;
215 // incremental?
216 if(opts.wasSetByUserIncrementalSolving() &&
217 opts.getIncrementalSolving() &&
218 (! opts.getIncrementalParallel()) ) {
219 Notice() << "Notice: In --incremental mode, using the sequential solver"
220 << " unless forced by...\n"
221 << "Notice: ...the experimental --incremental-parallel option.\n";
222 useParallelExecutor = false;
223 }
224 // proofs?
225 if(opts.getCheckProofs()) {
226 if(opts.getFallbackSequential()) {
227 Warning() << "Warning: Falling back to sequential mode, as cannot run"
228 << " portfolio in check-proofs mode.\n";
229 useParallelExecutor = false;
230 }
231 else {
232 throw OptionException("Cannot run portfolio in check-proofs mode.");
233 }
234 }
235 // pick appropriate one
236 if(useParallelExecutor) {
237 exprMgr = new ExprManager(threadOpts[0]);
238 pExecutor = new CommandExecutorPortfolio(*exprMgr, opts, threadOpts);
239 } else {
240 exprMgr = new ExprManager(opts);
241 pExecutor = new CommandExecutor(*exprMgr, opts);
242 }
243 # endif
244
245 PtrCloser<Parser> replayParser;
246 if( opts.getReplayInputFilename() != "" ) {
247 std::string replayFilename = opts.getReplayInputFilename();
248 ParserBuilder replayParserBuilder(exprMgr, replayFilename, opts);
249
250 if( replayFilename == "-") {
251 if( inputFromStdin ) {
252 throw OptionException("Replay file and input file can't both be stdin.");
253 }
254 replayParserBuilder.withStreamInput(cin);
255 }
256 replayParser.reset(replayParserBuilder.build());
257 pExecutor->setReplayStream(new Parser::ExprStream(replayParser.get()));
258 }
259
260 int returnValue = 0;
261 {
262 // Timer statistic
263 RegisterStatistic statTotalTime(&pExecutor->getStatisticsRegistry(),
264 pTotalTime);
265
266 // Filename statistics
267 ReferenceStat< const char* > s_statFilename("filename", filename);
268 RegisterStatistic statFilenameReg(&pExecutor->getStatisticsRegistry(),
269 &s_statFilename);
270
271 // Parse and execute commands until we are done
272 Command* cmd;
273 bool status = true;
274 if(opts.getInteractive() && inputFromStdin) {
275 if(opts.getTearDownIncremental() > 0) {
276 throw OptionException(
277 "--tear-down-incremental doesn't work in interactive mode");
278 }
279 #ifndef PORTFOLIO_BUILD
280 if(!opts.wasSetByUserIncrementalSolving()) {
281 cmd = new SetOptionCommand("incremental", SExpr(true));
282 cmd->setMuted(true);
283 pExecutor->doCommand(cmd);
284 delete cmd;
285 }
286 #endif /* PORTFOLIO_BUILD */
287 InteractiveShell shell(*exprMgr, opts);
288 if(opts.getInteractivePrompt()) {
289 Message() << Configuration::getPackageName()
290 << " " << Configuration::getVersionString();
291 if(Configuration::isGitBuild()) {
292 Message() << " [" << Configuration::getGitId() << "]";
293 } else if(Configuration::isSubversionBuild()) {
294 Message() << " [" << Configuration::getSubversionId() << "]";
295 }
296 Message() << (Configuration::isDebugBuild() ? " DEBUG" : "")
297 << " assertions:"
298 << (Configuration::isAssertionBuild() ? "on" : "off")
299 << endl;
300 }
301 if(replayParser) {
302 // have the replay parser use the declarations input interactively
303 replayParser->useDeclarationsFrom(shell.getParser());
304 }
305
306 while(true) {
307 try {
308 cmd = shell.readCommand();
309 } catch(UnsafeInterruptException& e) {
310 (*opts.getOut()) << CommandInterrupted();
311 break;
312 }
313 if (cmd == NULL)
314 break;
315 status = pExecutor->doCommand(cmd) && status;
316 if (cmd->interrupted()) {
317 delete cmd;
318 break;
319 }
320 delete cmd;
321 }
322 } else if( opts.getTearDownIncremental() > 0) {
323 if(!opts.getIncrementalSolving()) {
324 cmd = new SetOptionCommand("incremental", SExpr(true));
325 cmd->setMuted(true);
326 pExecutor->doCommand(cmd);
327 delete cmd;
328 // if(opts.wasSetByUserIncrementalSolving()) {
329 // throw OptionException(
330 // "--tear-down-incremental incompatible with --incremental");
331 // }
332
333 // cmd = new SetOptionCommand("incremental", SExpr(false));
334 // cmd->setMuted(true);
335 // pExecutor->doCommand(cmd);
336 // delete cmd;
337 }
338
339 ParserBuilder parserBuilder(exprMgr, filename, opts);
340
341 if( inputFromStdin ) {
342 #if defined(CVC4_COMPETITION_MODE) && !defined(CVC4_SMTCOMP_APPLICATION_TRACK)
343 parserBuilder.withStreamInput(cin);
344 #else /* CVC4_COMPETITION_MODE && !CVC4_SMTCOMP_APPLICATION_TRACK */
345 parserBuilder.withLineBufferedStreamInput(cin);
346 #endif /* CVC4_COMPETITION_MODE && !CVC4_SMTCOMP_APPLICATION_TRACK */
347 }
348
349 vector< vector<Command*> > allCommands;
350 allCommands.push_back(vector<Command*>());
351 PtrCloser<Parser> parser(parserBuilder.build());
352 if(replayParser) {
353 // have the replay parser use the file's declarations
354 replayParser->useDeclarationsFrom(parser.get());
355 }
356 int needReset = 0;
357 // true if one of the commands was interrupted
358 bool interrupted = false;
359 while (status || opts.getContinuedExecution()) {
360 if (interrupted) {
361 (*opts.getOut()) << CommandInterrupted();
362 break;
363 }
364
365 try {
366 cmd = parser->nextCommand();
367 if (cmd == NULL) break;
368 } catch (UnsafeInterruptException& e) {
369 interrupted = true;
370 continue;
371 }
372
373 if(dynamic_cast<PushCommand*>(cmd) != NULL) {
374 if(needReset >= opts.getTearDownIncremental()) {
375 pExecutor->reset();
376 for(size_t i = 0; i < allCommands.size() && !interrupted; ++i) {
377 if (interrupted) break;
378 for(size_t j = 0; j < allCommands[i].size() && !interrupted; ++j)
379 {
380 Command* cmd = allCommands[i][j]->clone();
381 cmd->setMuted(true);
382 pExecutor->doCommand(cmd);
383 if(cmd->interrupted()) {
384 interrupted = true;
385 }
386 delete cmd;
387 }
388 }
389 needReset = 0;
390 }
391 allCommands.push_back(vector<Command*>());
392 Command* copy = cmd->clone();
393 allCommands.back().push_back(copy);
394 status = pExecutor->doCommand(cmd);
395 if(cmd->interrupted()) {
396 interrupted = true;
397 continue;
398 }
399 } else if(dynamic_cast<PopCommand*>(cmd) != NULL) {
400 allCommands.pop_back(); // fixme leaks cmds here
401 if (needReset >= opts.getTearDownIncremental()) {
402 pExecutor->reset();
403 for(size_t i = 0; i < allCommands.size() && !interrupted; ++i) {
404 for(size_t j = 0; j < allCommands[i].size() && !interrupted; ++j)
405 {
406 Command* cmd = allCommands[i][j]->clone();
407 cmd->setMuted(true);
408 pExecutor->doCommand(cmd);
409 if(cmd->interrupted()) {
410 interrupted = true;
411 }
412 delete cmd;
413 }
414 }
415 if (interrupted) continue;
416 (*opts.getOut()) << CommandSuccess();
417 needReset = 0;
418 } else {
419 status = pExecutor->doCommand(cmd);
420 if(cmd->interrupted()) {
421 interrupted = true;
422 continue;
423 }
424 }
425 } else if(dynamic_cast<CheckSatCommand*>(cmd) != NULL ||
426 dynamic_cast<QueryCommand*>(cmd) != NULL) {
427 if(needReset >= opts.getTearDownIncremental()) {
428 pExecutor->reset();
429 for(size_t i = 0; i < allCommands.size() && !interrupted; ++i) {
430 for(size_t j = 0; j < allCommands[i].size() && !interrupted; ++j)
431 {
432 Command* cmd = allCommands[i][j]->clone();
433 cmd->setMuted(true);
434 pExecutor->doCommand(cmd);
435 if(cmd->interrupted()) {
436 interrupted = true;
437 }
438 delete cmd;
439 }
440 }
441 needReset = 0;
442 } else {
443 ++needReset;
444 }
445 if (interrupted) {
446 continue;
447 }
448
449 status = pExecutor->doCommand(cmd);
450 if(cmd->interrupted()) {
451 interrupted = true;
452 continue;
453 }
454 } else if(dynamic_cast<ResetCommand*>(cmd) != NULL) {
455 pExecutor->doCommand(cmd);
456 allCommands.clear();
457 allCommands.push_back(vector<Command*>());
458 } else {
459 // We shouldn't copy certain commands, because they can cause
460 // an error on replay since there's no associated sat/unsat check
461 // preceding them.
462 if(dynamic_cast<GetUnsatCoreCommand*>(cmd) == NULL &&
463 dynamic_cast<GetProofCommand*>(cmd) == NULL &&
464 dynamic_cast<GetValueCommand*>(cmd) == NULL &&
465 dynamic_cast<GetModelCommand*>(cmd) == NULL &&
466 dynamic_cast<GetAssignmentCommand*>(cmd) == NULL &&
467 dynamic_cast<GetInstantiationsCommand*>(cmd) == NULL &&
468 dynamic_cast<GetAssertionsCommand*>(cmd) == NULL &&
469 dynamic_cast<GetInfoCommand*>(cmd) == NULL &&
470 dynamic_cast<GetOptionCommand*>(cmd) == NULL &&
471 dynamic_cast<EchoCommand*>(cmd) == NULL) {
472 Command* copy = cmd->clone();
473 allCommands.back().push_back(copy);
474 }
475 status = pExecutor->doCommand(cmd);
476 if(cmd->interrupted()) {
477 interrupted = true;
478 continue;
479 }
480
481 if(dynamic_cast<QuitCommand*>(cmd) != NULL) {
482 delete cmd;
483 break;
484 }
485 }
486 delete cmd;
487 }
488 } else {
489 if(!opts.wasSetByUserIncrementalSolving()) {
490 cmd = new SetOptionCommand("incremental", SExpr(false));
491 cmd->setMuted(true);
492 pExecutor->doCommand(cmd);
493 delete cmd;
494 }
495
496 ParserBuilder parserBuilder(exprMgr, filename, opts);
497
498 if( inputFromStdin ) {
499 #if defined(CVC4_COMPETITION_MODE) && !defined(CVC4_SMTCOMP_APPLICATION_TRACK)
500 parserBuilder.withStreamInput(cin);
501 #else /* CVC4_COMPETITION_MODE && !CVC4_SMTCOMP_APPLICATION_TRACK */
502 parserBuilder.withLineBufferedStreamInput(cin);
503 #endif /* CVC4_COMPETITION_MODE && !CVC4_SMTCOMP_APPLICATION_TRACK */
504 }
505
506 PtrCloser<Parser> parser(parserBuilder.build());
507 if(replayParser) {
508 // have the replay parser use the file's declarations
509 replayParser->useDeclarationsFrom(parser.get());
510 }
511 bool interrupted = false;
512 while(status || opts.getContinuedExecution()) {
513 if (interrupted) {
514 (*opts.getOut()) << CommandInterrupted();
515 pExecutor->reset();
516 break;
517 }
518 try {
519 cmd = parser->nextCommand();
520 if (cmd == NULL) break;
521 } catch (UnsafeInterruptException& e) {
522 interrupted = true;
523 continue;
524 }
525
526 status = pExecutor->doCommand(cmd);
527 if (cmd->interrupted() && status == 0) {
528 interrupted = true;
529 break;
530 }
531
532 if(dynamic_cast<QuitCommand*>(cmd) != NULL) {
533 delete cmd;
534 break;
535 }
536 delete cmd;
537 }
538 }
539
540 Result result;
541 if(status) {
542 result = pExecutor->getResult();
543 returnValue = 0;
544 } else {
545 // there was some kind of error
546 returnValue = 1;
547 }
548
549 #ifdef CVC4_COMPETITION_MODE
550 opts.flushOut();
551 // exit, don't return (don't want destructors to run)
552 // _exit() from unistd.h doesn't run global destructors
553 // or other on_exit/atexit stuff.
554 _exit(returnValue);
555 #endif /* CVC4_COMPETITION_MODE */
556
557 ReferenceStat< Result > s_statSatResult("sat/unsat", result);
558 RegisterStatistic statSatResultReg(&pExecutor->getStatisticsRegistry(),
559 &s_statSatResult);
560
561 pTotalTime->stop();
562
563 // Tim: I think that following comment is out of date?
564 // Set the global executor pointer to NULL first. If we get a
565 // signal while dumping statistics, we don't want to try again.
566 pExecutor->flushOutputStreams();
567
568 #ifdef CVC4_DEBUG
569 if(opts.getEarlyExit() && opts.wasSetByUserEarlyExit()) {
570 _exit(returnValue);
571 }
572 #else /* CVC4_DEBUG */
573 if(opts.getEarlyExit()) {
574 _exit(returnValue);
575 }
576 #endif /* CVC4_DEBUG */
577 }
578
579 // On exceptional exit, these are leaked, but that's okay... they
580 // need to be around in that case for main() to print statistics.
581 delete pTotalTime;
582 delete pExecutor;
583 delete exprMgr;
584
585 pTotalTime = NULL;
586 pExecutor = NULL;
587
588 cvc4_shutdown();
589
590 return returnValue;
591 }