Debian Codegraph @

libpotassco/potassco/program_opts/program_options.h

raw
1 //
2 // Copyright (c) 2004-2017 Benjamin Kaufmann
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to
6 // deal in the Software without restriction, including without limitation the
7 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 // sell copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 // IN THE SOFTWARE.
21 //
22 //
23 // NOTE: ProgramOptions is inspired by Boost.Program_options
24 // see: www.boost.org/libs/program_options
25 //
26 #ifndef PROGRAM_OPTIONS_PROGRAM_OPTIONS_H_INCLUDED
27 #define PROGRAM_OPTIONS_PROGRAM_OPTIONS_H_INCLUDED
28 #include <potassco/program_opts/value.h>
29 #include <potassco/program_opts/detail/refcountable.h>
30 #include <iosfwd>
31 #include <set>
32 #include <map>
33 #include <vector>
34 #include <stdexcept>
35 #include <cstdio>
36 namespace Potassco { namespace ProgramOptions {
37
38 //! Represents one program option.
39 /*!
40 * An Option consists of a description (long name, short name, description),
41 * a (typed) value, and an optional default value.
42 *
43 * \note
44 * When printing an option, occurrences of %D, %I and %A in its description are replaced
45 * with the option's default value, implicit value and the argument name,
46 * respectively.
47 */
48 class Option : public detail::RefCountable {
49 public:
50 /*!
51 * \pre longName != ""
52 * \pre vd != 0
53 * \param longName name (and unique key) of the option
54 * \param shortName possible alias name
55 * \param description description of the option, used for printing help
56 * \param value value object to be associated with this option
57 */
58 Option(const std::string& longName, char shortName,
59 const char* description, Value* value);
60
61 ~Option();
62
63 const std::string& name() const { return name_; }
64 char alias() const { return value_->alias(); }
65 Value* value() const { return value_; }
66 const char* description() const { return description_; }
67 const char* argName() const { return value_->arg(); }
68 bool assignDefault() const;
69 std::size_t maxColumn() const;
70 DescriptionLevel descLevel() const { return value_->level(); }
71 private:
72 std::string name_; // name (and unique key) of option
73 const char* description_; // description of the option (used for --help)
74 Value* value_; // the option's value manager
75 };
76
77 typedef detail::IntrusiveSharedPtr<Option> SharedOptPtr;
78
79 class OptionInitHelper;
80 class OptionContext;
81 class OptionParser;
82 class ParsedValues;
83 class ParsedOptions;
84 class OptionOutput;
85
86 //! A list of options logically grouped under a caption.
87 /*!
88 * The class provides a logical grouping of options that
89 * is mainly useful for printing help.
90 */
91 class OptionGroup {
92 public:
93 typedef std::vector<SharedOptPtr> OptionList;
94 typedef OptionList::const_iterator option_iterator;
95
96 /*!
97 * Creates a new group of options under the given caption.
98 */
99 OptionGroup(const std::string& caption = "", DescriptionLevel descLevel = desc_level_default);
100 ~OptionGroup();
101
102 //! Returns the caption of this group.
103 const std::string& caption() const { return caption_; }
104
105 std::size_t size() const { return options_.size(); }
106 bool empty() const { return options_.empty(); }
107 option_iterator begin() const { return options_.begin(); }
108 option_iterator end() const { return options_.end(); }
109 DescriptionLevel descLevel()const { return level_; }
110
111 //! Returns an object that can be used to add options.
112 /*!
113 * \par usage \n
114 * \code
115 * OptionGroup g("Some Options");
116 * ValueMap m;
117 * g.addOptions()
118 * ("opt1", store<int>(m), "some int value") // <- no semicolon
119 * ("opt2", store<double>(m)) // <- no semicolon
120 * ("opt3", store<char>(m)) // <- no semicolon
121 * ; // <- note the semicolon!
122 * \endcode
123 */
124 OptionInitHelper addOptions();
125
126 //! Adds option to this group.
127 void addOption(const SharedOptPtr& option);
128
129 void setDescriptionLevel(DescriptionLevel level) { level_ = level; }
130
131 //! Creates a formated description of all options with level() <= level in this group.
132 void format(OptionOutput& out, size_t maxW, DescriptionLevel level = desc_level_default) const;
133
134 std::size_t maxColumn(DescriptionLevel level) const;
135 private:
136 friend class OptionContext;
137 std::string caption_;
138 OptionList options_;
139 DescriptionLevel level_;
140 };
141
142 class OptionInitHelper {
143 public:
144 explicit OptionInitHelper(OptionGroup& owner);
145
146 //! Factory function for creating an option.
147 /*!
148 * \param key <name>[!][,<alias>][,@<level>]
149 * \param val Value of the option
150 * \param desc Description of the option
151 *
152 * \note If <name> is followed by an exclamation mark ('!')
153 * the option is marked as negatable.
154 */
155 OptionInitHelper& operator()(const char* key,
156 Value* val, const char* desc);
157 private:
158 OptionGroup* owner_;
159 };
160
161 //! A (logically grouped) list of unique options.
162 /*!
163 * An option context stores a list of option groups.
164 * Options in a context have to be unique (w.r.t name and alias)
165 * within that context.
166 *
167 * An OptionContext defines the granularity of option parsing
168 * and option lookup.
169 */
170 class OptionContext {
171 private:
172 typedef std::size_t key_type;
173 typedef std::map<std::string, key_type> Name2Key;
174 typedef std::vector<OptionGroup> GroupList;
175 typedef Name2Key::const_iterator index_iterator;
176 typedef std::pair<index_iterator, index_iterator> PrefixRange;
177 typedef OptionGroup::OptionList OptionList;
178 public:
179 //! Type for identifying an option within a context
180 typedef OptionList::const_iterator option_iterator;
181 typedef PrefixRange OptionRange;
182
183 OptionContext(const std::string& caption = "", DescriptionLevel desc_default = desc_level_default);
184 ~OptionContext();
185
186 const std::string& caption() const;
187
188 //! Adds the given group of options to this context.
189 /*!
190 * \note If this object already contains a group with
191 * the same caption as group, the groups are merged.
192 *
193 * \throw DuplicateOption if an option in group
194 * has the same short or long name as one of the
195 * options in this context.
196 */
197 OptionContext& add(const OptionGroup& group);
198
199 //! Adds an alias name for the given option.
200 /*!
201 * \throw DuplicateOption if an option with the name aliasName already exists.
202 */
203 OptionContext& addAlias(const std::string& aliasName, option_iterator option);
204
205 //! Adds all groups (and their options) from other to this context.
206 /*!
207 * \throw DuplicateOption if an option in other
208 * has the same short or long name as one of the
209 * options in this context.
210 *
211 * \see OptionContext& add(const OptionGroup&);
212 */
213 OptionContext& add(const OptionContext& other);
214
215 option_iterator begin() const { return options_.begin(); }
216 option_iterator end() const { return options_.end(); }
217
218 //! Returns the number of options in this context.
219 std::size_t size() const { return options_.size(); }
220 //! Returns the number of groups in this context
221 std::size_t groups() const { return groups_.size(); }
222
223 enum FindType { find_name = 1, find_prefix = 2, find_name_or_prefix = find_name|find_prefix, find_alias = 4 };
224
225 //! Returns the option with the given key.
226 /*!
227 * \note The second parameter defines how key is interpreted:
228 * - find_name: search for an option whose name equals key.
229 * - find_prefix: search for an option whose name starts with the given key.
230 * - find_alias: search for an option whose alias equals key.
231 * .
232 *
233 * \note If second parameter is find_alias, a starting '-'
234 * in key is valid but not required.
235 *
236 * \throw UnknownOption if no option matches key.
237 * \throw AmbiguousOption if more than one option matches key.
238 */
239 option_iterator find(const char* key, FindType t = find_name) const;
240 /*!
241 * Behaves like find but returns end() instead of throwing
242 * UnknownOption or AmbiguousOption.
243 */
244 option_iterator tryFind(const char* key, FindType t = find_name) const;
245
246 OptionRange findImpl(const char* key, FindType t, unsigned eMask = unsigned(-1)) const { return findImpl(key, t, eMask, caption()); }
247 OptionRange findImpl(const char* key, FindType t, unsigned eMask, const std::string& eCtx) const;
248
249 const OptionGroup& findGroup(const std::string& caption) const;
250 const OptionGroup* tryFindGroup(const std::string& caption) const;
251
252 //! Sets the description level to be used when generating description.
253 /*!
254 * Once set, functions generating descriptions will only consider groups
255 * and options with description level <= std::min(level, desc_level_all).
256 */
257 void setActiveDescLevel(DescriptionLevel level);
258 DescriptionLevel getActiveDescLevel() const { return descLevel_; }
259
260 //! Writes a formatted description of options in this context.
261 OptionOutput& description(OptionOutput& out) const;
262
263 //! Returns the default command-line of this context.
264 std::string defaults(std::size_t prefixSize = 0) const;
265
266 //! Writes a formatted description of options in this context to os.
267 friend std::ostream& operator<<(std::ostream& os, const OptionContext& ctx);
268
269 //! Assigns any default values to all options not in exclude.
270 /*!
271 * \throw ValueError if some default value is actually invalid for its option.
272 */
273 bool assignDefaults(const ParsedOptions& exclude) const;
274 private:
275 void insertOption(size_t groupId, const SharedOptPtr& o);
276 size_t findGroupKey(const std::string& name) const;
277
278 Name2Key index_;
279 OptionList options_;
280 GroupList groups_;
281 std::string caption_;
282 DescriptionLevel descLevel_;
283 };
284
285 class OptionParser;
286 class ParsedValues;
287
288 //! Set of options holding a parsed value.
289 class ParsedOptions {
290 public:
291 ParsedOptions();
292 ~ParsedOptions();
293 bool empty() const { return parsed_.empty(); }
294 std::size_t size() const { return parsed_.size(); }
295 std::size_t count(const std::string& name) const { return parsed_.count(name); }
296 void add(const std::string& name) { parsed_.insert(name); }
297
298 //! Assigns the parsed values in p to their options.
299 /*!
300 * Parsed values for options that already have a value (and are
301 * not composing) are ignored. On the other hand, parsed values
302 * overwrite any existing default values.
303 *
304 * \param p parsed values to assign
305 *
306 * \throw ValueError if p contains more than one value
307 * for a non-composing option or if p contains a value that is
308 * invalid for its option.
309 */
310 bool assign(const ParsedValues& p, const ParsedOptions* exclude = 0);
311 private:
312 std::set<std::string> parsed_;
313 int assign(const Option& o, const std::string& value);
314 };
315
316 /*!
317 * Container of option-value-pairs representing values found by a parser.
318 */
319 class ParsedValues {
320 public:
321 typedef std::pair<SharedOptPtr, std::string> OptionAndValue;
322 typedef std::vector<OptionAndValue> Values;
323 typedef Values::const_iterator iterator;
324
325 /*!
326 * \param a_ctx The OptionContext for which this object stores raw-values.
327 */
328 explicit ParsedValues(const OptionContext& a_ctx)
329 : ctx(&a_ctx) {}
330 const OptionContext* ctx;
331
332 //! Adds a value for option opt.
333 void add(const std::string& opt, const std::string& value);
334 void add(const SharedOptPtr& opt, const std::string& value) {
335 parsed_.push_back(OptionAndValue(opt, value));
336 }
337
338 iterator begin() const { return parsed_.begin(); }
339 iterator end() const { return parsed_.end(); }
340
341 void clear() { parsed_.clear(); }
342 private:
343 Values parsed_;
344 };
345
346 class ParseContext {
347 public:
348 typedef OptionContext::FindType FindType;
349 virtual ~ParseContext();
350 virtual SharedOptPtr getOption(const char* name, FindType ft) = 0;
351 virtual SharedOptPtr getOption(int posKey, const char* tok) = 0;
352 virtual void addValue(const SharedOptPtr& key, const std::string& value) = 0;
353 };
354
355 //! Base class for options parsers.
356 class OptionParser {
357 public:
358 typedef OptionContext::FindType FindType;
359 explicit OptionParser(ParseContext& ctx);
360 virtual ~OptionParser();
361 ParseContext& parse();
362 protected:
363 ParseContext& ctx() const { return *ctx_; }
364 SharedOptPtr getOption(const char* name, FindType ft) const { return ctx_->getOption(name, ft); }
365 SharedOptPtr getOption(int posKey, const char* tok) const { return ctx_->getOption(posKey, tok); }
366 void addOptionValue(const SharedOptPtr& key, const std::string& value) { ctx_->addValue(key, value); }
367 private:
368 virtual void doParse() = 0;
369 ParseContext* ctx_;
370 };
371
372 //! Default formatting for options.
373 struct DefaultFormat {
374 std::size_t format(std::vector<char>&, const OptionContext&) { return 0; }
375 //! Writes g.caption() to buffer.
376 std::size_t format(std::vector<char>& buffer, const OptionGroup& g);
377 //! Writes long name, short name, and argument name to buffer.
378 std::size_t format(std::vector<char>& buffer, const Option& o, std::size_t maxW);
379 //! Writes description to buffer.
380 /*!
381 * Occurrences of %D, %I and %A in desc are replaced with
382 * the value's default value, implicit value, and name, respectively.
383 */
384 std::size_t format(std::vector<char>& buffer, const char* desc, const Value&, std::size_t maxW);
385 };
386
387 //! Base class for printing options.
388 class OptionOutput {
389 public:
390 OptionOutput() {}
391 virtual ~OptionOutput() {}
392 virtual bool printContext(const OptionContext& ctx) = 0;
393 virtual bool printGroup(const OptionGroup& group) = 0;
394 virtual bool printOption(const Option& opt, std::size_t maxW) = 0;
395 };
396
397 //! Implementation class for printing options.
398 template <class Writer, class Formatter = DefaultFormat>
399 class OptionOutputImpl : public OptionOutput {
400 public:
401 OptionOutputImpl(const Writer& w = Writer(), const Formatter& form = Formatter())
402 : writer_(w)
403 , formatter_(form) {}
404 bool printContext(const OptionContext& ctx) {
405 writer_.write(buffer_, formatter_.format(buffer_, ctx));
406 return true;
407 }
408 bool printGroup(const OptionGroup& group) {
409 writer_.write(buffer_, formatter_.format(buffer_, group));
410 return true;
411 }
412 bool printOption(const Option& opt, std::size_t maxW) {
413 writer_.write(buffer_, formatter_.format(buffer_, opt, maxW));
414 writer_.write(buffer_, formatter_.format(buffer_, opt.description(), *opt.value(), maxW));
415 return true;
416 }
417 private:
418 std::vector<char> buffer_;
419 Writer writer_;
420 Formatter formatter_;
421 };
422 //! Writes formatted option descriptions to an std::ostream.
423 struct OstreamWriter {
424 OstreamWriter(std::ostream& os) : out(os) {}
425 void write(const std::vector<char>& buf, std::size_t num);
426 std::ostream& out;
427 private: void operator=(const OstreamWriter&);
428 };
429 //! Writes formatted option descriptions to an std::string.
430 struct StringWriter {
431 StringWriter(std::string& str) : out(str) {}
432 void write(const std::vector<char>& buf, std::size_t num);
433 std::string& out;
434 private: void operator=(const StringWriter&);
435 };
436 //! Writes formatted option descriptions to a FILE.
437 struct FileWriter {
438 FileWriter(FILE* f) : out(f) {}
439 void write(const std::vector<char>& buf, std::size_t num);
440 FILE* out;
441 };
442 typedef OptionOutputImpl<OstreamWriter> StreamOut;
443 typedef OptionOutputImpl<StringWriter> StringOut;
444 typedef OptionOutputImpl<FileWriter> FileOut;
445 ///////////////////////////////////////////////////////////////////////////////
446 // parse functions
447 ///////////////////////////////////////////////////////////////////////////////
448 /*!
449 * A function type that is used by parsers for processing tokens that
450 * have no option name. Concrete functions shall either return true
451 * and store the name of the option that should receive the token as value
452 * in its second argument or return false to signal an error.
453 */
454 typedef bool(*PosOption)(const std::string&, std::string&);
455
456 enum CommandLineFlags {
457 command_line_allow_flag_value = 1u
458 };
459
460 /*!
461 * Parses the command line starting at index 1 and removes
462 * all found options from argv.
463 * \param argc nr of arguments in argv
464 * \param argv the command line arguments
465 * \param ctx options to search in the command line.
466 * \param allowUnregistered Allow arguments that match no option in ctx
467 * \param posParser parse function for positional options
468 *
469 * \return A ParsedOptions-Object containing names and values for all options found.
470 *
471 * \throw SyntaxError if command line syntax is incorrect.
472 * \throw UnknownOption if allowUnregistered is false and an argument is found
473 * that does not match any option.
474 */
475 ParsedValues parseCommandLine(int& argc, char** argv, const OptionContext& ctx,
476 bool allowUnregistered = true,
477 PosOption posParser = 0, unsigned flags = 0);
478
479 ParseContext& parseCommandLine(int& argc, char** argv, ParseContext& ctx, unsigned flags = 0);
480
481 /*!
482 * Parses the command arguments given in the array args.
483 * \param args the arguments to parse
484 * \param nArgs number of arguments in args.
485 * \param ctx options to search in the arguments
486 * \param allowUnregistered Allow arguments that match no option in ctx
487 * \param posParser parse function for positional options
488 *
489 * \return A ParsedOptions-Object containing names and values for all options found.
490 *
491 * \throw SyntaxError if argument syntax is incorrect.
492 * \throw UnknownOption if allowUnregistered is false and an argument is found
493 * that does not match any option.
494 */
495 ParsedValues parseCommandArray(const char* const args[], unsigned nArgs, const OptionContext& ctx,
496 bool allowUnregistered = true,
497 PosOption posParser = 0, unsigned flags = 0);
498
499 /*!
500 * Parses the command line given in the first parameter.
501 * \param cmd command line to parse
502 * \param ctx options to search in the command string.
503 * \param allowUnregistered Allow arguments that match no option in ctx
504 * \param posParser parse function for positional options
505 *
506 * \return A ParsedOptions-Object containing names and values for all options found.
507 *
508 * \throw SyntaxError if command line syntax is incorrect.
509 * \throw UnknownOption if an argument is found that does not match any option.
510 */
511 ParsedValues parseCommandString(const std::string& cmd, const OptionContext& ctx, bool allowUnreg = false, PosOption posParser = 0, unsigned flags = command_line_allow_flag_value);
512 ParseContext& parseCommandString(const char* cmd, ParseContext& ctx, unsigned flags = command_line_allow_flag_value);
513
514 /*!
515 * Parses a config file having the format key = value.
516 * \param is the stream representing the config file
517 * \param o options to search in the config file
518 * \param allowUnregistered Allow arguments that match no option in ctx
519 *
520 * \return A ParsedOptions-Object containing names and values for all options found.
521 *
522 * \throw SyntaxError if command line syntax is incorrect.
523 * \throw UnknownOption if an argument is found that does not match any option.
524 * \note Keys are option's long names.
525 * \note Lines starting with # are treated as comments and are ignored.
526 */
527 ParsedValues parseCfgFile(std::istream& is, const OptionContext& o, bool allowUnregistered);
528
529 } // namespace ProgramOptions
530 } // namespace Potassco
531
532 #endif