Updated copyright headers.
[cvc5.git] / src / options / options_template.cpp
1 /********************* */
2 /*! \file options_template.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Tim King, Mathias Preiner
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 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 "\
428 Languages currently supported as arguments to the -L / --lang option:\n\
429 auto attempt to automatically determine language\n\
430 cvc4 | presentation | pl CVC4 presentation language\n\
431 smt1 | smtlib1 SMT-LIB format 1.2\n\
432 smt | smtlib | smt2 |\n\
433 smt2.0 | smtlib2 | smtlib2.0 SMT-LIB format 2.0\n\
434 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
435 smt2.6 | smtlib2.6 SMT-LIB format 2.6\n\
436 smt2.6.1 | smtlib2.6.1 SMT-LIB format 2.6 with support for the strings standard\n\
437 tptp TPTP format (cnf and fof)\n\
438 sygus SyGuS format\n\
439 \n\
440 Languages currently supported as arguments to the --output-lang option:\n\
441 auto match output language to input language\n\
442 cvc4 | presentation | pl CVC4 presentation language\n\
443 cvc3 CVC3 presentation language\n\
444 smt | smtlib | smt2 |\n\
445 smt2.0 | smtlib2.0 | smtlib2 SMT-LIB format 2.0\n\
446 smt2.5 | smtlib2.5 SMT-LIB format 2.5\n\
447 smt2.6 | smtlib2.6 SMT-LIB format 2.6\n\
448 smt2.6.1 | smtlib2.6.1 SMT-LIB format 2.6 with support for the strings standard\n\
449 tptp TPTP format\n\
450 z3str SMT-LIB 2.0 with Z3-str string constraints\n\
451 ast internal format (simple syntax trees)\n\
452 ";
453
454 std::string Options::getDescription() const {
455 return optionsDescription;
456 }
457
458 void Options::printUsage(const std::string msg, std::ostream& out) {
459 out << msg << optionsDescription << std::endl
460 << optionsFootnote << std::endl << std::flush;
461 }
462
463 void Options::printShortUsage(const std::string msg, std::ostream& out) {
464 out << msg << mostCommonOptionsDescription << std::endl
465 << optionsFootnote << std::endl
466 << "For full usage, please use --help."
467 << std::endl << std::endl << std::flush;
468 }
469
470 void Options::printLanguageHelp(std::ostream& out) {
471 out << languageDescription << std::flush;
472 }
473
474 /**
475 * This is a table of long options. By policy, each short option
476 * should have an equivalent long option (but the reverse isn't the
477 * case), so this table should thus contain all command-line options.
478 *
479 * Each option in this array has four elements:
480 *
481 * 1. the long option string
482 * 2. argument behavior for the option:
483 * no_argument - no argument permitted
484 * required_argument - an argument is expected
485 * optional_argument - an argument is permitted but not required
486 * 3. this is a pointer to an int which is set to the 4th entry of the
487 * array if the option is present; or NULL, in which case
488 * getopt_long() returns the 4th entry
489 * 4. the return value for getopt_long() when this long option (or the
490 * value to set the 3rd entry to; see #3)
491 *
492 * If you add something here, you should add it in src/main/usage.h
493 * also, to document it.
494 *
495 * If you add something that has a short option equivalent, you should
496 * add it to the getopt_long() call in parseOptions().
497 */
498 static struct option cmdlineOptions[] = {
499 ${cmdline_options}$
500 { NULL, no_argument, NULL, '\0' }
501 };/* cmdlineOptions */
502
503
504 // static void preemptGetopt(int& argc, char**& argv, const char* opt) {
505
506 // Debug("preemptGetopt") << "preempting getopt() with " << opt << std::endl;
507
508 // AlwaysAssert(opt != NULL && *opt != '\0');
509 // AlwaysAssert(strlen(opt) <= maxoptlen);
510
511 // ++argc;
512 // unsigned i = 1;
513 // while(argv[i] != NULL && argv[i][0] != '\0') {
514 // ++i;
515 // }
516
517 // if(argv[i] == NULL) {
518 // argv = (char**) realloc(argv, (i + 6) * sizeof(char*));
519 // for(unsigned j = i; j < i + 5; ++j) {
520 // argv[j] = (char*) malloc(sizeof(char) * maxoptlen);
521 // argv[j][0] = '\0';
522 // }
523 // argv[i + 5] = NULL;
524 // }
525
526 // strncpy(argv[i], opt, maxoptlen - 1);
527 // argv[i][maxoptlen - 1] = '\0'; // ensure NUL-termination even on overflow
528 // }
529
530 namespace options {
531
532 /** Set a given Options* as "current" just for a particular scope. */
533 class OptionsGuard {
534 Options** d_field;
535 Options* d_old;
536 public:
537 OptionsGuard(Options** field, Options* opts) :
538 d_field(field),
539 d_old(*field) {
540 *field = opts;
541 }
542 ~OptionsGuard() {
543 *d_field = d_old;
544 }
545 };/* class OptionsGuard */
546
547 }/* CVC4::options namespace */
548
549 /**
550 * Parse argc/argv and put the result into a CVC4::Options.
551 * The return value is what's left of the command line (that is, the
552 * non-option arguments).
553 *
554 * Throws OptionException on failures.
555 */
556 std::vector<std::string> Options::parseOptions(Options* options,
557 int argc,
558 char* argv[])
559 {
560 Assert(options != NULL);
561 Assert(argv != NULL);
562
563 options::OptionsGuard guard(&s_current, options);
564
565 const char *progName = argv[0];
566
567 // To debug options parsing, you may prefer to simply uncomment this
568 // and recompile. Debug flags have not been parsed yet so these have
569 // not been set.
570 //DebugChannel.on("options");
571
572 Debug("options") << "Options::parseOptions == " << options << std::endl;
573 Debug("options") << "argv == " << argv << std::endl;
574
575 // Find the base name of the program.
576 const char *x = strrchr(progName, '/');
577 if(x != NULL) {
578 progName = x + 1;
579 }
580 options->d_holder->binary_name = std::string(progName);
581
582 ArgumentExtender* argumentExtender = new ArgumentExtenderImplementation();
583 for(int position = 1; position < argc; position++) {
584 argumentExtender->pushBackArgument(argv[position]);
585 }
586
587 std::vector<std::string> nonoptions;
588 parseOptionsRecursive(options, argumentExtender, &nonoptions);
589 if(Debug.isOn("options")){
590 for(std::vector<std::string>::const_iterator i = nonoptions.begin(),
591 iend = nonoptions.end(); i != iend; ++i){
592 Debug("options") << "nonoptions " << *i << std::endl;
593 }
594 }
595
596 delete argumentExtender;
597 return nonoptions;
598 }
599
600 void Options::parseOptionsRecursive(Options* options,
601 ArgumentExtender* extender,
602 std::vector<std::string>* nonoptions)
603 {
604 int argc;
605 char** argv;
606
607 extender->movePreemptionsToArguments();
608 extender->pushFrontArgument("");
609 extender->getArguments(&argc, &argv);
610
611 if(Debug.isOn("options")) {
612 Debug("options") << "starting a new parseOptionsRecursive with "
613 << argc << " arguments" << std::endl;
614 for( int i = 0; i < argc ; i++ ){
615 Assert(argv[i] != NULL);
616 Debug("options") << " argv[" << i << "] = " << argv[i] << std::endl;
617 }
618 }
619
620 // Having this synonym simplifies the generation code in mkoptions.
621 options::OptionsHandler* handler = options->d_handler;
622 options::OptionsHolder* holder = options->d_holder;
623
624 // Reset getopt(), in the case of multiple calls to parseOptions().
625 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
626 optind = 0;
627 #if HAVE_DECL_OPTRESET
628 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
629 #endif /* HAVE_DECL_OPTRESET */
630
631
632 int main_optind = 0;
633 int old_optind;
634
635
636 while(true) { // Repeat Forever
637
638 if(extender->hasPreemptions()){
639 // Stop this round of parsing. We now parse recursively
640 // to start on a new character array for argv.
641 parseOptionsRecursive(options, extender, nonoptions);
642 break;
643 }
644
645 optopt = 0;
646 std::string option, optionarg;
647
648 optind = main_optind;
649 old_optind = main_optind;
650 //optind_ref = &main_optind;
651 //argv = main_argv;
652
653 // If we encounter an element that is not at zero and does not start
654 // with a "-", this is a non-option. We consume this element as a
655 // non-option.
656 if (main_optind > 0 && main_optind < argc &&
657 argv[main_optind][0] != '-') {
658 Debug("options") << "enqueueing " << argv[main_optind]
659 << " as a non-option." << std::endl;
660 nonoptions->push_back(argv[main_optind]);
661 ++main_optind;
662 extender->popFrontArgument();
663 continue;
664 }
665
666
667 Debug("options") << "[ before, main_optind == " << main_optind << " ]"
668 << std::endl;
669 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
670 Debug("options") << "[ argc == " << argc << ", argv == " << argv << " ]"
671 << std::endl;
672 int c = getopt_long(argc, argv,
673 "+:${options_short}$",
674 cmdlineOptions, NULL);
675
676 while(main_optind < optind) {
677 main_optind++;
678 extender->popFrontArgument();
679 }
680
681 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]"
682 << "[ next option will be at pos: " << optind << " ]"
683 << std::endl;
684
685 // The initial getopt_long call should always determine that argv[0]
686 // is not an option and returns -1. We always manually advance beyond
687 // this element.
688 //
689 // We have to reinitialize optind to 0 instead of 1 as we need to support
690 // changing the argv array passed to getopt.
691 // This is needed as are using GNU extensions.
692 // From: http://man7.org/linux/man-pages/man3/getopt.3.html
693 // A program that scans multiple argument vectors, or rescans the same
694 // vector more than once, and wants to make use of GNU extensions such
695 // as '+' and '-' at the start of optstring, or changes the value of
696 // POSIXLY_CORRECT between scans, must reinitialize getopt() by
697 // resetting optind to 0, rather than the traditional value of 1.
698 // (Resetting to 0 forces the invocation of an internal initialization
699 // routine that rechecks POSIXLY_CORRECT and checks for GNU extensions
700 // in optstring.)
701 if ( old_optind == 0 && c == -1 ) {
702 Assert(main_optind > 0);
703 continue;
704 }
705
706 if ( c == -1 ) {
707 if(Debug.isOn("options")) {
708 Debug("options") << "done with option parsing" << std::endl;
709 for(int index = optind; index < argc; ++index) {
710 Debug("options") << "remaining " << argv[index] << std::endl;
711 }
712 }
713 break;
714 }
715
716 option = argv[old_optind == 0 ? 1 : old_optind];
717 optionarg = (optarg == NULL) ? "" : optarg;
718
719 Debug("preemptGetopt") << "processing option " << c
720 << " (`" << char(c) << "'), " << option << std::endl;
721
722 switch(c) {
723 ${options_handler}$
724
725
726 case ':':
727 // This can be a long or short option, and the way to get at the
728 // name of it is different.
729 throw OptionException(std::string("option `") + option +
730 "' missing its required argument");
731
732 case '?':
733 default:
734 if( ( optopt == 0 ||
735 ( optopt >= ${option_value_begin}$ &&
736 optopt <= ${option_value_end}$ )
737 ) && !strncmp(argv[optind - 1], "--thread", 8) &&
738 strlen(argv[optind - 1]) > 8 )
739 {
740 if(! isdigit(argv[optind - 1][8])) {
741 throw OptionException(formatThreadOptionException(option));
742 }
743 std::vector<std::string>& threadArgv = holder->threadArgv;
744 char *end;
745 long tnum = strtol(argv[optind - 1] + 8, &end, 10);
746 if(tnum < 0 || (*end != '\0' && *end != '=')) {
747 throw OptionException(formatThreadOptionException(option));
748 }
749 if(threadArgv.size() <= size_t(tnum)) {
750 threadArgv.resize(tnum + 1);
751 }
752 if(threadArgv[tnum] != "") {
753 threadArgv[tnum] += " ";
754 }
755 if(*end == '\0') { // e.g., we have --thread0 "foo"
756 if(argc <= optind) {
757 throw OptionException(std::string("option `") + option +
758 "' missing its required argument");
759 }
760 Debug("options") << "thread " << tnum << " gets option "
761 << argv[optind] << std::endl;
762 threadArgv[tnum] += argv[main_optind];
763 main_optind++;
764 } else { // e.g., we have --thread0="foo"
765 if(end[1] == '\0') {
766 throw OptionException(std::string("option `") + option +
767 "' missing its required argument");
768 }
769 Debug("options") << "thread " << tnum << " gets option "
770 << (end + 1) << std::endl;
771 threadArgv[tnum] += end + 1;
772 }
773 Debug("options") << "thread " << tnum << " now has "
774 << threadArgv[tnum] << std::endl;
775 break;
776 }
777
778 throw OptionException(std::string("can't understand option `") + option +
779 "'" + suggestCommandLineOptions(option));
780 }
781 }
782
783 Debug("options") << "got " << nonoptions->size()
784 << " non-option arguments." << std::endl;
785
786 free(argv);
787 }
788
789 std::string Options::suggestCommandLineOptions(const std::string& optionName)
790 {
791 DidYouMean didYouMean;
792
793 const char* opt;
794 for(size_t i = 0; (opt = cmdlineOptions[i].name) != NULL; ++i) {
795 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
796 }
797
798 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
799 }
800
801 static const char* smtOptions[] = {
802 ${options_smt}$
803 NULL
804 };/* smtOptions[] */
805
806 std::vector<std::string> Options::suggestSmtOptions(
807 const std::string& optionName)
808 {
809 std::vector<std::string> suggestions;
810
811 const char* opt;
812 for(size_t i = 0; (opt = smtOptions[i]) != NULL; ++i) {
813 if(std::strstr(opt, optionName.c_str()) != NULL) {
814 suggestions.push_back(opt);
815 }
816 }
817
818 return suggestions;
819 }
820
821 std::vector<std::vector<std::string> > Options::getOptions() const
822 {
823 std::vector< std::vector<std::string> > opts;
824
825 ${options_getoptions}$
826
827
828 return opts;
829 }
830
831 void Options::setOption(const std::string& key, const std::string& optionarg)
832 {
833 options::OptionsHandler* handler = d_handler;
834 Options *options = Options::current();
835 Trace("options") << "SMT setOption(" << key << ", " << optionarg << ")"
836 << std::endl;
837
838 ${setoption_handlers}$
839
840
841 throw UnrecognizedOptionException(key);
842 }
843
844 std::string Options::getOption(const std::string& key) const
845 {
846 Trace("options") << "SMT getOption(" << key << ")" << std::endl;
847
848 ${getoption_handlers}$
849
850
851 throw UnrecognizedOptionException(key);
852 }
853
854 #undef USE_EARLY_TYPE_CHECKING_BY_DEFAULT
855 #undef DO_SEMANTIC_CHECKS_BY_DEFAULT
856
857 } // namespace CVC4