Refactoring Options Handler & Library Cycle Breaking
[cvc5.git] / src / options / options_template.cpp
1 /********************* */
2 /*! \file options_template.cpp
3 ** \verbatim
4 ** Original author: Morgan Deters
5 ** Major contributors: none
6 ** Minor contributors (to current version): Kshitij Bansal
7 ** This file is part of the CVC4 project.
8 ** Copyright (c) 2009-2014 New York University and The University of Iowa
9 ** See the file COPYING in the top-level source directory for licensing
10 ** information.\endverbatim
11 **
12 ** \brief Contains code for handling command-line options.
13 **
14 ** Contains code for handling command-line options
15 **/
16
17 #warning "TODO: Remove ExprStream forward declaration from options.h."
18
19 #if !defined(_BSD_SOURCE) && defined(__MINGW32__) && !defined(__MINGW64__)
20 // force use of optreset; mingw32 croaks on argv-switching otherwise
21 # include "cvc4autoconfig.h"
22 # define _BSD_SOURCE
23 # undef HAVE_DECL_OPTRESET
24 # define HAVE_DECL_OPTRESET 1
25 # define CVC4_IS_NOT_REALLY_BSD
26 #endif /* !_BSD_SOURCE && __MINGW32__ && !__MINGW64__ */
27
28 #ifdef __MINGW64__
29 extern int optreset;
30 #endif /* __MINGW64__ */
31
32 #include <getopt.h>
33
34 // clean up
35 #ifdef CVC4_IS_NOT_REALLY_BSD
36 # undef _BSD_SOURCE
37 #endif /* CVC4_IS_NOT_REALLY_BSD */
38
39 #include <unistd.h>
40 #include <string.h>
41 #include <stdint.h>
42 #include <time.h>
43
44 #include <cstdio>
45 #include <cstdlib>
46 #include <cstring>
47 #include <iomanip>
48 #include <new>
49 #include <string>
50 #include <sstream>
51 #include <limits>
52
53 #include "base/cvc4_assert.h"
54 #include "base/exception.h"
55 #include "base/output.h"
56 #include "base/tls.h"
57 #include "options/didyoumean.h"
58 #include "options/language.h"
59 #include "options/options_handler_interface.h"
60
61 ${include_all_option_headers}
62
63 #line 58 "${template}"
64
65 #include "options/options_holder.h"
66 #include "cvc4autoconfig.h"
67 #include "options/base_handlers.h"
68
69 ${option_handler_includes}
70
71 #line 67 "${template}"
72
73 using namespace CVC4;
74 using namespace CVC4::options;
75
76 namespace CVC4 {
77
78 CVC4_THREADLOCAL(Options*) Options::s_current = NULL;
79
80 /**
81 * This is a default handler for options of built-in C++ type. This
82 * template is really just a helper for the handleOption() template,
83 * below. Variants of this template handle numeric and non-numeric,
84 * integral and non-integral, signed and unsigned C++ types.
85 * handleOption() makes sure to instantiate the right one.
86 *
87 * This implements default behavior when e.g. an option is
88 * unsigned but the user specifies a negative argument; etc.
89 */
90 template <class T, bool is_numeric, bool is_integer>
91 struct OptionHandler {
92 static T handle(std::string option, std::string optionarg);
93 };/* struct OptionHandler<> */
94
95 /** Variant for integral C++ types */
96 template <class T>
97 struct OptionHandler<T, true, true> {
98 static bool stringToInt(T& t, const std::string& str) {
99 std::istringstream ss(str);
100 ss >> t;
101 char tmp;
102 return !(ss.fail() || ss.get(tmp));
103 }
104
105 static bool containsMinus(const std::string& str) {
106 return str.find('-') != std::string::npos;
107 }
108
109 static T handle(const std::string& option, const std::string& optionarg) {
110 try {
111 T i;
112 bool success = stringToInt(i, optionarg);
113
114 if(!success){
115 throw OptionException(option + ": failed to parse "+ optionarg +" as an integer of the appropraite type.");
116 }
117
118 // Depending in the platform unsigned numbers with '-' signs may parse.
119 // Reject these by looking for any minus if it is not signed.
120 if( (! std::numeric_limits<T>::is_signed) && containsMinus(optionarg) ) {
121 // unsigned type but user gave negative argument
122 throw OptionException(option + " requires a nonnegative argument");
123 } else if(i < std::numeric_limits<T>::min()) {
124 // negative overflow for type
125 std::stringstream ss;
126 ss << option << " requires an argument >= " << std::numeric_limits<T>::min();
127 throw OptionException(ss.str());
128 } else if(i > std::numeric_limits<T>::max()) {
129 // positive overflow for type
130 std::stringstream ss;
131 ss << option << " requires an argument <= " << std::numeric_limits<T>::max();
132 throw OptionException(ss.str());
133 }
134
135 return i;
136
137 // if(std::numeric_limits<T>::is_signed) {
138 // return T(i.getLong());
139 // } else {
140 // return T(i.getUnsignedLong());
141 // }
142 } catch(std::invalid_argument&) {
143 // user gave something other than an integer
144 throw OptionException(option + " requires an integer argument");
145 }
146 }
147 };/* struct OptionHandler<T, true, true> */
148
149 /** Variant for numeric but non-integral C++ types */
150 template <class T>
151 struct OptionHandler<T, true, false> {
152 static T handle(std::string option, std::string optionarg) {
153 std::stringstream in(optionarg);
154 long double r;
155 in >> r;
156 if(! in.eof()) {
157 // we didn't consume the whole string (junk at end)
158 throw OptionException(option + " requires a numeric argument");
159 }
160
161 if(! std::numeric_limits<T>::is_signed && r < 0.0) {
162 // unsigned type but user gave negative value
163 throw OptionException(option + " requires a nonnegative argument");
164 } else if(r < -std::numeric_limits<T>::max()) {
165 // negative overflow for type
166 std::stringstream ss;
167 ss << option << " requires an argument >= " << -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 <= " << 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 ${all_custom_handlers}
227
228 #line 204 "${template}"
229
230 #ifdef CVC4_DEBUG
231 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT true
232 #else /* CVC4_DEBUG */
233 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT false
234 #endif /* CVC4_DEBUG */
235
236 #if defined(CVC4_MUZZLED) || defined(CVC4_COMPETITION_MODE)
237 # define DO_SEMANTIC_CHECKS_BY_DEFAULT false
238 #else /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
239 # define DO_SEMANTIC_CHECKS_BY_DEFAULT true
240 #endif /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
241
242 Options::Options() :
243 d_holder(new options::OptionsHolder()) {
244 }
245
246 Options::Options(const Options& options) :
247 d_holder(new options::OptionsHolder(*options.d_holder)) {
248 }
249
250 Options::~Options() {
251 delete d_holder;
252 }
253
254 Options& Options::operator=(const Options& options) {
255 if(this != &options) {
256 delete d_holder;
257 d_holder = new options::OptionsHolder(*options.d_holder);
258 }
259 return *this;
260 }
261
262 options::OptionsHolder::OptionsHolder() : ${all_modules_defaults}
263 {
264 }
265
266 #line 242 "${template}"
267
268 static const std::string mostCommonOptionsDescription = "\
269 Most commonly-used CVC4 options:${common_documentation}";
270
271 #line 247 "${template}"
272
273 static const std::string optionsDescription = mostCommonOptionsDescription + "\n\
274 \n\
275 Additional CVC4 options:${remaining_documentation}";
276
277 #line 253 "${template}"
278
279 static const std::string optionsFootnote = "\n\
280 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
281 sense of the option.\n\
282 ";
283
284 static const std::string languageDescription = "\
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 smt1 | smtlib1 SMT-LIB format 1.2\n\
289 smt | smtlib | smt2 |\n\
290 smt2.0 | smtlib2 | smtlib2.0 SMT-LIB format 2.0\n\
291 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
292 tptp TPTP format (cnf and fof)\n\
293 sygus SyGuS format\n\
294 \n\
295 Languages currently supported as arguments to the --output-lang option:\n\
296 auto match output language to input language\n\
297 cvc4 | presentation | pl CVC4 presentation language\n\
298 cvc3 CVC3 presentation language\n\
299 smt1 | smtlib1 SMT-LIB format 1.2\n\
300 smt | smtlib | smt2 |\n\
301 smt2.0 | smtlib2.0 | smtlib2 SMT-LIB format 2.0\n\
302 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
303 tptp TPTP format\n\
304 z3str SMT-LIB 2.0 with Z3-str string constraints\n\
305 ast internal format (simple syntax trees)\n\
306 ";
307
308 std::string Options::getDescription() const {
309 return optionsDescription;
310 }
311
312 void Options::printUsage(const std::string msg, std::ostream& out) {
313 out << msg << optionsDescription << std::endl
314 << optionsFootnote << std::endl << std::flush;
315 }
316
317 void Options::printShortUsage(const std::string msg, std::ostream& out) {
318 out << msg << mostCommonOptionsDescription << std::endl
319 << optionsFootnote << std::endl
320 << "For full usage, please use --help." << std::endl << std::endl << std::flush;
321 }
322
323 void Options::printLanguageHelp(std::ostream& out) {
324 out << languageDescription << std::flush;
325 }
326
327 /**
328 * This is a table of long options. By policy, each short option
329 * should have an equivalent long option (but the reverse isn't the
330 * case), so this table should thus contain all command-line options.
331 *
332 * Each option in this array has four elements:
333 *
334 * 1. the long option string
335 * 2. argument behavior for the option:
336 * no_argument - no argument permitted
337 * required_argument - an argument is expected
338 * optional_argument - an argument is permitted but not required
339 * 3. this is a pointer to an int which is set to the 4th entry of the
340 * array if the option is present; or NULL, in which case
341 * getopt_long() returns the 4th entry
342 * 4. the return value for getopt_long() when this long option (or the
343 * value to set the 3rd entry to; see #3)
344 *
345 * If you add something here, you should add it in src/main/usage.h
346 * also, to document it.
347 *
348 * If you add something that has a short option equivalent, you should
349 * add it to the getopt_long() call in parseOptions().
350 */
351 static struct option cmdlineOptions[] = {${all_modules_long_options}
352 { NULL, no_argument, NULL, '\0' }
353 };/* cmdlineOptions */
354
355 #line 330 "${template}"
356
357 static void preemptGetopt(int& argc, char**& argv, const char* opt) {
358 const size_t maxoptlen = 128;
359
360 Debug("preemptGetopt") << "preempting getopt() with " << opt << std::endl;
361
362 AlwaysAssert(opt != NULL && *opt != '\0');
363 AlwaysAssert(strlen(opt) <= maxoptlen);
364
365 ++argc;
366 unsigned i = 1;
367 while(argv[i] != NULL && argv[i][0] != '\0') {
368 ++i;
369 }
370
371 if(argv[i] == NULL) {
372 argv = (char**) realloc(argv, (i + 6) * sizeof(char*));
373 for(unsigned j = i; j < i + 5; ++j) {
374 argv[j] = (char*) malloc(sizeof(char) * maxoptlen);
375 argv[j][0] = '\0';
376 }
377 argv[i + 5] = NULL;
378 }
379
380 strncpy(argv[i], opt, maxoptlen - 1);
381 argv[i][maxoptlen - 1] = '\0'; // ensure NUL-termination even on overflow
382 }
383
384 namespace options {
385
386 /** Set a given Options* as "current" just for a particular scope. */
387 class OptionsGuard {
388 CVC4_THREADLOCAL_TYPE(Options*)* d_field;
389 Options* d_old;
390 public:
391 OptionsGuard(CVC4_THREADLOCAL_TYPE(Options*)* field, Options* opts) :
392 d_field(field),
393 d_old(*field) {
394 *field = opts;
395 }
396 ~OptionsGuard() {
397 *d_field = d_old;
398 }
399 };/* class OptionsGuard */
400
401 }/* CVC4::options namespace */
402
403 /**
404 * Parse argc/argv and put the result into a CVC4::Options.
405 * The return value is what's left of the command line (that is, the
406 * non-option arguments).
407 */
408 std::vector<std::string> Options::parseOptions(int argc, char* main_argv[], options::OptionsHandler* const handler) throw(OptionException) {
409 options::OptionsGuard guard(&s_current, this);
410
411 const char *progName = main_argv[0];
412
413 Debug("options") << "main_argv == " << main_argv << std::endl;
414
415 // Reset getopt(), in the case of multiple calls to parseOptions().
416 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
417 optind = 0;
418 #if HAVE_DECL_OPTRESET
419 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
420 #endif /* HAVE_DECL_OPTRESET */
421
422 // find the base name of the program
423 const char *x = strrchr(progName, '/');
424 if(x != NULL) {
425 progName = x + 1;
426 }
427 d_holder->binary_name = std::string(progName);
428
429 int extra_argc = 1;
430 char **extra_argv = (char**) malloc(2 * sizeof(char*));
431 extra_argv[0] = NULL;
432 extra_argv[1] = NULL;
433
434 int extra_optind = 0, main_optind = 0;
435 int old_optind;
436 int *optind_ref = &main_optind;
437
438 char** argv = main_argv;
439
440 std::vector<std::string> nonOptions;
441
442 for(;;) {
443 int c = -1;
444 optopt = 0;
445 std::string option, optionarg;
446 Debug("preemptGetopt") << "top of loop, extra_optind == " << extra_optind << ", extra_argc == " << extra_argc << std::endl;
447 if((extra_optind == 0 ? 1 : extra_optind) < extra_argc) {
448 #if HAVE_DECL_OPTRESET
449 if(optind_ref != &extra_optind) {
450 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
451 }
452 #endif /* HAVE_DECL_OPTRESET */
453 old_optind = optind = extra_optind;
454 optind_ref = &extra_optind;
455 argv = extra_argv;
456 Debug("preemptGetopt") << "in preempt code, next arg is " << extra_argv[optind == 0 ? 1 : optind] << std::endl;
457 if(extra_argv[extra_optind == 0 ? 1 : extra_optind][0] != '-') {
458 InternalError("preempted args cannot give non-options command-line args (found `%s')", extra_argv[extra_optind == 0 ? 1 : extra_optind]);
459 }
460 c = getopt_long(extra_argc, extra_argv,
461 "+:${all_modules_short_options}",
462 cmdlineOptions, NULL);
463 Debug("preemptGetopt") << "in preempt code, c == " << c << " (`" << char(c) << "') optind == " << optind << std::endl;
464 if(optopt == 0 ||
465 ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} )) {
466 // long option
467 option = argv[old_optind == 0 ? 1 : old_optind];
468 optionarg = (optarg == NULL) ? "" : optarg;
469 } else {
470 // short option
471 option = std::string("-") + char(optopt);
472 optionarg = (optarg == NULL) ? "" : optarg;
473 }
474 if(optind >= extra_argc) {
475 Debug("preemptGetopt") << "-- no more preempt args" << std::endl;
476 unsigned i = 1;
477 while(extra_argv[i] != NULL && extra_argv[i][0] != '\0') {
478 extra_argv[i][0] = '\0';
479 ++i;
480 }
481 extra_argc = 1;
482 extra_optind = 0;
483 } else {
484 Debug("preemptGetopt") << "-- more preempt args" << std::endl;
485 extra_optind = optind;
486 }
487 }
488 if(c == -1) {
489 #if HAVE_DECL_OPTRESET
490 if(optind_ref != &main_optind) {
491 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
492 }
493 #endif /* HAVE_DECL_OPTRESET */
494 old_optind = optind = main_optind;
495 optind_ref = &main_optind;
496 argv = main_argv;
497 if(main_optind < argc && main_argv[main_optind][0] != '-') {
498 do {
499 if(main_optind != 0) {
500 nonOptions.push_back(main_argv[main_optind]);
501 }
502 ++main_optind;
503 } while(main_optind < argc && main_argv[main_optind][0] != '-');
504 continue;
505 }
506 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
507 #if defined(__MINGW32__) || defined(__MINGW64__)
508 if(optreset == 1 && optind > 1) {
509 // on mingw, optreset will reset the optind, so we have to
510 // manually advance argc, argv
511 main_argv[optind - 1] = main_argv[0];
512 argv = main_argv += optind - 1;
513 argc -= optind - 1;
514 old_optind = optind = main_optind = 1;
515 if(argc > 0) {
516 Debug("options") << "looking at : " << argv[0] << std::endl;
517 }
518 /*c = getopt_long(argc, main_argv,
519 "+:${all_modules_short_options}",
520 cmdlineOptions, NULL);
521 Debug("options") << "pre-emptory c is " << c << " (" << char(c) << ")" << std::endl;
522 Debug("options") << "optind was reset to " << optind << std::endl;
523 optind = main_optind;
524 Debug("options") << "I restored optind to " << optind << std::endl;*/
525 }
526 #endif /* __MINGW32__ || __MINGW64__ */
527 Debug("options") << "[ argc == " << argc << ", main_argv == " << main_argv << " ]" << std::endl;
528 c = getopt_long(argc, main_argv,
529 "+:${all_modules_short_options}",
530 cmdlineOptions, NULL);
531 main_optind = optind;
532 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]" << std::endl;
533 Debug("options") << "[ next option will be at pos: " << optind << " ]" << std::endl;
534 if(c == -1) {
535 Debug("options") << "done with option parsing" << std::endl;
536 break;
537 }
538 option = argv[old_optind == 0 ? 1 : old_optind];
539 optionarg = (optarg == NULL) ? "" : optarg;
540 }
541
542 Debug("preemptGetopt") << "processing option " << c << " (`" << char(c) << "'), " << option << std::endl;
543
544 switch(c) {
545 ${all_modules_option_handlers}
546
547 #line 523 "${template}"
548
549 case ':':
550 // This can be a long or short option, and the way to get at the
551 // name of it is different.
552 throw OptionException(std::string("option `") + option + "' missing its required argument");
553
554 case '?':
555 default:
556 if( ( optopt == 0 || ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} ) ) &&
557 !strncmp(argv[optind - 1], "--thread", 8) &&
558 strlen(argv[optind - 1]) > 8 ) {
559 if(! isdigit(argv[optind - 1][8])) {
560 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
561 }
562 std::vector<std::string>& threadArgv = d_holder->threadArgv;
563 char *end;
564 long tnum = strtol(argv[optind - 1] + 8, &end, 10);
565 if(tnum < 0 || (*end != '\0' && *end != '=')) {
566 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
567 }
568 if(threadArgv.size() <= size_t(tnum)) {
569 threadArgv.resize(tnum + 1);
570 }
571 if(threadArgv[tnum] != "") {
572 threadArgv[tnum] += " ";
573 }
574 if(*end == '\0') { // e.g., we have --thread0 "foo"
575 if(argc <= optind) {
576 throw OptionException(std::string("option `") + option + "' missing its required argument");
577 }
578 Debug("options") << "thread " << tnum << " gets option " << argv[optind] << std::endl;
579 threadArgv[tnum] += argv[(*optind_ref)++];
580 } else { // e.g., we have --thread0="foo"
581 if(end[1] == '\0') {
582 throw OptionException(std::string("option `") + option + "' missing its required argument");
583 }
584 Debug("options") << "thread " << tnum << " gets option " << (end + 1) << std::endl;
585 threadArgv[tnum] += end + 1;
586 }
587 Debug("options") << "thread " << tnum << " now has " << threadArgv[tnum] << std::endl;
588 break;
589 }
590
591 throw OptionException(std::string("can't understand option `") + option + "'"
592 + suggestCommandLineOptions(option));
593 }
594 }
595
596 Debug("options") << "returning " << nonOptions.size() << " non-option arguments." << std::endl;
597
598 free(extra_argv);
599
600 return nonOptions;
601 }
602
603 std::string Options::suggestCommandLineOptions(const std::string& optionName) throw() {
604 DidYouMean didYouMean;
605
606 const char* opt;
607 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
608 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
609 }
610
611 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
612 }
613
614 static const char* smtOptions[] = {
615 ${all_modules_smt_options},
616 #line 592 "${template}"
617 NULL
618 };/* smtOptions[] */
619
620 std::vector<std::string> Options::suggestSmtOptions(const std::string& optionName) throw() {
621 std::vector<std::string> suggestions;
622
623 const char* opt;
624 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
625 if(std::strstr(opt, optionName.c_str()) != NULL) {
626 suggestions.push_back(opt);
627 }
628 }
629
630 return suggestions;
631 }
632
633 std::vector< std::vector<std::string> > Options::getOptions() const throw() {
634 std::vector< std::vector<std::string> > opts;
635
636 ${all_modules_get_options}
637
638 #line 614 "${template}"
639
640 return opts;
641 }
642
643 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
644 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
645
646 }/* CVC4 namespace */