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