File: program_options.h

package info (click to toggle)
gringo 4.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,260 kB
  • ctags: 10,755
  • sloc: cpp: 55,049; python: 629; yacc: 569; sh: 124; makefile: 23
file content (511 lines) | stat: -rw-r--r-- 18,642 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//
//  Copyright (c) Benjamin Kaufmann 2004
//
//  This is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version. 
// 
//  This file is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
// NOTE: ProgramOptions is inspired by Boost.Program_options
//       see: www.boost.org/libs/program_options
//
#ifndef PROGRAM_OPTIONS_PROGRAM_OPTIONS_H_INCLUDED
#define PROGRAM_OPTIONS_PROGRAM_OPTIONS_H_INCLUDED
#include "value.h"
#include "detail/refcountable.h"
#include <iosfwd>
#include <set>
#include <map>
#include <vector>
#include <stdexcept>
#include <memory>
#include <cstdio>
namespace ProgramOptions {

//! Represents one program option.
/*!
 * An Option consists of a description (long name, short name, description),
 * a (typed) value, and an optional default value.
 *
 * \note 
 *   When printing an option, occurrences of %D, %I and %A in its description are replaced 
 *   with the option's default value, implicit value and the argument name,
 *   respectively.
 */
class Option : public detail::RefCountable {
public:
	/*!
	* \pre longName != ""
	* \pre vd != 0
	* \param longName    name (and unique key) of the option
	* \param shortName   possible alias name
	* \param description description of the option, used for printing help
	* \param value       value object to be associated with this option
	*/
	Option( const std::string& longName, char shortName,
		const char* description, Value* value);

	~Option();

	const std::string& name()           const  { return name_; }
	char               alias()          const  { return value_->alias(); }
	Value*             value()          const  { return value_; }
	const char*        description()    const  { return description_; }
	const char*        argName()        const  { return value_->arg(); }
	bool               assignDefault()  const;
	std::size_t        maxColumn()      const;
	DescriptionLevel   descLevel()      const  { return value_->level(); }
private:
	std::string name_;        // name (and unique key) of option
	const char* description_; // description of the option (used for --help)
	Value*      value_;       // the option's value manager
};

typedef detail::IntrusiveSharedPtr<Option> SharedOptPtr;

class OptionInitHelper;
class OptionContext;
class OptionParser;
class ParsedValues;
class ParsedOptions;
class OptionOutput;

//! A list of options logically grouped under a caption.
/*!
 * The class provides a logical grouping of options that
 * is mainly useful for printing help.
 */
class OptionGroup {
public:
	typedef std::vector<SharedOptPtr>  OptionList;
	typedef OptionList::const_iterator option_iterator;

	/*!
	 * Creates a new group of options under the given caption.
	 */
	OptionGroup(const std::string& caption = "", DescriptionLevel descLevel = desc_level_default);
	~OptionGroup();

	//! Returns the caption of this group.
	const std::string& caption() const { return caption_; }

	std::size_t      size()     const { return options_.size();  }
	bool             empty()    const { return options_.empty(); }
	option_iterator  begin()    const { return options_.begin(); }
	option_iterator  end()      const { return options_.end();   }
	DescriptionLevel descLevel()const { return level_; }
	
	//! Returns an object that can be used to add options.
	/*!
	 * \par usage \n
	 * \code
	 * OptionGroup g("Some Options");
	 * ValueMap m;
	 * g.addOptions()
	 *   ("opt1", store<int>(m), "some int value")   // <- no semicolon
	 *   ("opt2", store<double>(m))                  // <- no semicolon
	 *   ("opt3", store<char>(m))                    // <- no semicolon
	 * ;                                            // <- note the semicolon!
	 * \endcode
	 */
	OptionInitHelper addOptions();

	//! Adds option to this group.
	void addOption(std::auto_ptr<Option> option);
	void addOption(const SharedOptPtr& option);

	void setDescriptionLevel(DescriptionLevel level) { level_ = level; }

	//! Creates a formated description of all options with level() <= level in this group.
	void format(OptionOutput& out, size_t maxW, DescriptionLevel level = desc_level_default) const;

	std::size_t maxColumn(DescriptionLevel level) const;
private:
	friend class OptionContext;
	std::string      caption_;
	OptionList       options_;
	DescriptionLevel level_;
};

class OptionInitHelper {
public:
	explicit OptionInitHelper(OptionGroup& owner);
	
