Merge pull request #37 from mdeters/quants-kinds
[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-2013 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::OptionsHolder::OptionsHolder() : ${all_modules_defaults}
230 {
231 }
232
233 #line 234 "${template}"
234
235 static const std::string mostCommonOptionsDescription = "\
236 Most commonly-used CVC4 options:${common_documentation}";
237
238 #line 239 "${template}"
239
240 static const std::string optionsDescription = mostCommonOptionsDescription + "\n\
241 \n\
242 Additional CVC4 options:${remaining_documentation}";
243
244 #line 245 "${template}"
245
246 static const std::string optionsFootnote = "\n\
247 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
248 sense of the option.\n\
249 ";
250
251 static const std::string languageDescription = "\
252 Languages currently supported as arguments to the -L / --lang option:\n\
253 auto attempt to automatically determine language\n\
254 cvc4 | presentation | pl CVC4 presentation language\n\
255 smt1 | smtlib1 SMT-LIB format 1.2\n\
256 smt | smtlib | smt2 | smtlib2 SMT-LIB format 2.0\n\
257 tptp TPTP format (cnf and fof)\n\
258 \n\
259 Languages currently supported as arguments to the --output-lang option:\n\
260 auto match output language to input language\n\
261 cvc4 | presentation | pl CVC4 presentation language\n\
262 cvc3 CVC3 presentation language\n\
263 smt1 | smtlib1 SMT-LIB format 1.2\n\
264 smt | smtlib | smt2 | smtlib2 SMT-LIB format 2.0\n\
265 z3str SMT-LIB 2.0 with Z3-str string constraints\n\
266 tptp TPTP format\n\
267 ast internal format (simple syntax trees)\n\
268 ";
269
270 std::string Options::getDescription() const {
271 return optionsDescription;
272 }
273
274 void Options::printUsage(const std::string msg, std::ostream& out) {
275 out << msg << optionsDescription << std::endl
276 << optionsFootnote << std::endl << std::flush;
277 }
278
279 void Options::printShortUsage(const std::string msg, std::ostream& out) {
280 out << msg << mostCommonOptionsDescription << std::endl
281 << optionsFootnote << std::endl
282 << "For full usage, please use --help." << std::endl << std::endl << std::flush;
283 }
284
285 void Options::printLanguageHelp(std::ostream& out) {
286 out << languageDescription << std::flush;
287 }
288
289 /**
290 * This is a table of long options. By policy, each short option
291 * should have an equivalent long option (but the reverse isn't the
292 * case), so this table should thus contain all command-line options.
293 *
294 * Each option in this array has four elements:
295 *
296 * 1. the long option string
297 * 2. argument behavior for the option:
298 * no_argument - no argument permitted
299 * required_argument - an argument is expected
300 * optional_argument - an argument is permitted but not required
301 * 3. this is a pointer to an int which is set to the 4th entry of the
302 * array if the option is present; or NULL, in which case
303 * getopt_long() returns the 4th entry
304 * 4. the return value for getopt_long() when this long option (or the
305 * value to set the 3rd entry to; see #3)
306 *
307 * If you add something here, you should add it in src/main/usage.h
308 * also, to document it.
309 *
310 * If you add something that has a short option equivalent, you should
311 * add it to the getopt_long() call in parseOptions().
312 */
313 static struct option cmdlineOptions[] = {${all_modules_long_options}
314 { NULL, no_argument, NULL, '\0' }
315 };/* cmdlineOptions */
316
317 #line 318 "${template}"
318
319 static void preemptGetopt(int& argc, char**& argv, const char* opt) {
320 const size_t maxoptlen = 128;
321
322 Debug("preemptGetopt") << "preempting getopt() with " << opt << std::endl;
323
324 AlwaysAssert(opt != NULL && *opt != '\0');
325 AlwaysAssert(strlen(opt) <= maxoptlen);
326
327 ++argc;
328 unsigned i = 1;
329 while(argv[i] != NULL && argv[i][0] != '\0') {
330 ++i;
331 }
332
333 if(argv[i] == NULL) {
334 argv = (char**) realloc(argv, (i + 6) * sizeof(char*));
335 for(unsigned j = i; j < i + 5; ++j) {
336 argv[j] = (char*) malloc(sizeof(char) * maxoptlen);
337 argv[j][0] = '\0';
338 }
339 argv[i + 5] = NULL;
340 }
341
342 strncpy(argv[i], opt, maxoptlen - 1);
343 argv[i][maxoptlen - 1] = '\0'; // ensure NUL-termination even on overflow
344 }
345
346 namespace options {
347
348 /** Set a given Options* as "current" just for a particular scope. */
349 class OptionsGuard {
350 CVC4_THREADLOCAL_TYPE(Options*)* d_field;
351 Options* d_old;
352 public:
353 OptionsGuard(CVC4_THREADLOCAL_TYPE(Options*)* field, Options* opts) :
354 d_field(field),
355 d_old(*field) {
356 *field = opts;
357 }
358 ~OptionsGuard() {
359 *d_field = d_old;
360 }
361 };/* class OptionsGuard */
362
363 }/* CVC4::options namespace */
364
365 /**
366 * Parse argc/argv and put the result into a CVC4::Options.
367 * The return value is what's left of the command line (that is, the
368 * non-option arguments).
369 */
370 std::vector<std::string> Options::parseOptions(int argc, char* main_argv[]) throw(OptionException) {
371 options::OptionsGuard guard(&s_current, this);
372
373 const char *progName = main_argv[0];
374 SmtEngine* const smt = NULL;
375
376 Debug("options") << "main_argv == " << main_argv << std::endl;
377
378 // Reset getopt(), in the case of multiple calls to parseOptions().
379 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
380 optind = 0;
381 #if HAVE_DECL_OPTRESET
382 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
383 #endif /* HAVE_DECL_OPTRESET */
384
385 // find the base name of the program
386 const char *x = strrchr(progName, '/');
387 if(x != NULL) {
388 progName = x + 1;
389 }
390 d_holder->binary_name = std::string(progName);
391
392 int extra_argc = 1;
393 char **extra_argv = (char**) malloc(2 * sizeof(char*));
394 extra_argv[0] = NULL;
395 extra_argv[1] = NULL;
396
397 int extra_optind = 0, main_optind = 0;
398 int old_optind;
399 int *optind_ref = &main_optind;
400
401 char** argv = main_argv;
402
403 std::vector<std::string> nonOptions;
404
405 for(;;) {
406 int c = -1;
407 optopt = 0;
408 std::string option, optionarg;
409 Debug("preemptGetopt") << "top of loop, extra_optind == " << extra_optind << ", extra_argc == " << extra_argc << std::endl;
410 if((extra_optind == 0 ? 1 : extra_optind) < extra_argc) {
411 #if HAVE_DECL_OPTRESET
412 if(optind_ref != &extra_optind) {
413 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
414 }
415 #endif /* HAVE_DECL_OPTRESET */
416 old_optind = optind = extra_optind;
417 optind_ref = &extra_optind;
418 argv = extra_argv;
419 Debug("preemptGetopt") << "in preempt code, next arg is " << extra_argv[optind == 0 ? 1 : optind] << std::endl;
420 if(extra_argv[extra_optind == 0 ? 1 : extra_optind][0] != '-') {
421 InternalError("preempted args cannot give non-options command-line args (found `%s')", extra_argv[extra_optind == 0 ? 1 : extra_optind]);
422 }
423 c = getopt_long(extra_argc, extra_argv,
424 "+:${all_modules_short_options}",
425 cmdlineOptions, NULL);
426 Debug("preemptGetopt") << "in preempt code, c == " << c << " (`" << char(c) << "') optind == " << optind << std::endl;
427 if(optopt == 0 ||
428 ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} )) {
429 // long option
430 option = argv[old_optind == 0 ? 1 : old_optind];
431 optionarg = (optarg == NULL) ? "" : optarg;
432 } else {
433 // short option
434 option = std::string("-") + char(optopt);
435 optionarg = (optarg == NULL) ? "" : optarg;
436 }
437 if(optind >= extra_argc) {
438 Debug("preemptGetopt") << "-- no more preempt args" << std::endl;
439 unsigned i = 1;
440 while(extra_argv[i] != NULL && extra_argv[i][0] != '\0') {
441 extra_argv[i][0] = '\0';
442 ++i;
443 }
444 extra_argc = 1;
445 extra_optind = 0;
446 } else {
447 Debug("preemptGetopt") << "-- more preempt args" << std::endl;
448 extra_optind = optind;
449 }
450 }
451 if(c == -1) {
452 #if HAVE_DECL_OPTRESET
453 if(optind_ref != &main_optind) {
454 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
455 }
456 #endif /* HAVE_DECL_OPTRESET */
457 old_optind = optind = main_optind;
458 optind_ref = &main_optind;
459 argv = main_argv;
460 if(main_optind < argc && main_argv[main_optind][0] != '-') {
461 do {
462 if(main_optind != 0) {
463 nonOptions.push_back(main_argv[main_optind]);
464 }
465 ++main_optind;
466 } while(main_optind < argc && main_argv[main_optind][0] != '-');
467 continue;
468 }
469 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
470 #if defined(__MINGW32__) || defined(__MINGW64__)
471 if(optreset == 1 && optind > 1) {
472 // on mingw, optreset will reset the optind, so we have to
473 // manually advance argc, argv
474 main_argv[optind - 1] = main_argv[0];
475 argv = main_argv += optind - 1;
476 argc -= optind - 1;
477 old_optind = optind = main_optind = 1;
478 if(argc > 0) {
479 Debug("options") << "looking at : " << argv[0] << std::endl;
480 }
481 /*c = getopt_long(argc, main_argv,
482 "+:${all_modules_short_options}",
483 cmdlineOptions, NULL);
484 Debug("options") << "pre-emptory c is " << c << " (" << char(c) << ")" << std::endl;
485 Debug("options") << "optind was reset to " << optind << std::endl;
486 optind = main_optind;
487 Debug("options") << "I restored optind to " << optind << std::endl;*/
488 }
489 #endif /* __MINGW32__ || __MINGW64__ */
490 Debug("options") << "[ argc == " << argc << ", main_argv == " << main_argv << " ]" << std::endl;
491 c = getopt_long(argc, main_argv,
492 "+:${all_modules_short_options}",
493 cmdlineOptions, NULL);
494 main_optind = optind;
495 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]" << std::endl;
496 Debug("options") << "[ next option will be at pos: " << optind << " ]" << std::endl;
497 if(c == -1) {
498 Debug("options") << "done with option parsing" << std::endl;
499 break;
500 }
501 option = argv[old_optind == 0 ? 1 : old_optind];
502 optionarg = (optarg == NULL) ? "" : optarg;
503 }
504
505 Debug("preemptGetopt") << "processing option " << c << " (`" << char(c) << "'), " << option << std::endl;
506
507 switch(c) {
508 ${all_modules_option_handlers}
509
510 #line 511 "${template}"
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 + "' missing its required argument");
516
517 case '?':
518 default:
519 if( ( optopt == 0 || ( optopt >= ${long_option_value_begin} && optopt <= ${long_option_value_end} ) ) &&
520 !strncmp(argv[optind - 1], "--thread", 8) &&
521 strlen(argv[optind - 1]) > 8 ) {
522 if(! isdigit(argv[optind - 1][8])) {
523 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
524 }
525 std::vector<std::string>& threadArgv = d_holder->threadArgv;
526 char *end;
527 long tnum = strtol(argv[optind - 1] + 8, &end, 10);
528 if(tnum < 0 || (*end != '\0' && *end != '=')) {
529 throw OptionException(std::string("can't understand option `") + option + "': expected something like --threadN=\"--option1 --option2\", where N is a nonnegative integer");
530 }
531 if(threadArgv.size() <= size_t(tnum)) {
532 threadArgv.resize(tnum + 1);
533 }
534 if(threadArgv[tnum] != "") {
535 threadArgv[tnum] += " ";
536 }
537 if(*end == '\0') { // e.g., we have --thread0 "foo"
538 if(argc <= optind) {
539 throw OptionException(std::string("option `") + option + "' missing its required argument");
540 }
541 Debug("options") << "thread " << tnum << " gets option " << argv[optind] << std::endl;
542 threadArgv[tnum] += argv[(*optind_ref)++];
543 } else { // e.g., we have --thread0="foo"
544 if(end[1] == '\0') {
545 throw OptionException(std::string("option `") + option + "' missing its required argument");
546 }
547 Debug("options") << "thread " << tnum << " gets option " << (end + 1) << std::endl;
548 threadArgv[tnum] += end + 1;
549 }
550 Debug("options") << "thread " << tnum << " now has " << threadArgv[tnum] << std::endl;
551 break;
552 }
553
554 throw OptionException(std::string("can't understand option `") + option + "'"
555 + suggestCommandLineOptions(option));
556 }
557 }
558
559 Debug("options") << "returning " << nonOptions.size() << " non-option arguments." << std::endl;
560
561 free(extra_argv);
562
563 return nonOptions;
564 }
565
566 std::string Options::suggestCommandLineOptions(const std::string& optionName) throw() {
567 DidYouMean didYouMean;
568
569 const char* opt;
570 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
571 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
572 }
573
574 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
575 }
576
577 static const char* smtOptions[] = {
578 ${all_modules_smt_options},
579 #line 580 "${template}"
580 NULL
581 };/* smtOptions[] */
582
583 std::vector<std::string> Options::suggestSmtOptions(const std::string& optionName) throw() {
584 std::vector<std::string> suggestions;
585
586 const char* opt;
587 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
588 if(std::strstr(opt, optionName.c_str()) != NULL) {
589 suggestions.push_back(opt);
590 }
591 }
592
593 return suggestions;
594 }
595
596 SExpr Options::getOptions() const throw() {
597 std::vector<SExpr> opts;
598
599 ${all_modules_get_options}
600
601 #line 602 "${template}"
602
603 return SExpr(opts);
604 }
605
606 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
607 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
608
609 }/* CVC4 namespace */