1 | /* |
2 | * The Lean Mean C++ Option Parser |
3 | * |
4 | * Copyright (C) 2012 Matthias S. Benkmann |
5 | * |
6 | * The "Software" in the following 2 paragraphs refers to this file containing |
7 | * the code to The Lean Mean C++ Option Parser. |
8 | * The "Software" does NOT refer to any other files which you |
9 | * may have received alongside this file (e.g. as part of a larger project that |
10 | * incorporates The Lean Mean C++ Option Parser). |
11 | * |
12 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
13 | * of this software, to deal in the Software without restriction, including |
14 | * without limitation the rights to use, copy, modify, merge, publish, |
15 | * distribute, sublicense, and/or sell copies of the Software, and to permit |
16 | * persons to whom the Software is furnished to do so, subject to the following |
17 | * conditions: |
18 | * The above copyright notice and this permission notice shall be included in |
19 | * all copies or substantial portions of the Software. |
20 | * |
21 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
22 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
23 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
24 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
25 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
26 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
27 | * SOFTWARE. |
28 | */ |
29 | |
30 | /* |
31 | * NOTE: It is recommended that you read the processed HTML doxygen documentation |
32 | * rather than this source. If you don't know doxygen, it's like javadoc for C++. |
33 | * If you don't want to install doxygen you can find a copy of the processed |
34 | * documentation at |
35 | * |
36 | * http://optionparser.sourceforge.net/ |
37 | * |
38 | */ |
39 | |
40 | /** |
41 | * @file |
42 | * |
43 | * @brief This is the only file required to use The Lean Mean C++ Option Parser. |
44 | * Just \#include it and you're set. |
45 | * |
46 | * The Lean Mean C++ Option Parser handles the program's command line arguments |
47 | * (argc, argv). |
48 | * It supports the short and long option formats of getopt(), getopt_long() |
49 | * and getopt_long_only() but has a more convenient interface. |
50 | * The following features set it apart from other option parsers: |
51 | * |
52 | * @par Highlights: |
53 | * <ul style="padding-left:1em;margin-left:0"> |
54 | * <li> It is a header-only library. Just <code>\#include "optionparser.h"</code> and you're set. |
55 | * <li> It is freestanding. There are no dependencies whatsoever, not even the |
56 | * C or C++ standard library. |
57 | * <li> It has a usage message formatter that supports column alignment and |
58 | * line wrapping. This aids localization because it adapts to |
59 | * translated strings that are shorter or longer (even if they contain |
60 | * Asian wide characters). |
61 | * <li> Unlike getopt() and derivatives it doesn't force you to loop through |
62 | * options sequentially. Instead you can access options directly like this: |
63 | * <ul style="margin-top:.5em"> |
64 | * <li> Test for presence of a switch in the argument vector: |
65 | * @code if ( options[QUIET] ) ... @endcode |
66 | * <li> Evaluate --enable-foo/--disable-foo pair where the last one used wins: |
67 | * @code if ( options[FOO].last()->type() == DISABLE ) ... @endcode |
68 | * <li> Cumulative option (-v verbose, -vv more verbose, -vvv even more verbose): |
69 | * @code int verbosity = options[VERBOSE].count(); @endcode |
70 | * <li> Iterate over all --file=<fname> arguments: |
71 | * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) |
72 | * fname = opt->arg; ... @endcode |
73 | * <li> If you really want to, you can still process all arguments in order: |
74 | * @code |
75 | * for (int i = 0; i < p.optionsCount(); ++i) { |
76 | * Option& opt = buffer[i]; |
77 | * switch(opt.index()) { |
78 | * case HELP: ... |
79 | * case VERBOSE: ... |
80 | * case FILE: fname = opt.arg; ... |
81 | * case UNKNOWN: ... |
82 | * @endcode |
83 | * </ul> |
84 | * </ul> @n |
85 | * Despite these features the code size remains tiny. |
86 | * It is smaller than <a href="http://uclibc.org">uClibc</a>'s GNU getopt() and just a |
87 | * couple 100 bytes larger than uClibc's SUSv3 getopt(). @n |
88 | * (This does not include the usage formatter, of course. But you don't have to use that.) |
89 | * |
90 | * @par Download: |
91 | * Tarball with examples and test programs: |
92 | * <a style="font-size:larger;font-weight:bold" href="http://sourceforge.net/projects/optionparser/files/optionparser-1.4.tar.gz/download">optionparser-1.4.tar.gz</a> @n |
93 | * Just the header (this is all you really need): |
94 | * <a style="font-size:larger;font-weight:bold" href="http://optionparser.sourceforge.net/optionparser.h">optionparser.h</a> |
95 | * |
96 | * @par Changelog: |
97 | * <b>Version 1.4:</b> Fixed 2 printUsage() bugs that messed up output with small COLUMNS values @n |
98 | * <b>Version 1.3:</b> Compatible with Microsoft Visual C++. @n |
99 | * <b>Version 1.2:</b> Added @ref option::Option::namelen "Option::namelen" and removed the extraction |
100 | * of short option characters into a special buffer. @n |
101 | * Changed @ref option::Arg::Optional "Arg::Optional" to accept arguments if they are attached |
102 | * rather than separate. This is what GNU getopt() does and how POSIX recommends |
103 | * utilities should interpret their arguments.@n |
104 | * <b>Version 1.1:</b> Optional mode with argument reordering as done by GNU getopt(), so that |
105 | * options and non-options can be mixed. See |
106 | * @ref option::Parser::parse() "Parser::parse()". |
107 | * |
108 | * @par Feedback: |
109 | * Send questions, bug reports, feature requests etc. to: <tt><b>optionparser-feedback<span id="antispam"> (a) </span>lists.sourceforge.net</b></tt> |
110 | * @htmlonly <script type="text/javascript">document.getElementById("antispam").innerHTML="@"</script> @endhtmlonly |
111 | * |
112 | * |
113 | * @par Example program: |
114 | * (Note: @c option::* identifiers are links that take you to their documentation.) |
115 | * @code |
116 | * #include <iostream> |
117 | * #include "optionparser.h" |
118 | * |
119 | * enum optionIndex { UNKNOWN, HELP, PLUS }; |
120 | * const option::Descriptor usage[] = |
121 | * { |
122 | * {UNKNOWN, 0,"" , "" ,option::Arg::None, "USAGE: example [options]\n\n" |
123 | * "Options:" }, |
124 | * {HELP, 0,"" , "help",option::Arg::None, " --help \tPrint usage and exit." }, |
125 | * {PLUS, 0,"p", "plus",option::Arg::None, " --plus, -p \tIncrement count." }, |
126 | * {UNKNOWN, 0,"" , "" ,option::Arg::None, "\nExamples:\n" |
127 | * " example --unknown -- --this_is_no_option\n" |
128 | * " example -unk --plus -ppp file1 file2\n" }, |
129 | * {0,0,0,0,0,0} |
130 | * }; |
131 | * |
132 | * int main(int argc, char* argv[]) |
133 | * { |
134 | * argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present |
135 | * option::Stats stats(usage, argc, argv); |
136 | * option::Option options[stats.options_max], buffer[stats.buffer_max]; |
137 | * option::Parser parse(usage, argc, argv, options, buffer); |
138 | * |
139 | * if (parse.error()) |
140 | * return 1; |
141 | * |
142 | * if (options[HELP] || argc == 0) { |
143 | * option::printUsage(std::cout, usage); |
144 | * return 0; |
145 | * } |
146 | * |
147 | * std::cout << "--plus count: " << |
148 | * options[PLUS].count() << "\n"; |
149 | * |
150 | * for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next()) |
151 | * std::cout << "Unknown option: " << opt->name << "\n"; |
152 | * |
153 | * for (int i = 0; i < parse.nonOptionsCount(); ++i) |
154 | * std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n"; |
155 | * } |
156 | * @endcode |
157 | * |
158 | * @par Option syntax: |
159 | * @li The Lean Mean C++ Option Parser follows POSIX <code>getopt()</code> conventions and supports |
160 | * GNU-style <code>getopt_long()</code> long options as well as Perl-style single-minus |
161 | * long options (<code>getopt_long_only()</code>). |
162 | * @li short options have the format @c -X where @c X is any character that fits in a char. |
163 | * @li short options can be grouped, i.e. <code>-X -Y</code> is equivalent to @c -XY. |
164 | * @li a short option may take an argument either separate (<code>-X foo</code>) or |
165 | * attached (@c -Xfoo). You can make the parser accept the additional format @c -X=foo by |
166 | * registering @c X as a long option (in addition to being a short option) and |
167 | * enabling single-minus long options. |
168 | * @li an argument-taking short option may be grouped if it is the last in the group, e.g. |
169 | * @c -ABCXfoo or <code> -ABCX foo </code> (@c foo is the argument to the @c -X option). |
170 | * @li a lone minus character @c '-' is not treated as an option. It is customarily used where |
171 | * a file name is expected to refer to stdin or stdout. |
172 | * @li long options have the format @c --option-name. |
173 | * @li the option-name of a long option can be anything and include any characters. |
174 | * Even @c = characters will work, but don't do that. |
175 | * @li [optional] long options may be abbreviated as long as the abbreviation is unambiguous. |
176 | * You can set a minimum length for abbreviations. |
177 | * @li [optional] long options may begin with a single minus. The double minus form is always |
178 | * accepted, too. |
179 | * @li a long option may take an argument either separate (<code> --option arg </code>) or |
180 | * attached (<code> --option=arg </code>). In the attached form the equals sign is mandatory. |
181 | * @li an empty string can be passed as an attached long option argument: <code> --option-name= </code>. |
182 | * Note the distinction between an empty string as argument and no argument at all. |
183 | * @li an empty string is permitted as separate argument to both long and short options. |
184 | * @li Arguments to both short and long options may start with a @c '-' character. E.g. |
185 | * <code> -X-X </code>, <code>-X -X</code> or <code> --long-X=-X </code>. If @c -X |
186 | * and @c --long-X take an argument, that argument will be @c "-X" in all 3 cases. |
187 | * @li If using the built-in @ref option::Arg::Optional "Arg::Optional", optional arguments must |
188 | * be attached. |
189 | * @li the special option @c -- (i.e. without a name) terminates the list of |
190 | * options. Everything that follows is a non-option argument, even if it starts with |
191 | * a @c '-' character. The @c -- itself will not appear in the parse results. |
192 | * @li the first argument that doesn't start with @c '-' or @c '--' and does not belong to |
193 | * a preceding argument-taking option, will terminate the option list and is the |
194 | * first non-option argument. All following command line arguments are treated as |
195 | * non-option arguments, even if they start with @c '-' . @n |
196 | * NOTE: This behaviour is mandated by POSIX, but GNU getopt() only honours this if it is |
197 | * explicitly requested (e.g. by setting POSIXLY_CORRECT). @n |
198 | * You can enable the GNU behaviour by passing @c true as first argument to |
199 | * e.g. @ref option::Parser::parse() "Parser::parse()". |
200 | * @li Arguments that look like options (i.e. @c '-' followed by at least 1 character) but |
201 | * aren't, are NOT treated as non-option arguments. They are treated as unknown options and |
202 | * are collected into a list of unknown options for error reporting. @n |
203 | * This means that in order to pass a first non-option |
204 | * argument beginning with the minus character it is required to use the |
205 | * @c -- special option, e.g. |
206 | * @code |
207 | * program -x -- --strange-filename |
208 | * @endcode |
209 | * In this example, @c --strange-filename is a non-option argument. If the @c -- |
210 | * were omitted, it would be treated as an unknown option. @n |
211 | * See @ref option::Descriptor::longopt for information on how to collect unknown options. |
212 | * |
213 | */ |
214 | |
215 | #ifndef OPTIONPARSER_H_ |
216 | #define OPTIONPARSER_H_ |
217 | |
218 | /** @brief The namespace of The Lean Mean C++ Option Parser. */ |
219 | namespace option |
220 | { |
221 | |
222 | #ifdef _MSC_VER |
223 | #include <intrin.h> |
224 | #pragma intrinsic(_BitScanReverse) |
225 | struct MSC_Builtin_CLZ |
226 | { |
227 | static int builtin_clz(unsigned x) |
228 | { |
229 | unsigned long index; |
230 | _BitScanReverse(&index, x); |
231 | return 32-index; // int is always 32bit on Windows, even for target x64 |
232 | } |
233 | }; |
234 | #define __builtin_clz(x) MSC_Builtin_CLZ::builtin_clz(x) |
235 | #endif |
236 | |
237 | class Option; |
238 | |
239 | /** |
240 | * @brief Possible results when checking if an argument is valid for a certain option. |
241 | * |
242 | * In the case that no argument is provided for an option that takes an |
243 | * optional argument, return codes @c ARG_OK and @c ARG_IGNORE are equivalent. |
244 | */ |
245 | enum ArgStatus |
246 | { |
247 | //! The option does not take an argument. |
248 | ARG_NONE, |
249 | //! The argument is acceptable for the option. |
250 | ARG_OK, |
251 | //! The argument is not acceptable but that's non-fatal because the option's argument is optional. |
252 | ARG_IGNORE, |
253 | //! The argument is not acceptable and that's fatal. |
254 | ARG_ILLEGAL |
255 | }; |
256 | |
257 | /** |
258 | * @brief Signature of functions that check if an argument is valid for a certain type of option. |
259 | * |
260 | * Every Option has such a function assigned in its Descriptor. |
261 | * @code |
262 | * Descriptor usage[] = { {UNKNOWN, 0, "", "", Arg::None, ""}, ... }; |
263 | * @endcode |
264 | * |
265 | * A CheckArg function has the following signature: |
266 | * @code ArgStatus CheckArg(const Option& option, bool msg); @endcode |
267 | * |
268 | * It is used to check if a potential argument would be acceptable for the option. |
269 | * It will even be called if there is no argument. In that case @c option.arg will be @c NULL. |
270 | * |
271 | * If @c msg is @c true and the function determines that an argument is not acceptable and |
272 | * that this is a fatal error, it should output a message to the user before |
273 | * returning @ref ARG_ILLEGAL. If @c msg is @c false the function should remain silent (or you |
274 | * will get duplicate messages). |
275 | * |
276 | * See @ref ArgStatus for the meaning of the return values. |
277 | * |
278 | * While you can provide your own functions, |
279 | * often the following pre-defined checks (which never return @ref ARG_ILLEGAL) will suffice: |
280 | * |
281 | * @li @c Arg::None @copybrief Arg::None |
282 | * @li @c Arg::Optional @copybrief Arg::Optional |
283 | * |
284 | */ |
285 | typedef ArgStatus (*CheckArg)(const Option& option, bool msg); |
286 | |
287 | /** |
288 | * @brief Describes an option, its help text (usage) and how it should be parsed. |
289 | * |
290 | * The main input when constructing an option::Parser is an array of Descriptors. |
291 | |
292 | * @par Example: |
293 | * @code |
294 | * enum OptionIndex {CREATE, ...}; |
295 | * enum OptionType {DISABLE, ENABLE, OTHER}; |
296 | * |
297 | * const option::Descriptor usage[] = { |
298 | * { CREATE, // index |
299 | * OTHER, // type |
300 | * "c", // shortopt |
301 | * "create", // longopt |
302 | * Arg::None, // check_arg |
303 | * "--create Tells the program to create something." // help |
304 | * } |
305 | * , ... |
306 | * }; |
307 | * @endcode |
308 | */ |
309 | struct Descriptor |
310 | { |
311 | /** |
312 | * @brief Index of this option's linked list in the array filled in by the parser. |
313 | * |
314 | * Command line options whose Descriptors have the same index will end up in the same |
315 | * linked list in the order in which they appear on the command line. If you have |
316 | * multiple long option aliases that refer to the same option, give their descriptors |
317 | * the same @c index. |
318 | * |
319 | * If you have options that mean exactly opposite things |
320 | * (e.g. @c --enable-foo and @c --disable-foo ), you should also give them the same |
321 | * @c index, but distinguish them through different values for @ref type. |
322 | * That way they end up in the same list and you can just take the last element of the |
323 | * list and use its type. This way you get the usual behaviour where switches later |
324 | * on the command line override earlier ones without having to code it manually. |
325 | * |
326 | * @par Tip: |
327 | * Use an enum rather than plain ints for better readability, as shown in the example |
328 | * at Descriptor. |
329 | */ |
330 | const unsigned index; |
331 | |
332 | /** |
333 | * @brief Used to distinguish between options with the same @ref index. |
334 | * See @ref index for details. |
335 | * |
336 | * It is recommended that you use an enum rather than a plain int to make your |
337 | * code more readable. |
338 | */ |
339 | const int type; |
340 | |
341 | /** |
342 | * @brief Each char in this string will be accepted as a short option character. |
343 | * |
344 | * The string must not include the minus character @c '-' or you'll get undefined |
345 | * behaviour. |
346 | * |
347 | * If this Descriptor should not have short option characters, use the empty |
348 | * string "". NULL is not permitted here! |
349 | * |
350 | * See @ref longopt for more information. |
351 | */ |
352 | const char* const shortopt; |
353 | |
354 | /** |
355 | * @brief The long option name (without the leading @c -- ). |
356 | * |
357 | * If this Descriptor should not have a long option name, use the empty |
358 | * string "". NULL is not permitted here! |
359 | * |
360 | * While @ref shortopt allows multiple short option characters, each |
361 | * Descriptor can have only a single long option name. If you have multiple |
362 | * long option names referring to the same option use separate Descriptors |
363 | * that have the same @ref index and @ref type. You may repeat |
364 | * short option characters in such an alias Descriptor but there's no need to. |
365 | * |
366 | * @par Dummy Descriptors: |
367 | * You can use dummy Descriptors with an |
368 | * empty string for both @ref shortopt and @ref longopt to add text to |
369 | * the usage that is not related to a specific option. See @ref help. |
370 | * The first dummy Descriptor will be used for unknown options (see below). |
371 | * |
372 | * @par Unknown Option Descriptor: |
373 | * The first dummy Descriptor in the list of Descriptors, |
374 | * whose @ref shortopt and @ref longopt are both the empty string, will be used |
375 | * as the Descriptor for unknown options. An unknown option is a string in |
376 | * the argument vector that is not a lone minus @c '-' but starts with a minus |
377 | * character and does not match any Descriptor's @ref shortopt or @ref longopt. @n |
378 | * Note that the dummy descriptor's @ref check_arg function @e will be called and |
379 | * its return value will be evaluated as usual. I.e. if it returns @ref ARG_ILLEGAL |
380 | * the parsing will be aborted with <code>Parser::error()==true</code>. @n |
381 | * if @c check_arg does not return @ref ARG_ILLEGAL the descriptor's |
382 | * @ref index @e will be used to pick the linked list into which |
383 | * to put the unknown option. @n |
384 | * If there is no dummy descriptor, unknown options will be dropped silently. |
385 | * |
386 | */ |
387 | const char* const longopt; |
388 | |
389 | /** |
390 | * @brief For each option that matches @ref shortopt or @ref longopt this function |
391 | * will be called to check a potential argument to the option. |
392 | * |
393 | * This function will be called even if there is no potential argument. In that case |
394 | * it will be passed @c NULL as @c arg parameter. Do not confuse this with the empty |
395 | * string. |
396 | * |
397 | * See @ref CheckArg for more information. |
398 | */ |
399 | const CheckArg check_arg; |
400 | |
401 | /** |
402 | * @brief The usage text associated with the options in this Descriptor. |
403 | * |
404 | * You can use option::printUsage() to format your usage message based on |
405 | * the @c help texts. You can use dummy Descriptors where |
406 | * @ref shortopt and @ref longopt are both the empty string to add text to |
407 | * the usage that is not related to a specific option. |
408 | * |
409 | * See option::printUsage() for special formatting characters you can use in |
410 | * @c help to get a column layout. |
411 | * |
412 | * @attention |
413 | * Must be UTF-8-encoded. If your compiler supports C++11 you can use the "u8" |
414 | * prefix to make sure string literals are properly encoded. |
415 | */ |
416 | const char* help; |
417 | }; |
418 | |
419 | /** |
420 | * @brief A parsed option from the command line together with its argument if it has one. |
421 | * |
422 | * The Parser chains all parsed options with the same Descriptor::index together |
423 | * to form a linked list. This allows you to easily implement all of the common ways |
424 | * of handling repeated options and enable/disable pairs. |
425 | * |
426 | * @li Test for presence of a switch in the argument vector: |
427 | * @code if ( options[QUIET] ) ... @endcode |
428 | * @li Evaluate --enable-foo/--disable-foo pair where the last one used wins: |
429 | * @code if ( options[FOO].last()->type() == DISABLE ) ... @endcode |
430 | * @li Cumulative option (-v verbose, -vv more verbose, -vvv even more verbose): |
431 | * @code int verbosity = options[VERBOSE].count(); @endcode |
432 | * @li Iterate over all --file=<fname> arguments: |
433 | * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) |
434 | * fname = opt->arg; ... @endcode |
435 | */ |
436 | class Option |
437 | { |
438 | Option* next_; |
439 | Option* prev_; |
440 | public: |
441 | /** |
442 | * @brief Pointer to this Option's Descriptor. |
443 | * |
444 | * Remember that the first dummy descriptor (see @ref Descriptor::longopt) is used |
445 | * for unknown options. |
446 | * |
447 | * @attention |
448 | * @c desc==NULL signals that this Option is unused. This is the default state of |
449 | * elements in the result array. You don't need to test @c desc explicitly. You |
450 | * can simply write something like this: |
451 | * @code |
452 | * if (options[CREATE]) |
453 | * { |
454 | * ... |
455 | * } |
456 | * @endcode |
457 | * This works because of <code> operator const Option*() </code>. |
458 | */ |
459 | const Descriptor* desc; |
460 | |
461 | /** |
462 | * @brief The name of the option as used on the command line. |
463 | * |
464 | * The main purpose of this string is to be presented to the user in messages. |
465 | * |
466 | * In the case of a long option, this is the actual @c argv pointer, i.e. the first |
467 | * character is a '-'. In the case of a short option this points to the option |
468 | * character within the @c argv string. |
469 | * |
470 | * Note that in the case of a short option group or an attached option argument, this |
471 | * string will contain additional characters following the actual name. Use @ref namelen |
472 | * to filter out the actual option name only. |
473 | * |
474 | */ |
475 | const char* name; |
476 | |
477 | /** |
478 | * @brief Pointer to this Option's argument (if any). |
479 | * |
480 | * NULL if this option has no argument. Do not confuse this with the empty string which |
481 | * is a valid argument. |
482 | */ |
483 | const char* arg; |
484 | |
485 | /** |
486 | * @brief The length of the option @ref name. |
487 | * |
488 | * Because @ref name points into the actual @c argv string, the option name may be |
489 | * followed by more characters (e.g. other short options in the same short option group). |
490 | * This value is the number of bytes (not characters!) that are part of the actual name. |
491 | * |
492 | * For a short option, this length is always 1. For a long option this length is always |
493 | * at least 2 if single minus long options are permitted and at least 3 if they are disabled. |
494 | * |
495 | * @note |
496 | * In the pathological case of a minus within a short option group (e.g. @c -xf-z), this |
497 | * length is incorrect, because this case will be misinterpreted as a long option and the |
498 | * name will therefore extend to the string's 0-terminator or a following '=" character |
499 | * if there is one. This is irrelevant for most uses of @ref name and @c namelen. If you |
500 | * really need to distinguish the case of a long and a short option, compare @ref name to |
501 | * the @c argv pointers. A long option's @c name is always identical to one of them, |
502 | * whereas a short option's is never. |
503 | */ |
504 | int namelen; |
505 | |
506 | /** |
507 | * @brief Returns Descriptor::type of this Option's Descriptor, or 0 if this Option |
508 | * is invalid (unused). |
509 | * |
510 | * Because this method (and last(), too) can be used even on unused Options with desc==0, you can (provided |
511 | * you arrange your types properly) switch on type() without testing validity first. |
512 | * @code |
513 | * enum OptionType { UNUSED=0, DISABLED=0, ENABLED=1 }; |
514 | * enum OptionIndex { FOO }; |
515 | * const Descriptor usage[] = { |
516 | * { FOO, ENABLED, "", "enable-foo", Arg::None, 0 }, |
517 | * { FOO, DISABLED, "", "disable-foo", Arg::None, 0 }, |
518 | * { 0, 0, 0, 0, 0, 0 } }; |
519 | * ... |
520 | * switch(options[FOO].last()->type()) // no validity check required! |
521 | * { |
522 | * case ENABLED: ... |
523 | * case DISABLED: ... // UNUSED==DISABLED ! |
524 | * } |
525 | * @endcode |
526 | */ |
527 | int type() const |
528 | { |
529 | return desc == 0 ? 0 : desc->type; |
530 | } |
531 | |
532 | /** |
533 | * @brief Returns Descriptor::index of this Option's Descriptor, or -1 if this Option |
534 | * is invalid (unused). |
535 | */ |
536 | int index() const |
537 | { |
538 | return desc == 0 ? -1 : (int)desc->index; |
539 | } |
540 | |
541 | /** |
542 | * @brief Returns the number of times this Option (or others with the same Descriptor::index) |
543 | * occurs in the argument vector. |
544 | * |
545 | * This corresponds to the number of elements in the linked list this Option is part of. |
546 | * It doesn't matter on which element you call count(). The return value is always the same. |
547 | * |
548 | * Use this to implement cumulative options, such as -v, -vv, -vvv for |
549 | * different verbosity levels. |
550 | * |
551 | * Returns 0 when called for an unused/invalid option. |
552 | */ |
553 | int count() |
554 | { |
555 | int c = (desc == 0 ? 0 : 1); |
556 | Option* p = first(); |
557 | while (!p->isLast()) |
558 | { |
559 | ++c; |
560 | p = p->next_; |
561 | }; |
562 | return c; |
563 | } |
564 | |
565 | /** |
566 | * @brief Returns true iff this is the first element of the linked list. |
567 | * |
568 | * The first element in the linked list is the first option on the command line |
569 | * that has the respective Descriptor::index value. |
570 | * |
571 | * Returns true for an unused/invalid option. |
572 | */ |
573 | bool isFirst() const |
574 | { |
575 | return isTagged(prev_); |
576 | } |
577 | |
578 | /** |
579 | * @brief Returns true iff this is the last element of the linked list. |
580 | * |
581 | * The last element in the linked list is the last option on the command line |
582 | * that has the respective Descriptor::index value. |
583 | * |
584 | * Returns true for an unused/invalid option. |
585 | */ |
586 | bool isLast() const |
587 | { |
588 | return isTagged(next_); |
589 | } |
590 | |
591 | /** |
592 | * @brief Returns a pointer to the first element of the linked list. |
593 | * |
594 | * Use this when you want the first occurrence of an option on the command line to |
595 | * take precedence. Note that this is not the way most programs handle options. |
596 | * You should probably be using last() instead. |
597 | * |
598 | * @note |
599 | * This method may be called on an unused/invalid option and will return a pointer to the |
600 | * option itself. |
601 | */ |
602 | Option* first() |
603 | { |
604 | Option* p = this; |
605 | while (!p->isFirst()) |
606 | p = p->prev_; |
607 | return p; |
608 | } |
609 | |
610 | /** |
611 | * @brief Returns a pointer to the last element of the linked list. |
612 | * |
613 | * Use this when you want the last occurrence of an option on the command line to |
614 | * take precedence. This is the most common way of handling conflicting options. |
615 | * |
616 | * @note |
617 | * This method may be called on an unused/invalid option and will return a pointer to the |
618 | * option itself. |
619 | * |
620 | * @par Tip: |
621 | * If you have options with opposite meanings (e.g. @c --enable-foo and @c --disable-foo), you |
622 | * can assign them the same Descriptor::index to get them into the same list. Distinguish them by |
623 | * Descriptor::type and all you have to do is check <code> last()->type() </code> to get |
624 | * the state listed last on the command line. |
625 | */ |
626 | Option* last() |
627 | { |
628 | return first()->prevwrap(); |
629 | } |
630 | |
631 | /** |
632 | * @brief Returns a pointer to the previous element of the linked list or NULL if |
633 | * called on first(). |
634 | * |
635 | * If called on first() this method returns NULL. Otherwise it will return the |
636 | * option with the same Descriptor::index that precedes this option on the command |
637 | * line. |
638 | */ |
639 | Option* prev() |
640 | { |
641 | return isFirst() ? 0 : prev_; |
642 | } |
643 | |
644 | /** |
645 | * @brief Returns a pointer to the previous element of the linked list with wrap-around from |
646 | * first() to last(). |
647 | * |
648 | * If called on first() this method returns last(). Otherwise it will return the |
649 | * option with the same Descriptor::index that precedes this option on the command |
650 | * line. |
651 | */ |
652 | Option* prevwrap() |
653 | { |
654 | return untag(prev_); |
655 | } |
656 | |
657 | /** |
658 | * @brief Returns a pointer to the next element of the linked list or NULL if called |
659 | * on last(). |
660 | * |
661 | * If called on last() this method returns NULL. Otherwise it will return the |
662 | * option with the same Descriptor::index that follows this option on the command |
663 | * line. |
664 | */ |
665 | Option* next() |
666 | { |
667 | return isLast() ? 0 : next_; |
668 | } |
669 | |
670 | /** |
671 | * @brief Returns a pointer to the next element of the linked list with wrap-around from |
672 | * last() to first(). |
673 | * |
674 | * If called on last() this method returns first(). Otherwise it will return the |
675 | * option with the same Descriptor::index that follows this option on the command |
676 | * line. |
677 | */ |
678 | Option* nextwrap() |
679 | { |
680 | return untag(next_); |
681 | } |
682 | |
683 | /** |
684 | * @brief Makes @c new_last the new last() by chaining it into the list after last(). |
685 | * |
686 | * It doesn't matter which element you call append() on. The new element will always |
687 | * be appended to last(). |
688 | * |
689 | * @attention |
690 | * @c new_last must not yet be part of a list, or that list will become corrupted, because |
691 | * this method does not unchain @c new_last from an existing list. |
692 | */ |
693 | void append(Option* new_last) |
694 | { |
695 | Option* p = last(); |
696 | Option* f = first(); |
697 | p->next_ = new_last; |
698 | new_last->prev_ = p; |
699 | new_last->next_ = tag(f); |
700 | f->prev_ = tag(new_last); |
701 | } |
702 | |
703 | /** |
704 | * @brief Casts from Option to const Option* but only if this Option is valid. |
705 | * |
706 | * If this Option is valid (i.e. @c desc!=NULL), returns this. |
707 | * Otherwise returns NULL. This allows testing an Option directly |
708 | * in an if-clause to see if it is used: |
709 | * @code |
710 | * if (options[CREATE]) |
711 | * { |
712 | * ... |
713 | * } |
714 | * @endcode |
715 | * It also allows you to write loops like this: |
716 | * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) |
717 | * fname = opt->arg; ... @endcode |
718 | */ |
719 | operator const Option*() const |
720 | { |
721 | return desc ? this : 0; |
722 | } |
723 | |
724 | /** |
725 | * @brief Casts from Option to Option* but only if this Option is valid. |
726 | * |
727 | * If this Option is valid (i.e. @c desc!=NULL), returns this. |
728 | * Otherwise returns NULL. This allows testing an Option directly |
729 | * in an if-clause to see if it is used: |
730 | * @code |
731 | * if (options[CREATE]) |
732 | * { |
733 | * ... |
734 | * } |
735 | * @endcode |
736 | * It also allows you to write loops like this: |
737 | * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) |
738 | * fname = opt->arg; ... @endcode |
739 | */ |
740 | operator Option*() |
741 | { |
742 | return desc ? this : 0; |
743 | } |
744 | |
745 | /** |
746 | * @brief Creates a new Option that is a one-element linked list and has NULL |
747 | * @ref desc, @ref name, @ref arg and @ref namelen. |
748 | */ |
749 | Option() : |
750 | desc(0), name(0), arg(0), namelen(0) |
751 | { |
752 | prev_ = tag(this); |
753 | next_ = tag(this); |
754 | } |
755 | |
756 | /** |
757 | * @brief Creates a new Option that is a one-element linked list and has the given |
758 | * values for @ref desc, @ref name and @ref arg. |
759 | * |
760 | * If @c name_ points at a character other than '-' it will be assumed to refer to a |
761 | * short option and @ref namelen will be set to 1. Otherwise the length will extend to |
762 | * the first '=' character or the string's 0-terminator. |
763 | */ |
764 | Option(const Descriptor* desc_, const char* name_, const char* arg_) |
765 | { |
766 | init(desc_, name_, arg_); |
767 | } |
768 | |
769 | /** |
770 | * @brief Makes @c *this a copy of @c orig except for the linked list pointers. |
771 | * |
772 | * After this operation @c *this will be a one-element linked list. |
773 | */ |
774 | void operator=(const Option& orig) |
775 | { |
776 | init(orig.desc, orig.name, orig.arg); |
777 | } |
778 | |
779 | /** |
780 | * @brief Makes @c *this a copy of @c orig except for the linked list pointers. |
781 | * |
782 | * After this operation @c *this will be a one-element linked list. |
783 | */ |
784 | Option(const Option& orig) |
785 | { |
786 | init(orig.desc, orig.name, orig.arg); |
787 | } |
788 | |
789 | private: |
790 | /** |
791 | * @internal |
792 | * @brief Sets the fields of this Option to the given values (extracting @c name if necessary). |
793 | * |
794 | * If @c name_ points at a character other than '-' it will be assumed to refer to a |
795 | * short option and @ref namelen will be set to 1. Otherwise the length will extend to |
796 | * the first '=' character or the string's 0-terminator. |
797 | */ |
798 | void init(const Descriptor* desc_, const char* name_, const char* arg_) |
799 | { |
800 | desc = desc_; |
801 | name = name_; |
802 | arg = arg_; |
803 | prev_ = tag(this); |
804 | next_ = tag(this); |
805 | namelen = 0; |
806 | if (name == 0) |
807 | return; |
808 | namelen = 1; |
809 | if (name[0] != '-') |
810 | return; |
811 | while (name[namelen] != 0 && name[namelen] != '=') |
812 | ++namelen; |
813 | } |
814 | |
815 | static Option* tag(Option* ptr) |
816 | { |
817 | return (Option*) ((unsigned long long) ptr | 1); |
818 | } |
819 | |
820 | static Option* untag(Option* ptr) |
821 | { |
822 | return (Option*) ((unsigned long long) ptr & ~1ull); |
823 | } |
824 | |
825 | static bool isTagged(Option* ptr) |
826 | { |
827 | return ((unsigned long long) ptr & 1); |
828 | } |
829 | }; |
830 | |
831 | /** |
832 | * @brief Functions for checking the validity of option arguments. |
833 | * |
834 | * @copydetails CheckArg |
835 | * |
836 | * The following example code |
837 | * can serve as starting place for writing your own more complex CheckArg functions: |
838 | * @code |
839 | * struct Arg: public option::Arg |
840 | * { |
841 | * static void printError(const char* msg1, const option::Option& opt, const char* msg2) |
842 | * { |
843 | * fprintf(stderr, "ERROR: %s", msg1); |
844 | * fwrite(opt.name, opt.namelen, 1, stderr); |
845 | * fprintf(stderr, "%s", msg2); |
846 | * } |
847 | * |
848 | * static option::ArgStatus Unknown(const option::Option& option, bool msg) |
849 | * { |
850 | * if (msg) printError("Unknown option '", option, "'\n"); |
851 | * return option::ARG_ILLEGAL; |
852 | * } |
853 | * |
854 | * static option::ArgStatus Required(const option::Option& option, bool msg) |
855 | * { |
856 | * if (option.arg != 0) |
857 | * return option::ARG_OK; |
858 | * |
859 | * if (msg) printError("Option '", option, "' requires an argument\n"); |
860 | * return option::ARG_ILLEGAL; |
861 | * } |
862 | * |
863 | * static option::ArgStatus NonEmpty(const option::Option& option, bool msg) |
864 | * { |
865 | * if (option.arg != 0 && option.arg[0] != 0) |
866 | * return option::ARG_OK; |
867 | * |
868 | * if (msg) printError("Option '", option, "' requires a non-empty argument\n"); |
869 | * return option::ARG_ILLEGAL; |
870 | * } |
871 | * |
872 | * static option::ArgStatus Numeric(const option::Option& option, bool msg) |
873 | * { |
874 | * char* endptr = 0; |
875 | * if (option.arg != 0 && strtol(option.arg, &endptr, 10)){}; |
876 | * if (endptr != option.arg && *endptr == 0) |
877 | * return option::ARG_OK; |
878 | * |
879 | * if (msg) printError("Option '", option, "' requires a numeric argument\n"); |
880 | * return option::ARG_ILLEGAL; |
881 | * } |
882 | * }; |
883 | * @endcode |
884 | */ |
885 | struct Arg |
886 | { |
887 | //! @brief For options that don't take an argument: Returns ARG_NONE. |
888 | static ArgStatus None(const Option&, bool) |
889 | { |
890 | return ARG_NONE; |
891 | } |
892 | |
893 | //! @brief Returns ARG_OK if the argument is attached and ARG_IGNORE otherwise. |
894 | static ArgStatus Optional(const Option& option, bool) |
895 | { |
896 | if (option.arg && option.name[option.namelen] != 0) |
897 | return ARG_OK; |
898 | else |
899 | return ARG_IGNORE; |
900 | } |
901 | }; |
902 | |
903 | /** |
904 | * @brief Determines the minimum lengths of the buffer and options arrays used for Parser. |
905 | * |
906 | * Because Parser doesn't use dynamic memory its output arrays have to be pre-allocated. |
907 | * If you don't want to use fixed size arrays (which may turn out too small, causing |
908 | * command line arguments to be dropped), you can use Stats to determine the correct sizes. |
909 | * Stats work cumulative. You can first pass in your default options and then the real |
910 | * options and afterwards the counts will reflect the union. |
911 | */ |
912 | struct Stats |
913 | { |
914 | /** |
915 | * @brief Number of elements needed for a @c buffer[] array to be used for |
916 | * @ref Parser::parse() "parsing" the same argument vectors that were fed |
917 | * into this Stats object. |
918 | * |
919 | * @note |
920 | * This number is always 1 greater than the actual number needed, to give |
921 | * you a sentinel element. |
922 | */ |
923 | unsigned buffer_max; |
924 | |
925 | /** |
926 | * @brief Number of elements needed for an @c options[] array to be used for |
927 | * @ref Parser::parse() "parsing" the same argument vectors that were fed |
928 | * into this Stats object. |
929 | * |
930 | * @note |
931 | * @li This number is always 1 greater than the actual number needed, to give |
932 | * you a sentinel element. |
933 | * @li This number depends only on the @c usage, not the argument vectors, because |
934 | * the @c options array needs exactly one slot for each possible Descriptor::index. |
935 | */ |
936 | unsigned options_max; |
937 | |
938 | /** |
939 | * @brief Creates a Stats object with counts set to 1 (for the sentinel element). |
940 | */ |
941 | Stats() : |
942 | buffer_max(1), options_max(1) // 1 more than necessary as sentinel |
943 | { |
944 | } |
945 | |
946 | /** |
947 | * @brief Creates a new Stats object and immediately updates it for the |
948 | * given @c usage and argument vector. You may pass 0 for @c argc and/or @c argv, |
949 | * if you just want to update @ref options_max. |
950 | * |
951 | * @note |
952 | * The calls to Stats methods must match the later calls to Parser methods. |
953 | * See Parser::parse() for the meaning of the arguments. |
954 | */ |
955 | Stats(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // |
956 | bool single_minus_longopt = false) : |
957 | buffer_max(1), options_max(1) // 1 more than necessary as sentinel |
958 | { |
959 | add(gnu, usage, argc, argv, min_abbr_len, single_minus_longopt); |
960 | } |
961 | |
962 | //! @brief Stats(...) with non-const argv. |
963 | Stats(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // |
964 | bool single_minus_longopt = false) : |
965 | buffer_max(1), options_max(1) // 1 more than necessary as sentinel |
966 | { |
967 | add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); |
968 | } |
969 | |
970 | //! @brief POSIX Stats(...) (gnu==false). |
971 | Stats(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // |
972 | bool single_minus_longopt = false) : |
973 | buffer_max(1), options_max(1) // 1 more than necessary as sentinel |
974 | { |
975 | add(false, usage, argc, argv, min_abbr_len, single_minus_longopt); |
976 | } |
977 | |
978 | //! @brief POSIX Stats(...) (gnu==false) with non-const argv. |
979 | Stats(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // |
980 | bool single_minus_longopt = false) : |
981 | buffer_max(1), options_max(1) // 1 more than necessary as sentinel |
982 | { |
983 | add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); |
984 | } |
985 | |
986 | /** |
987 | * @brief Updates this Stats object for the |
988 | * given @c usage and argument vector. You may pass 0 for @c argc and/or @c argv, |
989 | * if you just want to update @ref options_max. |
990 | * |
991 | * @note |
992 | * The calls to Stats methods must match the later calls to Parser methods. |
993 | * See Parser::parse() for the meaning of the arguments. |
994 | */ |
995 | void add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // |
996 | bool single_minus_longopt = false); |
997 | |
998 | //! @brief add() with non-const argv. |
999 | void add(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // |
1000 | bool single_minus_longopt = false) |
1001 | { |
1002 | add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); |
1003 | } |
1004 | |
1005 | //! @brief POSIX add() (gnu==false). |
1006 | void add(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // |
1007 | bool single_minus_longopt = false) |
1008 | { |
1009 | add(false, usage, argc, argv, min_abbr_len, single_minus_longopt); |
1010 | } |
1011 | |
1012 | //! @brief POSIX add() (gnu==false) with non-const argv. |
1013 | void add(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // |
1014 | bool single_minus_longopt = false) |
1015 | { |
1016 | add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); |
1017 | } |
1018 | private: |
1019 | class CountOptionsAction; |
1020 | }; |
1021 | |
1022 | /** |
1023 | * @brief Checks argument vectors for validity and parses them into data |
1024 | * structures that are easier to work with. |
1025 | * |
1026 | * @par Example: |
1027 | * @code |
1028 | * int main(int argc, char* argv[]) |
1029 | * { |
1030 | * argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present |
1031 | * option::Stats stats(usage, argc, argv); |
1032 | * option::Option options[stats.options_max], buffer[stats.buffer_max]; |
1033 | * option::Parser parse(usage, argc, argv, options, buffer); |
1034 | * |
1035 | * if (parse.error()) |
1036 | * return 1; |
1037 | * |
1038 | * if (options[HELP]) |
1039 | * ... |
1040 | * @endcode |
1041 | */ |
1042 | class Parser |
1043 | { |
1044 | int op_count; //!< @internal @brief see optionsCount() |
1045 | int nonop_count; //!< @internal @brief see nonOptionsCount() |
1046 | const char** nonop_args; //!< @internal @brief see nonOptions() |
1047 | bool err; //!< @internal @brief see error() |
1048 | public: |
1049 | |
1050 | /** |
1051 | * @brief Creates a new Parser. |
1052 | */ |
1053 | Parser() : |
1054 | op_count(0), nonop_count(0), nonop_args(0), err(false) |
1055 | { |
1056 | } |
1057 | |
1058 | /** |
1059 | * @brief Creates a new Parser and immediately parses the given argument vector. |
1060 | * @copydetails parse() |
1061 | */ |
1062 | Parser(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], |
1063 | int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : |
1064 | op_count(0), nonop_count(0), nonop_args(0), err(false) |
1065 | { |
1066 | parse(gnu, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1067 | } |
1068 | |
1069 | //! @brief Parser(...) with non-const argv. |
1070 | Parser(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], |
1071 | int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : |
1072 | op_count(0), nonop_count(0), nonop_args(0), err(false) |
1073 | { |
1074 | parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1075 | } |
1076 | |
1077 | //! @brief POSIX Parser(...) (gnu==false). |
1078 | Parser(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], int min_abbr_len = 0, |
1079 | bool single_minus_longopt = false, int bufmax = -1) : |
1080 | op_count(0), nonop_count(0), nonop_args(0), err(false) |
1081 | { |
1082 | parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1083 | } |
1084 | |
1085 | //! @brief POSIX Parser(...) (gnu==false) with non-const argv. |
1086 | Parser(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0, |
1087 | bool single_minus_longopt = false, int bufmax = -1) : |
1088 | op_count(0), nonop_count(0), nonop_args(0), err(false) |
1089 | { |
1090 | parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1091 | } |
1092 | |
1093 | /** |
1094 | * @brief Parses the given argument vector. |
1095 | * |
1096 | * @param gnu if true, parse() will not stop at the first non-option argument. Instead it will |
1097 | * reorder arguments so that all non-options are at the end. This is the default behaviour |
1098 | * of GNU getopt() but is not conforming to POSIX. @n |
1099 | * Note, that once the argument vector has been reordered, the @c gnu flag will have |
1100 | * no further effect on this argument vector. So it is enough to pass @c gnu==true when |
1101 | * creating Stats. |
1102 | * @param usage Array of Descriptor objects that describe the options to support. The last entry |
1103 | * of this array must have 0 in all fields. |
1104 | * @param argc The number of elements from @c argv that are to be parsed. If you pass -1, the number |
1105 | * will be determined automatically. In that case the @c argv list must end with a NULL |
1106 | * pointer. |
1107 | * @param argv The arguments to be parsed. If you pass -1 as @c argc the last pointer in the @c argv |
1108 | * list must be NULL to mark the end. |
1109 | * @param options Each entry is the first element of a linked list of Options. Each new option |
1110 | * that is parsed will be appended to the list specified by that Option's |
1111 | * Descriptor::index. If an entry is not yet used (i.e. the Option is invalid), |
1112 | * it will be replaced rather than appended to. @n |
1113 | * The minimum length of this array is the greatest Descriptor::index value that |
1114 | * occurs in @c usage @e PLUS ONE. |
1115 | * @param buffer Each argument that is successfully parsed (including unknown arguments, if they |
1116 | * have a Descriptor whose CheckArg does not return @ref ARG_ILLEGAL) will be stored in this |
1117 | * array. parse() scans the array for the first invalid entry and begins writing at that |
1118 | * index. You can pass @c bufmax to limit the number of options stored. |
1119 | * @param min_abbr_len Passing a value <code> min_abbr_len > 0 </code> enables abbreviated long |
1120 | * options. The parser will match a prefix of a long option as if it was |
1121 | * the full long option (e.g. @c --foob=10 will be interpreted as if it was |
1122 | * @c --foobar=10 ), as long as the prefix has at least @c min_abbr_len characters |
1123 | * (not counting the @c -- ) and is unambiguous. |
1124 | * @n Be careful if combining @c min_abbr_len=1 with @c single_minus_longopt=true |
1125 | * because the ambiguity check does not consider short options and abbreviated |
1126 | * single minus long options will take precedence over short options. |
1127 | * @param single_minus_longopt Passing @c true for this option allows long options to begin with |
1128 | * a single minus. The double minus form will still be recognized. Note that |
1129 | * single minus long options take precedence over short options and short option |
1130 | * groups. E.g. @c -file would be interpreted as @c --file and not as |
1131 | * <code> -f -i -l -e </code> (assuming a long option named @c "file" exists). |
1132 | * @param bufmax The greatest index in the @c buffer[] array that parse() will write to is |
1133 | * @c bufmax-1. If there are more options, they will be processed (in particular |
1134 | * their CheckArg will be called) but not stored. @n |
1135 | * If you used Stats::buffer_max to dimension this array, you can pass |
1136 | * -1 (or not pass @c bufmax at all) which tells parse() that the buffer is |
1137 | * "large enough". |
1138 | * @attention |
1139 | * Remember that @c options and @c buffer store Option @e objects, not pointers. Therefore it |
1140 | * is not possible for the same object to be in both arrays. For those options that are found in |
1141 | * both @c buffer[] and @c options[] the respective objects are independent copies. And only the |
1142 | * objects in @c options[] are properly linked via Option::next() and Option::prev(). |
1143 | * You can iterate over @c buffer[] to |
1144 | * process all options in the order they appear in the argument vector, but if you want access to |
1145 | * the other Options with the same Descriptor::index, then you @e must access the linked list via |
1146 | * @c options[]. You can get the linked list in options from a buffer object via something like |
1147 | * @c options[buffer[i].index()]. |
1148 | */ |
1149 | void parse(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], |
1150 | int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1); |
1151 | |
1152 | //! @brief parse() with non-const argv. |
1153 | void parse(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], |
1154 | int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) |
1155 | { |
1156 | parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1157 | } |
1158 | |
1159 | //! @brief POSIX parse() (gnu==false). |
1160 | void parse(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], |
1161 | int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) |
1162 | { |
1163 | parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1164 | } |
1165 | |
1166 | //! @brief POSIX parse() (gnu==false) with non-const argv. |
1167 | void parse(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0, |
1168 | bool single_minus_longopt = false, int bufmax = -1) |
1169 | { |
1170 | parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); |
1171 | } |
1172 | |
1173 | /** |
1174 | * @brief Returns the number of valid Option objects in @c buffer[]. |
1175 | * |
1176 | * @note |
1177 | * @li The returned value always reflects the number of Options in the buffer[] array used for |
1178 | * the most recent call to parse(). |
1179 | * @li The count (and the buffer[]) includes unknown options if they are collected |
1180 | * (see Descriptor::longopt). |
1181 | */ |
1182 | int optionsCount() |
1183 | { |
1184 | return op_count; |
1185 | } |
1186 | |
1187 | /** |
1188 | * @brief Returns the number of non-option arguments that remained at the end of the |
1189 | * most recent parse() that actually encountered non-option arguments. |
1190 | * |
1191 | * @note |
1192 | * A parse() that does not encounter non-option arguments will leave this value |
1193 | * as well as nonOptions() undisturbed. This means you can feed the Parser a |
1194 | * default argument vector that contains non-option arguments (e.g. a default filename). |
1195 | * Then you feed it the actual arguments from the user. If the user has supplied at |
1196 | * least one non-option argument, all of the non-option arguments from the default |
1197 | * disappear and are replaced by the user's non-option arguments. However, if the |
1198 | * user does not supply any non-option arguments the defaults will still be in |
1199 | * effect. |
1200 | */ |
1201 | int nonOptionsCount() |
1202 | { |
1203 | return nonop_count; |
1204 | } |
1205 | |
1206 | /** |
1207 | * @brief Returns a pointer to an array of non-option arguments (only valid |
1208 | * if <code>nonOptionsCount() >0 </code>). |
1209 | * |
1210 | * @note |
1211 | * @li parse() does not copy arguments, so this pointer points into the actual argument |
1212 | * vector as passed to parse(). |
1213 | * @li As explained at nonOptionsCount() this pointer is only changed by parse() calls |
1214 | * that actually encounter non-option arguments. A parse() call that encounters only |
1215 | * options, will not change nonOptions(). |
1216 | */ |
1217 | const char** nonOptions() |
1218 | { |
1219 | return nonop_args; |
1220 | } |
1221 | |
1222 | /** |
1223 | * @brief Returns <b><code>nonOptions()[i]</code></b> (@e without checking if i is in range!). |
1224 | */ |
1225 | const char* nonOption(int i) |
1226 | { |
1227 | return nonOptions()[i]; |
1228 | } |
1229 | |
1230 | /** |
1231 | * @brief Returns @c true if an unrecoverable error occurred while parsing options. |
1232 | * |
1233 | * An illegal argument to an option (i.e. CheckArg returns @ref ARG_ILLEGAL) is an |
1234 | * unrecoverable error that aborts the parse. Unknown options are only an error if |
1235 | * their CheckArg function returns @ref ARG_ILLEGAL. Otherwise they are collected. |
1236 | * In that case if you want to exit the program if either an illegal argument |
1237 | * or an unknown option has been passed, use code like this |
1238 | * |
1239 | * @code |
1240 | * if (parser.error() || options[UNKNOWN]) |
1241 | * exit(1); |
1242 | * @endcode |
1243 | * |
1244 | */ |
1245 | bool error() |
1246 | { |
1247 | return err; |
1248 | } |
1249 | |
1250 | private: |
1251 | friend struct Stats; |
1252 | class StoreOptionAction; |
1253 | struct Action; |
1254 | |
1255 | /** |
1256 | * @internal |
1257 | * @brief This is the core function that does all the parsing. |
1258 | * @retval false iff an unrecoverable error occurred. |
1259 | */ |
1260 | static bool workhorse(bool gnu, const Descriptor usage[], int numargs, const char** args, Action& action, |
1261 | bool single_minus_longopt, bool print_errors, int min_abbr_len); |
1262 | |
1263 | /** |
1264 | * @internal |
1265 | * @brief Returns true iff @c st1 is a prefix of @c st2 and |
1266 | * in case @c st2 is longer than @c st1, then |
1267 | * the first additional character is '='. |
1268 | * |
1269 | * @par Examples: |
1270 | * @code |
1271 | * streq("foo", "foo=bar") == true |
1272 | * streq("foo", "foobar") == false |
1273 | * streq("foo", "foo") == true |
1274 | * streq("foo=bar", "foo") == false |
1275 | * @endcode |
1276 | */ |
1277 | static bool streq(const char* st1, const char* st2) |
1278 | { |
1279 | while (*st1 != 0) |
1280 | if (*st1++ != *st2++) |
1281 | return false; |
1282 | return (*st2 == 0 || *st2 == '='); |
1283 | } |
1284 | |
1285 | /** |
1286 | * @internal |
1287 | * @brief Like streq() but handles abbreviations. |
1288 | * |
1289 | * Returns true iff @c st1 and @c st2 have a common |
1290 | * prefix with the following properties: |
1291 | * @li (if min > 0) its length is at least @c min characters or the same length as @c st1 (whichever is smaller). |
1292 | * @li (if min <= 0) its length is the same as that of @c st1 |
1293 | * @li within @c st2 the character following the common prefix is either '=' or end-of-string. |
1294 | * |
1295 | * Examples: |
1296 | * @code |
1297 | * streqabbr("foo", "foo=bar",<anything>) == true |
1298 | * streqabbr("foo", "fo=bar" , 2) == true |
1299 | * streqabbr("foo", "fo" , 2) == true |
1300 | * streqabbr("foo", "fo" , 0) == false |
1301 | * streqabbr("foo", "f=bar" , 2) == false |
1302 | * streqabbr("foo", "f" , 2) == false |
1303 | * streqabbr("fo" , "foo=bar",<anything>) == false |
1304 | * streqabbr("foo", "foobar" ,<anything>) == false |
1305 | * streqabbr("foo", "fobar" ,<anything>) == false |
1306 | * streqabbr("foo", "foo" ,<anything>) == true |
1307 | * @endcode |
1308 | */ |
1309 | static bool streqabbr(const char* st1, const char* st2, long long min) |
1310 | { |
1311 | const char* st1start = st1; |
1312 | while (*st1 != 0 && (*st1 == *st2)) |
1313 | { |
1314 | ++st1; |
1315 | ++st2; |
1316 | } |
1317 | |
1318 | return (*st1 == 0 || (min > 0 && (st1 - st1start) >= min)) && (*st2 == 0 || *st2 == '='); |
1319 | } |
1320 | |
1321 | /** |
1322 | * @internal |
1323 | * @brief Returns true iff character @c ch is contained in the string @c st. |
1324 | * |
1325 | * Returns @c true for @c ch==0 . |
1326 | */ |
1327 | static bool instr(char ch, const char* st) |
1328 | { |
1329 | while (*st != 0 && *st != ch) |
1330 | ++st; |
1331 | return *st == ch; |
1332 | } |
1333 | |
1334 | /** |
1335 | * @internal |
1336 | * @brief Rotates <code>args[-count],...,args[-1],args[0]</code> to become |
1337 | * <code>args[0],args[-count],...,args[-1]</code>. |
1338 | */ |
1339 | static void shift(const char** args, int count) |
1340 | { |
1341 | for (int i = 0; i > -count; --i) |
1342 | { |
1343 | const char* temp = args[i]; |
1344 | args[i] = args[i - 1]; |
1345 | args[i - 1] = temp; |
1346 | } |
1347 | } |
1348 | }; |
1349 | |
1350 | /** |
1351 | * @internal |
1352 | * @brief Interface for actions Parser::workhorse() should perform for each Option it |
1353 | * parses. |
1354 | */ |
1355 | struct Parser::Action |
1356 | { |
1357 | /** |
1358 | * @brief Called by Parser::workhorse() for each Option that has been successfully |
1359 | * parsed (including unknown |
1360 | * options if they have a Descriptor whose Descriptor::check_arg does not return |
1361 | * @ref ARG_ILLEGAL. |
1362 | * |
1363 | * Returns @c false iff a fatal error has occured and the parse should be aborted. |
1364 | */ |
1365 | virtual bool perform(Option&) |
1366 | { |
1367 | return true; |
1368 | } |
1369 | |
1370 | /** |
1371 | * @brief Called by Parser::workhorse() after finishing the parse. |
1372 | * @param numargs the number of non-option arguments remaining |
1373 | * @param args pointer to the first remaining non-option argument (if numargs > 0). |
1374 | * |
1375 | * @return |
1376 | * @c false iff a fatal error has occurred. |
1377 | */ |
1378 | virtual bool finished(int numargs, const char** args) |
1379 | { |
1380 | (void) numargs; |
1381 | (void) args; |
1382 | return true; |
1383 | } |
1384 | }; |
1385 | |
1386 | /** |
1387 | * @internal |
1388 | * @brief An Action to pass to Parser::workhorse() that will increment a counter for |
1389 | * each parsed Option. |
1390 | */ |
1391 | class Stats::CountOptionsAction: public Parser::Action |
1392 | { |
1393 | unsigned* buffer_max; |
1394 | public: |
1395 | /** |
1396 | * Creates a new CountOptionsAction that will increase @c *buffer_max_ for each |
1397 | * parsed Option. |
1398 | */ |
1399 | CountOptionsAction(unsigned* buffer_max_) : |
1400 | buffer_max(buffer_max_) |
1401 | { |
1402 | } |
1403 | |
1404 | bool perform(Option&) |
1405 | { |
1406 | if (*buffer_max == 0x7fffffff) |
1407 | return false; // overflow protection: don't accept number of options that doesn't fit signed int |
1408 | ++*buffer_max; |
1409 | return true; |
1410 | } |
1411 | }; |
1412 | |
1413 | /** |
1414 | * @internal |
1415 | * @brief An Action to pass to Parser::workhorse() that will store each parsed Option in |
1416 | * appropriate arrays (see Parser::parse()). |
1417 | */ |
1418 | class Parser::StoreOptionAction: public Parser::Action |
1419 | { |
1420 | Parser& parser; |
1421 | Option* options; |
1422 | Option* buffer; |
1423 | int bufmax; //! Number of slots in @c buffer. @c -1 means "large enough". |
1424 | public: |
1425 | /** |
1426 | * @brief Creates a new StoreOption action. |
1427 | * @param parser_ the parser whose op_count should be updated. |
1428 | * @param options_ each Option @c o is chained into the linked list @c options_[o.desc->index] |
1429 | * @param buffer_ each Option is appended to this array as long as there's a free slot. |
1430 | * @param bufmax_ number of slots in @c buffer_. @c -1 means "large enough". |
1431 | */ |
1432 | StoreOptionAction(Parser& parser_, Option options_[], Option buffer_[], int bufmax_) : |
1433 | parser(parser_), options(options_), buffer(buffer_), bufmax(bufmax_) |
1434 | { |
1435 | // find first empty slot in buffer (if any) |
1436 | int bufidx = 0; |
1437 | while ((bufmax < 0 || bufidx < bufmax) && buffer[bufidx]) |
1438 | ++bufidx; |
1439 | |
1440 | // set parser's optionCount |
1441 | parser.op_count = bufidx; |
1442 | } |
1443 | |
1444 | bool perform(Option& option) |
1445 | { |
1446 | if (bufmax < 0 || parser.op_count < bufmax) |
1447 | { |
1448 | if (parser.op_count == 0x7fffffff) |
1449 | return false; // overflow protection: don't accept number of options that doesn't fit signed int |
1450 | |
1451 | buffer[parser.op_count] = option; |
1452 | int idx = buffer[parser.op_count].desc->index; |
1453 | if (options[idx]) |
1454 | options[idx].append(buffer[parser.op_count]); |
1455 | else |
1456 | options[idx] = buffer[parser.op_count]; |
1457 | ++parser.op_count; |
1458 | } |
1459 | return true; // NOTE: an option that is discarded because of a full buffer is not fatal |
1460 | } |
1461 | |
1462 | bool finished(int numargs, const char** args) |
1463 | { |
1464 | // only overwrite non-option argument list if there's at least 1 |
1465 | // new non-option argument. Otherwise we keep the old list. This |
1466 | // makes it easy to use default non-option arguments. |
1467 | if (numargs > 0) |
1468 | { |
1469 | parser.nonop_count = numargs; |
1470 | parser.nonop_args = args; |
1471 | } |
1472 | |
1473 | return true; |
1474 | } |
1475 | }; |
1476 | |
1477 | inline void Parser::parse(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], |
1478 | Option buffer[], int min_abbr_len, bool single_minus_longopt, int bufmax) |
1479 | { |
1480 | StoreOptionAction action(*this, options, buffer, bufmax); |
1481 | err = !workhorse(gnu, usage, argc, argv, action, single_minus_longopt, true, min_abbr_len); |
1482 | } |
1483 | |
1484 | inline void Stats::add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len, |
1485 | bool single_minus_longopt) |
1486 | { |
1487 | // determine size of options array. This is the greatest index used in the usage + 1 |
1488 | int i = 0; |
1489 | while (usage[i].shortopt != 0) |
1490 | { |
1491 | if (usage[i].index + 1 >= options_max) |
1492 | options_max = (usage[i].index + 1) + 1; // 1 more than necessary as sentinel |
1493 | |
1494 | ++i; |
1495 | } |
1496 | |
1497 | CountOptionsAction action(&buffer_max); |
1498 | Parser::workhorse(gnu, usage, argc, argv, action, single_minus_longopt, false, min_abbr_len); |
1499 | } |
1500 | |
1501 | inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, const char** args, Action& action, |
1502 | bool single_minus_longopt, bool print_errors, int min_abbr_len) |
1503 | { |
1504 | // protect against NULL pointer |
1505 | if (args == 0) |
1506 | numargs = 0; |
1507 | |
1508 | int nonops = 0; |
1509 | |
1510 | while (numargs != 0 && *args != 0) |
1511 | { |
1512 | const char* param = *args; // param can be --long-option, -srto or non-option argument |
1513 | |
1514 | // in POSIX mode the first non-option argument terminates the option list |
1515 | // a lone minus character is a non-option argument |
1516 | if (param[0] != '-' || param[1] == 0) |
1517 | { |
1518 | if (gnu) |
1519 | { |
1520 | ++nonops; |
1521 | ++args; |
1522 | if (numargs > 0) |
1523 | --numargs; |
1524 | continue; |
1525 | } |
1526 | else |
1527 | break; |
1528 | } |
1529 | |
1530 | // -- terminates the option list. The -- itself is skipped. |
1531 | if (param[1] == '-' && param[2] == 0) |
1532 | { |
1533 | shift(args, nonops); |
1534 | ++args; |
1535 | if (numargs > 0) |
1536 | --numargs; |
1537 | break; |
1538 | } |
1539 | |
1540 | bool handle_short_options; |
1541 | const char* longopt_name; |
1542 | if (param[1] == '-') // if --long-option |
1543 | { |
1544 | handle_short_options = false; |
1545 | longopt_name = param + 2; |
1546 | } |
1547 | else |
1548 | { |
1549 | handle_short_options = true; |
1550 | longopt_name = param + 1; //for testing a potential -long-option |
1551 | } |
1552 | |
1553 | bool try_single_minus_longopt = single_minus_longopt; |
1554 | bool have_more_args = (numargs > 1 || numargs < 0); // is referencing argv[1] valid? |
1555 | |
1556 | do // loop over short options in group, for long options the body is executed only once |
1557 | { |
1558 | int idx; |
1559 | |
1560 | const char* optarg; |
1561 | |
1562 | /******************** long option **********************/ |
1563 | if (handle_short_options == false || try_single_minus_longopt) |
1564 | { |
1565 | idx = 0; |
1566 | while (usage[idx].longopt != 0 && !streq(usage[idx].longopt, longopt_name)) |
1567 | ++idx; |
1568 | |
1569 | if (usage[idx].longopt == 0 && min_abbr_len > 0) // if we should try to match abbreviated long options |
1570 | { |
1571 | int i1 = 0; |
1572 | while (usage[i1].longopt != 0 && !streqabbr(usage[i1].longopt, longopt_name, min_abbr_len)) |
1573 | ++i1; |
1574 | if (usage[i1].longopt != 0) |
1575 | { // now test if the match is unambiguous by checking for another match |
1576 | int i2 = i1 + 1; |
1577 | while (usage[i2].longopt != 0 && !streqabbr(usage[i2].longopt, longopt_name, min_abbr_len)) |
1578 | ++i2; |
1579 | |
1580 | if (usage[i2].longopt == 0) // if there was no second match it's unambiguous, so accept i1 as idx |
1581 | idx = i1; |
1582 | } |
1583 | } |
1584 | |
1585 | // if we found something, disable handle_short_options (only relevant if single_minus_longopt) |
1586 | if (usage[idx].longopt != 0) |
1587 | handle_short_options = false; |
1588 | |
1589 | try_single_minus_longopt = false; // prevent looking for longopt in the middle of shortopt group |
1590 | |
1591 | optarg = longopt_name; |
1592 | while (*optarg != 0 && *optarg != '=') |
1593 | ++optarg; |
1594 | if (*optarg == '=') // attached argument |
1595 | ++optarg; |
1596 | else |
1597 | // possibly detached argument |
1598 | optarg = (have_more_args ? args[1] : 0); |
1599 | } |
1600 | |
1601 | /************************ short option ***********************************/ |
1602 | if (handle_short_options) |
1603 | { |
1604 | if (*++param == 0) // point at the 1st/next option character |
1605 | break; // end of short option group |
1606 | |
1607 | idx = 0; |
1608 | while (usage[idx].shortopt != 0 && !instr(*param, usage[idx].shortopt)) |
1609 | ++idx; |
1610 | |
1611 | if (param[1] == 0) // if the potential argument is separate |
1612 | optarg = (have_more_args ? args[1] : 0); |
1613 | else |
1614 | // if the potential argument is attached |
1615 | optarg = param + 1; |
1616 | } |
1617 | |
1618 | const Descriptor* descriptor = &usage[idx]; |
1619 | |
1620 | if (descriptor->shortopt == 0) /************** unknown option ********************/ |
1621 | { |
1622 | // look for dummy entry (shortopt == "" and longopt == "") to use as Descriptor for unknown options |
1623 | idx = 0; |
1624 | while (usage[idx].shortopt != 0 && (usage[idx].shortopt[0] != 0 || usage[idx].longopt[0] != 0)) |
1625 | ++idx; |
1626 | descriptor = (usage[idx].shortopt == 0 ? 0 : &usage[idx]); |
1627 | } |
1628 | |
1629 | if (descriptor != 0) |
1630 | { |
1631 | Option option(descriptor, param, optarg); |
1632 | switch (descriptor->check_arg(option, print_errors)) |
1633 | { |
1634 | case ARG_ILLEGAL: |
1635 | return false; // fatal |
1636 | case ARG_OK: |
1637 | // skip one element of the argument vector, if it's a separated argument |
1638 | if (optarg != 0 && have_more_args && optarg == args[1]) |
1639 | { |
1640 | shift(args, nonops); |
1641 | if (numargs > 0) |
1642 | --numargs; |
1643 | ++args; |
1644 | } |
1645 | |
1646 | // No further short options are possible after an argument |
1647 | handle_short_options = false; |
1648 | |
1649 | break; |
1650 | case ARG_IGNORE: |
1651 | case ARG_NONE: |
1652 | option.arg = 0; |
1653 | break; |
1654 | } |
1655 | |
1656 | if (!action.perform(option)) |
1657 | return false; |
1658 | } |
1659 | |
1660 | } while (handle_short_options); |
1661 | |
1662 | shift(args, nonops); |
1663 | ++args; |
1664 | if (numargs > 0) |
1665 | --numargs; |
1666 | |
1667 | } // while |
1668 | |
1669 | if (numargs > 0 && *args == 0) // It's a bug in the caller if numargs is greater than the actual number |
1670 | numargs = 0; // of arguments, but as a service to the user we fix this if we spot it. |
1671 | |
1672 | if (numargs < 0) // if we don't know the number of remaining non-option arguments |
1673 | { // we need to count them |
1674 | numargs = 0; |
1675 | while (args[numargs] != 0) |
1676 | ++numargs; |
1677 | } |
1678 | |
1679 | return action.finished(numargs + nonops, args - nonops); |
1680 | } |
1681 | |
1682 | /** |
1683 | * @internal |
1684 | * @brief The implementation of option::printUsage(). |
1685 | */ |
1686 | struct PrintUsageImplementation |
1687 | { |
1688 | /** |
1689 | * @internal |
1690 | * @brief Interface for Functors that write (part of) a string somewhere. |
1691 | */ |
1692 | struct IStringWriter |
1693 | { |
1694 | /** |
1695 | * @brief Writes the given number of chars beginning at the given pointer somewhere. |
1696 | */ |
1697 | virtual void operator()(const char*, int) |
1698 | { |
1699 | } |
1700 | }; |
1701 | |
1702 | /** |
1703 | * @internal |
1704 | * @brief Encapsulates a function with signature <code>func(string, size)</code> where |
1705 | * string can be initialized with a const char* and size with an int. |
1706 | */ |
1707 | template<typename Function> |
1708 | struct FunctionWriter: public IStringWriter |
1709 | { |
1710 | Function* write; |
1711 | |
1712 | virtual void operator()(const char* str, int size) |
1713 | { |
1714 | (*write)(str, size); |
1715 | } |
1716 | |
1717 | FunctionWriter(Function* w) : |
1718 | write(w) |
1719 | { |
1720 | } |
1721 | }; |
1722 | |
1723 | /** |
1724 | * @internal |
1725 | * @brief Encapsulates a reference to an object with a <code>write(string, size)</code> |
1726 | * method like that of @c std::ostream. |
1727 | */ |
1728 | template<typename OStream> |
1729 | struct OStreamWriter: public IStringWriter |
1730 | { |
1731 | OStream& ostream; |
1732 | |
1733 | virtual void operator()(const char* str, int size) |
1734 | { |
1735 | ostream.write(str, size); |
1736 | } |
1737 | |
1738 | OStreamWriter(OStream& o) : |
1739 | ostream(o) |
1740 | { |
1741 | } |
1742 | }; |
1743 | |
1744 | /** |
1745 | * @internal |
1746 | * @brief Like OStreamWriter but encapsulates a @c const reference, which is |
1747 | * typically a temporary object of a user class. |
1748 | */ |
1749 | template<typename Temporary> |
1750 | struct TemporaryWriter: public IStringWriter |
1751 | { |
1752 | const Temporary& userstream; |
1753 | |
1754 | virtual void operator()(const char* str, int size) |
1755 | { |
1756 | userstream.write(str, size); |
1757 | } |
1758 | |
1759 | TemporaryWriter(const Temporary& u) : |
1760 | userstream(u) |
1761 | { |
1762 | } |
1763 | }; |
1764 | |
1765 | /** |
1766 | * @internal |
1767 | * @brief Encapsulates a function with the signature <code>func(fd, string, size)</code> (the |
1768 | * signature of the @c write() system call) |
1769 | * where fd can be initialized from an int, string from a const char* and size from an int. |
1770 | */ |
1771 | template<typename Syscall> |
1772 | struct SyscallWriter: public IStringWriter |
1773 | { |
1774 | Syscall* write; |
1775 | int fd; |
1776 | |
1777 | virtual void operator()(const char* str, int size) |
1778 | { |
1779 | (*write)(fd, str, size); |
1780 | } |
1781 | |
1782 | SyscallWriter(Syscall* w, int f) : |
1783 | write(w), fd(f) |
1784 | { |
1785 | } |
1786 | }; |
1787 | |
1788 | /** |
1789 | * @internal |
1790 | * @brief Encapsulates a function with the same signature as @c std::fwrite(). |
1791 | */ |
1792 | template<typename Function, typename Stream> |
1793 | struct StreamWriter: public IStringWriter |
1794 | { |
1795 | Function* fwrite; |
1796 | Stream* stream; |
1797 | |
1798 | virtual void operator()(const char* str, int size) |
1799 | { |
1800 | (*fwrite)(str, size, 1, stream); |
1801 | } |
1802 | |
1803 | StreamWriter(Function* w, Stream* s) : |
1804 | fwrite(w), stream(s) |
1805 | { |
1806 | } |
1807 | }; |
1808 | |
1809 | /** |
1810 | * @internal |
1811 | * @brief Sets <code> i1 = max(i1, i2) </code> |
1812 | */ |
1813 | static void upmax(int& i1, int i2) |
1814 | { |
1815 | i1 = (i1 >= i2 ? i1 : i2); |
1816 | } |
1817 | |
1818 | /** |
1819 | * @internal |
1820 | * @brief Moves the "cursor" to column @c want_x assuming it is currently at column @c x |
1821 | * and sets @c x=want_x . |
1822 | * If <code> x > want_x </code>, a line break is output before indenting. |
1823 | * |
1824 | * @param write Spaces and possibly a line break are written via this functor to get |
1825 | * the desired indentation @c want_x . |
1826 | * @param[in,out] x the current indentation. Set to @c want_x by this method. |
1827 | * @param want_x the desired indentation. |
1828 | */ |
1829 | static void indent(IStringWriter& write, int& x, int want_x) |
1830 | { |
1831 | int indent = want_x - x; |
1832 | if (indent < 0) |
1833 | { |
1834 | write("\n" , 1); |
1835 | indent = want_x; |
1836 | } |
1837 | |
1838 | if (indent > 0) |
1839 | { |
1840 | char space = ' '; |
1841 | for (int i = 0; i < indent; ++i) |
1842 | write(&space, 1); |
1843 | x = want_x; |
1844 | } |
1845 | } |
1846 | |
1847 | /** |
1848 | * @brief Returns true if ch is the unicode code point of a wide character. |
1849 | * |
1850 | * @note |
1851 | * The following character ranges are treated as wide |
1852 | * @code |
1853 | * 1100..115F |
1854 | * 2329..232A (just 2 characters!) |
1855 | * 2E80..A4C6 except for 303F |
1856 | * A960..A97C |
1857 | * AC00..D7FB |
1858 | * F900..FAFF |
1859 | * FE10..FE6B |
1860 | * FF01..FF60 |
1861 | * FFE0..FFE6 |
1862 | * 1B000...... |
1863 | * @endcode |
1864 | */ |
1865 | static bool isWideChar(unsigned ch) |
1866 | { |
1867 | if (ch == 0x303F) |
1868 | return false; |
1869 | |
1870 | return ((0x1100 <= ch && ch <= 0x115F) || (0x2329 <= ch && ch <= 0x232A) || (0x2E80 <= ch && ch <= 0xA4C6) |
1871 | || (0xA960 <= ch && ch <= 0xA97C) || (0xAC00 <= ch && ch <= 0xD7FB) || (0xF900 <= ch && ch <= 0xFAFF) |
1872 | || (0xFE10 <= ch && ch <= 0xFE6B) || (0xFF01 <= ch && ch <= 0xFF60) || (0xFFE0 <= ch && ch <= 0xFFE6) |
1873 | || (0x1B000 <= ch)); |
1874 | } |
1875 | |
1876 | /** |
1877 | * @internal |
1878 | * @brief Splits a @c Descriptor[] array into tables, rows, lines and columns and |
1879 | * iterates over these components. |
1880 | * |
1881 | * The top-level organizational unit is the @e table. |
1882 | * A table begins at a Descriptor with @c help!=NULL and extends up to |
1883 | * a Descriptor with @c help==NULL. |
1884 | * |
1885 | * A table consists of @e rows. Due to line-wrapping and explicit breaks |
1886 | * a row may take multiple lines on screen. Rows within the table are separated |
1887 | * by \\n. They never cross Descriptor boundaries. This means a row ends either |
1888 | * at \\n or the 0 at the end of the help string. |
1889 | * |
1890 | * A row consists of columns/cells. Columns/cells within a row are separated by \\t. |
1891 | * Line breaks within a cell are marked by \\v. |
1892 | * |
1893 | * Rows in the same table need not have the same number of columns/cells. The |
1894 | * extreme case are interjections, which are rows that contain neither \\t nor \\v. |
1895 | * These are NOT treated specially by LinePartIterator, but they are treated |
1896 | * specially by printUsage(). |
1897 | * |
1898 | * LinePartIterator iterates through the usage at 3 levels: table, row and part. |
1899 | * Tables and rows are as described above. A @e part is a line within a cell. |
1900 | * LinePartIterator iterates through 1st parts of all cells, then through the 2nd |
1901 | * parts of all cells (if any),... @n |
1902 | * Example: The row <code> "1 \v 3 \t 2 \v 4" </code> has 2 cells/columns and 4 parts. |
1903 | * The parts will be returned in the order 1, 2, 3, 4. |
1904 | * |
1905 | * It is possible that some cells have fewer parts than others. In this case |
1906 | * LinePartIterator will "fill up" these cells with 0-length parts. IOW, LinePartIterator |
1907 | * always returns the same number of parts for each column. Note that this is different |
1908 | * from the way rows and columns are handled. LinePartIterator does @e not guarantee that |
1909 | * the same number of columns will be returned for each row. |
1910 | * |
1911 | */ |
1912 | class LinePartIterator |
1913 | { |
1914 | const Descriptor* tablestart; //!< The 1st descriptor of the current table. |
1915 | const Descriptor* rowdesc; //!< The Descriptor that contains the current row. |
1916 | const char* rowstart; //!< Ptr to 1st character of current row within rowdesc->help. |
1917 | const char* ptr; //!< Ptr to current part within the current row. |
1918 | int col; //!< Index of current column. |
1919 | int len; //!< Length of the current part (that ptr points at) in BYTES |
1920 | int screenlen; //!< Length of the current part in screen columns (taking narrow/wide chars into account). |
1921 | int max_line_in_block; //!< Greatest index of a line within the block. This is the number of \\v within the cell with the most \\vs. |
1922 | int line_in_block; //!< Line index within the current cell of the current part. |
1923 | int target_line_in_block; //!< Line index of the parts we should return to the user on this iteration. |
1924 | bool hit_target_line; //!< Flag whether we encountered a part with line index target_line_in_block in the current cell. |
1925 | |
1926 | /** |
1927 | * @brief Determines the byte and character lengths of the part at @ref ptr and |
1928 | * stores them in @ref len and @ref screenlen respectively. |
1929 | */ |
1930 | void update_length() |
1931 | { |
1932 | screenlen = 0; |
1933 | for (len = 0; ptr[len] != 0 && ptr[len] != '\v' && ptr[len] != '\t' && ptr[len] != '\n'; ++len) |
1934 | { |
1935 | ++screenlen; |
1936 | unsigned ch = (unsigned char) ptr[len]; |
1937 | if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte |
1938 | { |
1939 | // int __builtin_clz (unsigned int x) |
1940 | // Returns the number of leading 0-bits in x, starting at the most significant bit |
1941 | unsigned mask = (unsigned) -1 >> __builtin_clz(ch ^ 0xff); |
1942 | ch = ch & mask; // mask out length bits, we don't verify their correctness |
1943 | while (((unsigned char) ptr[len + 1] ^ 0x80) <= 0x3F) // while next byte is continuation byte |
1944 | { |
1945 | ch = (ch << 6) ^ (unsigned char) ptr[len + 1] ^ 0x80; // add continuation to char code |
1946 | ++len; |
1947 | } |
1948 | // ch is the decoded unicode code point |
1949 | if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case |
1950 | ++screenlen; |
1951 | } |
1952 | } |
1953 | } |
1954 | |
1955 | public: |
1956 | //! @brief Creates an iterator for @c usage. |
1957 | LinePartIterator(const Descriptor usage[]) : |
1958 | tablestart(usage), rowdesc(0), rowstart(0), ptr(0), col(-1), len(0), max_line_in_block(0), line_in_block(0), |
1959 | target_line_in_block(0), hit_target_line(true) |
1960 | { |
1961 | } |
1962 | |
1963 | /** |
1964 | * @brief Moves iteration to the next table (if any). Has to be called once on a new |
1965 | * LinePartIterator to move to the 1st table. |
1966 | * @retval false if moving to next table failed because no further table exists. |
1967 | */ |
1968 | bool nextTable() |
1969 | { |
1970 | // If this is NOT the first time nextTable() is called after the constructor, |
1971 | // then skip to the next table break (i.e. a Descriptor with help == 0) |
1972 | if (rowdesc != 0) |
1973 | { |
1974 | while (tablestart->help != 0 && tablestart->shortopt != 0) |
1975 | ++tablestart; |
1976 | } |
1977 | |
1978 | // Find the next table after the break (if any) |
1979 | while (tablestart->help == 0 && tablestart->shortopt != 0) |
1980 | ++tablestart; |
1981 | |
1982 | restartTable(); |
1983 | return rowstart != 0; |
1984 | } |
1985 | |
1986 | /** |
1987 | * @brief Reset iteration to the beginning of the current table. |
1988 | */ |
1989 | void restartTable() |
1990 | { |
1991 | rowdesc = tablestart; |
1992 | rowstart = tablestart->help; |
1993 | ptr = 0; |
1994 | } |
1995 | |
1996 | /** |
1997 | * @brief Moves iteration to the next row (if any). Has to be called once after each call to |
1998 | * @ref nextTable() to move to the 1st row of the table. |
1999 | * @retval false if moving to next row failed because no further row exists. |
2000 | */ |
2001 | bool nextRow() |
2002 | { |
2003 | if (ptr == 0) |
2004 | { |
2005 | restartRow(); |
2006 | return rowstart != 0; |
2007 | } |
2008 | |
2009 | while (*ptr != 0 && *ptr != '\n') |
2010 | ++ptr; |
2011 | |
2012 | if (*ptr == 0) |
2013 | { |
2014 | if ((rowdesc + 1)->help == 0) // table break |
2015 | return false; |
2016 | |
2017 | ++rowdesc; |
2018 | rowstart = rowdesc->help; |
2019 | } |
2020 | else // if (*ptr == '\n') |
2021 | { |
2022 | rowstart = ptr + 1; |
2023 | } |
2024 | |
2025 | restartRow(); |
2026 | return true; |
2027 | } |
2028 | |
2029 | /** |
2030 | * @brief Reset iteration to the beginning of the current row. |
2031 | */ |
2032 | void restartRow() |
2033 | { |
2034 | ptr = rowstart; |
2035 | col = -1; |
2036 | len = 0; |
2037 | screenlen = 0; |
2038 | max_line_in_block = 0; |
2039 | line_in_block = 0; |
2040 | target_line_in_block = 0; |
2041 | hit_target_line = true; |
2042 | } |
2043 | |
2044 | /** |
2045 | * @brief Moves iteration to the next part (if any). Has to be called once after each call to |
2046 | * @ref nextRow() to move to the 1st part of the row. |
2047 | * @retval false if moving to next part failed because no further part exists. |
2048 | * |
2049 | * See @ref LinePartIterator for details about the iteration. |
2050 | */ |
2051 | bool next() |
2052 | { |
2053 | if (ptr == 0) |
2054 | return false; |
2055 | |
2056 | if (col == -1) |
2057 | { |
2058 | col = 0; |
2059 | update_length(); |
2060 | return true; |
2061 | } |
2062 | |
2063 | ptr += len; |
2064 | while (true) |
2065 | { |
2066 | switch (*ptr) |
2067 | { |
2068 | case '\v': |
2069 | upmax(max_line_in_block, ++line_in_block); |
2070 | ++ptr; |
2071 | break; |
2072 | case '\t': |
2073 | if (!hit_target_line) // if previous column did not have the targetline |
2074 | { // then "insert" a 0-length part |
2075 | update_length(); |
2076 | hit_target_line = true; |
2077 | return true; |
2078 | } |
2079 | |
2080 | hit_target_line = false; |
2081 | line_in_block = 0; |
2082 | ++col; |
2083 | ++ptr; |
2084 | break; |
2085 | case 0: |
2086 | case '\n': |
2087 | if (!hit_target_line) // if previous column did not have the targetline |
2088 | { // then "insert" a 0-length part |
2089 | update_length(); |
2090 | hit_target_line = true; |
2091 | return true; |
2092 | } |
2093 | |
2094 | if (++target_line_in_block > max_line_in_block) |
2095 | { |
2096 | update_length(); |
2097 | return false; |
2098 | } |
2099 | |
2100 | hit_target_line = false; |
2101 | line_in_block = 0; |
2102 | col = 0; |
2103 | ptr = rowstart; |
2104 | continue; |
2105 | default: |
2106 | ++ptr; |
2107 | continue; |
2108 | } // switch |
2109 | |
2110 | if (line_in_block == target_line_in_block) |
2111 | { |
2112 | update_length(); |
2113 | hit_target_line = true; |
2114 | return true; |
2115 | } |
2116 | } // while |
2117 | } |
2118 | |
2119 | /** |
2120 | * @brief Returns the index (counting from 0) of the column in which |
2121 | * the part pointed to by @ref data() is located. |
2122 | */ |
2123 | int column() |
2124 | { |
2125 | return col; |
2126 | } |
2127 | |
2128 | /** |
2129 | * @brief Returns the index (counting from 0) of the line within the current column |
2130 | * this part belongs to. |
2131 | */ |
2132 | int line() |
2133 | { |
2134 | return target_line_in_block; // NOT line_in_block !!! It would be wrong if !hit_target_line |
2135 | } |
2136 | |
2137 | /** |
2138 | * @brief Returns the length of the part pointed to by @ref data() in raw chars (not UTF-8 characters). |
2139 | */ |
2140 | int length() |
2141 | { |
2142 | return len; |
2143 | } |
2144 | |
2145 | /** |
2146 | * @brief Returns the width in screen columns of the part pointed to by @ref data(). |
2147 | * Takes multi-byte UTF-8 sequences and wide characters into account. |
2148 | */ |
2149 | int screenLength() |
2150 | { |
2151 | return screenlen; |
2152 | } |
2153 | |
2154 | /** |
2155 | * @brief Returns the current part of the iteration. |
2156 | */ |
2157 | const char* data() |
2158 | { |
2159 | return ptr; |
2160 | } |
2161 | }; |
2162 | |
2163 | /** |
2164 | * @internal |
2165 | * @brief Takes input and line wraps it, writing out one line at a time so that |
2166 | * it can be interleaved with output from other columns. |
2167 | * |
2168 | * The LineWrapper is used to handle the last column of each table as well as interjections. |
2169 | * The LineWrapper is called once for each line of output. If the data given to it fits |
2170 | * into the designated width of the last column it is simply written out. If there |
2171 | * is too much data, an appropriate split point is located and only the data up to this |
2172 | * split point is written out. The rest of the data is queued for the next line. |
2173 | * That way the last column can be line wrapped and interleaved with data from |
2174 | * other columns. The following example makes this clearer: |
2175 | * @code |
2176 | * Column 1,1 Column 2,1 This is a long text |
2177 | * Column 1,2 Column 2,2 that does not fit into |
2178 | * a single line. |
2179 | * @endcode |
2180 | * |
2181 | * The difficulty in producing this output is that the whole string |
2182 | * "This is a long text that does not fit into a single line" is the |
2183 | * 1st and only part of column 3. In order to produce the above |
2184 | * output the string must be output piecemeal, interleaved with |
2185 | * the data from the other columns. |
2186 | */ |
2187 | class LineWrapper |
2188 | { |
2189 | static const int bufmask = 15; //!< Must be a power of 2 minus 1. |
2190 | /** |
2191 | * @brief Ring buffer for length component of pair (data, length). |
2192 | */ |
2193 | int lenbuf[bufmask + 1]; |
2194 | /** |
2195 | * @brief Ring buffer for data component of pair (data, length). |
2196 | */ |
2197 | const char* datbuf[bufmask + 1]; |
2198 | /** |
2199 | * @brief The indentation of the column to which the LineBuffer outputs. LineBuffer |
2200 | * assumes that the indentation has already been written when @ref process() |
2201 | * is called, so this value is only used when a buffer flush requires writing |
2202 | * additional lines of output. |
2203 | */ |
2204 | int x; |
2205 | /** |
2206 | * @brief The width of the column to line wrap. |
2207 | */ |
2208 | int width; |
2209 | int head; //!< @brief index for next write |
2210 | int tail; //!< @brief index for next read - 1 (i.e. increment tail BEFORE read) |
2211 | |
2212 | /** |
2213 | * @brief Multiple methods of LineWrapper may decide to flush part of the buffer to |
2214 | * free up space. The contract of process() says that only 1 line is output. So |
2215 | * this variable is used to track whether something has output a line. It is |
2216 | * reset at the beginning of process() and checked at the end to decide if |
2217 | * output has already occurred or is still needed. |
2218 | */ |
2219 | bool wrote_something; |
2220 | |
2221 | bool buf_empty() |
2222 | { |
2223 | return ((tail + 1) & bufmask) == head; |
2224 | } |
2225 | |
2226 | bool buf_full() |
2227 | { |
2228 | return tail == head; |
2229 | } |
2230 | |
2231 | void buf_store(const char* data, int len) |
2232 | { |
2233 | lenbuf[head] = len; |
2234 | datbuf[head] = data; |
2235 | head = (head + 1) & bufmask; |
2236 | } |
2237 | |
2238 | //! @brief Call BEFORE reading ...buf[tail]. |
2239 | void buf_next() |
2240 | { |
2241 | tail = (tail + 1) & bufmask; |
2242 | } |
2243 | |
2244 | /** |
2245 | * @brief Writes (data,len) into the ring buffer. If the buffer is full, a single line |
2246 | * is flushed out of the buffer into @c write. |
2247 | */ |
2248 | void output(IStringWriter& write, const char* data, int len) |
2249 | { |
2250 | if (buf_full()) |
2251 | write_one_line(write); |
2252 | |
2253 | buf_store(data, len); |
2254 | } |
2255 | |
2256 | /** |
2257 | * @brief Writes a single line of output from the buffer to @c write. |
2258 | */ |
2259 | void write_one_line(IStringWriter& write) |
2260 | { |
2261 | if (wrote_something) // if we already wrote something, we need to start a new line |
2262 | { |
2263 | write("\n" , 1); |
2264 | int _ = 0; |
2265 | indent(write, _, x); |
2266 | } |
2267 | |
2268 | if (!buf_empty()) |
2269 | { |
2270 | buf_next(); |
2271 | write(datbuf[tail], lenbuf[tail]); |
2272 | } |
2273 | |
2274 | wrote_something = true; |
2275 | } |
2276 | public: |
2277 | |
2278 | /** |
2279 | * @brief Writes out all remaining data from the LineWrapper using @c write. |
2280 | * Unlike @ref process() this method indents all lines including the first and |
2281 | * will output a \\n at the end (but only if something has been written). |
2282 | */ |
2283 | void flush(IStringWriter& write) |
2284 | { |
2285 | if (buf_empty()) |
2286 | return; |
2287 | int _ = 0; |
2288 | indent(write, _, x); |
2289 | wrote_something = false; |
2290 | while (!buf_empty()) |
2291 | write_one_line(write); |
2292 | write("\n" , 1); |
2293 | } |
2294 | |
2295 | /** |
2296 | * @brief Process, wrap and output the next piece of data. |
2297 | * |
2298 | * process() will output at least one line of output. This is not necessarily |
2299 | * the @c data passed in. It may be data queued from a prior call to process(). |
2300 | * If the internal buffer is full, more than 1 line will be output. |
2301 | * |
2302 | * process() assumes that the a proper amount of indentation has already been |
2303 | * output. It won't write any further indentation before the 1st line. If |
2304 | * more than 1 line is written due to buffer constraints, the lines following |
2305 | * the first will be indented by this method, though. |
2306 | * |
2307 | * No \\n is written by this method after the last line that is written. |
2308 | * |
2309 | * @param write where to write the data. |
2310 | * @param data the new chunk of data to write. |
2311 | * @param len the length of the chunk of data to write. |
2312 | */ |
2313 | void process(IStringWriter& write, const char* data, int len) |
2314 | { |
2315 | wrote_something = false; |
2316 | |
2317 | while (len > 0) |
2318 | { |
2319 | if (len <= width) // quick test that works because utf8width <= len (all wide chars have at least 2 bytes) |
2320 | { |
2321 | output(write, data, len); |
2322 | len = 0; |
2323 | } |
2324 | else // if (len > width) it's possible (but not guaranteed) that utf8len > width |
2325 | { |
2326 | int utf8width = 0; |
2327 | int maxi = 0; |
2328 | while (maxi < len && utf8width < width) |
2329 | { |
2330 | int charbytes = 1; |
2331 | unsigned ch = (unsigned char) data[maxi]; |
2332 | if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte |
2333 | { |
2334 | // int __builtin_clz (unsigned int x) |
2335 | // Returns the number of leading 0-bits in x, starting at the most significant bit |
2336 | unsigned mask = (unsigned) -1 >> __builtin_clz(ch ^ 0xff); |
2337 | ch = ch & mask; // mask out length bits, we don't verify their correctness |
2338 | while ((maxi + charbytes < len) && // |
2339 | (((unsigned char) data[maxi + charbytes] ^ 0x80) <= 0x3F)) // while next byte is continuation byte |
2340 | { |
2341 | ch = (ch << 6) ^ (unsigned char) data[maxi + charbytes] ^ 0x80; // add continuation to char code |
2342 | ++charbytes; |
2343 | } |
2344 | // ch is the decoded unicode code point |
2345 | if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case |
2346 | { |
2347 | if (utf8width + 2 > width) |
2348 | break; |
2349 | ++utf8width; |
2350 | } |
2351 | } |
2352 | ++utf8width; |
2353 | maxi += charbytes; |
2354 | } |
2355 | |
2356 | // data[maxi-1] is the last byte of the UTF-8 sequence of the last character that fits |
2357 | // onto the 1st line. If maxi == len, all characters fit on the line. |
2358 | |
2359 | if (maxi == len) |
2360 | { |
2361 | output(write, data, len); |
2362 | len = 0; |
2363 | } |
2364 | else // if (maxi < len) at least 1 character (data[maxi] that is) doesn't fit on the line |
2365 | { |
2366 | int i; |
2367 | for (i = maxi; i >= 0; --i) |
2368 | if (data[i] == ' ') |
2369 | break; |
2370 | |
2371 | if (i >= 0) |
2372 | { |
2373 | output(write, data, i); |
2374 | data += i + 1; |
2375 | len -= i + 1; |
2376 | } |
2377 | else // did not find a space to split at => split before data[maxi] |
2378 | { // data[maxi] is always the beginning of a character, never a continuation byte |
2379 | output(write, data, maxi); |
2380 | data += maxi; |
2381 | len -= maxi; |
2382 | } |
2383 | } |
2384 | } |
2385 | } |
2386 | if (!wrote_something) // if we didn't already write something to make space in the buffer |
2387 | write_one_line(write); // write at most one line of actual output |
2388 | } |
2389 | |
2390 | /** |
2391 | * @brief Constructs a LineWrapper that wraps its output to fit into |
2392 | * screen columns @c x1 (incl.) to @c x2 (excl.). |
2393 | * |
2394 | * @c x1 gives the indentation LineWrapper uses if it needs to indent. |
2395 | */ |
2396 | LineWrapper(int x1, int x2) : |
2397 | x(x1), width(x2 - x1), head(0), tail(bufmask) |
2398 | { |
2399 | if (width < 2) // because of wide characters we need at least width 2 or the code breaks |
2400 | width = 2; |
2401 | } |
2402 | }; |
2403 | |
2404 | /** |
2405 | * @internal |
2406 | * @brief This is the implementation that is shared between all printUsage() templates. |
2407 | * Because all printUsage() templates share this implementation, there is no template bloat. |
2408 | */ |
2409 | static void printUsage(IStringWriter& write, const Descriptor usage[], int width = 80, // |
2410 | int last_column_min_percent = 50, int last_column_own_line_max_percent = 75) |
2411 | { |
2412 | if (width < 1) // protect against nonsense values |
2413 | width = 80; |
2414 | |
2415 | if (width > 10000) // protect against overflow in the following computation |
2416 | width = 10000; |
2417 | |
2418 | int last_column_min_width = ((width * last_column_min_percent) + 50) / 100; |
2419 | int last_column_own_line_max_width = ((width * last_column_own_line_max_percent) + 50) / 100; |
2420 | if (last_column_own_line_max_width == 0) |
2421 | last_column_own_line_max_width = 1; |
2422 | |
2423 | LinePartIterator part(usage); |
2424 | while (part.nextTable()) |
2425 | { |
2426 | |
2427 | /***************** Determine column widths *******************************/ |
2428 | |
2429 | const int maxcolumns = 8; // 8 columns are enough for everyone |
2430 | int col_width[maxcolumns]; |
2431 | int lastcolumn; |
2432 | int leftwidth; |
2433 | int overlong_column_threshold = 10000; |
2434 | do |
2435 | { |
2436 | lastcolumn = 0; |
2437 | for (int i = 0; i < maxcolumns; ++i) |
2438 | col_width[i] = 0; |
2439 | |
2440 | part.restartTable(); |
2441 | while (part.nextRow()) |
2442 | { |
2443 | while (part.next()) |
2444 | { |
2445 | if (part.column() < maxcolumns) |
2446 | { |
2447 | upmax(lastcolumn, part.column()); |
2448 | if (part.screenLength() < overlong_column_threshold) |
2449 | // We don't let rows that don't use table separators (\t or \v) influence |
2450 | // the width of column 0. This allows the user to interject section headers |
2451 | // or explanatory paragraphs that do not participate in the table layout. |
2452 | if (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' |
2453 | || part.data()[part.length()] == '\v') |
2454 | upmax(col_width[part.column()], part.screenLength()); |
2455 | } |
2456 | } |
2457 | } |
2458 | |
2459 | /* |
2460 | * If the last column doesn't fit on the same |
2461 | * line as the other columns, we can fix that by starting it on its own line. |
2462 | * However we can't do this for any of the columns 0..lastcolumn-1. |
2463 | * If their sum exceeds the maximum width we try to fix this by iteratively |
2464 | * ignoring the widest line parts in the width determination until |
2465 | * we arrive at a series of column widths that fit into one line. |
2466 | * The result is a layout where everything is nicely formatted |
2467 | * except for a few overlong fragments. |
2468 | * */ |
2469 | |
2470 | leftwidth = 0; |
2471 | overlong_column_threshold = 0; |
2472 | for (int i = 0; i < lastcolumn; ++i) |
2473 | { |
2474 | leftwidth += col_width[i]; |
2475 | upmax(overlong_column_threshold, col_width[i]); |
2476 | } |
2477 | |
2478 | } while (leftwidth > width); |
2479 | |
2480 | /**************** Determine tab stops and last column handling **********************/ |
2481 | |
2482 | int tabstop[maxcolumns]; |
2483 | tabstop[0] = 0; |
2484 | for (int i = 1; i < maxcolumns; ++i) |
2485 | tabstop[i] = tabstop[i - 1] + col_width[i - 1]; |
2486 | |
2487 | int rightwidth = width - tabstop[lastcolumn]; |
2488 | bool print_last_column_on_own_line = false; |
2489 | if (rightwidth < last_column_min_width && // if we don't have the minimum requested width for the last column |
2490 | ( col_width[lastcolumn] == 0 || // and all last columns are > overlong_column_threshold |
2491 | rightwidth < col_width[lastcolumn] // or there is at least one last column that requires more than the space available |
2492 | ) |
2493 | ) |
2494 | { |
2495 | print_last_column_on_own_line = true; |
2496 | rightwidth = last_column_own_line_max_width; |
2497 | } |
2498 | |
2499 | // If lastcolumn == 0 we must disable print_last_column_on_own_line because |
2500 | // otherwise 2 copies of the last (and only) column would be output. |
2501 | // Actually this is just defensive programming. It is currently not |
2502 | // possible that lastcolumn==0 and print_last_column_on_own_line==true |
2503 | // at the same time, because lastcolumn==0 => tabstop[lastcolumn] == 0 => |
2504 | // rightwidth==width => rightwidth>=last_column_min_width (unless someone passes |
2505 | // a bullshit value >100 for last_column_min_percent) => the above if condition |
2506 | // is false => print_last_column_on_own_line==false |
2507 | if (lastcolumn == 0) |
2508 | print_last_column_on_own_line = false; |
2509 | |
2510 | LineWrapper lastColumnLineWrapper(width - rightwidth, width); |
2511 | LineWrapper interjectionLineWrapper(0, width); |
2512 | |
2513 | part.restartTable(); |
2514 | |
2515 | /***************** Print out all rows of the table *************************************/ |
2516 | |
2517 | while (part.nextRow()) |
2518 | { |
2519 | int x = -1; |
2520 | while (part.next()) |
2521 | { |
2522 | if (part.column() > lastcolumn) |
2523 | continue; // drop excess columns (can happen if lastcolumn == maxcolumns-1) |
2524 | |
2525 | if (part.column() == 0) |
2526 | { |
2527 | if (x >= 0) |
2528 | write("\n" , 1); |
2529 | x = 0; |
2530 | } |
2531 | |
2532 | indent(write, x, tabstop[part.column()]); |
2533 | |
2534 | if ((part.column() < lastcolumn) |
2535 | && (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' |
2536 | || part.data()[part.length()] == '\v')) |
2537 | { |
2538 | write(part.data(), part.length()); |
2539 | x += part.screenLength(); |
2540 | } |
2541 | else // either part.column() == lastcolumn or we are in the special case of |
2542 | // an interjection that doesn't contain \v or \t |
2543 | { |
2544 | // NOTE: This code block is not necessarily executed for |
2545 | // each line, because some rows may have fewer columns. |
2546 | |
2547 | LineWrapper& lineWrapper = (part.column() == 0) ? interjectionLineWrapper : lastColumnLineWrapper; |
2548 | |
2549 | if (!print_last_column_on_own_line || part.column() != lastcolumn) |
2550 | lineWrapper.process(write, part.data(), part.length()); |
2551 | } |
2552 | } // while |
2553 | |
2554 | if (print_last_column_on_own_line) |
2555 | { |
2556 | part.restartRow(); |
2557 | while (part.next()) |
2558 | { |
2559 | if (part.column() == lastcolumn) |
2560 | { |
2561 | write("\n" , 1); |
2562 | int _ = 0; |
2563 | indent(write, _, width - rightwidth); |
2564 | lastColumnLineWrapper.process(write, part.data(), part.length()); |
2565 | } |
2566 | } |
2567 | } |
2568 | |
2569 | write("\n" , 1); |
2570 | lastColumnLineWrapper.flush(write); |
2571 | interjectionLineWrapper.flush(write); |
2572 | } |
2573 | } |
2574 | } |
2575 | |
2576 | } |
2577 | ; |
2578 | |
2579 | /** |
2580 | * @brief Outputs a nicely formatted usage string with support for multi-column formatting |
2581 | * and line-wrapping. |
2582 | * |
2583 | * printUsage() takes the @c help texts of a Descriptor[] array and formats them into |
2584 | * a usage message, wrapping lines to achieve the desired output width. |
2585 | * |
2586 | * <b>Table formatting:</b> |
2587 | * |
2588 | * Aside from plain strings which are simply line-wrapped, the usage may contain tables. Tables |
2589 | * are used to align elements in the output. |
2590 | * |
2591 | * @code |
2592 | * // Without a table. The explanatory texts are not aligned. |
2593 | * -c, --create |Creates something. |
2594 | * -k, --kill |Destroys something. |
2595 | * |
2596 | * // With table formatting. The explanatory texts are aligned. |
2597 | * -c, --create |Creates something. |
2598 | * -k, --kill |Destroys something. |
2599 | * @endcode |
2600 | * |
2601 | * Table formatting removes the need to pad help texts manually with spaces to achieve |
2602 | * alignment. To create a table, simply insert \\t (tab) characters to separate the cells |
2603 | * within a row. |
2604 | * |
2605 | * @code |
2606 | * const option::Descriptor usage[] = { |
2607 | * {..., "-c, --create \tCreates something." }, |
2608 | * {..., "-k, --kill \tDestroys something." }, ... |
2609 | * @endcode |
2610 | * |
2611 | * Note that you must include the minimum amount of space desired between cells yourself. |
2612 | * Table formatting will insert further spaces as needed to achieve alignment. |
2613 | * |
2614 | * You can insert line breaks within cells by using \\v (vertical tab). |
2615 | * |
2616 | * @code |
2617 | * const option::Descriptor usage[] = { |
2618 | * {..., "-c,\v--create \tCreates\vsomething." }, |
2619 | * {..., "-k,\v--kill \tDestroys\vsomething." }, ... |
2620 | * |
2621 | * // results in |
2622 | * |
2623 | * -c, Creates |
2624 | * --create something. |
2625 | * -k, Destroys |
2626 | * --kill something. |
2627 | * @endcode |
2628 | * |
2629 | * You can mix lines that do not use \\t or \\v with those that do. The plain |
2630 | * lines will not mess up the table layout. Alignment of the table columns will |
2631 | * be maintained even across these interjections. |
2632 | * |
2633 | * @code |
2634 | * const option::Descriptor usage[] = { |
2635 | * {..., "-c, --create \tCreates something." }, |
2636 | * {..., "----------------------------------" }, |
2637 | * {..., "-k, --kill \tDestroys something." }, ... |
2638 | * |
2639 | * // results in |
2640 | * |
2641 | * -c, --create Creates something. |
2642 | * ---------------------------------- |
2643 | * -k, --kill Destroys something. |
2644 | * @endcode |
2645 | * |
2646 | * You can have multiple tables within the same usage whose columns are |
2647 | * aligned independently. Simply insert a dummy Descriptor with @c help==0. |
2648 | * |
2649 | * @code |
2650 | * const option::Descriptor usage[] = { |
2651 | * {..., "Long options:" }, |
2652 | * {..., "--very-long-option \tDoes something long." }, |
2653 | * {..., "--ultra-super-mega-long-option \tTakes forever to complete." }, |
2654 | * {..., 0 }, // ---------- table break ----------- |
2655 | * {..., "Short options:" }, |
2656 | * {..., "-s \tShort." }, |
2657 | * {..., "-q \tQuick." }, ... |
2658 | * |
2659 | * // results in |
2660 | * |
2661 | * Long options: |
2662 | * --very-long-option Does something long. |
2663 | * --ultra-super-mega-long-option Takes forever to complete. |
2664 | * Short options: |
2665 | * -s Short. |
2666 | * -q Quick. |
2667 | * |
2668 | * // Without the table break it would be |
2669 | * |
2670 | * Long options: |
2671 | * --very-long-option Does something long. |
2672 | * --ultra-super-mega-long-option Takes forever to complete. |
2673 | * Short options: |
2674 | * -s Short. |
2675 | * -q Quick. |
2676 | * @endcode |
2677 | * |
2678 | * <b>Output methods:</b> |
2679 | * |
2680 | * Because TheLeanMeanC++Option parser is freestanding, you have to provide the means for |
2681 | * output in the first argument(s) to printUsage(). Because printUsage() is implemented as |
2682 | * a set of template functions, you have great flexibility in your choice of output |
2683 | * method. The following example demonstrates typical uses. Anything that's similar enough |
2684 | * will work. |
2685 | * |
2686 | * @code |
2687 | * #include <unistd.h> // write() |
2688 | * #include <iostream> // cout |
2689 | * #include <sstream> // ostringstream |
2690 | * #include <cstdio> // fwrite() |
2691 | * using namespace std; |
2692 | * |
2693 | * void my_write(const char* str, int size) { |
2694 | * fwrite(str, size, 1, stdout); |
2695 | * } |
2696 | * |
2697 | * struct MyWriter { |
2698 | * void write(const char* buf, size_t size) const { |
2699 | * fwrite(str, size, 1, stdout); |
2700 | * } |
2701 | * }; |
2702 | * |
2703 | * struct MyWriteFunctor { |
2704 | * void operator()(const char* buf, size_t size) { |
2705 | * fwrite(str, size, 1, stdout); |
2706 | * } |
2707 | * }; |
2708 | * ... |
2709 | * printUsage(my_write, usage); // custom write function |
2710 | * printUsage(MyWriter(), usage); // temporary of a custom class |
2711 | * MyWriter writer; |
2712 | * printUsage(writer, usage); // custom class object |
2713 | * MyWriteFunctor wfunctor; |
2714 | * printUsage(&wfunctor, usage); // custom functor |
2715 | * printUsage(write, 1, usage); // write() to file descriptor 1 |
2716 | * printUsage(cout, usage); // an ostream& |
2717 | * printUsage(fwrite, stdout, usage); // fwrite() to stdout |
2718 | * ostringstream sstr; |
2719 | * printUsage(sstr, usage); // an ostringstream& |
2720 | * |
2721 | * @endcode |
2722 | * |
2723 | * @par Notes: |
2724 | * @li the @c write() method of a class that is to be passed as a temporary |
2725 | * as @c MyWriter() is in the example, must be a @c const method, because |
2726 | * temporary objects are passed as const reference. This only applies to |
2727 | * temporary objects that are created and destroyed in the same statement. |
2728 | * If you create an object like @c writer in the example, this restriction |
2729 | * does not apply. |
2730 | * @li a functor like @c MyWriteFunctor in the example must be passed as a pointer. |
2731 | * This differs from the way functors are passed to e.g. the STL algorithms. |
2732 | * @li All printUsage() templates are tiny wrappers around a shared non-template implementation. |
2733 | * So there's no penalty for using different versions in the same program. |
2734 | * @li printUsage() always interprets Descriptor::help as UTF-8 and always produces UTF-8-encoded |
2735 | * output. If your system uses a different charset, you must do your own conversion. You |
2736 | * may also need to change the font of the console to see non-ASCII characters properly. |
2737 | * This is particularly true for Windows. |
2738 | * @li @b Security @b warning: Do not insert untrusted strings (such as user-supplied arguments) |
2739 | * into the usage. printUsage() has no protection against malicious UTF-8 sequences. |
2740 | * |
2741 | * @param prn The output method to use. See the examples above. |
2742 | * @param usage the Descriptor[] array whose @c help texts will be formatted. |
2743 | * @param width the maximum number of characters per output line. Note that this number is |
2744 | * in actual characters, not bytes. printUsage() supports UTF-8 in @c help and will |
2745 | * count multi-byte UTF-8 sequences properly. Asian wide characters are counted |
2746 | * as 2 characters. |
2747 | * @param last_column_min_percent (0-100) The minimum percentage of @c width that should be available |
2748 | * for the last column (which typically contains the textual explanation of an option). |
2749 | * If less space is available, the last column will be printed on its own line, indented |
2750 | * according to @c last_column_own_line_max_percent. |
2751 | * @param last_column_own_line_max_percent (0-100) If the last column is printed on its own line due to |
2752 | * less than @c last_column_min_percent of the width being available, then only |
2753 | * @c last_column_own_line_max_percent of the extra line(s) will be used for the |
2754 | * last column's text. This ensures an indentation. See example below. |
2755 | * |
2756 | * @code |
2757 | * // width=20, last_column_min_percent=50 (i.e. last col. min. width=10) |
2758 | * --3456789 1234567890 |
2759 | * 1234567890 |
2760 | * |
2761 | * // width=20, last_column_min_percent=75 (i.e. last col. min. width=15) |
2762 | * // last_column_own_line_max_percent=75 |
2763 | * --3456789 |
2764 | * 123456789012345 |
2765 | * 67890 |
2766 | * |
2767 | * // width=20, last_column_min_percent=75 (i.e. last col. min. width=15) |
2768 | * // last_column_own_line_max_percent=33 (i.e. max. 5) |
2769 | * --3456789 |
2770 | * 12345 |
2771 | * 67890 |
2772 | * 12345 |
2773 | * 67890 |
2774 | * @endcode |
2775 | */ |
2776 | template<typename OStream> |
2777 | void printUsage(OStream& prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, |
2778 | int last_column_own_line_max_percent = 75) |
2779 | { |
2780 | PrintUsageImplementation::OStreamWriter<OStream> write(prn); |
2781 | PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); |
2782 | } |
2783 | |
2784 | template<typename Function> |
2785 | void printUsage(Function* prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, |
2786 | int last_column_own_line_max_percent = 75) |
2787 | { |
2788 | PrintUsageImplementation::FunctionWriter<Function> write(prn); |
2789 | PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); |
2790 | } |
2791 | |
2792 | template<typename Temporary> |
2793 | void printUsage(const Temporary& prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, |
2794 | int last_column_own_line_max_percent = 75) |
2795 | { |
2796 | PrintUsageImplementation::TemporaryWriter<Temporary> write(prn); |
2797 | PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); |
2798 | } |
2799 | |
2800 | template<typename Syscall> |
2801 | void printUsage(Syscall* prn, int fd, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, |
2802 | int last_column_own_line_max_percent = 75) |
2803 | { |
2804 | PrintUsageImplementation::SyscallWriter<Syscall> write(prn, fd); |
2805 | PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); |
2806 | } |
2807 | |
2808 | template<typename Function, typename Stream> |
2809 | void printUsage(Function* prn, Stream* stream, const Descriptor usage[], int width = 80, int last_column_min_percent = |
2810 | 50, |
2811 | int last_column_own_line_max_percent = 75) |
2812 | { |
2813 | PrintUsageImplementation::StreamWriter<Function, Stream> write(prn, stream); |
2814 | PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); |
2815 | } |
2816 | |
2817 | } |
2818 | // namespace option |
2819 | |
2820 | #endif /* OPTIONPARSER_H_ */ |
2821 | |