Transfer ownership of internal Options from NodeManager to SmtEngine (#4682)
[cvc5.git] / src / options / options_template.cpp
1 /********************* */
2 /*! \file options_template.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Tim King, Mathias Preiner
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2020 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 Contains code for handling command-line options.
13 **
14 ** Contains code for handling command-line options
15 **/
16
17 #if !defined(_BSD_SOURCE) && defined(__MINGW32__) && !defined(__MINGW64__)
18 // force use of optreset; mingw32 croaks on argv-switching otherwise
19 # include "cvc4autoconfig.h"
20 # define _BSD_SOURCE
21 # undef HAVE_DECL_OPTRESET
22 # define HAVE_DECL_OPTRESET 1
23 # define CVC4_IS_NOT_REALLY_BSD
24 #endif /* !_BSD_SOURCE && __MINGW32__ && !__MINGW64__ */
25
26 #ifdef __MINGW64__
27 extern int optreset;
28 #endif /* __MINGW64__ */
29
30 #include <getopt.h>
31
32 // clean up
33 #ifdef CVC4_IS_NOT_REALLY_BSD
34 # undef _BSD_SOURCE
35 #endif /* CVC4_IS_NOT_REALLY_BSD */
36
37 #include <unistd.h>
38 #include <string.h>
39 #include <stdint.h>
40 #include <time.h>
41
42 #include <cstdio>
43 #include <cstdlib>
44 #include <cstring>
45 #include <iomanip>
46 #include <new>
47 #include <string>
48 #include <sstream>
49 #include <limits>
50
51 #include "base/check.h"
52 #include "base/exception.h"
53 #include "base/output.h"
54 #include "options/didyoumean.h"
55 #include "options/language.h"
56 #include "options/options_handler.h"
57
58 ${headers_module}$
59
60
61 #include "options/options_holder.h"
62 #include "cvc4autoconfig.h"
63 #include "options/base_handlers.h"
64
65 ${headers_handler}$
66
67
68 using namespace CVC4;
69 using namespace CVC4::options;
70
71 namespace CVC4 {
72
73 thread_local Options* Options::s_current = NULL;
74
75 /**
76 * This is a default handler for options of built-in C++ type. This
77 * template is really just a helper for the handleOption() template,
78 * below. Variants of this template handle numeric and non-numeric,
79 * integral and non-integral, signed and unsigned C++ types.
80 * handleOption() makes sure to instantiate the right one.
81 *
82 * This implements default behavior when e.g. an option is
83 * unsigned but the user specifies a negative argument; etc.
84 */
85 template <class T, bool is_numeric, bool is_integer>
86 struct OptionHandler {
87 static T handle(std::string option, std::string optionarg);
88 };/* struct OptionHandler<> */
89
90 /** Variant for integral C++ types */
91 template <class T>
92 struct OptionHandler<T, true, true> {
93 static bool stringToInt(T& t, const std::string& str) {
94 std::istringstream ss(str);
95 ss >> t;
96 char tmp;
97 return !(ss.fail() || ss.get(tmp));
98 }
99
100 static bool containsMinus(const std::string& str) {
101 return str.find('-') != std::string::npos;
102 }
103
104 static T handle(const std::string& option, const std::string& optionarg) {
105 try {
106 T i;
107 bool success = stringToInt(i, optionarg);
108
109 if(!success){
110 throw OptionException(option + ": failed to parse "+ optionarg +
111 " as an integer of the appropriate type.");
112 }
113
114 // Depending in the platform unsigned numbers with '-' signs may parse.
115 // Reject these by looking for any minus if it is not signed.
116 if( (! std::numeric_limits<T>::is_signed) && containsMinus(optionarg) ) {
117 // unsigned type but user gave negative argument
118 throw OptionException(option + " requires a nonnegative argument");
119 } else if(i < std::numeric_limits<T>::min()) {
120 // negative overflow for type
121 std::stringstream ss;
122 ss << option << " requires an argument >= "
123 << std::numeric_limits<T>::min();
124 throw OptionException(ss.str());
125 } else if(i > std::numeric_limits<T>::max()) {
126 // positive overflow for type
127 std::stringstream ss;
128 ss << option << " requires an argument <= "
129 << std::numeric_limits<T>::max();
130 throw OptionException(ss.str());
131 }
132
133 return i;
134
135 // if(std::numeric_limits<T>::is_signed) {
136 // return T(i.getLong());
137 // } else {
138 // return T(i.getUnsignedLong());
139 // }
140 } catch(std::invalid_argument&) {
141 // user gave something other than an integer
142 throw OptionException(option + " requires an integer argument");
143 }
144 }
145 };/* struct OptionHandler<T, true, true> */
146
147 /** Variant for numeric but non-integral C++ types */
148 template <class T>
149 struct OptionHandler<T, true, false> {
150 static T handle(std::string option, std::string optionarg) {
151 std::stringstream in(optionarg);
152 long double r;
153 in >> r;
154 if(! in.eof()) {
155 // we didn't consume the whole string (junk at end)
156 throw OptionException(option + " requires a numeric argument");
157 }
158
159 if(! std::numeric_limits<T>::is_signed && r < 0.0) {
160 // unsigned type but user gave negative value
161 throw OptionException(option + " requires a nonnegative argument");
162 } else if(r < -std::numeric_limits<T>::max()) {
163 // negative overflow for type
164 std::stringstream ss;
165 ss << option << " requires an argument >= "
166 << -std::numeric_limits<T>::max();
167 throw OptionException(ss.str());
168 } else if(r > std::numeric_limits<T>::max()) {
169 // positive overflow for type
170 std::stringstream ss;
171 ss << option << " requires an argument <= "
172 << std::numeric_limits<T>::max();
173 throw OptionException(ss.str());
174 }
175
176 return T(r);
177 }
178 };/* struct OptionHandler<T, true, false> */
179
180 /** Variant for non-numeric C++ types */
181 template <class T>
182 struct OptionHandler<T, false, false> {
183 static T handle(std::string option, std::string optionarg) {
184 T::unsupported_handleOption_call___please_write_me;
185 // The above line causes a compiler error if this version of the template
186 // is ever instantiated (meaning that a specialization is missing). So
187 // don't worry about the segfault in the next line, the "return" is only
188 // there to keep the compiler from giving additional, distracting errors
189 // and warnings.
190 return *(T*)0;
191 }
192 };/* struct OptionHandler<T, false, false> */
193
194 /** Handle an option of type T in the default way. */
195 template <class T>
196 T handleOption(std::string option, std::string optionarg) {
197 return OptionHandler<T, std::numeric_limits<T>::is_specialized, std::numeric_limits<T>::is_integer>::handle(option, optionarg);
198 }
199
200 /** Handle an option of type std::string in the default way. */
201 template <>
202 std::string handleOption<std::string>(std::string option, std::string optionarg) {
203 return optionarg;
204 }
205
206 /**
207 * Run handler, and any user-given predicates, for option T.
208 * If a user specifies a :handler or :predicates, it overrides this.
209 */
210 template <class T>
211 typename T::type runHandlerAndPredicates(T, std::string option, std::string optionarg, options::OptionsHandler* handler) {
212 // By default, parse the option argument in a way appropriate for its type.
213 // E.g., for "unsigned int" options, ensure that the provided argument is
214 // a nonnegative integer that fits in the unsigned int type.
215
216 return handleOption<typename T::type>(option, optionarg);
217 }
218
219 template <class T>
220 void runBoolPredicates(T, std::string option, bool b, options::OptionsHandler* handler) {
221 // By default, nothing to do for bool. Users add things with
222 // :predicate in options files to provide custom checking routines
223 // that can throw exceptions.
224 }
225
226
227 Options::Options()
228 : d_holder(new options::OptionsHolder())
229 , d_handler(new options::OptionsHandler(this))
230 , d_beforeSearchListeners()
231 {}
232
233 Options::~Options() {
234 delete d_handler;
235 delete d_holder;
236 }
237
238 void Options::copyValues(const Options& options){
239 if(this != &options) {
240 delete d_holder;
241 d_holder = new options::OptionsHolder(*options.d_holder);
242 }
243 }
244
245 std::string Options::formatThreadOptionException(const std::string& option) {
246 std::stringstream ss;
247 ss << "can't understand option `" << option
248 << "': expected something like --threadN=\"--option1 --option2\","
249 << " where N is a nonnegative integer";
250 return ss.str();
251 }
252
253 ListenerCollection::Registration* Options::registerAndNotify(
254 ListenerCollection& collection, Listener* listener, bool notify)
255 {
256 ListenerCollection::Registration* registration =
257 collection.registerListener(listener);
258 if(notify) {
259 try
260 {
261 listener->notify();
262 }
263 catch (OptionException& e)
264 {
265 // It can happen that listener->notify() throws an OptionException. In
266 // that case, we have to make sure that we delete the registration of our
267 // listener before rethrowing the exception. Otherwise the
268 // ListenerCollection deconstructor will complain that not all
269 // registrations have been removed before invoking the deconstructor.
270 delete registration;
271 throw OptionException(e.getRawMessage());
272 }
273 }
274 return registration;
275 }
276
277 ListenerCollection::Registration* Options::registerBeforeSearchListener(
278 Listener* listener)
279 {
280 return d_beforeSearchListeners.registerListener(listener);
281 }
282
283 ListenerCollection::Registration* Options::registerSetDefaultExprDepthListener(
284 Listener* listener, bool notifyIfSet)
285 {
286 bool notify = notifyIfSet && wasSetByUser(options::defaultExprDepth);
287 return registerAndNotify(d_setDefaultExprDepthListeners, listener, notify);
288 }
289
290 ListenerCollection::Registration* Options::registerSetDefaultExprDagListener(
291 Listener* listener, bool notifyIfSet)
292 {
293 bool notify = notifyIfSet && wasSetByUser(options::defaultDagThresh);
294 return registerAndNotify(d_setDefaultDagThreshListeners, listener, notify);
295 }
296
297 ListenerCollection::Registration* Options::registerSetPrintExprTypesListener(
298 Listener* listener, bool notifyIfSet)
299 {
300 bool notify = notifyIfSet && wasSetByUser(options::printExprTypes);
301 return registerAndNotify(d_setPrintExprTypesListeners, listener, notify);
302 }
303
304 ListenerCollection::Registration* Options::registerSetDumpModeListener(
305 Listener* listener, bool notifyIfSet)
306 {
307 bool notify = notifyIfSet && wasSetByUser(options::dumpModeString);
308 return registerAndNotify(d_setDumpModeListeners, listener, notify);
309 }
310
311 ListenerCollection::Registration* Options::registerSetPrintSuccessListener(
312 Listener* listener, bool notifyIfSet)
313 {
314 bool notify = notifyIfSet && wasSetByUser(options::printSuccess);
315 return registerAndNotify(d_setPrintSuccessListeners, listener, notify);
316 }
317
318 ListenerCollection::Registration* Options::registerDumpToFileNameListener(
319 Listener* listener, bool notifyIfSet)
320 {
321 bool notify = notifyIfSet && wasSetByUser(options::dumpToFileName);
322 return registerAndNotify(d_dumpToFileListeners, listener, notify);
323 }
324
325 ListenerCollection::Registration*
326 Options::registerSetRegularOutputChannelListener(
327 Listener* listener, bool notifyIfSet)
328 {
329 bool notify = notifyIfSet && wasSetByUser(options::regularChannelName);
330 return registerAndNotify(d_setRegularChannelListeners, listener, notify);
331 }
332
333 ListenerCollection::Registration*
334 Options::registerSetDiagnosticOutputChannelListener(
335 Listener* listener, bool notifyIfSet)
336 {
337 bool notify = notifyIfSet && wasSetByUser(options::diagnosticChannelName);
338 return registerAndNotify(d_setDiagnosticChannelListeners, listener, notify);
339 }
340
341 ${custom_handlers}$
342
343 #if defined(CVC4_MUZZLED) || defined(CVC4_COMPETITION_MODE)
344 # define DO_SEMANTIC_CHECKS_BY_DEFAULT false
345 #else /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
346 # define DO_SEMANTIC_CHECKS_BY_DEFAULT true
347 #endif /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
348
349 options::OptionsHolder::OptionsHolder() :
350 ${module_defaults}$
351 {
352 }
353
354
355 static const std::string mostCommonOptionsDescription = "\
356 Most commonly-used CVC4 options:\n"
357 ${help_common}$;
358
359
360 static const std::string optionsDescription = mostCommonOptionsDescription + "\n\
361 \n\
362 Additional CVC4 options:\n"
363 ${help_others}$;
364
365
366 static const std::string optionsFootnote = "\n\
367 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
368 sense of the option.\n\
369 ";
370
371 static const std::string languageDescription =
372 "\
373 Languages currently supported as arguments to the -L / --lang option:\n\
374 auto attempt to automatically determine language\n\
375 cvc4 | presentation | pl CVC4 presentation language\n\
376 smt | smtlib | smt2 |\n\
377 smt2.0 | smtlib2 | smtlib2.0 SMT-LIB format 2.0\n\
378 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
379 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
380 tptp TPTP format (cnf, fof and tff)\n\
381 sygus | sygus2 SyGuS version 2.0\n\
382 \n\
383 Languages currently supported as arguments to the --output-lang option:\n\
384 auto match output language to input language\n\
385 cvc4 | presentation | pl CVC4 presentation language\n\
386 cvc3 CVC3 presentation language\n\
387 smt | smtlib | smt2 |\n\
388 smt2.0 | smtlib2.0 | smtlib2 SMT-LIB format 2.0\n\
389 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
390 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
391 tptp TPTP format\n\
392 ast internal format (simple syntax trees)\n\
393 ";
394
395 std::string Options::getDescription() const {
396 return optionsDescription;
397 }
398
399 void Options::printUsage(const std::string msg, std::ostream& out) {
400 out << msg << optionsDescription << std::endl
401 << optionsFootnote << std::endl << std::flush;
402 }
403
404 void Options::printShortUsage(const std::string msg, std::ostream& out) {
405 out << msg << mostCommonOptionsDescription << std::endl
406 << optionsFootnote << std::endl
407 << "For full usage, please use --help."
408 << std::endl << std::endl << std::flush;
409 }
410
411 void Options::printLanguageHelp(std::ostream& out) {
412 out << languageDescription << std::flush;
413 }
414
415 /**
416 * This is a table of long options. By policy, each short option
417 * should have an equivalent long option (but the reverse isn't the
418 * case), so this table should thus contain all command-line options.
419 *
420 * Each option in this array has four elements:
421 *
422 * 1. the long option string
423 * 2. argument behavior for the option:
424 * no_argument - no argument permitted
425 * required_argument - an argument is expected
426 * optional_argument - an argument is permitted but not required
427 * 3. this is a pointer to an int which is set to the 4th entry of the
428 * array if the option is present; or NULL, in which case
429 * getopt_long() returns the 4th entry
430 * 4. the return value for getopt_long() when this long option (or the
431 * value to set the 3rd entry to; see #3)
432 *
433 * If you add something here, you should add it in src/main/usage.h
434 * also, to document it.
435 *
436 * If you add something that has a short option equivalent, you should
437 * add it to the getopt_long() call in parseOptions().
438 */
439 static struct option cmdlineOptions[] = {
440 ${cmdline_options}$
441 { NULL, no_argument, NULL, '\0' }
442 };/* cmdlineOptions */
443
444 namespace options {
445
446 /** Set a given Options* as "current" just for a particular scope. */
447 class OptionsGuard {
448 Options** d_field;
449 Options* d_old;
450 public:
451 OptionsGuard(Options** field, Options* opts) :
452 d_field(field),
453 d_old(*field) {
454 *field = opts;
455 }
456 ~OptionsGuard() {
457 *d_field = d_old;
458 }
459 };/* class OptionsGuard */
460
461 }/* CVC4::options namespace */
462
463 /**
464 * Parse argc/argv and put the result into a CVC4::Options.
465 * The return value is what's left of the command line (that is, the
466 * non-option arguments).
467 *
468 * Throws OptionException on failures.
469 */
470 std::vector<std::string> Options::parseOptions(Options* options,
471 int argc,
472 char* argv[])
473 {
474 Assert(options != NULL);
475 Assert(argv != NULL);
476
477 options::OptionsGuard guard(&s_current, options);
478
479 const char *progName = argv[0];
480
481 // To debug options parsing, you may prefer to simply uncomment this
482 // and recompile. Debug flags have not been parsed yet so these have
483 // not been set.
484 //DebugChannel.on("options");
485
486 Debug("options") << "Options::parseOptions == " << options << std::endl;
487 Debug("options") << "argv == " << argv << std::endl;
488
489 // Find the base name of the program.
490 const char *x = strrchr(progName, '/');
491 if(x != NULL) {
492 progName = x + 1;
493 }
494 options->d_holder->binary_name = std::string(progName);
495
496
497 std::vector<std::string> nonoptions;
498 parseOptionsRecursive(options, argc, argv, &nonoptions);
499 if(Debug.isOn("options")){
500 for(std::vector<std::string>::const_iterator i = nonoptions.begin(),
501 iend = nonoptions.end(); i != iend; ++i){
502 Debug("options") << "nonoptions " << *i << std::endl;
503 }
504 }
505
506 return nonoptions;
507 }
508
509 void Options::parseOptionsRecursive(Options* options,
510 int argc,
511 char* argv[],
512 std::vector<std::string>* nonoptions)
513 {
514
515 if(Debug.isOn("options")) {
516 Debug("options") << "starting a new parseOptionsRecursive with "
517 << argc << " arguments" << std::endl;
518 for( int i = 0; i < argc ; i++ ){
519 Assert(argv[i] != NULL);
520 Debug("options") << " argv[" << i << "] = " << argv[i] << std::endl;
521 }
522 }
523
524 // Having this synonym simplifies the generation code in mkoptions.
525 options::OptionsHandler* handler = options->d_handler;
526
527 // Reset getopt(), in the case of multiple calls to parseOptions().
528 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
529 optind = 0;
530 #if HAVE_DECL_OPTRESET
531 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
532 #endif /* HAVE_DECL_OPTRESET */
533
534 // We must parse the binary name, which is manually ignored below. Setting
535 // this to 1 leads to incorrect behavior on some platforms.
536 int main_optind = 0;
537 int old_optind;
538
539
540 while(true) { // Repeat Forever
541
542 optopt = 0;
543 std::string option, optionarg;
544
545 optind = main_optind;
546 old_optind = main_optind;
547
548 // If we encounter an element that is not at zero and does not start
549 // with a "-", this is a non-option. We consume this element as a
550 // non-option.
551 if (main_optind > 0 && main_optind < argc &&
552 argv[main_optind][0] != '-') {
553 Debug("options") << "enqueueing " << argv[main_optind]
554 << " as a non-option." << std::endl;
555 nonoptions->push_back(argv[main_optind]);
556 ++main_optind;
557 continue;
558 }
559
560
561 Debug("options") << "[ before, main_optind == " << main_optind << " ]"
562 << std::endl;
563 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
564 Debug("options") << "[ argc == " << argc << ", argv == " << argv << " ]"
565 << std::endl;
566 int c = getopt_long(argc, argv,
567 "+:${options_short}$",
568 cmdlineOptions, NULL);
569
570 main_optind = optind;
571
572 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]"
573 << "[ next option will be at pos: " << optind << " ]"
574 << std::endl;
575
576 // The initial getopt_long call should always determine that argv[0]
577 // is not an option and returns -1. We always manually advance beyond
578 // this element.
579 if ( old_optind == 0 && c == -1 ) {
580 Assert(main_optind > 0);
581 continue;
582 }
583
584 if ( c == -1 ) {
585 if(Debug.isOn("options")) {
586 Debug("options") << "done with option parsing" << std::endl;
587 for(int index = optind; index < argc; ++index) {
588 Debug("options") << "remaining " << argv[index] << std::endl;
589 }
590 }
591 break;
592 }
593
594 option = argv[old_optind == 0 ? 1 : old_optind];
595 optionarg = (optarg == NULL) ? "" : optarg;
596
597 Debug("preemptGetopt") << "processing option " << c
598 << " (`" << char(c) << "'), " << option << std::endl;
599
600 switch(c) {
601 ${options_handler}$
602
603
604 case ':':
605 // This can be a long or short option, and the way to get at the
606 // name of it is different.
607 throw OptionException(std::string("option `") + option +
608 "' missing its required argument");
609
610 case '?':
611 default:
612 throw OptionException(std::string("can't understand option `") + option +
613 "'" + suggestCommandLineOptions(option));
614 }
615 }
616
617 Debug("options") << "got " << nonoptions->size()
618 << " non-option arguments." << std::endl;
619 }
620
621 std::string Options::suggestCommandLineOptions(const std::string& optionName)
622 {
623 DidYouMean didYouMean;
624
625 const char* opt;
626 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
627 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
628 }
629
630 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
631 }
632
633 static const char* smtOptions[] = {
634 ${options_smt}$
635 NULL
636 };/* smtOptions[] */
637
638 std::vector<std::string> Options::suggestSmtOptions(
639 const std::string& optionName)
640 {
641 std::vector<std::string> suggestions;
642
643 const char* opt;
644 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
645 if(std::strstr(opt, optionName.c_str()) != NULL) {
646 suggestions.push_back(opt);
647 }
648 }
649
650 return suggestions;
651 }
652
653 std::vector<std::vector<std::string> > Options::getOptions() const
654 {
655 std::vector< std::vector<std::string> > opts;
656
657 ${options_getoptions}$
658
659
660 return opts;
661 }
662
663 void Options::setOption(const std::string& key, const std::string& optionarg)
664 {
665 options::OptionsHandler* handler = d_handler;
666 Options* options = this;
667 Trace("options") << "SMT setOption(" << key << ", " << optionarg << ")"
668 << std::endl;
669
670 ${setoption_handlers}$
671
672
673 throw UnrecognizedOptionException(key);
674 }
675
676 std::string Options::getOption(const std::string& key) const
677 {
678 Trace("options") << "SMT getOption(" << key << ")" << std::endl;
679
680 ${getoption_handlers}$
681
682
683 throw UnrecognizedOptionException(key);
684 }
685
686 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
687 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
688
689 } // namespace CVC4