	//! Factory function for creating an option.
	/*!
	 * \param key <name>[!][,<alias>][,@<level>]
	 * \param val  Value of the option
	 * \param desc Description of the option
	 * 
	 * \note If <name> is followed by an exclamation mark ('!')
	 *       the option is marked as negatable.
	 */
	OptionInitHelper& operator()(const char* key,
		Value* val, const char* desc);
private:
	OptionGroup* owner_;
};

//! A (logically grouped) list of unique options.
/*!
 * An option context stores a list of option groups.
 * Options in a context have to be unique (w.r.t name and alias) 
 * within that context.
 *
 * An OptionContext defines the granularity of option parsing
 * and option lookup.
 */
class OptionContext {
private:
	typedef std::size_t                               key_type;
	typedef std::map<std::string, key_type>           Name2Key;
	typedef std::vector<OptionGroup>                  GroupList;
	typedef Name2Key::const_iterator                  index_iterator;
	typedef std::pair<index_iterator, index_iterator> PrefixRange;
	typedef OptionGroup::OptionList                   OptionList;
public:
	//! Type for identifying an option within a context
	typedef OptionList::const_iterator option_iterator;
	typedef PrefixRange                OptionRange;  
	
	OptionContext(const std::string& caption = "", DescriptionLevel desc_default = desc_level_default);
	~OptionContext();

	const std::string& caption() const;
	
	//! Adds the given group of options to this context.
	/*!
	 * \note  If this object already contains a group with
	 *        the same caption as group, the groups are merged.
	 *
	 * \throw DuplicateOption if an option in group
	 *        has the same short or long name as one of the
	 *        options in this context.
	 */
	OptionContext& add(const OptionGroup& group);

	//! Adds an alias name for the given option.
	/*!
	 * \throw DuplicateOption if an option with the name aliasName already exists.
	 */
	OptionContext& addAlias(const std::string& aliasName, option_iterator option);

	//! Adds all groups (and their options) from other to this context.
	/*!
	 * \throw DuplicateOption if an option in other
	 *        has the same short or long name as one of the
	 *        options in this context.
	 *
	 * \see OptionContext& add(const OptionGroup&);
	 */
	OptionContext& add(const OptionContext& other);
	
	option_iterator begin() const { return options_.begin(); }
	option_iterator end()   const { return options_.end();   }
	
	//! Returns the number of options in this context.
	std::size_t    size()   const { return options_.size(); }
	//! Returns the number of groups in this context
	std::size_t    groups() const { return groups_.size(); }

	enum FindType { find_name = 1, find_prefix = 2, find_name_or_prefix = find_name|find_prefix, find_alias = 4 };
	
	//! Returns the option with the given key.
	/*!
	 * \note The second parameter defines how key is interpreted:
	 *        - find_name:   search for an option whose name equals key.
	 *        - find_prefix: search for an option whose name starts with the given key.
	 *        - find_alias:  search for an option whose alias equals key.
	 *       .
	 *
	 * \note If second parameter is find_alias, a starting '-'
	 *       in key is valid but not required.
	 *
	 * \throw UnknownOption if no option matches key.
	 * \throw AmbiguousOption if more than one option matches key.
	 */
	option_iterator find(const char* key, FindType t = find_name) const;
	/*!
	 * Behaves like find but returns end() instead of throwing
	 * UnknownOption or AmbiguousOption.
	 */
	option_iterator tryFind(const char* key, FindType t = find_name) const;

	OptionRange findImpl(const char* key, FindType t, unsigned eMask = unsigned(-1)) const { return findImpl(key, t, eMask, caption()); }
	OptionRange findImpl(const char* key, FindType t, unsigned eMask, const std::string& eCtx) const;

	const OptionGroup& findGroup(const std::string& caption) const;
	const OptionGroup* tryFindGroup(const std::string& caption) const;
	
	//! Sets the description level to be used when generating description.
	/*!
	 * Once set, functions generating descriptions will only consider groups
	 * and options with description level <= std::min(level, desc_level_all).
	 */
	void             setActiveDescLevel(DescriptionLevel level);
	DescriptionLevel getActiveDescLevel() const { return descLevel_; }
	
	//! Writes a formatted description of options in this context.
	OptionOutput& description(OptionOutput& out) const;
	
	//! Returns the default command-line of this context.
	std::string defaults(std::size_t prefixSize = 0) const;
	
	//! Writes a formatted description of options in this context to os.
	friend std::ostream& operator<<(std::ostream& os,  const OptionContext& ctx);

