Refactor mkoptions (#1631)
[cvc5.git] / src / options / options_template.cpp
1 /********************* */
2 /*! \file options.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Tim King, Morgan Deters, Kshitij Bansal
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2017 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/tls.h"
52 #include "base/cvc4_assert.h"
53 #include "base/exception.h"
54 #include "base/output.h"
55 #include "options/argument_extender.h"
56 #include "options/argument_extender_implementation.h"
57 #include "options/didyoumean.h"
58 #include "options/language.h"
59 #include "options/options_handler.h"
60
61 ${headers_module}$
62
63
64 #include "options/options_holder.h"
65 #include "cvc4autoconfig.h"
66 #include "options/base_handlers.h"
67
68 ${headers_handler}$
69
70
71 using namespace CVC4;
72 using namespace CVC4::options;
73
74 namespace CVC4 {
75
76 CVC4_THREAD_LOCAL Options* Options::s_current = NULL;
77
78
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 +
116 " as an integer of the appropraite type.");
117 }
118
119 // Depending in the platform unsigned numbers with '-' signs may parse.
120 // Reject these by looking for any minus if it is not signed.
121 if( (! std::numeric_limits<T>::is_signed) && containsMinus(optionarg) ) {
122 // unsigned type but user gave negative argument
123 throw OptionException(option + " requires a nonnegative argument");
124 } else if(i < std::numeric_limits<T>::min()) {
125 // negative overflow for type
126 std::stringstream ss;
127 ss << option << " requires an argument >= "
128 << std::numeric_limits<T>::min();
129 throw OptionException(ss.str());
130 } else if(i > std::numeric_limits<T>::max()) {
131 // positive overflow for type
132 std::stringstream ss;
133 ss << option << " requires an argument <= "
134 << std::numeric_limits<T>::max();
135 throw OptionException(ss.str());
136 }
137
138 return i;
139
140 // if(std::numeric_limits<T>::is_signed) {
141 // return T(i.getLong());
142 // } else {
143 // return T(i.getUnsignedLong());
144 // }
145 } catch(std::invalid_argument&) {
146 // user gave something other than an integer
147 throw OptionException(option + " requires an integer argument");
148 }
149 }
150 };/* struct OptionHandler<T, true, true> */
151
152 /** Variant for numeric but non-integral C++ types */
153 template <class T>
154 struct OptionHandler<T, true, false> {
155 static T handle(std::string option, std::string optionarg) {
156 std::stringstream in(optionarg);
157 long double r;
158 in >> r;
159 if(! in.eof()) {
160 // we didn't consume the whole string (junk at end)
161 throw OptionException(option + " requires a numeric argument");
162 }
163
164 if(! std::numeric_limits<T>::is_signed && r < 0.0) {
165 // unsigned type but user gave negative value
166 throw OptionException(option + " requires a nonnegative argument");
167 } else if(r < -std::numeric_limits<T>::max()) {
168 // negative 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 } else if(r > std::numeric_limits<T>::max()) {
174 // positive overflow for type
175 std::stringstream ss;
176 ss << option << " requires an argument <= "
177 << std::numeric_limits<T>::max();
178 throw OptionException(ss.str());
179 }
180
181 return T(r);
182 }
183 };/* struct OptionHandler<T, true, false> */
184
185 /** Variant for non-numeric C++ types */
186 template <class T>
187 struct OptionHandler<T, false, false> {
188 static T handle(std::string option, std::string optionarg) {
189 T::unsupported_handleOption_call___please_write_me;
190 // The above line causes a compiler error if this version of the template
191 // is ever instantiated (meaning that a specialization is missing). So
192 // don't worry about the segfault in the next line, the "return" is only
193 // there to keep the compiler from giving additional, distracting errors
194 // and warnings.
195 return *(T*)0;
196 }
197 };/* struct OptionHandler<T, false, false> */
198
199 /** Handle an option of type T in the default way. */
200 template <class T>
201 T handleOption(std::string option, std::string optionarg) {
202 return OptionHandler<T, std::numeric_limits<T>::is_specialized, std::numeric_limits<T>::is_integer>::handle(option, optionarg);
203 }
204
205 /** Handle an option of type std::string in the default way. */
206 template <>
207 std::string handleOption<std::string>(std::string option, std::string optionarg) {
208 return optionarg;
209 }
210
211 /**
212 * Run handler, and any user-given predicates, for option T.
213 * If a user specifies a :handler or :predicates, it overrides this.
214 */
215 template <class T>
216 typename T::type runHandlerAndPredicates(T, std::string option, std::string optionarg, options::OptionsHandler* handler) {
217 // By default, parse the option argument in a way appropriate for its type.
218 // E.g., for "unsigned int" options, ensure that the provided argument is
219 // a nonnegative integer that fits in the unsigned int type.
220
221 return handleOption<typename T::type>(option, optionarg);
222 }
223
224 template <class T>
225 void runBoolPredicates(T, std::string option, bool b, options::OptionsHandler* handler) {
226 // By default, nothing to do for bool. Users add things with
227 // :predicate in options files to provide custom checking routines
228 // that can throw exceptions.
229 }
230
231
232 Options::Options()
233 : d_holder(new options::OptionsHolder())
234 , d_handler(new options::OptionsHandler(this))
235 , d_forceLogicListeners()
236 , d_beforeSearchListeners()
237 , d_tlimitListeners()
238 , d_tlimitPerListeners()
239 , d_rlimitListeners()
240 , d_rlimitPerListeners()
241 {}
242
243 Options::~Options() {
244 delete d_handler;
245 delete d_holder;
246 }
247
248 void Options::copyValues(const Options& options){
249 if(this != &options) {
250 delete d_holder;
251 d_holder = new options::OptionsHolder(*options.d_holder);
252 }
253 }
254
255 std::string Options::formatThreadOptionException(const std::string& option) {
256 std::stringstream ss;
257 ss << "can't understand option `" << option
258 << "': expected something like --threadN=\"--option1 --option2\","
259 << " where N is a nonnegative integer";
260 return ss.str();
261 }
262
263 ListenerCollection::Registration* Options::registerAndNotify(
264 ListenerCollection& collection, Listener* listener, bool notify)
265 {
266 ListenerCollection::Registration* registration =
267 collection.registerListener(listener);
268 if(notify) {
269 listener->notify();
270 }
271 return registration;
272 }
273
274 ListenerCollection::Registration* Options::registerForceLogicListener(
275 Listener* listener, bool notifyIfSet)
276 {
277 bool notify = notifyIfSet && wasSetByUser(options::forceLogicString);
278 return registerAndNotify(d_forceLogicListeners, listener, notify);
279 }
280
281 ListenerCollection::Registration* Options::registerBeforeSearchListener(
282 Listener* listener)
283 {
284 return d_beforeSearchListeners.registerListener(listener);
285 }
286
287 ListenerCollection::Registration* Options::registerTlimitListener(
288 Listener* listener, bool notifyIfSet)
289 {
290 bool notify = notifyIfSet &&
291 wasSetByUser(options::cumulativeMillisecondLimit);
292 return registerAndNotify(d_tlimitListeners, listener, notify);
293 }
294
295 ListenerCollection::Registration* Options::registerTlimitPerListener(
296 Listener* listener, bool notifyIfSet)
297 {
298 bool notify = notifyIfSet && wasSetByUser(options::perCallMillisecondLimit);
299 return registerAndNotify(d_tlimitPerListeners, listener, notify);
300 }
301
302 ListenerCollection::Registration* Options::registerRlimitListener(
303 Listener* listener, bool notifyIfSet)
304 {
305 bool notify = notifyIfSet && wasSetByUser(options::cumulativeResourceLimit);
306 return registerAndNotify(d_rlimitListeners, listener, notify);
307 }
308
309 ListenerCollection::Registration* Options::registerRlimitPerListener(
310 Listener* listener, bool notifyIfSet)
311 {
312 bool notify = notifyIfSet && wasSetByUser(options::perCallResourceLimit);
313 return registerAndNotify(d_rlimitPerListeners, listener, notify);
314 }
315
316 ListenerCollection::Registration* Options::registerUseTheoryListListener(
317 Listener* listener, bool notifyIfSet)
318 {
319 bool notify = notifyIfSet && wasSetByUser(options::useTheoryList);
320 return registerAndNotify(d_useTheoryListListeners, listener, notify);
321 }
322
323 ListenerCollection::Registration* Options::registerSetDefaultExprDepthListener(
324 Listener* listener, bool notifyIfSet)
325 {
326 bool notify = notifyIfSet && wasSetByUser(options::defaultExprDepth);
327 return registerAndNotify(d_setDefaultExprDepthListeners, listener, notify);
328 }
329
330 ListenerCollection::Registration* Options::registerSetDefaultExprDagListener(
331 Listener* listener, bool notifyIfSet)
332 {
333 bool notify = notifyIfSet && wasSetByUser(options::defaultDagThresh);
334 return registerAndNotify(d_setDefaultDagThreshListeners, listener, notify);
335 }
336
337 ListenerCollection::Registration* Options::registerSetPrintExprTypesListener(
338 Listener* listener, bool notifyIfSet)
339 {
340 bool notify = notifyIfSet && wasSetByUser(options::printExprTypes);
341 return registerAndNotify(d_setPrintExprTypesListeners, listener, notify);
342 }
343
344 ListenerCollection::Registration* Options::registerSetDumpModeListener(
345 Listener* listener, bool notifyIfSet)
346 {
347 bool notify = notifyIfSet && wasSetByUser(options::dumpModeString);
348 return registerAndNotify(d_setDumpModeListeners, listener, notify);
349 }
350
351 ListenerCollection::Registration* Options::registerSetPrintSuccessListener(
352 Listener* listener, bool notifyIfSet)
353 {
354 bool notify = notifyIfSet && wasSetByUser(options::printSuccess);
355 return registerAndNotify(d_setPrintSuccessListeners, listener, notify);
356 }
357
358 ListenerCollection::Registration* Options::registerDumpToFileNameListener(
359 Listener* listener, bool notifyIfSet)
360 {
361 bool notify = notifyIfSet && wasSetByUser(options::dumpToFileName);
362 return registerAndNotify(d_dumpToFileListeners, listener, notify);
363 }
364
365 ListenerCollection::Registration*
366 Options::registerSetRegularOutputChannelListener(
367 Listener* listener, bool notifyIfSet)
368 {
369 bool notify = notifyIfSet && wasSetByUser(options::regularChannelName);
370 return registerAndNotify(d_setRegularChannelListeners, listener, notify);
371 }
372
373 ListenerCollection::Registration*
374 Options::registerSetDiagnosticOutputChannelListener(
375 Listener* listener, bool notifyIfSet)
376 {
377 bool notify = notifyIfSet && wasSetByUser(options::diagnosticChannelName);
378 return registerAndNotify(d_setDiagnosticChannelListeners, listener, notify);
379 }
380
381 ListenerCollection::Registration*
382 Options::registerSetReplayLogFilename(
383 Listener* listener, bool notifyIfSet)
384 {
385 bool notify = notifyIfSet && wasSetByUser(options::replayLogFilename);
386 return registerAndNotify(d_setReplayFilenameListeners, listener, notify);
387 }
388
389 ${custom_handlers}$
390
391
392 #ifdef CVC4_DEBUG
393 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT true
394 #else /* CVC4_DEBUG */
395 # define USE_EARLY_TYPE_CHECKING_BY_DEFAULT false
396 #endif /* CVC4_DEBUG */
397
398 #if defined(CVC4_MUZZLED) || defined(CVC4_COMPETITION_MODE)
399 # define DO_SEMANTIC_CHECKS_BY_DEFAULT false
400 #else /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
401 # define DO_SEMANTIC_CHECKS_BY_DEFAULT true
402 #endif /* CVC4_MUZZLED || CVC4_COMPETITION_MODE */
403
404 options::OptionsHolder::OptionsHolder() :
405 ${module_defaults}$
406 {
407 }
408
409
410 static const std::string mostCommonOptionsDescription = "\
411 Most commonly-used CVC4 options:\n"
412 ${help_common}$;
413
414
415 static const std::string optionsDescription = mostCommonOptionsDescription + "\n\
416 \n\
417 Additional CVC4 options:\n"
418 ${help_others}$;
419
420
421 static const std::string optionsFootnote = "\n\
422 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
423 sense of the option.\n\
424 ";
425
426 static const std::string languageDescription = "\
427 Languages currently supported as arguments to the -L / --lang option:\n\
428 auto attempt to automatically determine language\n\
429 cvc4 | presentation | pl CVC4 presentation language\n\
430 smt1 | smtlib1 SMT-LIB format 1.2\n\
431 smt | smtlib | smt2 |\n\
432 smt2.0 | smtlib2 | smtlib2.0 SMT-LIB format 2.0\n\
433 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
434 smt2.6 | smtlib2.6 SMT-LIB format 2.6\n\
435 tptp TPTP format (cnf and fof)\n\
436 sygus SyGuS format\n\
437 \n\
438 Languages currently supported as arguments to the --output-lang option:\n\
439 auto match output language to input language\n\
440 cvc4 | presentation | pl CVC4 presentation language\n\
441 cvc3 CVC3 presentation language\n\
442 smt1 | smtlib1 SMT-LIB format 1.2\n\
443 smt | smtlib | smt2 |\n\
444 smt2.0 | smtlib2.0 | smtlib2 SMT-LIB format 2.0\n\
445 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
446 smt2.6 | smtlib2.6 SMT-LIB format 2.6\n\
447 tptp TPTP format\n\
448 z3str SMT-LIB 2.0 with Z3-str string constraints\n\
449 ast internal format (simple syntax trees)\n\
450 ";
451
452 std::string Options::getDescription() const {
453 return optionsDescription;
454 }
455
456 void Options::printUsage(const std::string msg, std::ostream& out) {
457 out << msg << optionsDescription << std::endl
458 << optionsFootnote << std::endl << std::flush;
459 }
460
461 void Options::printShortUsage(const std::string msg, std::ostream& out) {
462 out << msg << mostCommonOptionsDescription << std::endl
463 << optionsFootnote << std::endl
464 << "For full usage, please use --help."
465 << std::endl << std::endl << std::flush;
466 }
467
468 void Options::printLanguageHelp(std::ostream& out) {
469 out << languageDescription << std::flush;
470 }
471
472 /**
473 * This is a table of long options. By policy, each short option
474 * should have an equivalent long option (but the reverse isn't the
475 * case), so this table should thus contain all command-line options.
476 *
477 * Each option in this array has four elements:
478 *
479 * 1. the long option string
480 * 2. argument behavior for the option:
481 * no_argument - no argument permitted
482 * required_argument - an argument is expected
483 * optional_argument - an argument is permitted but not required
484 * 3. this is a pointer to an int which is set to the 4th entry of the
485 * array if the option is present; or NULL, in which case
486 * getopt_long() returns the 4th entry
487 * 4. the return value for getopt_long() when this long option (or the
488 * value to set the 3rd entry to; see #3)
489 *
490 * If you add something here, you should add it in src/main/usage.h
491 * also, to document it.
492 *
493 * If you add something that has a short option equivalent, you should
494 * add it to the getopt_long() call in parseOptions().
495 */
496 static struct option cmdlineOptions[] = {
497 ${cmdline_options}$
498 { NULL, no_argument, NULL, '\0' }
499 };/* cmdlineOptions */
500
501
502 // static void preemptGetopt(int& argc, char**& argv, const char* opt) {
503
504 // Debug("preemptGetopt") << "preempting getopt() with " << opt << std::endl;
505
506 // AlwaysAssert(opt != NULL && *opt != '\0');
507 // AlwaysAssert(strlen(opt) <= maxoptlen);
508
509 // ++argc;
510 // unsigned i = 1;
511 // while(argv[i] != NULL && argv[i][0] != '\0') {
512 // ++i;
513 // }
514
515 // if(argv[i] == NULL) {
516 // argv = (char**) realloc(argv, (i + 6) * sizeof(char*));
517 // for(unsigned j = i; j < i + 5; ++j) {
518 // argv[j] = (char*) malloc(sizeof(char) * maxoptlen);
519 // argv[j][0] = '\0';
520 // }
521 // argv[i + 5] = NULL;
522 // }
523
524 // strncpy(argv[i], opt, maxoptlen - 1);
525 // argv[i][maxoptlen - 1] = '\0'; // ensure NUL-termination even on overflow
526 // }
527
528 namespace options {
529
530 /** Set a given Options* as "current" just for a particular scope. */
531 class OptionsGuard {
532 Options** d_field;
533 Options* d_old;
534 public:
535 OptionsGuard(Options** field, Options* opts) :
536 d_field(field),
537 d_old(*field) {
538 *field = opts;
539 }
540 ~OptionsGuard() {
541 *d_field = d_old;
542 }
543 };/* class OptionsGuard */
544
545 }/* CVC4::options namespace */
546
547 /**
548 * Parse argc/argv and put the result into a CVC4::Options.
549 * The return value is what's left of the command line (that is, the
550 * non-option arguments).
551 *
552 * Throws OptionException on failures.
553 */
554 std::vector<std::string> Options::parseOptions(Options* options,
555 int argc,
556 char* argv[])
557 {
558 Assert(options != NULL);
559 Assert(argv != NULL);
560
561 options::OptionsGuard guard(&s_current, options);
562
563 const char *progName = argv[0];
564
565 // To debug options parsing, you may prefer to simply uncomment this
566 // and recompile. Debug flags have not been parsed yet so these have
567 // not been set.
568 //DebugChannel.on("options");
569
570 Debug("options") << "Options::parseOptions == " << options << std::endl;
571 Debug("options") << "argv == " << argv << std::endl;
572
573 // Find the base name of the program.
574 const char *x = strrchr(progName, '/');
575 if(x != NULL) {
576 progName = x + 1;
577 }
578 options->d_holder->binary_name = std::string(progName);
579
580 ArgumentExtender* argumentExtender = new ArgumentExtenderImplementation();
581 for(int position = 1; position < argc; position++) {
582 argumentExtender->pushBackArgument(argv[position]);
583 }
584
585 std::vector<std::string> nonoptions;
586 parseOptionsRecursive(options, argumentExtender, &nonoptions);
587 if(Debug.isOn("options")){
588 for(std::vector<std::string>::const_iterator i = nonoptions.begin(),
589 iend = nonoptions.end(); i != iend; ++i){
590 Debug("options") << "nonoptions " << *i << std::endl;
591 }
592 }
593
594 delete argumentExtender;
595 return nonoptions;
596 }
597
598 void Options::parseOptionsRecursive(Options* options,
599 ArgumentExtender* extender,
600 std::vector<std::string>* nonoptions)
601 {
602 int argc;
603 char** argv;
604
605 extender->movePreemptionsToArguments();
606 extender->pushFrontArgument("");
607 extender->getArguments(&argc, &argv);
608
609 if(Debug.isOn("options")) {
610 Debug("options") << "starting a new parseOptionsRecursive with "
611 << argc << " arguments" << std::endl;
612 for( int i = 0; i < argc ; i++ ){
613 Assert(argv[i] != NULL);
614 Debug("options") << " argv[" << i << "] = " << argv[i] << std::endl;
615 }
616 }
617
618 // Having this synonym simplifies the generation code in mkoptions.
619 options::OptionsHandler* handler = options->d_handler;
620 options::OptionsHolder* holder = options->d_holder;
621
622 // Reset getopt(), in the case of multiple calls to parseOptions().
623 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
624 optind = 0;
625 #if HAVE_DECL_OPTRESET
626 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
627 #endif /* HAVE_DECL_OPTRESET */
628
629
630 int main_optind = 0;
631 int old_optind;
632
633
634 while(true) { // Repeat Forever
635
636 if(extender->hasPreemptions()){
637 // Stop this round of parsing. We now parse recursively
638 // to start on a new character array for argv.
639 parseOptionsRecursive(options, extender, nonoptions);
640 break;
641 }
642
643 optopt = 0;
644 std::string option, optionarg;
645
646 optind = main_optind;
647 old_optind = main_optind;
648 //optind_ref = &main_optind;
649 //argv = main_argv;
650
651 // If we encounter an element that is not at zero and does not start
652 // with a "-", this is a non-option. We consume this element as a
653 // non-option.
654 if (main_optind > 0 && main_optind < argc &&
655 argv[main_optind][0] != '-') {
656 Debug("options") << "enqueueing " << argv[main_optind]
657 << " as a non-option." << std::endl;
658 nonoptions->push_back(argv[main_optind]);
659 ++main_optind;
660 extender->popFrontArgument();
661 continue;
662 }
663
664
665 Debug("options") << "[ before, main_optind == " << main_optind << " ]"
666 << std::endl;
667 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
668 Debug("options") << "[ argc == " << argc << ", argv == " << argv << " ]"
669 << std::endl;
670 int c = getopt_long(argc, argv,
671 "+:${options_short}$",
672 cmdlineOptions, NULL);
673
674 while(main_optind < optind) {
675 main_optind++;
676 extender->popFrontArgument();
677 }
678
679 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]"
680 << "[ next option will be at pos: " << optind << " ]"
681 << std::endl;
682
683 // The initial getopt_long call should always determine that argv[0]
684 // is not an option and returns -1. We always manually advance beyond
685 // this element.
686 //
687 // We have to reinitialize optind to 0 instead of 1 as we need to support
688 // changing the argv array passed to getopt.
689 // This is needed as are using GNU extensions.
690 // From: http://man7.org/linux/man-pages/man3/getopt.3.html
691 // A program that scans multiple argument vectors, or rescans the same
692 // vector more than once, and wants to make use of GNU extensions such
693 // as '+' and '-' at the start of optstring, or changes the value of
694 // POSIXLY_CORRECT between scans, must reinitialize getopt() by
695 // resetting optind to 0, rather than the traditional value of 1.
696 // (Resetting to 0 forces the invocation of an internal initialization
697 // routine that rechecks POSIXLY_CORRECT and checks for GNU extensions
698 // in optstring.)
699 if ( old_optind == 0 && c == -1 ) {
700 Assert(main_optind > 0);
701 continue;
702 }
703
704 if ( c == -1 ) {
705 if(Debug.isOn("options")) {
706 Debug("options") << "done with option parsing" << std::endl;
707 for(int index = optind; index < argc; ++index) {
708 Debug("options") << "remaining " << argv[index] << std::endl;
709 }
710 }
711 break;
712 }
713
714 option = argv[old_optind == 0 ? 1 : old_optind];
715 optionarg = (optarg == NULL) ? "" : optarg;
716
717 Debug("preemptGetopt") << "processing option " << c
718 << " (`" << char(c) << "'), " << option << std::endl;
719
720 switch(c) {
721 ${options_handler}$
722
723
724 case ':':
725 // This can be a long or short option, and the way to get at the
726 // name of it is different.
727 throw OptionException(std::string("option `") + option +
728 "' missing its required argument");
729
730 case '?':
731 default:
732 if( ( optopt == 0 ||
733 ( optopt >= ${option_value_begin}$ &&
734 optopt <= ${option_value_end}$ )
735 ) && !strncmp(argv[optind - 1], "--thread", 8) &&
736 strlen(argv[optind - 1]) > 8 )
737 {
738 if(! isdigit(argv[optind - 1][8])) {
739 throw OptionException(formatThreadOptionException(option));
740 }
741 std::vector<std::string>& threadArgv = holder->threadArgv;
742 char *end;
743 long tnum = strtol(argv[optind - 1] + 8, &end, 10);
744 if(tnum < 0 || (*end != '\0' && *end != '=')) {
745 throw OptionException(formatThreadOptionException(option));
746 }
747 if(threadArgv.size() <= size_t(tnum)) {
748 threadArgv.resize(tnum + 1);
749 }
750 if(threadArgv[tnum] != "") {
751 threadArgv[tnum] += " ";
752 }
753 if(*end == '\0') { // e.g., we have --thread0 "foo"
754 if(argc <= optind) {
755 throw OptionException(std::string("option `") + option +
756 "' missing its required argument");
757 }
758 Debug("options") << "thread " << tnum << " gets option "
759 << argv[optind] << std::endl;
760 threadArgv[tnum] += argv[main_optind];
761 main_optind++;
762 } else { // e.g., we have --thread0="foo"
763 if(end[1] == '\0') {
764 throw OptionException(std::string("option `") + option +
765 "' missing its required argument");
766 }
767 Debug("options") << "thread " << tnum << " gets option "
768 << (end + 1) << std::endl;
769 threadArgv[tnum] += end + 1;
770 }
771 Debug("options") << "thread " << tnum << " now has "
772 << threadArgv[tnum] << std::endl;
773 break;
774 }
775
776 throw OptionException(std::string("can't understand option `") + option +
777 "'" + suggestCommandLineOptions(option));
778 }
779 }
780
781 Debug("options") << "got " << nonoptions->size()
782 << " non-option arguments." << std::endl;
783
784 free(argv);
785 }
786
787 std::string Options::suggestCommandLineOptions(const std::string& optionName)
788 {
789 DidYouMean didYouMean;
790
791 const char* opt;
792 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
793 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
794 }
795
796 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
797 }
798
799 static const char* smtOptions[] = {
800 ${options_smt}$
801 NULL
802 };/* smtOptions[] */
803
804 std::vector<std::string> Options::suggestSmtOptions(
805 const std::string& optionName)
806 {
807 std::vector<std::string> suggestions;
808
809 const char* opt;
810 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
811 if(std::strstr(opt, optionName.c_str()) != NULL) {
812 suggestions.push_back(opt);
813 }
814 }
815
816 return suggestions;
817 }
818
819 std::vector<std::vector<std::string> > Options::getOptions() const
820 {
821 std::vector< std::vector<std::string> > opts;
822
823 ${options_getoptions}$
824
825
826 return opts;
827 }
828
829 void Options::setOption(const std::string& key, const std::string& optionarg)
830 {
831 options::OptionsHandler* handler = d_handler;
832 Options *options = Options::current();
833 Trace("options") << "SMT setOption(" << key << ", " << optionarg << ")"
834 << std::endl;
835
836 ${setoption_handlers}$
837
838
839 throw UnrecognizedOptionException(key);
840 }
841
842 std::string Options::getOption(const std::string& key) const
843 {
844 Trace("options") << "SMT getOption(" << key << ")" << std::endl;
845
846 ${getoption_handlers}$
847
848
849 throw UnrecognizedOptionException(key);
850 }
851
852 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
853 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
854
855 } // namespace CVC4