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