	//! Assigns any default values to all options not in exclude.
	/*!
	 * \throw ValueError if some default value is actually invalid for its option.
	 */
	bool assignDefaults(const ParsedOptions& exclude) const;
private:
	void        insertOption(size_t groupId, const SharedOptPtr& o);
	size_t      findGroupKey(const std::string& name) const;
	
	Name2Key         index_;
	OptionList       options_;
	GroupList        groups_;
	std::string      caption_;
	DescriptionLevel descLevel_;
};

class OptionParser;
class ParsedValues;

//! Set of options holding a parsed value.
class ParsedOptions {
public:
	ParsedOptions();
	~ParsedOptions();
	bool        empty()                        const  { return parsed_.empty(); }
	std::size_t size()                         const  { return parsed_.size(); }
	std::size_t count(const std::string& name) const  { return parsed_.count(name); }
	void        add(const std::string& name)          { parsed_.insert(name); }
	
	//! Assigns the parsed values in p to their options.
	/*!
	 * Parsed values for options that already have a value (and are
   * not composing) are ignored. On the other hand, parsed values
	 * overwrite any existing default values.
	 *
	 * \param p parsed values to assign
	 *
	 * \throw ValueError if p contains more than one value 
	 *        for a non-composing option or if p contains a value that is 
	 *        invalid for its option.
	 */
	bool        assign(const ParsedValues& p, const ParsedOptions* exclude = 0);
private:
	std::set<std::string> parsed_;
	int assign(const Option& o, const std::string& value);
};

/*!
* Container of option-value-pairs representing values found by a parser.
*/
class ParsedValues {
public:
	typedef std::pair<SharedOptPtr, std::string> OptionAndValue;
	typedef std::vector<OptionAndValue> Values;
	typedef Values::const_iterator iterator;

	/*!
	* \param a_ctx The OptionContext for which this object stores raw-values.
	*/
	explicit ParsedValues(const OptionContext& a_ctx)
		: ctx(&a_ctx)
	{}
	const OptionContext* ctx;
	
	//! Adds a value for option opt.
	void add(const std::string& opt, const std::string& value);
	void add(const SharedOptPtr& opt, const std::string& value) {
		parsed_.push_back(OptionAndValue(opt, value));
	}

	iterator begin() const { return parsed_.begin(); }
	iterator end()   const { return parsed_.end(); }

