-
Notifications
You must be signed in to change notification settings - Fork 0
/
optionparser.h
2858 lines (2636 loc) · 99.7 KB
/
optionparser.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The Lean Mean C++ Option Parser
*
* Copyright (C) 2012-2017 Matthias S. Benkmann
*
* The "Software" in the following 2 paragraphs refers to this file containing
* the code to The Lean Mean C++ Option Parser.
* The "Software" does NOT refer to any other files which you
* may have received alongside this file (e.g. as part of a larger project that
* incorporates The Lean Mean C++ Option Parser).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software, to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* NOTE: It is recommended that you read the processed HTML doxygen documentation
* rather than this source. If you don't know doxygen, it's like javadoc for C++.
* If you don't want to install doxygen you can find a copy of the processed
* documentation at
*
* http://optionparser.sourceforge.net/
*
*/
/**
* @file
*
* @brief This is the only file required to use The Lean Mean C++ Option Parser.
* Just \#include it and you're set.
*
* The Lean Mean C++ Option Parser handles the program's command line arguments
* (argc, argv).
* It supports the short and long option formats of getopt(), getopt_long()
* and getopt_long_only() but has a more convenient interface.
*
* @par Feedback:
* Send questions, bug reports, feature requests etc. to: <tt><b>optionparser-feedback(a)lists.sourceforge.net</b></tt>
*
* @par Highlights:
* <ul style="padding-left:1em;margin-left:0">
* <li> It is a header-only library. Just <code>\#include "optionparser.h"</code> and you're set.
* <li> It is freestanding. There are no dependencies whatsoever, not even the
* C or C++ standard library.
* <li> It has a usage message formatter that supports column alignment and
* line wrapping. This aids localization because it adapts to
* translated strings that are shorter or longer (even if they contain
* Asian wide characters).
* <li> Unlike getopt() and derivatives it doesn't force you to loop through
* options sequentially. Instead you can access options directly like this:
* <ul style="margin-top:.5em">
* <li> Test for presence of a switch in the argument vector:
* @code if ( options[QUIET] ) ... @endcode
* <li> Evaluate --enable-foo/--disable-foo pair where the last one used wins:
* @code if ( options[FOO].last()->type() == DISABLE ) ... @endcode
* <li> Cumulative option (-v verbose, -vv more verbose, -vvv even more verbose):
* @code int verbosity = options[VERBOSE].count(); @endcode
* <li> Iterate over all --file=<fname> arguments:
* @code for (Option* opt = options[FILE]; opt; opt = opt->next())
* fname = opt->arg; ... @endcode
* <li> If you really want to, you can still process all arguments in order:
* @code
* for (int i = 0; i < p.optionsCount(); ++i) {
* Option& opt = buffer[i];
* switch(opt.index()) {
* case HELP: ...
* case VERBOSE: ...
* case FILE: fname = opt.arg; ...
* case UNKNOWN: ...
* @endcode
* </ul>
* </ul> @n
* Despite these features the code size remains tiny.
* It is smaller than <a href="http://uclibc.org">uClibc</a>'s GNU getopt() and just a
* couple 100 bytes larger than uClibc's SUSv3 getopt(). @n
* (This does not include the usage formatter, of course. But you don't have to use that.)
*
* @par Download:
* Tarball with examples and test programs:
* <a style="font-size:larger;font-weight:bold" href="http://sourceforge.net/projects/optionparser/files/optionparser-1.7.tar.gz/download">optionparser-1.7.tar.gz</a> @n
* Just the header (this is all you really need):
* <a style="font-size:larger;font-weight:bold" href="http://optionparser.sourceforge.net/optionparser.h">optionparser.h</a>
*
* @par Changelog:
* <b>Version 1.7:</b> Work on const-correctness. @n
* <b>Version 1.6:</b> Fix for MSC compiler. @n
* <b>Version 1.5:</b> Fixed 2 warnings about potentially uninitialized variables. @n
* Added const version of Option::next(). @n
* <b>Version 1.4:</b> Fixed 2 printUsage() bugs that messed up output with small COLUMNS values. @n
* <b>Version 1.3:</b> Compatible with Microsoft Visual C++. @n
* <b>Version 1.2:</b> Added @ref option::Option::namelen "Option::namelen" and removed the extraction
* of short option characters into a special buffer. @n
* Changed @ref option::Arg::Optional "Arg::Optional" to accept arguments if they are attached
* rather than separate. This is what GNU getopt() does and how POSIX recommends
* utilities should interpret their arguments.@n
* <b>Version 1.1:</b> Optional mode with argument reordering as done by GNU getopt(), so that
* options and non-options can be mixed. See
* @ref option::Parser::parse() "Parser::parse()".
*
*
* @par Example program:
* (Note: @c option::* identifiers are links that take you to their documentation.)
* @code
* #error EXAMPLE SHORTENED FOR READABILITY. BETTER EXAMPLES ARE IN THE .TAR.GZ!
* #include <iostream>
* #include "optionparser.h"
*
* enum optionIndex { UNKNOWN, HELP, PLUS };
* const option::Descriptor usage[] =
* {
* {UNKNOWN, 0,"" , "" ,option::Arg::None, "USAGE: example [options]\n\n"
* "Options:" },
* {HELP, 0,"" , "help",option::Arg::None, " --help \tPrint usage and exit." },
* {PLUS, 0,"p", "plus",option::Arg::None, " --plus, -p \tIncrement count." },
* {UNKNOWN, 0,"" , "" ,option::Arg::None, "\nExamples:\n"
* " example --unknown -- --this_is_no_option\n"
* " example -unk --plus -ppp file1 file2\n" },
* {0,0,0,0,0,0}
* };
*
* int main(int argc, char* argv[])
* {
* argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
* option::Stats stats(usage, argc, argv);
* option::Option options[stats.options_max], buffer[stats.buffer_max];
* option::Parser parse(usage, argc, argv, options, buffer);
*
* if (parse.error())
* return 1;
*
* if (options[HELP] || argc == 0) {
* option::printUsage(std::cout, usage);
* return 0;
* }
*
* std::cout << "--plus count: " <<
* options[PLUS].count() << "\n";
*
* for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next())
* std::cout << "Unknown option: " << opt->name << "\n";
*
* for (int i = 0; i < parse.nonOptionsCount(); ++i)
* std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n";
* }
* @endcode
*
* @par Option syntax:
* @li The Lean Mean C++ Option Parser follows POSIX <code>getopt()</code> conventions and supports
* GNU-style <code>getopt_long()</code> long options as well as Perl-style single-minus
* long options (<code>getopt_long_only()</code>).
* @li short options have the format @c -X where @c X is any character that fits in a char.
* @li short options can be grouped, i.e. <code>-X -Y</code> is equivalent to @c -XY.
* @li a short option may take an argument either separate (<code>-X foo</code>) or
* attached (@c -Xfoo). You can make the parser accept the additional format @c -X=foo by
* registering @c X as a long option (in addition to being a short option) and
* enabling single-minus long options.
* @li an argument-taking short option may be grouped if it is the last in the group, e.g.
* @c -ABCXfoo or <code> -ABCX foo </code> (@c foo is the argument to the @c -X option).
* @li a lone minus character @c '-' is not treated as an option. It is customarily used where
* a file name is expected to refer to stdin or stdout.
* @li long options have the format @c --option-name.
* @li the option-name of a long option can be anything and include any characters.
* Even @c = characters will work, but don't do that.
* @li [optional] long options may be abbreviated as long as the abbreviation is unambiguous.
* You can set a minimum length for abbreviations.
* @li [optional] long options may begin with a single minus. The double minus form is always
* accepted, too.
* @li a long option may take an argument either separate (<code> --option arg </code>) or
* attached (<code> --option=arg </code>). In the attached form the equals sign is mandatory.
* @li an empty string can be passed as an attached long option argument: <code> --option-name= </code>.
* Note the distinction between an empty string as argument and no argument at all.
* @li an empty string is permitted as separate argument to both long and short options.
* @li Arguments to both short and long options may start with a @c '-' character. E.g.
* <code> -X-X </code>, <code>-X -X</code> or <code> --long-X=-X </code>. If @c -X
* and @c --long-X take an argument, that argument will be @c "-X" in all 3 cases.
* @li If using the built-in @ref option::Arg::Optional "Arg::Optional", optional arguments must
* be attached.
* @li the special option @c -- (i.e. without a name) terminates the list of
* options. Everything that follows is a non-option argument, even if it starts with
* a @c '-' character. The @c -- itself will not appear in the parse results.
* @li the first argument that doesn't start with @c '-' or @c '--' and does not belong to
* a preceding argument-taking option, will terminate the option list and is the
* first non-option argument. All following command line arguments are treated as
* non-option arguments, even if they start with @c '-' . @n
* NOTE: This behaviour is mandated by POSIX, but GNU getopt() only honours this if it is
* explicitly requested (e.g. by setting POSIXLY_CORRECT). @n
* You can enable the GNU behaviour by passing @c true as first argument to
* e.g. @ref option::Parser::parse() "Parser::parse()".
* @li Arguments that look like options (i.e. @c '-' followed by at least 1 character) but
* aren't, are NOT treated as non-option arguments. They are treated as unknown options and
* are collected into a list of unknown options for error reporting. @n
* This means that in order to pass a first non-option
* argument beginning with the minus character it is required to use the
* @c -- special option, e.g.
* @code
* program -x -- --strange-filename
* @endcode
* In this example, @c --strange-filename is a non-option argument. If the @c --
* were omitted, it would be treated as an unknown option. @n
* See @ref option::Descriptor::longopt for information on how to collect unknown options.
*
*/
#ifndef OPTIONPARSER_H_
#define OPTIONPARSER_H_
#ifdef _MSC_VER
#include <intrin.h>
#pragma intrinsic(_BitScanReverse)
#endif
/** @brief The namespace of The Lean Mean C++ Option Parser. */
namespace option
{
#ifdef _MSC_VER
struct MSC_Builtin_CLZ
{
static int builtin_clz(unsigned x)
{
unsigned long index;
_BitScanReverse(&index, x);
return 32-index; // int is always 32bit on Windows, even for target x64
}
};
#define __builtin_clz(x) MSC_Builtin_CLZ::builtin_clz(x)
#endif
class Option;
/**
* @brief Possible results when checking if an argument is valid for a certain option.
*
* In the case that no argument is provided for an option that takes an
* optional argument, return codes @c ARG_OK and @c ARG_IGNORE are equivalent.
*/
enum ArgStatus
{
//! The option does not take an argument.
ARG_NONE,
//! The argument is acceptable for the option.
ARG_OK,
//! The argument is not acceptable but that's non-fatal because the option's argument is optional.
ARG_IGNORE,
//! The argument is not acceptable and that's fatal.
ARG_ILLEGAL
};
/**
* @brief Signature of functions that check if an argument is valid for a certain type of option.
*
* Every Option has such a function assigned in its Descriptor.
* @code
* Descriptor usage[] = { {UNKNOWN, 0, "", "", Arg::None, ""}, ... };
* @endcode
*
* A CheckArg function has the following signature:
* @code ArgStatus CheckArg(const Option& option, bool msg); @endcode
*
* It is used to check if a potential argument would be acceptable for the option.
* It will even be called if there is no argument. In that case @c option.arg will be @c NULL.
*
* If @c msg is @c true and the function determines that an argument is not acceptable and
* that this is a fatal error, it should output a message to the user before
* returning @ref ARG_ILLEGAL. If @c msg is @c false the function should remain silent (or you
* will get duplicate messages).
*
* See @ref ArgStatus for the meaning of the return values.
*
* While you can provide your own functions,
* often the following pre-defined checks (which never return @ref ARG_ILLEGAL) will suffice:
*
* @li @c Arg::None @copybrief Arg::None
* @li @c Arg::Optional @copybrief Arg::Optional
*
*/
typedef ArgStatus (*CheckArg)(const Option& option, bool msg);
/**
* @brief Describes an option, its help text (usage) and how it should be parsed.
*
* The main input when constructing an option::Parser is an array of Descriptors.
* @par Example:
* @code
* enum OptionIndex {CREATE, ...};
* enum OptionType {DISABLE, ENABLE, OTHER};
*
* const option::Descriptor usage[] = {
* { CREATE, // index
* OTHER, // type
* "c", // shortopt
* "create", // longopt
* Arg::None, // check_arg
* "--create Tells the program to create something." // help
* }
* , ...
* };
* @endcode
*/
struct Descriptor
{
/**
* @brief Index of this option's linked list in the array filled in by the parser.
*
* Command line options whose Descriptors have the same index will end up in the same
* linked list in the order in which they appear on the command line. If you have
* multiple long option aliases that refer to the same option, give their descriptors
* the same @c index.
*
* If you have options that mean exactly opposite things
* (e.g. @c --enable-foo and @c --disable-foo ), you should also give them the same
* @c index, but distinguish them through different values for @ref type.
* That way they end up in the same list and you can just take the last element of the
* list and use its type. This way you get the usual behaviour where switches later
* on the command line override earlier ones without having to code it manually.
*
* @par Tip:
* Use an enum rather than plain ints for better readability, as shown in the example
* at Descriptor.
*/
const unsigned index;
/**
* @brief Used to distinguish between options with the same @ref index.
* See @ref index for details.
*
* It is recommended that you use an enum rather than a plain int to make your
* code more readable.
*/
const int type;
/**
* @brief Each char in this string will be accepted as a short option character.
*
* The string must not include the minus character @c '-' or you'll get undefined
* behaviour.
*
* If this Descriptor should not have short option characters, use the empty
* string "". NULL is not permitted here!
*
* See @ref longopt for more information.
*/
const char* const shortopt;
/**
* @brief The long option name (without the leading @c -- ).
*
* If this Descriptor should not have a long option name, use the empty
* string "". NULL is not permitted here!
*
* While @ref shortopt allows multiple short option characters, each
* Descriptor can have only a single long option name. If you have multiple
* long option names referring to the same option use separate Descriptors
* that have the same @ref index and @ref type. You may repeat
* short option characters in such an alias Descriptor but there's no need to.
*
* @par Dummy Descriptors:
* You can use dummy Descriptors with an
* empty string for both @ref shortopt and @ref longopt to add text to
* the usage that is not related to a specific option. See @ref help.
* The first dummy Descriptor will be used for unknown options (see below).
*
* @par Unknown Option Descriptor:
* The first dummy Descriptor in the list of Descriptors,
* whose @ref shortopt and @ref longopt are both the empty string, will be used
* as the Descriptor for unknown options. An unknown option is a string in
* the argument vector that is not a lone minus @c '-' but starts with a minus
* character and does not match any Descriptor's @ref shortopt or @ref longopt. @n
* Note that the dummy descriptor's @ref check_arg function @e will be called and
* its return value will be evaluated as usual. I.e. if it returns @ref ARG_ILLEGAL
* the parsing will be aborted with <code>Parser::error()==true</code>. @n
* if @c check_arg does not return @ref ARG_ILLEGAL the descriptor's
* @ref index @e will be used to pick the linked list into which
* to put the unknown option. @n
* If there is no dummy descriptor, unknown options will be dropped silently.
*
*/
const char* const longopt;
/**
* @brief For each option that matches @ref shortopt or @ref longopt this function
* will be called to check a potential argument to the option.
*
* This function will be called even if there is no potential argument. In that case
* it will be passed @c NULL as @c arg parameter. Do not confuse this with the empty
* string.
*
* See @ref CheckArg for more information.
*/
const CheckArg check_arg;
/**
* @brief The usage text associated with the options in this Descriptor.
*
* You can use option::printUsage() to format your usage message based on
* the @c help texts. You can use dummy Descriptors where
* @ref shortopt and @ref longopt are both the empty string to add text to
* the usage that is not related to a specific option.
*
* See option::printUsage() for special formatting characters you can use in
* @c help to get a column layout.
*
* @attention
* Must be UTF-8-encoded. If your compiler supports C++11 you can use the "u8"
* prefix to make sure string literals are properly encoded.
*/
const char* help;
};
/**
* @brief A parsed option from the command line together with its argument if it has one.
*
* The Parser chains all parsed options with the same Descriptor::index together
* to form a linked list. This allows you to easily implement all of the common ways
* of handling repeated options and enable/disable pairs.
*
* @li Test for presence of a switch in the argument vector:
* @code if ( options[QUIET] ) ... @endcode
* @li Evaluate --enable-foo/--disable-foo pair where the last one used wins:
* @code if ( options[FOO].last()->type() == DISABLE ) ... @endcode
* @li Cumulative option (-v verbose, -vv more verbose, -vvv even more verbose):
* @code int verbosity = options[VERBOSE].count(); @endcode
* @li Iterate over all --file=<fname> arguments:
* @code for (Option* opt = options[FILE]; opt; opt = opt->next())
* fname = opt->arg; ... @endcode
*/
class Option
{
Option* next_;
Option* prev_;
public:
/**
* @brief Pointer to this Option's Descriptor.
*
* Remember that the first dummy descriptor (see @ref Descriptor::longopt) is used
* for unknown options.
*
* @attention
* @c desc==NULL signals that this Option is unused. This is the default state of
* elements in the result array. You don't need to test @c desc explicitly. You
* can simply write something like this:
* @code
* if (options[CREATE])
* {
* ...
* }
* @endcode
* This works because of <code> operator const Option*() </code>.
*/
const Descriptor* desc;
/**
* @brief The name of the option as used on the command line.
*
* The main purpose of this string is to be presented to the user in messages.
*
* In the case of a long option, this is the actual @c argv pointer, i.e. the first
* character is a '-'. In the case of a short option this points to the option
* character within the @c argv string.
*
* Note that in the case of a short option group or an attached option argument, this
* string will contain additional characters following the actual name. Use @ref namelen
* to filter out the actual option name only.
*
*/
const char* name;
/**
* @brief Pointer to this Option's argument (if any).
*
* NULL if this option has no argument. Do not confuse this with the empty string which
* is a valid argument.
*/
const char* arg;
/**
* @brief The length of the option @ref name.
*
* Because @ref name points into the actual @c argv string, the option name may be
* followed by more characters (e.g. other short options in the same short option group).
* This value is the number of bytes (not characters!) that are part of the actual name.
*
* For a short option, this length is always 1. For a long option this length is always
* at least 2 if single minus long options are permitted and at least 3 if they are disabled.
*
* @note
* In the pathological case of a minus within a short option group (e.g. @c -xf-z), this
* length is incorrect, because this case will be misinterpreted as a long option and the
* name will therefore extend to the string's 0-terminator or a following '=" character
* if there is one. This is irrelevant for most uses of @ref name and @c namelen. If you
* really need to distinguish the case of a long and a short option, compare @ref name to
* the @c argv pointers. A long option's @c name is always identical to one of them,
* whereas a short option's is never.
*/
int namelen;
/**
* @brief Returns Descriptor::type of this Option's Descriptor, or 0 if this Option
* is invalid (unused).
*
* Because this method (and last(), too) can be used even on unused Options with desc==0, you can (provided
* you arrange your types properly) switch on type() without testing validity first.
* @code
* enum OptionType { UNUSED=0, DISABLED=0, ENABLED=1 };
* enum OptionIndex { FOO };
* const Descriptor usage[] = {
* { FOO, ENABLED, "", "enable-foo", Arg::None, 0 },
* { FOO, DISABLED, "", "disable-foo", Arg::None, 0 },
* { 0, 0, 0, 0, 0, 0 } };
* ...
* switch(options[FOO].last()->type()) // no validity check required!
* {
* case ENABLED: ...
* case DISABLED: ... // UNUSED==DISABLED !
* }
* @endcode
*/
int type() const
{
return desc == 0 ? 0 : desc->type;
}
/**
* @brief Returns Descriptor::index of this Option's Descriptor, or -1 if this Option
* is invalid (unused).
*/
int index() const
{
return desc == 0 ? -1 : (int)desc->index;
}
/**
* @brief Returns the number of times this Option (or others with the same Descriptor::index)
* occurs in the argument vector.
*
* This corresponds to the number of elements in the linked list this Option is part of.
* It doesn't matter on which element you call count(). The return value is always the same.
*
* Use this to implement cumulative options, such as -v, -vv, -vvv for
* different verbosity levels.
*
* Returns 0 when called for an unused/invalid option.
*/
int count() const
{
int c = (desc == 0 ? 0 : 1);
const Option* p = first();
while (!p->isLast())
{
++c;
p = p->next_;
};
return c;
}
/**
* @brief Returns true iff this is the first element of the linked list.
*
* The first element in the linked list is the first option on the command line
* that has the respective Descriptor::index value.
*
* Returns true for an unused/invalid option.
*/
bool isFirst() const
{
return isTagged(prev_);
}
/**
* @brief Returns true iff this is the last element of the linked list.
*
* The last element in the linked list is the last option on the command line
* that has the respective Descriptor::index value.
*
* Returns true for an unused/invalid option.
*/
bool isLast() const
{
return isTagged(next_);
}
/**
* @brief Returns a pointer to the first element of the linked list.
*
* Use this when you want the first occurrence of an option on the command line to
* take precedence. Note that this is not the way most programs handle options.
* You should probably be using last() instead.
*
* @note
* This method may be called on an unused/invalid option and will return a pointer to the
* option itself.
*/
Option* first()
{
Option* p = this;
while (!p->isFirst())
p = p->prev_;
return p;
}
/**
* const version of Option::first().
*/
const Option* first() const
{
return const_cast<Option*>(this)->first();
}
/**
* @brief Returns a pointer to the last element of the linked list.
*
* Use this when you want the last occurrence of an option on the command line to
* take precedence. This is the most common way of handling conflicting options.
*
* @note
* This method may be called on an unused/invalid option and will return a pointer to the
* option itself.
*
* @par Tip:
* If you have options with opposite meanings (e.g. @c --enable-foo and @c --disable-foo), you
* can assign them the same Descriptor::index to get them into the same list. Distinguish them by
* Descriptor::type and all you have to do is check <code> last()->type() </code> to get
* the state listed last on the command line.
*/
Option* last()
{
return first()->prevwrap();
}
/**
* const version of Option::last().
*/
const Option* last() const
{
return first()->prevwrap();
}
/**
* @brief Returns a pointer to the previous element of the linked list or NULL if
* called on first().
*
* If called on first() this method returns NULL. Otherwise it will return the
* option with the same Descriptor::index that precedes this option on the command
* line.
*/
Option* prev()
{
return isFirst() ? 0 : prev_;
}
/**
* @brief Returns a pointer to the previous element of the linked list with wrap-around from
* first() to last().
*
* If called on first() this method returns last(). Otherwise it will return the
* option with the same Descriptor::index that precedes this option on the command
* line.
*/
Option* prevwrap()
{
return untag(prev_);
}
/**
* const version of Option::prevwrap().
*/
const Option* prevwrap() const
{
return untag(prev_);
}
/**
* @brief Returns a pointer to the next element of the linked list or NULL if called
* on last().
*
* If called on last() this method returns NULL. Otherwise it will return the
* option with the same Descriptor::index that follows this option on the command
* line.
*/
Option* next()
{
return isLast() ? 0 : next_;
}
/**
* const version of Option::next().
*/
const Option* next() const
{
return isLast() ? 0 : next_;
}
/**
* @brief Returns a pointer to the next element of the linked list with wrap-around from
* last() to first().
*
* If called on last() this method returns first(). Otherwise it will return the
* option with the same Descriptor::index that follows this option on the command
* line.
*/
Option* nextwrap()
{
return untag(next_);
}
/**
* @brief Makes @c new_last the new last() by chaining it into the list after last().
*
* It doesn't matter which element you call append() on. The new element will always
* be appended to last().
*
* @attention
* @c new_last must not yet be part of a list, or that list will become corrupted, because
* this method does not unchain @c new_last from an existing list.
*/
void append(Option* new_last)
{
Option* p = last();
Option* f = first();
p->next_ = new_last;
new_last->prev_ = p;
new_last->next_ = tag(f);
f->prev_ = tag(new_last);
}
/**
* @brief Casts from Option to const Option* but only if this Option is valid.
*
* If this Option is valid (i.e. @c desc!=NULL), returns this.
* Otherwise returns NULL. This allows testing an Option directly
* in an if-clause to see if it is used:
* @code
* if (options[CREATE])
* {
* ...
* }
* @endcode
* It also allows you to write loops like this:
* @code for (Option* opt = options[FILE]; opt; opt = opt->next())
* fname = opt->arg; ... @endcode
*/
operator const Option*() const
{
return desc ? this : 0;
}
/**
* @brief Casts from Option to Option* but only if this Option is valid.
*
* If this Option is valid (i.e. @c desc!=NULL), returns this.
* Otherwise returns NULL. This allows testing an Option directly
* in an if-clause to see if it is used:
* @code
* if (options[CREATE])
* {
* ...
* }
* @endcode
* It also allows you to write loops like this:
* @code for (Option* opt = options[FILE]; opt; opt = opt->next())
* fname = opt->arg; ... @endcode
*/
operator Option*()
{
return desc ? this : 0;
}
/**
* @brief Creates a new Option that is a one-element linked list and has NULL
* @ref desc, @ref name, @ref arg and @ref namelen.
*/
Option() :
desc(0), name(0), arg(0), namelen(0)
{
prev_ = tag(this);
next_ = tag(this);
}
/**
* @brief Creates a new Option that is a one-element linked list and has the given
* values for @ref desc, @ref name and @ref arg.
*
* If @c name_ points at a character other than '-' it will be assumed to refer to a
* short option and @ref namelen will be set to 1. Otherwise the length will extend to
* the first '=' character or the string's 0-terminator.
*/
Option(const Descriptor* desc_, const char* name_, const char* arg_)
{
init(desc_, name_, arg_);
}
/**
* @brief Makes @c *this a copy of @c orig except for the linked list pointers.
*
* After this operation @c *this will be a one-element linked list.
*/
void operator=(const Option& orig)
{
init(orig.desc, orig.name, orig.arg);
}
/**
* @brief Makes @c *this a copy of @c orig except for the linked list pointers.
*
* After this operation @c *this will be a one-element linked list.
*/
Option(const Option& orig)
{
init(orig.desc, orig.name, orig.arg);
}
private:
/**
* @internal
* @brief Sets the fields of this Option to the given values (extracting @c name if necessary).
*
* If @c name_ points at a character other than '-' it will be assumed to refer to a
* short option and @ref namelen will be set to 1. Otherwise the length will extend to
* the first '=' character or the string's 0-terminator.
*/
void init(const Descriptor* desc_, const char* name_, const char* arg_)
{
desc = desc_;
name = name_;
arg = arg_;
prev_ = tag(this);
next_ = tag(this);
namelen = 0;
if (name == 0)
return;
namelen = 1;
if (name[0] != '-')
return;
while (name[namelen] != 0 && name[namelen] != '=')
++namelen;
}
static Option* tag(Option* ptr)
{
return (Option*) ((unsigned long long) ptr | 1);
}
static Option* untag(Option* ptr)
{
return (Option*) ((unsigned long long) ptr & ~1ull);
}
static bool isTagged(Option* ptr)
{
return ((unsigned long long) ptr & 1);
}
};
/**
* @brief Functions for checking the validity of option arguments.
*
* @copydetails CheckArg
*
* The following example code
* can serve as starting place for writing your own more complex CheckArg functions:
* @code
* struct Arg: public option::Arg
* {
* static void printError(const char* msg1, const option::Option& opt, const char* msg2)
* {
* fprintf(stderr, "ERROR: %s", msg1);
* fwrite(opt.name, opt.namelen, 1, stderr);
* fprintf(stderr, "%s", msg2);
* }
*
* static option::ArgStatus Unknown(const option::Option& option, bool msg)
* {
* if (msg) printError("Unknown option '", option, "'\n");
* return option::ARG_ILLEGAL;
* }
*
* static option::ArgStatus Required(const option::Option& option, bool msg)
* {
* if (option.arg != 0)
* return option::ARG_OK;
*
* if (msg) printError("Option '", option, "' requires an argument\n");
* return option::ARG_ILLEGAL;
* }
*
* static option::ArgStatus NonEmpty(const option::Option& option, bool msg)
* {
* if (option.arg != 0 && option.arg[0] != 0)
* return option::ARG_OK;
*
* if (msg) printError("Option '", option, "' requires a non-empty argument\n");
* return option::ARG_ILLEGAL;
* }
*
* static option::ArgStatus Numeric(const option::Option& option, bool msg)
* {
* char* endptr = 0;
* if (option.arg != 0 && strtol(option.arg, &endptr, 10)){};
* if (endptr != option.arg && *endptr == 0)
* return option::ARG_OK;
*
* if (msg) printError("Option '", option, "' requires a numeric argument\n");
* return option::ARG_ILLEGAL;
* }
* };
* @endcode
*/
struct Arg
{
//! @brief For options that don't take an argument: Returns ARG_NONE.
static ArgStatus None(const Option&, bool)
{
return ARG_NONE;
}
//! @brief Returns ARG_OK if the argument is attached and ARG_IGNORE otherwise.
static ArgStatus Optional(const Option& option, bool)
{
if (option.arg && option.name[option.namelen] != 0)
return ARG_OK;
else
return ARG_IGNORE;
}
};
/**
* @brief Determines the minimum lengths of the buffer and options arrays used for Parser.
*
* Because Parser doesn't use dynamic memory its output arrays have to be pre-allocated.
* If you don't want to use fixed size arrays (which may turn out too small, causing
* command line arguments to be dropped), you can use Stats to determine the correct sizes.
* Stats work cumulative. You can first pass in your default options and then the real
* options and afterwards the counts will reflect the union.
*/
struct Stats
{
/**
* @brief Number of elements needed for a @c buffer[] array to be used for
* @ref Parser::parse() "parsing" the same argument vectors that were fed
* into this Stats object.
*
* @note
* This number is always 1 greater than the actual number needed, to give
* you a sentinel element.
*/
unsigned buffer_max;
/**
* @brief Number of elements needed for an @c options[] array to be used for
* @ref Parser::parse() "parsing" the same argument vectors that were fed
* into this Stats object.
*
* @note
* @li This number is always 1 greater than the actual number needed, to give
* you a sentinel element.
* @li This number depends only on the @c usage, not the argument vectors, because
* the @c options array needs exactly one slot for each possible Descriptor::index.
*/
unsigned options_max;
/**
* @brief Creates a Stats object with counts set to 1 (for the sentinel element).
*/
Stats() :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
}
/**
* @brief Creates a new Stats object and immediately updates it for the
* given @c usage and argument vector. You may pass 0 for @c argc and/or @c argv,
* if you just want to update @ref options_max.
*
* @note
* The calls to Stats methods must match the later calls to Parser methods.
* See Parser::parse() for the meaning of the arguments.
*/
Stats(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, //
bool single_minus_longopt = false) :
buffer_max(1), options_max(1) // 1 more than necessary as sentinel
{
add(gnu, usage, argc, argv, min_abbr_len, single_minus_longopt);
}
//! @brief Stats(...) with non-const argv.