9419e9914abf147d2246369a0f6221f52a5e232d
[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 // clang-format on
229 d_olisten(ol)
230 {}
231
232 Options::~Options() {
233 delete d_handler;
234 }
235
236 void Options::copyValues(const Options& options){
237 if(this != &options) {
238 // clang-format off
239 ${holder_mem_copy}$
240 // clang-format on
241 }
242 }
243
244 ${holder_getter_impl}$
245
246 std::string Options::formatThreadOptionException(const std::string& option) {
247 std::stringstream ss;
248 ss << "can't understand option `" << option
249 << "': expected something like --threadN=\"--option1 --option2\","
250 << " where N is a nonnegative integer";
251 return ss.str();
252 }
253
254 void Options::setListener(OptionsListener* ol) { d_olisten = ol; }
255
256 // clang-format off
257 ${custom_handlers}$
258 // clang-format on
259
260 static const std::string mostCommonOptionsDescription =
261 "\
262 Most commonly-used cvc5 options:\n"
263 // clang-format off
264 ${help_common}$
265 // clang-format on
266 ;
267
268 // clang-format off
269 static const std::string optionsDescription =
270 mostCommonOptionsDescription + "\n\nAdditional cvc5 options:\n"
271 ${help_others}$;
272 // clang-format on
273
274 static const std::string optionsFootnote = "\n\
275 [*] Each of these options has a --no-OPTIONNAME variant, which reverses the\n\
276 sense of the option.\n\
277 ";
278
279 static const std::string languageDescription =
280 "\
281 Languages currently supported as arguments to the -L / --lang option:\n\
282 auto attempt to automatically determine language\n\
283 cvc | presentation | pl CVC presentation language\n\
284 smt | smtlib | smt2 |\n\
285 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
286 tptp TPTP format (cnf, fof and tff)\n\
287 sygus | sygus2 SyGuS version 2.0\n\
288 \n\
289 Languages currently supported as arguments to the --output-lang option:\n\
290 auto match output language to input language\n\
291 cvc | presentation | pl CVC presentation language\n\
292 smt | smtlib | smt2 |\n\
293 smt2.6 | smtlib2.6 SMT-LIB format 2.6 with support for the strings standard\n\
294 tptp TPTP format\n\
295 ast internal format (simple syntax trees)\n\
296 ";
297
298 std::string Options::getDescription() const {
299 return optionsDescription;
300 }
301
302 void Options::printUsage(const std::string msg, std::ostream& out) {
303 out << msg << optionsDescription << std::endl
304 << optionsFootnote << std::endl << std::flush;
305 }
306
307 void Options::printShortUsage(const std::string msg, std::ostream& out) {
308 out << msg << mostCommonOptionsDescription << std::endl
309 << optionsFootnote << std::endl
310 << "For full usage, please use --help."
311 << std::endl << std::endl << std::flush;
312 }
313
314 void Options::printLanguageHelp(std::ostream& out) {
315 out << languageDescription << std::flush;
316 }
317
318 /**
319 * This is a table of long options. By policy, each short option
320 * should have an equivalent long option (but the reverse isn't the
321 * case), so this table should thus contain all command-line options.
322 *
323 * Each option in this array has four elements:
324 *
325 * 1. the long option string
326 * 2. argument behavior for the option:
327 * no_argument - no argument permitted
328 * required_argument - an argument is expected
329 * optional_argument - an argument is permitted but not required
330 * 3. this is a pointer to an int which is set to the 4th entry of the
331 * array if the option is present; or NULL, in which case
332 * getopt_long() returns the 4th entry
333 * 4. the return value for getopt_long() when this long option (or the
334 * value to set the 3rd entry to; see #3)
335 *
336 * If you add something here, you should add it in src/main/usage.h
337 * also, to document it.
338 *
339 * If you add something that has a short option equivalent, you should
340 * add it to the getopt_long() call in parseOptions().
341 */
342 // clang-format off
343 static struct option cmdlineOptions[] = {
344 ${cmdline_options}$
345 {nullptr, no_argument, nullptr, '\0'}};
346 // clang-format on
347
348 namespace options {
349
350 /** Set a given Options* as "current" just for a particular scope. */
351 class OptionsGuard {
352 Options** d_field;
353 Options* d_old;
354 public:
355 OptionsGuard(Options** field, Options* opts) :
356 d_field(field),
357 d_old(*field) {
358 *field = opts;
359 }
360 ~OptionsGuard() {
361 *d_field = d_old;
362 }
363 };/* class OptionsGuard */
364
365 } // namespace options
366
367 /**
368 * Parse argc/argv and put the result into a cvc5::Options.
369 * The return value is what's left of the command line (that is, the
370 * non-option arguments).
371 *
372 * Throws OptionException on failures.
373 */
374 std::vector<std::string> Options::parseOptions(Options* options,
375 int argc,
376 char* argv[])
377 {
378 Assert(options != NULL);
379 Assert(argv != NULL);
380
381 options::OptionsGuard guard(&s_current, options);
382
383 const char *progName = argv[0];
384
385 // To debug options parsing, you may prefer to simply uncomment this
386 // and recompile. Debug flags have not been parsed yet so these have
387 // not been set.
388 //DebugChannel.on("options");
389
390 Debug("options") << "Options::parseOptions == " << options << std::endl;
391 Debug("options") << "argv == " << argv << std::endl;
392
393 // Find the base name of the program.
394 const char *x = strrchr(progName, '/');
395 if(x != NULL) {
396 progName = x + 1;
397 }
398 options->base().binary_name = std::string(progName);
399
400 std::vector<std::string> nonoptions;
401 options->parseOptionsRecursive(argc, argv, &nonoptions);
402 if(Debug.isOn("options")){
403 for(std::vector<std::string>::const_iterator i = nonoptions.begin(),
404 iend = nonoptions.end(); i != iend; ++i){
405 Debug("options") << "nonoptions " << *i << std::endl;
406 }
407 }
408
409 return nonoptions;
410 }
411
412 std::string suggestCommandLineOptions(const std::string& optionName)
413 {
414 DidYouMean didYouMean;
415
416 const char* opt;
417 for(size_t i = 0; (opt = cmdlineOptions[i].name) != nullptr; ++i) {
418 didYouMean.addWord(std::string("--") + cmdlineOptions[i].name);
419 }
420
421 return didYouMean.getMatchAsString(optionName.substr(0, optionName.find('=')));
422 }
423
424 void Options::parseOptionsRecursive(int argc,
425 char* argv[],
426 std::vector<std::string>* nonoptions)
427 {
428
429 if(Debug.isOn("options")) {
430 Debug("options") << "starting a new parseOptionsRecursive with "
431 << argc << " arguments" << std::endl;
432 for( int i = 0; i < argc ; i++ ){
433 Assert(argv[i] != NULL);
434 Debug("options") << " argv[" << i << "] = " << argv[i] << std::endl;
435 }
436 }
437
438 // Reset getopt(), in the case of multiple calls to parseOptions().
439 // This can be = 1 in newer GNU getopt, but older (< 2007) require = 0.
440 optind = 0;
441 #if HAVE_DECL_OPTRESET
442 optreset = 1; // on BSD getopt() (e.g. Mac OS), might need this
443 #endif /* HAVE_DECL_OPTRESET */
444
445 // We must parse the binary name, which is manually ignored below. Setting
446 // this to 1 leads to incorrect behavior on some platforms.
447 int main_optind = 0;
448 int old_optind;
449
450
451 while(true) { // Repeat Forever
452
453 optopt = 0;
454 std::string option, optionarg;
455
456 optind = main_optind;
457 old_optind = main_optind;
458
459 // If we encounter an element that is not at zero and does not start
460 // with a "-", this is a non-option. We consume this element as a
461 // non-option.
462 if (main_optind > 0 && main_optind < argc &&
463 argv[main_optind][0] != '-') {
464 Debug("options") << "enqueueing " << argv[main_optind]
465 << " as a non-option." << std::endl;
466 nonoptions->push_back(argv[main_optind]);
467 ++main_optind;
468 continue;
469 }
470
471
472 Debug("options") << "[ before, main_optind == " << main_optind << " ]"
473 << std::endl;
474 Debug("options") << "[ before, optind == " << optind << " ]" << std::endl;
475 Debug("options") << "[ argc == " << argc << ", argv == " << argv << " ]"
476 << std::endl;
477 // clang-format off
478 int c = getopt_long(argc, argv,
479 "+:${options_short}$",
480 cmdlineOptions, NULL);
481 // clang-format on
482
483 main_optind = optind;
484
485 Debug("options") << "[ got " << int(c) << " (" << char(c) << ") ]"
486 << "[ next option will be at pos: " << optind << " ]"
487 << std::endl;
488
489 // The initial getopt_long call should always determine that argv[0]
490 // is not an option and returns -1. We always manually advance beyond
491 // this element.
492 if ( old_optind == 0 && c == -1 ) {
493 Assert(main_optind > 0);
494 continue;
495 }
496
497 if ( c == -1 ) {
498 if(Debug.isOn("options")) {
499 Debug("options") << "done with option parsing" << std::endl;
500 for(int index = optind; index < argc; ++index) {
501 Debug("options") << "remaining " << argv[index] << std::endl;
502 }
503 }
504 break;
505 }
506
507 option = argv[old_optind == 0 ? 1 : old_optind];
508 optionarg = (optarg == NULL) ? "" : optarg;
509
510 Debug("preemptGetopt") << "processing option " << c
511 << " (`" << char(c) << "'), " << option << std::endl;
512
513 // clang-format off
514 switch(c)
515 {
516 ${options_handler}$
517
518 case ':' :
519 // This can be a long or short option, and the way to get at the
520 // name of it is different.
521 throw OptionException(std::string("option `") + option
522 + "' missing its required argument");
523
524 case '?':
525 default:
526 throw OptionException(std::string("can't understand option `") + option
527 + "'" + suggestCommandLineOptions(option));
528 }
529 }
530 // clang-format on
531
532 Debug("options") << "got " << nonoptions->size()
533 << " non-option arguments." << std::endl;
534 }
535
536 // clang-format off
537 std::vector<std::vector<std::string> > Options::getOptions() const
538 {
539 std::vector< std::vector<std::string> > opts;
540
541 ${options_getoptions}$
542
543 return opts;
544 }
545 // clang-format on
546
547 void Options::setOption(const std::string& key, const std::string& optionarg)
548 {
549 Trace("options") << "setOption(" << key << ", " << optionarg << ")"
550 << std::endl;
551 // first update this object
552 setOptionInternal(key, optionarg);
553 // then, notify the provided listener
554 if (d_olisten != nullptr)
555 {
556 d_olisten->notifySetOption(key);
557 }
558 }
559
560 // clang-format off
561 void Options::setOptionInternal(const std::string& key,
562 const std::string& optionarg)
563 {
564 options::OptionsHandler* handler = d_handler;
565 ${setoption_handlers}$
566 throw UnrecognizedOptionException(key);
567 }
568 // clang-format on
569
570 // clang-format off
571 std::string Options::getOption(const std::string& key) const
572 {
573 Trace("options") << "Options::getOption(" << key << ")" << std::endl;
574 ${getoption_handlers}$
575
576 throw UnrecognizedOptionException(key);
577 }
578 // clang-format on
579
580 } // namespace cvc5
581