	void clear() { parsed_.clear(); }
private:
	Values parsed_;
};

class ParseContext {
public:
	typedef OptionContext::FindType FindType;
	virtual ~ParseContext();
	virtual SharedOptPtr getOption(const char* name, FindType ft)                    = 0;
	virtual SharedOptPtr getOption(int posKey, const char* tok)                      = 0;
	virtual void         addValue(const SharedOptPtr& key, const std::string& value) = 0;
};

//! Base class for options parsers.
class OptionParser {
public:
	typedef OptionContext::FindType FindType;
	explicit OptionParser(ParseContext& ctx);
	virtual ~OptionParser();
	ParseContext& parse();
protected:
	ParseContext& ctx() const { return *ctx_; }
	SharedOptPtr  getOption(const char* name, FindType ft) const { return ctx_->getOption(name, ft); }
	SharedOptPtr  getOption(int posKey, const char* tok)   const { return ctx_->getOption(posKey, tok); }
	void          addOptionValue(const SharedOptPtr& key, const std::string& value) { ctx_->addValue(key, value); } 
private:
	virtual void doParse() = 0;
	ParseContext* ctx_;
};

//! Default formatting for options.
struct DefaultFormat {
	std::size_t format(std::vector<char>&, const OptionContext&) { return 0; }
	//! Writes g.caption() to buffer.
	std::size_t format(std::vector<char>& buffer, const OptionGroup& g);
	//! Writes long name, short name, and argument name to buffer.
	std::size_t format(std::vector<char>& buffer, const Option& o, std::size_t maxW);
	//! Writes description to buffer.
	/*!
	 * Occurrences of %D, %I and %A in desc are replaced with 
	 * the value's default value, implicit value, and name, respectively.
	 */
	std::size_t format(std::vector<char>& buffer, const char* desc, const Value&, std::size_t maxW);
};

//! Base class for printing options.
class OptionOutput {
public:
	OptionOutput() {}
	virtual ~OptionOutput() {}
	virtual bool printContext(const OptionContext& ctx)           = 0;
	virtual bool printGroup(const OptionGroup& group)             = 0;
	virtual bool printOption(const Option& opt, std::size_t maxW) = 0;
};

//! Implementation class for printing options.
template <class Writer, class Formatter = DefaultFormat>
class OptionOutputImpl : public OptionOutput {
public:
	OptionOutputImpl(const Writer& w = Writer(), const Formatter& form = Formatter()) 
		: writer_(w)
		, formatter_(form) { }
	bool printContext(const OptionContext& ctx) {
		writer_.write(buffer_, formatter_.format(buffer_, ctx));
		return true;
	}
	bool printGroup(const OptionGroup& group) {
		writer_.write(buffer_, formatter_.format(buffer_, group));
		return true;
	}
	bool printOption(const Option& opt, std::size_t maxW) {
		writer_.write(buffer_, formatter_.format(buffer_, opt, maxW));
		writer_.write(buffer_, formatter_.format(buffer_, opt.description(), *opt.value(), maxW));
		return true;
	}
private:
	std::vector<char> buffer_;
	Writer            writer_;
	Formatter         formatter_;
};
//! Writes formatted option descriptions to an std::ostream.
struct OstreamWriter {
	OstreamWriter(std::ostream& os) : out(os) {}
	void write(const std::vector<char>& buf, std::size_t num);
	std::ostream& out;
private: void operator=(const OstreamWriter&);
};
//! Writes formatted option descriptions to an std::string.
struct StringWriter {
	StringWriter(std::string& str) : out(str) {}
	void write(const std::vector<char>& buf, std::size_t num);
	std::string& out;
private: void operator=(const StringWriter&);
};
//! Writes formatted option descriptions to a FILE.
struct FileWriter {
	FileWriter(FILE* f) : out(f) {}
	void write(const std::vector<char>& buf, std::size_t num);
	FILE* out;
};
typedef OptionOutputImpl<OstreamWriter> StreamOut;
typedef OptionOutputImpl<StringWriter>  StringOut;
typedef OptionOutputImpl<FileWriter>    FileOut;
///////////////////////////////////////////////////////////////////////////////
// parse functions
///////////////////////////////////////////////////////////////////////////////
/*!
 * A function type that is used by parsers for processing tokens that
 * have no option name. Concrete functions shall either return true
 * and store the name of the option that should receive the token as value 
 * in its second argument or return false to signal an error.
 */
typedef bool (*PosOption)(const std::string&, std::string&);

enum CommandLineFlags {
	command_line_allow_flag_value = 1u,
};

/*!
* Parses the command line starting at index 1 and removes
* all found options from argv.
* \param argc nr of arguments in argv
* \param argv the command line arguments
* \param ctx options to search in the command line.
* \param allowUnregistered Allow arguments that match no option in ctx
* \param posParser parse function for positional options
*
* \return A ParsedOptions-Object containing names and values for all options found.
* 
* \throw SyntaxError if command line syntax is incorrect.
* \throw UnknownOption if allowUnregistered is false and an argument is found
* that does not match any option.
*/
ParsedValues parseCommandLine(int& argc, char** argv, const OptionContext& ctx,
	bool allowUnregistered = true,
	PosOption posParser = 0, unsigned flags = 0);

ParseContext& parseCommandLine(int& argc, char** argv, ParseContext& ctx, unsigned flags = 0); 

/*!
* Parses the command line given in the first parameter.
* \param cmd command line to parse
* \param ctx options to search in the command string.
* \param allowUnregistered Allow arguments that match no option in ctx
* \param posParser parse function for positional options
*
* \return A ParsedOptions-Object containing names and values for all options found.
* 
* \throw SyntaxError if command line syntax is incorrect.
* \throw UnknownOption if an argument is found that does not match any option.
*/
ParsedValues parseCommandString(const std::string& cmd, const OptionContext& ctx, bool allowUnreg = false, PosOption posParser = 0, unsigned flags = command_line_allow_flag_value);
ParseContext& parseCommandString(const char* cmd, ParseContext& ctx, unsigned flags = command_line_allow_flag_value); 

/*!
* Parses a config file having the format key = value.
* \param is the stream representing the config file
* \param o options to search in the config file
* \param allowUnregistered Allow arguments that match no option in ctx
* 
* \return A ParsedOptions-Object containing names and values for all options found.
*
* \throw SyntaxError if command line syntax is incorrect.
* \throw UnknownOption if an argument is found that does not match any option.
* \note Keys are option's long names.
* \note Lines starting with # are treated as comments and are ignored.
*/
ParsedValues parseCfgFile(std::istream& is, const OptionContext& o, bool allowUnregistered);

}

#endif