26e11a6701f34fb2dc3291d97509a9ba3ad3dd5d
[cvc5.git] / src / options / options_template.cpp
1 /******************************************************************************
2 * Top contributors (to current version):
3 * Morgan Deters, Tim King, Andrew Reynolds
4 *
5 * This file is part of the cvc5 project.
6 *
7 * Copyright (c) 2009-2021 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.
11 * ****************************************************************************
12 *
13 * Contains code for handling command-line options.
14 */
15
16 #if !defined(_BSD_SOURCE) && defined(__MINGW32__) && !defined(__MINGW64__)
17 // force use of optreset; mingw32 croaks on argv-switching otherwise
18 #include "base/cvc5config.h"
19 #define _BSD_SOURCE
20 #undef HAVE_DECL_OPTRESET
21 #define HAVE_DECL_OPTRESET 1
22 #define CVC5_IS_NOT_REALLY_BSD
23 #endif /* !_BSD_SOURCE && __MINGW32__ && !__MINGW64__ */
24
25 #ifdef __MINGW64__
26 extern int optreset;
27 #endif /* __MINGW64__ */
28
29 #include <getopt.h>
30
31 // clean up
32 #ifdef CVC5_IS_NOT_REALLY_BSD
33 # undef _BSD_SOURCE
34 #endif /* CVC5_IS_NOT_REALLY_BSD */
35
36 #include <unistd.h>
37 #include <string.h>
38 #include <time.h>
39
40 #include <cstdio>
41 #include <cstdlib>
42 #include <cstring>
43 #include <iomanip>
44 #include <new>
45 #include <string>
46 #include <sstream>
47 #include <limits>
48
49 #include "base/check.h"
50 #include "base/exception.h"
51 #include "base/output.h"
52 #include "options/didyoumean.h"
53 #include "options/language.h"
54 #include "options/options_handler.h"
55 #include "options/options_listener.h"
56
57 // clang-format off
58 ${headers_module}$
59
60 #include "base/cvc5config.h"
61 #include "options/base_handlers.h"
62
63 ${headers_handler}$
64
65 using namespace cvc5;
66 using namespace cvc5::options;
67 // clang-format on
68
69 namespace cvc5 {
70
71 thread_local Options* Options::s_current = NULL;
72
73 /**
74 * This is a default handler for options of built-in C++ type. This
75 * template is really just a helper for the handleOption() template,
76 * below. Variants of this template handle numeric and non-numeric,
77 * integral and non-integral, signed and unsigned C++ types.
78 * handleOption() makes sure to instantiate the right one.
79 *
80 * This implements default behavior when e.g. an option is
81 * unsigned but the user specifies a negative argument; etc.
82 */
83 template <class T, bool is_numeric, bool is_integer>
84 struct OptionHandler {
85 static T handle(std::string option, std::string optionarg);
86 };/* struct OptionHandler<> */
87
88 /** Variant for integral C++ types */
89 template <class T>
90 struct OptionHandler<T, true, true> {
91 static bool stringToInt(T& t, const std::string& str) {
92 std::istringstream ss(str);
93 ss >> t;
94 char tmp;
95 return !(ss.fail() || ss.get(tmp));
96 }
97
98 static bool containsMinus(const std::string& str) {
99 return str.find('-') != std::string::npos;
100 }
101
102 static T handle(const std::string& option, const std::string& optionarg) {
103 try {
104 T i;
105 bool success = stringToInt(i, optionarg);
106
107 if(!success){
108 throw OptionException(option + ": failed to parse "+ optionarg +
109 " as an integer of the appropriate type.");
110 }
111
112 // Depending in the platform unsigned numbers with '-' signs may parse.
113 // Reject these by looking for any minus if it is not signed.
114 if( (! std::numeric_limits<T>::is_signed) && containsMinus(optionarg) ) {
115 // unsigned type but user gave negative argument
116 throw OptionException(option + " requires a nonnegative argument");
117 } else if(i < std::numeric_limits<T>::min()) {
118 // negative overflow for type
119 std::stringstream ss;
120 ss << option << " requires an argument >= "
121 << std::numeric_limits<T>::min();
122 throw OptionException(ss.str());
123 } else if(i > std::numeric_limits<T>::max()) {
124 // positive overflow for type
125 std::stringstream ss;
126 ss << option << " requires an argument <= "
127 << std::numeric_limits<T>::max();
128 throw OptionException(ss.str());
129 }
130
131 return i;
132
133 // if(std::numeric_limits<T>::is_signed) {
134 // return T(i.getLong());
135 // } else {
136 // return T(i.getUnsignedLong());
137 // }
138 } catch(std::invalid_argument&) {
139 // user gave something other than an integer
140 throw OptionException(option + " requires an integer argument");
141 }
142 }
143 };/* struct OptionHandler<T, true, true> */
144
145 /** Variant for numeric but non-integral C++ types */
146 template <class T>
147 struct OptionHandler<T, true, false> {
148 static T handle(std::string option, std::string optionarg) {
149 std::stringstream in(optionarg);
150 long double r;
151 in >> r;
152 if(! in.eof()) {
153 // we didn't consume the whole string (junk at end)
154 throw OptionException(option + " requires a numeric argument");
155 }
156
157 if(! std::numeric_limits<T>::is_signed && r < 0.0) {
158 // unsigned type but user gave negative value
159 throw OptionException(option + " requires a nonnegative argument");
160 } else if(r < -std::numeric_limits<T>::max()) {
161 // negative overflow for type
162 std::stringstream ss;
163 ss << option << " requires an argument >= "
164 << -std::numeric_limits<T>::max();
165 throw OptionException(ss.str());
166 } else if(r > std::numeric_limits<T>::max()) {
167 // positive overflow for type
168 std::stringstream ss;
169 ss << option << " requires an argument <= "
170 << std::numeric_limits<T>::max();
171 throw OptionException(ss.str());
172 }
173
174 return T(r);
175 }
176 };/* struct OptionHandler<T, true, false> */
177
178 /** Variant for non-numeric C++ types */
179 template <class T>
180 struct OptionHandler<T, false, false> {
181 static T handle(std::string option, std::string optionarg) {
182 T::unsupported_handleOption_call___please_write_me;
183 // The above line causes a compiler error if this version of the template
184 // is ever instantiated (meaning that a specialization is missing). So
185 // don't worry about the segfault in the next line, the "return" is only
186 // there to keep the compiler from giving additional, distracting errors
187 // and warnings.
188 return *(T*)0;
189 }
190 };/* struct OptionHandler<T, false, false> */
191
192 /** Handle an option of type T in the default way. */
193 template <class T>
194 T handleOption(std::string option, std::string optionarg) {
195 return OptionHandler<T, std::numeric_limits<T>::is_specialized, std::numeric_limits<T>::is_integer>::handle(option, optionarg);
196 }
197
198 /** Handle an option of type std::string in the default way. */
199 template <>
200 std::string handleOption<std::string>(std::string option, std::string optionarg) {
201 return optionarg;
202 }
203
204 /**
205 * Run handler, and any user-given predicates, for option T.
206 * If a user specifies a :handler or :predicates, it overrides this.
207 */
208 template <class T>
209 typename T::type runHandlerAndPredicates(T, std::string option, std::string optionarg, options::OptionsHandler* handler) {
210 // By default, parse the option argument in a way appropriate for its type.
211 // E.g., for "unsigned int" options, ensure that the provided argument is
212 // a nonnegative integer that fits in the unsigned int type.
213
214 return handleOption<typename T::type>(option, optionarg);
215 }
216
217 template <class T>
218 void runBoolPredicates(T, std::string option, bool b, options::OptionsHandler* handler) {
219 // By default, nothing to do for bool. Users add things with
220 // :predicate in options files to provide custom checking routines
221 // that can throw exceptions.
222 }
223
224 Options::Options(OptionsListener* ol)
225 : d_handler(new options::OptionsHandler(this)),
226 // clang-format off
227 ${holder_mem_inits}$
228 ${holder_ref_inits}$
229 // clang-format on
230 d_olisten(ol)
231 {}
232
233 Options::~Options() {
234 delete d_handler;
235 }
236
237 void Options::copyValues(const Options& options){
238 if(this != &options) {
239 // clang-format off
240 ${holder_mem_copy}$
241 // clang-format on
242 }
243 }
244
245 std::string Options::formatThreadOptionException(const std::string& option) {
246 std::stringstream ss;
247 ss << "can't understand option `" << option
248 << "': expected something like --threadN=\"--option1 --option2\","
249 << " where N is a nonnegative integer";
250 return ss.str();
251 }
252
253 void Options::setListener(OptionsListener* ol) { d_olisten = ol; }
254
255 // clang-format off
256 ${custom_handlers}$
257 // clang-format on
258
259 static const std::string mostCommonOptionsDescription =
260 "\
261 Most commonly-used cvc5 options:\n"
262 // clang-format off
263 ${help_common}$
264 // clang-format on
265 ;
266
267 // clang-format off
268 static const std::string optionsDescription =
269 mostCommonOptionsDescription + "\n\nAdditional cvc5 options:\n"
270 ${help_others}$;
271 // clang-format on
272
273 static const std::string optionsFootnote = "\n\
274 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
275 sense of the option.\n\
276 ";
277
278 static const std::string languageDescription =
279 "\
280 Languages currently supported as arguments to the -L / --lang option:\n\
281 auto attempt to automatically determine language\n\
282 cvc | presentation | pl CVC presentation language\n\
283 smt | smtlib | smt2 |\n\
284 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
285 tptp TPTP format (cnf, fof and tff)\n\
286 sygus | sygus2 SyGuS version 2.0\n\
287 \n\
288 Languages currently supported as arguments to the --output-lang option:\n\
289 auto match output language to input language\n\
290 cvc | presentation | pl CVC presentation language\n\
291 smt | smtlib | smt2 |\n\
292 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
293 tptp TPTP format\n\
294 ast internal format (simple syntax trees)\n\
295 ";
296
297 std::string Options::getDescription() const {
298 return optionsDescription;
299 }
300
301 void Options::printUsage(const std::string msg, std::ostream& out) {
302 out << msg << optionsDescription << std::endl
303 << optionsFootnote << std::endl << std::flush;
304 }
305
306 void Options::printShortUsage(const std::string msg, std::ostream& out) {
307 out << msg << mostCommonOptionsDescription << std::endl
308 << optionsFootnote << std::endl
309 << "For full usage, please use --help."
310 << std::endl << std::endl << std::flush;
311 }
312
313 void Options::printLanguageHelp(std::ostream& out) {
314 out << languageDescription << std::flush;
315 }
316
317 /**
318 * This is a table of long options. By policy, each short option
319 * should have an equivalent long option (but the reverse isn't the
320 * case), so this table should thus contain all command-line options.
321 *
322 * Each option in this array has four elements:
323 *
324 * 1. the long option string
325 * 2. argument behavior for the option:
326 * no_argument - no argument permitted
327 * required_argument - an argument is expected
328 * optional_argument - an argument is permitted but not required
329 * 3. this is a pointer to an int which is set to the 4th entry of the
330 * array if the option is present; or NULL, in which case
331 * getopt_long() returns the 4th entry
332 * 4. the return value for getopt_long() when this long option (or the
333 * value to set the 3rd entry to; see #3)
334 *
335 * If you add something here, you should add it in src/main/usage.h
336 * also, to document it.
337 *
338 * If you add something that has a short option equivalent, you should
339 * add it to the getopt_long() call in parseOptions().
340 */
341 // clang-format off
342 static struct option cmdlineOptions[] = {
343 ${cmdline_options}$
344 {nullptr, no_argument, nullptr, '\0'}};
345 // clang-format on
346
347 namespace options {
348
349 /** Set a given Options* as "current" just for a particular scope. */
350 class OptionsGuard {
351 Options** d_field;
352 Options* d_old;
353 public:
354 OptionsGuard(Options** field, Options* opts) :
355 d_field(field),
356 d_old(*field) {
357 *field = opts;
358 }
359 ~OptionsGuard() {
360 *d_field = d_old;
361 }
362 };/* class OptionsGuard */
363
364 } // namespace options
365
366 /**
367 * Parse argc/argv and put the result into a cvc5::Options.
368 * The return value is what's left of the command line (that is, the
369 * non-option arguments).
370 *
371 * Throws OptionException on failures.
372 */
373 std::vector<std::string> Options::parseOptions(Options* options,
374 int argc,
375 char* argv[])
376 {
377 Assert(options != NULL);
378 Assert(argv != NULL);
379
380 options::OptionsGuard guard(&s_current, options);
381
382 const char *progName = argv[0];
383
384 // To debug options parsing, you may prefer to simply uncomment this
385 // and recompile. Debug flags have not been parsed yet so these have
386 // not been set.
387 //DebugChannel.on("options");
388
389 Debug("options") << "Options::parseOptions == " << options << std::endl;
390 Debug("options") << "argv == " << argv << std::endl;
391
392 // Find the base name of the program.
393 const char *x = strrchr(progName, '/');
394 if(x != NULL) {
395 progName = x + 1;
396 }
397 options->base.binary_name = std::string(progName);
398
399 std::vector<std::string> nonoptions;
400 options->parseOptionsRecursive(argc, argv, &nonoptions);
401 if(Debug.isOn("options")){
402 for(std::vector<std::string>::const_iterator i = nonoptions.begin(),
403 iend = nonoptions.end(); i != iend; ++i){
404 Debug("options") << "nonoptions " << *i << std::endl;
405 }
406 }
407
408 return nonoptions;
409 }
410
411 std::string suggestCommandLineOptions(const std::string& optionName)
412 {
413 DidYouMean didYouMean;
414
415 const char* opt;
416 for(size_t i = 0; (opt = cmdlineOptions[i].name) != nullptr; ++i) {
417 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
418 }
419
420 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
421 }
422
423 void Options::parseOptionsRecursive(int argc,
424 char* argv[],
425 std::vector<std::string>* nonoptions)
426 {
427
428 if(Debug.isOn("options")) {
429 Debug("options") << "starting a new parseOptionsRecursive with "
430 << argc << " arguments" << std::endl;
431 for( int i = 0; i < argc ; i++ ){
432 Assert(argv[i] != NULL);
433 Debug("options") << " argv[" << i << "] = " << argv[i] << std::endl;
434 }
435 }
436
437 // Reset getopt(), in the case of multiple calls to parseOptions().
438 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
439 optind = 0;
440 #if HAVE_DECL_OPTRESET
441 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
442 #endif /* HAVE_DECL_OPTRESET */
443
444 // We must parse the binary name, which is manually ignored below. Setting
445 // this to 1 leads to incorrect behavior on some platforms.
446 int main_optind = 0;
447 int old_optind;
448
449
450 while(true) { // Repeat Forever
451
452 optopt = 0;
453 std::string option, optionarg;
454
455 optind = main_optind;
456 old_optind = main_optind;
457
458 // If we encounter an element that is not at zero and does not start
459 // with a "-", this is a non-option. We consume this element as a
460 // non-option.
461 if (main_optind > 0 && main_optind < argc &&
462 argv[main_optind][0] != '-') {
463 Debug("options") << "enqueueing " << argv[main_optind]
464 << " as a non-option." << std::endl;
465 nonoptions->push_back(argv[main_optind]);
466 ++main_optind;
467 continue;
468 }
469
470
471 Debug("options") << "[ before, main_optind == " << main_optind << " ]"
472 << std::endl;
473 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
474 Debug("options") << "[ argc == " << argc << ", argv == " << argv << " ]"
475 << std::endl;
476 // clang-format off
477 int c = getopt_long(argc, argv,
478 "+:${options_short}$",
479 cmdlineOptions, NULL);
480 // clang-format on
481
482 main_optind = optind;
483
484 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]"
485 << "[ next option will be at pos: " << optind << " ]"
486 << std::endl;
487
488 // The initial getopt_long call should always determine that argv[0]
489 // is not an option and returns -1. We always manually advance beyond
490 // this element.
491 if ( old_optind == 0 && c == -1 ) {
492 Assert(main_optind > 0);
493 continue;
494 }
495
496 if ( c == -1 ) {
497 if(Debug.isOn("options")) {
498 Debug("options") << "done with option parsing" << std::endl;
499 for(int index = optind; index < argc; ++index) {
500 Debug("options") << "remaining " << argv[index] << std::endl;
501 }
502 }
503 break;
504 }
505
506 option = argv[old_optind == 0 ? 1 : old_optind];
507 optionarg = (optarg == NULL) ? "" : optarg;
508
509 Debug("preemptGetopt") << "processing option " << c
510 << " (`" << char(c) << "'), " << option << std::endl;
511
512 // clang-format off
513 switch(c)
514 {
515 ${options_handler}$
516
517 case ':' :
518 // This can be a long or short option, and the way to get at the
519 // name of it is different.
520 throw OptionException(std::string("option `") + option
521 + "' missing its required argument");
522
523 case '?':
524 default:
525 throw OptionException(std::string("can't understand option `") + option
526 + "'" + suggestCommandLineOptions(option));
527 }
528 }
529 // clang-format on
530
531 Debug("options") << "got " << nonoptions->size()
532 << " non-option arguments." << std::endl;
533 }
534
535 // clang-format off
536 std::vector<std::vector<std::string> > Options::getOptions() const
537 {
538 std::vector< std::vector<std::string> > opts;
539
540 ${options_getoptions}$
541
542 return opts;
543 }
544 // clang-format on
545
546 void Options::setOption(const std::string& key, const std::string& optionarg)
547 {
548 Trace("options") << "setOption(" << key << ", " << optionarg << ")"
549 << std::endl;
550 // first update this object
551 setOptionInternal(key, optionarg);
552 // then, notify the provided listener
553 if (d_olisten != nullptr)
554 {
555 d_olisten->notifySetOption(key);
556 }
557 }
558
559 // clang-format off
560 void Options::setOptionInternal(const std::string& key,
561 const std::string& optionarg)
562 {
563 options::OptionsHandler* handler = d_handler;
564 ${setoption_handlers}$
565 throw UnrecognizedOptionException(key);
566 }
567 // clang-format on
568
569 // clang-format off
570 std::string Options::getOption(const std::string& key) const
571 {
572 Trace("options") << "Options::getOption(" << key << ")" << std::endl;
573 ${getoption_handlers}$
574
575 throw UnrecognizedOptionException(key);
576 }
577 // clang-format on
578
579 } // namespace cvc5
580