Merge branch 'master' of github.com:tiliang/CVC4
[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 #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 <cstdio>
38 #include <cstdlib>
39 #include <new>
40 #include <string>
41 #include <sstream>
42 #include <limits>
43 #include <unistd.h>
44 #include <string.h>
45 #include <stdint.h>
46 #include <time.h>
47
48 #include "expr/expr.h"
49 #include "util/configuration.h"
50 #include "util/didyoumean.h"
51 #include "util/exception.h"
52 #include "util/language.h"
53 #include "util/tls.h"
54
55 ${include_all_option_headers}
56
57 #line 58 "${template}"
58
59 #include "util/output.h"
60 #include "options/options_holder.h"
61 #include "cvc4autoconfig.h"
62 #include "options/base_options_handlers.h"
63
64 ${option_handler_includes}
65
66 #line 67 "${template}"
67
68 using namespace CVC4;
69 using namespace CVC4::options;
70
71 namespace CVC4 {
72
73 CVC4_THREADLOCAL(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 T handle(std::string option, std::string optionarg) {
94 try {
95 Integer i(optionarg, 10);
96
97 if(! std::numeric_limits<T>::is_signed && i < 0) {
98 // unsigned type but user gave negative argument
99 throw OptionException(option + " requires a nonnegative argument");
100 } else if(i < std::numeric_limits<T>::min()) {
101 // negative overflow for type
102 std::stringstream ss;
103 ss << option << " requires an argument >= " << std::numeric_limits<T>::min();
104 throw OptionException(ss.str());
105 } else if(i > std::numeric_limits<T>::max()) {
106 // positive overflow for type
107 std::stringstream ss;
108 ss << option << " requires an argument <= " << std::numeric_limits<T>::max();
109 throw OptionException(ss.str());
110 }
111
112 if(std::numeric_limits<T>::is_signed) {
113 return T(i.getLong());
114 } else {
115 return T(i.getUnsignedLong());
116 }
117 } catch(std::invalid_argument&) {
118 // user gave something other than an integer
119 throw OptionException(option + " requires an integer argument");
120 }
121 }
122 };/* struct OptionHandler<T, true, true> */
123
124 /** Variant for numeric but non-integral C++ types */
125 template <class T>
126 struct OptionHandler<T, true, false> {
127 static T handle(std::string option, std::string optionarg) {
128 std::stringstream in(optionarg);
129 long double r;
130 in >> r;
131 if(! in.eof()) {
132 // we didn't consume the whole string (junk at end)
133 throw OptionException(option + " requires a numeric argument");
134 }
135
136 if(! std::numeric_limits<T>::is_signed && r < 0.0) {
137 // unsigned type but user gave negative value
138 throw OptionException(option + " requires a nonnegative argument");
139 } else if(r < -std::numeric_limits<T>::max()) {
140 // negative overflow for type
141 std::stringstream ss;
142 ss << option << " requires an argument >= " << -std::numeric_limits<T>::max();
143 throw OptionException(ss.str());
144 } else if(r > std::numeric_limits<T>::max()) {
145 // positive overflow for type
146 std::stringstream ss;
147 ss << option << " requires an argument <= " << std::numeric_limits<T>::max();
148 throw OptionException(ss.str());
149 }
150
151 return T(r);
152 }
153 };/* struct OptionHandler<T, true, false> */
154
155 /** Variant for non-numeric C++ types */
156 template <class T>
157 struct OptionHandler<T, false, false> {
158 static T handle(std::string option, std::string optionarg) {
159 T::unsupported_handleOption_call___please_write_me;
160 // The above line causes a compiler error if this version of the template
161 // is ever instantiated (meaning that a specialization is missing). So
162 // don't worry about the segfault in the next line, the "return" is only
163 // there to keep the compiler from giving additional, distracting errors
164 // and warnings.
165 return *(T*)0;
166 }
167 };/* struct OptionHandler<T, false, false> */
168
169 /** Handle an option of type T in the default way. */
170 template <class T>
171 T handleOption(std::string option, std::string optionarg) {
172 return OptionHandler<T, std::numeric_limits<T>::is_specialized, std::numeric_limits<T>::is_integer>::handle(option, optionarg);
173 }
174
175 /** Handle an option of type std::string in the default way. */
176 template <>
177 std::string handleOption<std::string>(std::string option, std::string optionarg) {
178 return optionarg;
179 }
180
181 /**
182 * Run handler, and any user-given predicates, for option T.
183 * If a user specifies a :handler or :predicates, it overrides this.
184 */
185 template <class T>
186 typename T::type runHandlerAndPredicates(T, std::string option, std::string optionarg, SmtEngine* smt) {
187 // By default, parse the option argument in a way appropriate for its type.
188 // E.g., for "unsigned int" options, ensure that the provided argument is
189 // a nonnegative integer that fits in the unsigned int type.
190
191 return handleOption<typename T::type>(option, optionarg);
192 }
193
194 template <class T>
195 void runBoolPredicates(T, std::string option, bool b, SmtEngine* smt) {
196 // By default, nothing to do for bool. Users add things with
197 // :predicate in options files to provide custom checking routines
198 // that can throw exceptions.
199 }
200
201 ${all_custom_handlers}
202
203 #line 204 "${template}"
204
205 #ifdef CVC4_DEBUG
206 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT true
207 #else /* CVC4_DEBUG */
208 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT false
209 #endif /* CVC4_DEBUG */
210
211 #if defined(CVC4_MUZZLED) || defined(CVC4_COMPETITION_MODE)
212 # define DO_SEMANTIC_CHECKS_BY_DEFAULT false
213 #else /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
214 # define DO_SEMANTIC_CHECKS_BY_DEFAULT true
215 #endif /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
216
217 Options::Options() :
218 d_holder(new options::OptionsHolder()) {
219 }
220
221 Options::Options(const Options& options) :
222 d_holder(new options::OptionsHolder(*options.d_holder)) {
223 }
224
225 Options::~Options() {
226 delete d_holder;
227 }
228
229 Options& Options::operator=(const Options& options) {
230 if(this != &options) {
231 delete d_holder;
232 d_holder = new options::OptionsHolder(*options.d_holder);
233 }
234 return *this;
235 }
236
237 options::OptionsHolder::OptionsHolder() : ${all_modules_defaults}
238 {
239 }
240
241 #line 241 "${template}"
242
243 static const std::string mostCommonOptionsDescription = "\
244 Most commonly-used CVC4 options:${common_documentation}";
245
246 #line 246 "${template}"
247
248 static const std::string optionsDescription = mostCommonOptionsDescription + "\n\
249 \n\
250 Additional CVC4 options:${remaining_documentation}";
251
252 #line 252 "${template}"
253
254 static const std::string optionsFootnote = "\n\
255 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
256 sense of the option.\n\
257 ";
258
259 static const std::string languageDescription = "\
260 Languages currently supported as arguments to the -L / --lang option:\n\
261 auto attempt to automatically determine language\n\
262 cvc4 | presentation | pl CVC4 presentation language\n\
263 smt1 | smtlib1 SMT-LIB format 1.2\n\
264 smt | smtlib | smt2 |\n\
265 smt2.0 | smtlib2 | smtlib2.0 SMT-LIB format 2.0\n\
266 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
267 tptp TPTP format (cnf and fof)\n\
268 \n\
269 Languages currently supported as arguments to the --output-lang option:\n\
270 auto match output language to input language\n\
271 cvc4 | presentation | pl CVC4 presentation language\n\
272 cvc3 CVC3 presentation language\n\
273 smt1 | smtlib1 SMT-LIB format 1.2\n\
274 smt | smtlib | smt2 |\n\
275 smt2.0 | smtlib2.0 | smtlib2 SMT-LIB format 2.0\n\
276 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
277 z3str SMT-LIB 2.0 with Z3-str string constraints\n\
278 tptp TPTP format\n\
279 ast internal format (simple syntax trees)\n\
280 ";
281
282 std::string Options::getDescription() const {
283 return optionsDescription;
284 }
285
286 void Options::printUsage(const std::string msg, std::ostream& out) {
287 out << msg << optionsDescription << std::endl
288 << optionsFootnote << std::endl << std::flush;
289 }
290
291 void Options::printShortUsage(const std::string msg, std::ostream& out) {
292 out << msg << mostCommonOptionsDescription << std::endl
293 << optionsFootnote << std::endl
294 << "For full usage, please use --help." << std::endl << std::endl << std::flush;
295 }
296
297 void Options::printLanguageHelp(std::ostream& out) {
298 out << languageDescription << std::flush;
299 }
300
301 /**
302 * This is a table of long options. By policy, each short option
303 * should have an equivalent long option (but the reverse isn't the
304 * case), so this table should thus contain all command-line options.
305 *
306 * Each option in this array has four elements:
307 *
308 * 1. the long option string
309 * 2. argument behavior for the option:
310 * no_argument - no argument permitted
311 * required_argument - an argument is expected
312 * optional_argument - an argument is permitted but not required
313 * 3. this is a pointer to an int which is set to the 4th entry of the
314 * array if the option is present; or NULL, in which case
315 * getopt_long() returns the 4th entry
316 * 4. the return value for getopt_long() when this long option (or the
317 * value to set the 3rd entry to; see #3)
318 *
319 * If you add something here, you should add it in src/main/usage.h
320 * also, to document it.
321 *
322 * If you add something that has a short option equivalent, you should
323 * add it to the getopt_long() call in parseOptions().
324 */
325 static struct option cmdlineOptions[] = {${all_modules_long_options}
326 { NULL, no_argument, NULL, '\0' }
327 };/* cmdlineOptions */
328
329 #line 329 "${template}"
330
331 static void preemptGetopt(int& argc, char**& argv, const char* opt) {
332 const size_t maxoptlen = 128;
333
334 Debug("preemptGetopt") << "preempting getopt() with " << opt << std::endl;
335
336 AlwaysAssert(opt != NULL && *opt != '\0');
337 AlwaysAssert(strlen(opt) <= maxoptlen);
338
339 ++argc;
340 unsigned i = 1;
341 while(argv[i] != NULL && argv[i][0] != '\0') {
342 ++i;
343 }
344
345 if(argv[i] == NULL) {
346 argv = (char**) realloc(argv, (i + 6) * sizeof(char*));
347 for(unsigned j = i; j < i + 5; ++j) {
348 argv[j] = (char*) malloc(sizeof(char) * maxoptlen);
349 argv[j][0] = '\0';
350 }
351 argv[i + 5] = NULL;
352 }
353
354 strncpy(argv[i], opt, maxoptlen - 1);
355 argv[i][maxoptlen - 1] = '\0'; // ensure NUL-termination even on overflow
356 }
357
358 namespace options {
359
360 /** Set a given Options* as "current" just for a particular scope. */
361 class OptionsGuard {
362 CVC4_THREADLOCAL_TYPE(Options*)* d_field;
363 Options* d_old;
364 public:
365 OptionsGuard(CVC4_THREADLOCAL_TYPE(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 std::vector<std::string> Options::parseOptions(int argc, char* main_argv[]) throw(OptionException) {
383 options::OptionsGuard guard(&s_current, this);
384
385 const char *progName = main_argv[0];
386 SmtEngine* const smt = NULL;
387
388 Debug("options") << "main_argv == " << main_argv << std::endl;
389
390 // Reset getopt(), in the case of multiple calls to parseOptions().
391 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
392 optind = 0;
393 #if HAVE_DECL_OPTRESET
394 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
395 #endif /* HAVE_DECL_OPTRESET */
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 d_holder->binary_name = std::string(progName);
403
404 int extra_argc = 1;
405 char **extra_argv = (char**) malloc(2 * sizeof(char*));
406 extra_argv[0] = NULL;
407 extra_argv[1] = NULL;
408
409 int extra_optind = 0, main_optind = 0;
410 int old_optind;
411 int *optind_ref = &main_optind;
412
413 char** argv = main_argv;
414
415 std::vector<std::string> nonOptions;
416
417 for(;;) {
418 int c = -1;
419 optopt = 0;
420 std::string option, optionarg;
421 Debug("preemptGetopt") << "top of loop, extra_optind == " << extra_optind << ", extra_argc == " << extra_argc << std::endl;
422 if((extra_optind == 0 ? 1 : extra_optind) < extra_argc) {
423 #if HAVE_DECL_OPTRESET
424 if(optind_ref != &extra_optind) {
425 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
426 }
427 #endif /* HAVE_DECL_OPTRESET */
428 old_optind = optind = extra_optind;
429 optind_ref = &extra_optind;
430 argv = extra_argv;
431 Debug("preemptGetopt") << "in preempt code, next arg is " << extra_argv[optind == 0 ? 1 : optind] << std::endl;
432 if(extra_argv[extra_optind == 0 ? 1 : extra_optind][0] != '-') {
433 InternalError("preempted args cannot give non-options command-line args (found `%s')", extra_argv[extra_optind == 0 ? 1 : extra_optind]);
434 }
435 c = getopt_long(extra_argc, extra_argv,
436 "+:${all_modules_short_options}",
437 cmdlineOptions, NULL);
438 Debug("preemptGetopt") << "in preempt code, c == " << c << " (`" << char(c) << "') optind == " << optind << std::endl;
439 if(optopt == 0 ||
440 ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} )) {
441 // long option
442 option = argv[old_optind == 0 ? 1 : old_optind];
443 optionarg = (optarg == NULL) ? "" : optarg;
444 } else {
445 // short option
446 option = std::string("-") + char(optopt);
447 optionarg = (optarg == NULL) ? "" : optarg;
448 }
449 if(optind >= extra_argc) {
450 Debug("preemptGetopt") << "-- no more preempt args" << std::endl;
451 unsigned i = 1;
452 while(extra_argv[i] != NULL && extra_argv[i][0] != '\0') {
453 extra_argv[i][0] = '\0';
454 ++i;
455 }
456 extra_argc = 1;
457 extra_optind = 0;
458 } else {
459 Debug("preemptGetopt") << "-- more preempt args" << std::endl;
460 extra_optind = optind;
461 }
462 }
463 if(c == -1) {
464 #if HAVE_DECL_OPTRESET
465 if(optind_ref != &main_optind) {
466 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
467 }
468 #endif /* HAVE_DECL_OPTRESET */
469 old_optind = optind = main_optind;
470 optind_ref = &main_optind;
471 argv = main_argv;
472 if(main_optind < argc && main_argv[main_optind][0] != '-') {
473 do {
474 if(main_optind != 0) {
475 nonOptions.push_back(main_argv[main_optind]);
476 }
477 ++main_optind;
478 } while(main_optind < argc && main_argv[main_optind][0] != '-');
479 continue;
480 }
481 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
482 #if defined(__MINGW32__) || defined(__MINGW64__)
483 if(optreset == 1 && optind > 1) {
484 // on mingw, optreset will reset the optind, so we have to
485 // manually advance argc, argv
486 main_argv[optind - 1] = main_argv[0];
487 argv = main_argv += optind - 1;
488 argc -= optind - 1;
489 old_optind = optind = main_optind = 1;
490 if(argc > 0) {
491 Debug("options") << "looking at : " << argv[0] << std::endl;
492 }
493 /*c = getopt_long(argc, main_argv,
494 "+:${all_modules_short_options}",
495 cmdlineOptions, NULL);
496 Debug("options") << "pre-emptory c is " << c << " (" << char(c) << ")" << std::endl;
497 Debug("options") << "optind was reset to " << optind << std::endl;
498 optind = main_optind;
499 Debug("options") << "I restored optind to " << optind << std::endl;*/
500 }
501 #endif /* __MINGW32__ || __MINGW64__ */
502 Debug("options") << "[ argc == " << argc << ", main_argv == " << main_argv << " ]" << std::endl;
503 c = getopt_long(argc, main_argv,
504 "+:${all_modules_short_options}",
505 cmdlineOptions, NULL);
506 main_optind = optind;
507 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]" << std::endl;
508 Debug("options") << "[ next option will be at pos: " << optind << " ]" << std::endl;
509 if(c == -1) {
510 Debug("options") << "done with option parsing" << std::endl;
511 break;
512 }
513 option = argv[old_optind == 0 ? 1 : old_optind];
514 optionarg = (optarg == NULL) ? "" : optarg;
515 }
516
517 Debug("preemptGetopt") << "processing option " << c << " (`" << char(c) << "'), " << option << std::endl;
518
519 switch(c) {
520 ${all_modules_option_handlers}
521
522 #line 522 "${template}"
523
524 case ':':
525 // This can be a long or short option, and the way to get at the
526 // name of it is different.
527 throw OptionException(std::string("option `") + option + "' missing its required argument");
528
529 case '?':
530 default:
531 if( ( optopt == 0 || ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} ) ) &&
532 !strncmp(argv[optind - 1], "--thread", 8) &&
533 strlen(argv[optind - 1]) > 8 ) {
534 if(! isdigit(argv[optind - 1][8])) {
535 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
536 }
537 std::vector<std::string>& threadArgv = d_holder->threadArgv;
538 char *end;
539 long tnum = strtol(argv[optind - 1] + 8, &end, 10);
540 if(tnum < 0 || (*end != '\0' && *end != '=')) {
541 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
542 }
543 if(threadArgv.size() <= size_t(tnum)) {
544 threadArgv.resize(tnum + 1);
545 }
546 if(threadArgv[tnum] != "") {
547 threadArgv[tnum] += " ";
548 }
549 if(*end == '\0') { // e.g., we have --thread0 "foo"
550 if(argc <= optind) {
551 throw OptionException(std::string("option `") + option + "' missing its required argument");
552 }
553 Debug("options") << "thread " << tnum << " gets option " << argv[optind] << std::endl;
554 threadArgv[tnum] += argv[(*optind_ref)++];
555 } else { // e.g., we have --thread0="foo"
556 if(end[1] == '\0') {
557 throw OptionException(std::string("option `") + option + "' missing its required argument");
558 }
559 Debug("options") << "thread " << tnum << " gets option " << (end + 1) << std::endl;
560 threadArgv[tnum] += end + 1;
561 }
562 Debug("options") << "thread " << tnum << " now has " << threadArgv[tnum] << std::endl;
563 break;
564 }
565
566 throw OptionException(std::string("can't understand option `") + option + "'"
567 + suggestCommandLineOptions(option));
568 }
569 }
570
571 Debug("options") << "returning " << nonOptions.size() << " non-option arguments." << std::endl;
572
573 free(extra_argv);
574
575 return nonOptions;
576 }
577
578 std::string Options::suggestCommandLineOptions(const std::string& optionName) throw() {
579 DidYouMean didYouMean;
580
581 const char* opt;
582 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
583 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
584 }
585
586 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
587 }
588
589 static const char* smtOptions[] = {
590 ${all_modules_smt_options},
591 #line 591 "${template}"
592 NULL
593 };/* smtOptions[] */
594
595 std::vector<std::string> Options::suggestSmtOptions(const std::string& optionName) throw() {
596 std::vector<std::string> suggestions;
597
598 const char* opt;
599 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
600 if(std::strstr(opt, optionName.c_str()) != NULL) {
601 suggestions.push_back(opt);
602 }
603 }
604
605 return suggestions;
606 }
607
608 SExpr Options::getOptions() const throw() {
609 std::vector<SExpr> opts;
610
611 ${all_modules_get_options}
612
613 #line 613 "${template}"
614
615 return SExpr(opts);
616 }
617
618 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
619 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
620
621 }/* CVC4 namespace */