forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 319
/
CommandLine.h
2269 lines (1813 loc) · 75 KB
/
CommandLine.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
//===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This class implements a command line argument processor that is useful when
// creating a tool. It provides a simple, minimalistic interface that is easily
// extensible and supports nonlocal (library) command line options.
//
// Note that rather than trying to figure out what this code does, you should
// read the library documentation located in docs/CommandLine.html or looks at
// the many example usages in tools/*/*.cpp
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_COMMANDLINE_H
#define LLVM_SUPPORT_COMMANDLINE_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <climits>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <string>
#include <type_traits>
#include <vector>
namespace llvm {
namespace vfs {
class FileSystem;
}
class StringSaver;
/// This namespace contains all of the command line option processing machinery.
/// It is intentionally a short name to make qualified usage concise.
namespace cl {
//===----------------------------------------------------------------------===//
// Command line option processing entry point.
//
// Returns true on success. Otherwise, this will print the error message to
// stderr and exit if \p Errs is not set (nullptr by default), or print the
// error message to \p Errs and return false if \p Errs is provided.
//
// If EnvVar is not nullptr, command-line options are also parsed from the
// environment variable named by EnvVar. Precedence is given to occurrences
// from argv. This precedence is currently implemented by parsing argv after
// the environment variable, so it is only implemented correctly for options
// that give precedence to later occurrences. If your program supports options
// that give precedence to earlier occurrences, you will need to extend this
// function to support it correctly.
bool ParseCommandLineOptions(int argc, const char *const *argv,
StringRef Overview = "",
raw_ostream *Errs = nullptr,
const char *EnvVar = nullptr,
bool LongOptionsUseDoubleDash = false);
// Function pointer type for printing version information.
using VersionPrinterTy = std::function<void(raw_ostream &)>;
///===---------------------------------------------------------------------===//
/// Override the default (LLVM specific) version printer used to print out the
/// version when --version is given on the command line. This allows other
/// systems using the CommandLine utilities to print their own version string.
void SetVersionPrinter(VersionPrinterTy func);
///===---------------------------------------------------------------------===//
/// Add an extra printer to use in addition to the default one. This can be
/// called multiple times, and each time it adds a new function to the list
/// which will be called after the basic LLVM version printing is complete.
/// Each can then add additional information specific to the tool.
void AddExtraVersionPrinter(VersionPrinterTy func);
// Print option values.
// With -print-options print the difference between option values and defaults.
// With -print-all-options print all option values.
// (Currently not perfect, but best-effort.)
void PrintOptionValues();
// Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
class Option;
/// Adds a new option for parsing and provides the option it refers to.
///
/// \param O pointer to the option
/// \param Name the string name for the option to handle during parsing
///
/// Literal options are used by some parsers to register special option values.
/// This is how the PassNameParser registers pass names for opt.
void AddLiteralOption(Option &O, StringRef Name);
//===----------------------------------------------------------------------===//
// Flags permitted to be passed to command line arguments
//
enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
Optional = 0x00, // Zero or One occurrence
ZeroOrMore = 0x01, // Zero or more occurrences allowed
Required = 0x02, // One occurrence required
OneOrMore = 0x03, // One or more occurrences required
// Indicates that this option is fed anything that follows the last positional
// argument required by the application (it is an error if there are zero
// positional arguments, and a ConsumeAfter option is used).
// Thus, for example, all arguments to LLI are processed until a filename is
// found. Once a filename is found, all of the succeeding arguments are
// passed, unprocessed, to the ConsumeAfter option.
//
ConsumeAfter = 0x04
};
enum ValueExpected { // Is a value required for the option?
// zero reserved for the unspecified value
ValueOptional = 0x01, // The value can appear... or not
ValueRequired = 0x02, // The value is required to appear!
ValueDisallowed = 0x03 // A value may not be specified (for flags)
};
enum OptionHidden { // Control whether -help shows this option
NotHidden = 0x00, // Option included in -help & -help-hidden
Hidden = 0x01, // -help doesn't, but -help-hidden does
ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
};
// This controls special features that the option might have that cause it to be
// parsed differently...
//
// Prefix - This option allows arguments that are otherwise unrecognized to be
// matched by options that are a prefix of the actual value. This is useful for
// cases like a linker, where options are typically of the form '-lfoo' or
// '-L../../include' where -l or -L are the actual flags. When prefix is
// enabled, and used, the value for the flag comes from the suffix of the
// argument.
//
// AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject
// the Option=Value form.
//
enum FormattingFlags {
NormalFormatting = 0x00, // Nothing special
Positional = 0x01, // Is a positional argument, no '-' required
Prefix = 0x02, // Can this option directly prefix its value?
AlwaysPrefix = 0x03 // Can this option only directly prefix its value?
};
enum MiscFlags { // Miscellaneous flags to adjust argument
CommaSeparated = 0x01, // Should this cl::list split between commas?
PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
Sink = 0x04, // Should this cl::list eat all unknown options?
// Can this option group with other options?
// If this is enabled, multiple letter options are allowed to bunch together
// with only a single hyphen for the whole group. This allows emulation
// of the behavior that ls uses for example: ls -la === ls -l -a
Grouping = 0x08,
// Default option
DefaultOption = 0x10
};
//===----------------------------------------------------------------------===//
//
class OptionCategory {
private:
StringRef const Name;
StringRef const Description;
void registerCategory();
public:
OptionCategory(StringRef const Name,
StringRef const Description = "")
: Name(Name), Description(Description) {
registerCategory();
}
StringRef getName() const { return Name; }
StringRef getDescription() const { return Description; }
};
// The general Option Category (used as default category).
OptionCategory &getGeneralCategory();
//===----------------------------------------------------------------------===//
//
class SubCommand {
private:
StringRef Name;
StringRef Description;
protected:
void registerSubCommand();
void unregisterSubCommand();
public:
SubCommand(StringRef Name, StringRef Description = "")
: Name(Name), Description(Description) {
registerSubCommand();
}
SubCommand() = default;
// Get the special subcommand representing no subcommand.
static SubCommand &getTopLevel();
// Get the special subcommand that can be used to put an option into all
// subcommands.
static SubCommand &getAll();
void reset();
explicit operator bool() const;
StringRef getName() const { return Name; }
StringRef getDescription() const { return Description; }
SmallVector<Option *, 4> PositionalOpts;
SmallVector<Option *, 4> SinkOpts;
StringMap<Option *> OptionsMap;
Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
};
// A special subcommand representing no subcommand
extern ManagedStatic<SubCommand> TopLevelSubCommand;
// A special subcommand that can be used to put an option into all subcommands.
extern ManagedStatic<SubCommand> AllSubCommands;
//===----------------------------------------------------------------------===//
//
class Option {
friend class alias;
// Overriden by subclasses to handle the value passed into an argument. Should
// return true if there was an error processing the argument and the program
// should exit.
//
virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
StringRef Arg) = 0;
virtual enum ValueExpected getValueExpectedFlagDefault() const {
return ValueOptional;
}
// Out of line virtual function to provide home for the class.
virtual void anchor();
uint16_t NumOccurrences; // The number of times specified
// Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
// problems with signed enums in bitfields.
uint16_t Occurrences : 3; // enum NumOccurrencesFlag
// not using the enum type for 'Value' because zero is an implementation
// detail representing the non-value
uint16_t Value : 2;
uint16_t HiddenFlag : 2; // enum OptionHidden
uint16_t Formatting : 2; // enum FormattingFlags
uint16_t Misc : 5;
uint16_t FullyInitialized : 1; // Has addArgument been called?
uint16_t Position; // Position of last occurrence of the option
uint16_t AdditionalVals; // Greater than 0 for multi-valued option.
public:
StringRef ArgStr; // The argument string itself (ex: "help", "o")
StringRef HelpStr; // The descriptive text message for -help
StringRef ValueStr; // String describing what the value of this option is
SmallVector<OptionCategory *, 1>
Categories; // The Categories this option belongs to
SmallPtrSet<SubCommand *, 1> Subs; // The subcommands this option belongs to.
inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
return (enum NumOccurrencesFlag)Occurrences;
}
inline enum ValueExpected getValueExpectedFlag() const {
return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
}
inline enum OptionHidden getOptionHiddenFlag() const {
return (enum OptionHidden)HiddenFlag;
}
inline enum FormattingFlags getFormattingFlag() const {
return (enum FormattingFlags)Formatting;
}
inline unsigned getMiscFlags() const { return Misc; }
inline unsigned getPosition() const { return Position; }
inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
// Return true if the argstr != ""
bool hasArgStr() const { return !ArgStr.empty(); }
bool isPositional() const { return getFormattingFlag() == cl::Positional; }
bool isSink() const { return getMiscFlags() & cl::Sink; }
bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; }
bool isConsumeAfter() const {
return getNumOccurrencesFlag() == cl::ConsumeAfter;
}
bool isInAllSubCommands() const {
return Subs.contains(&SubCommand::getAll());
}
//-------------------------------------------------------------------------===
// Accessor functions set by OptionModifiers
//
void setArgStr(StringRef S);
void setDescription(StringRef S) { HelpStr = S; }
void setValueStr(StringRef S) { ValueStr = S; }
void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
void setMiscFlag(enum MiscFlags M) { Misc |= M; }
void setPosition(unsigned pos) { Position = pos; }
void addCategory(OptionCategory &C);
void addSubCommand(SubCommand &S) { Subs.insert(&S); }
protected:
explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
enum OptionHidden Hidden)
: NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
FullyInitialized(false), Position(0), AdditionalVals(0) {
Categories.push_back(&getGeneralCategory());
}
inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
public:
virtual ~Option() = default;
// Register this argument with the commandline system.
//
void addArgument();
/// Unregisters this option from the CommandLine system.
///
/// This option must have been the last option registered.
/// For testing purposes only.
void removeArgument();
// Return the width of the option tag for printing...
virtual size_t getOptionWidth() const = 0;
// Print out information about this option. The to-be-maintained width is
// specified.
//
virtual void printOptionInfo(size_t GlobalWidth) const = 0;
virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
virtual void setDefault() = 0;
// Prints the help string for an option.
//
// This maintains the Indent for multi-line descriptions.
// FirstLineIndentedBy is the count of chars of the first line
// i.e. the one containing the --<option name>.
static void printHelpStr(StringRef HelpStr, size_t Indent,
size_t FirstLineIndentedBy);
// Prints the help string for an enum value.
//
// This maintains the Indent for multi-line descriptions.
// FirstLineIndentedBy is the count of chars of the first line
// i.e. the one containing the =<value>.
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent,
size_t FirstLineIndentedBy);
virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
// Wrapper around handleOccurrence that enforces Flags.
//
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
bool MultiArg = false);
// Prints option name followed by message. Always returns true.
bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
bool error(const Twine &Message, raw_ostream &Errs) {
return error(Message, StringRef(), Errs);
}
inline int getNumOccurrences() const { return NumOccurrences; }
void reset();
};
//===----------------------------------------------------------------------===//
// Command line option modifiers that can be used to modify the behavior of
// command line option parsers...
//
// Modifier to set the description shown in the -help output...
struct desc {
StringRef Desc;
desc(StringRef Str) : Desc(Str) {}
void apply(Option &O) const { O.setDescription(Desc); }
};
// Modifier to set the value description shown in the -help output...
struct value_desc {
StringRef Desc;
value_desc(StringRef Str) : Desc(Str) {}
void apply(Option &O) const { O.setValueStr(Desc); }
};
// Specify a default (initial) value for the command line argument, if the
// default constructor for the argument type does not give you what you want.
// This is only valid on "opt" arguments, not on "list" arguments.
template <class Ty> struct initializer {
const Ty &Init;
initializer(const Ty &Val) : Init(Val) {}
template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
};
template <class Ty> struct list_initializer {
ArrayRef<Ty> Inits;
list_initializer(ArrayRef<Ty> Vals) : Inits(Vals) {}
template <class Opt> void apply(Opt &O) const { O.setInitialValues(Inits); }
};
template <class Ty> initializer<Ty> init(const Ty &Val) {
return initializer<Ty>(Val);
}
template <class Ty>
list_initializer<Ty> list_init(ArrayRef<Ty> Vals) {
return list_initializer<Ty>(Vals);
}
// Allow the user to specify which external variable they want to store the
// results of the command line argument processing into, if they don't want to
// store it in the option itself.
template <class Ty> struct LocationClass {
Ty &Loc;
LocationClass(Ty &L) : Loc(L) {}
template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
};
template <class Ty> LocationClass<Ty> location(Ty &L) {
return LocationClass<Ty>(L);
}
// Specify the Option category for the command line argument to belong to.
struct cat {
OptionCategory &Category;
cat(OptionCategory &c) : Category(c) {}
template <class Opt> void apply(Opt &O) const { O.addCategory(Category); }
};
// Specify the subcommand that this option belongs to.
struct sub {
SubCommand ⋐
sub(SubCommand &S) : Sub(S) {}
template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
};
// Specify a callback function to be called when an option is seen.
// Can be used to set other options automatically.
template <typename R, typename Ty> struct cb {
std::function<R(Ty)> CB;
cb(std::function<R(Ty)> CB) : CB(CB) {}
template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); }
};
namespace detail {
template <typename F>
struct callback_traits : public callback_traits<decltype(&F::operator())> {};
template <typename R, typename C, typename... Args>
struct callback_traits<R (C::*)(Args...) const> {
using result_type = R;
using arg_type = std::tuple_element_t<0, std::tuple<Args...>>;
static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter");
static_assert(std::is_same_v<result_type, void>,
"callback return type must be void");
static_assert(std::is_lvalue_reference_v<arg_type> &&
std::is_const_v<std::remove_reference_t<arg_type>>,
"callback arg_type must be a const lvalue reference");
};
} // namespace detail
template <typename F>
cb<typename detail::callback_traits<F>::result_type,
typename detail::callback_traits<F>::arg_type>
callback(F CB) {
using result_type = typename detail::callback_traits<F>::result_type;
using arg_type = typename detail::callback_traits<F>::arg_type;
return cb<result_type, arg_type>(CB);
}
//===----------------------------------------------------------------------===//
// Support value comparison outside the template.
struct GenericOptionValue {
virtual bool compare(const GenericOptionValue &V) const = 0;
protected:
GenericOptionValue() = default;
GenericOptionValue(const GenericOptionValue&) = default;
GenericOptionValue &operator=(const GenericOptionValue &) = default;
~GenericOptionValue() = default;
private:
virtual void anchor();
};
template <class DataType> struct OptionValue;
// The default value safely does nothing. Option value printing is only
// best-effort.
template <class DataType, bool isClass>
struct OptionValueBase : public GenericOptionValue {
// Temporary storage for argument passing.
using WrapperType = OptionValue<DataType>;
bool hasValue() const { return false; }
const DataType &getValue() const { llvm_unreachable("no default value"); }
// Some options may take their value from a different data type.
template <class DT> void setValue(const DT & /*V*/) {}
bool compare(const DataType & /*V*/) const { return false; }
bool compare(const GenericOptionValue & /*V*/) const override {
return false;
}
protected:
~OptionValueBase() = default;
};
// Simple copy of the option value.
template <class DataType> class OptionValueCopy : public GenericOptionValue {
DataType Value;
bool Valid = false;
protected:
OptionValueCopy(const OptionValueCopy&) = default;
OptionValueCopy &operator=(const OptionValueCopy &) = default;
~OptionValueCopy() = default;
public:
OptionValueCopy() = default;
bool hasValue() const { return Valid; }
const DataType &getValue() const {
assert(Valid && "invalid option value");
return Value;
}
void setValue(const DataType &V) {
Valid = true;
Value = V;
}
bool compare(const DataType &V) const { return Valid && (Value != V); }
bool compare(const GenericOptionValue &V) const override {
const OptionValueCopy<DataType> &VC =
static_cast<const OptionValueCopy<DataType> &>(V);
if (!VC.hasValue())
return false;
return compare(VC.getValue());
}
};
// Non-class option values.
template <class DataType>
struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
using WrapperType = DataType;
protected:
OptionValueBase() = default;
OptionValueBase(const OptionValueBase&) = default;
OptionValueBase &operator=(const OptionValueBase &) = default;
~OptionValueBase() = default;
};
// Top-level option class.
template <class DataType>
struct OptionValue final
: OptionValueBase<DataType, std::is_class_v<DataType>> {
OptionValue() = default;
OptionValue(const DataType &V) { this->setValue(V); }
// Some options may take their value from a different data type.
template <class DT> OptionValue<DataType> &operator=(const DT &V) {
this->setValue(V);
return *this;
}
};
// Other safe-to-copy-by-value common option types.
enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
template <>
struct OptionValue<cl::boolOrDefault> final
: OptionValueCopy<cl::boolOrDefault> {
using WrapperType = cl::boolOrDefault;
OptionValue() = default;
OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
setValue(V);
return *this;
}
private:
void anchor() override;
};
template <>
struct OptionValue<std::string> final : OptionValueCopy<std::string> {
using WrapperType = StringRef;
OptionValue() = default;
OptionValue(const std::string &V) { this->setValue(V); }
OptionValue<std::string> &operator=(const std::string &V) {
setValue(V);
return *this;
}
private:
void anchor() override;
};
//===----------------------------------------------------------------------===//
// Enum valued command line option
//
// This represents a single enum value, using "int" as the underlying type.
struct OptionEnumValue {
StringRef Name;
int Value;
StringRef Description;
};
#define clEnumVal(ENUMVAL, DESC) \
llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
#define clEnumValN(ENUMVAL, FLAGNAME, DESC) \
llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
// For custom data types, allow specifying a group of values together as the
// values that go into the mapping that the option handler uses.
//
class ValuesClass {
// Use a vector instead of a map, because the lists should be short,
// the overhead is less, and most importantly, it keeps them in the order
// inserted so we can print our option out nicely.
SmallVector<OptionEnumValue, 4> Values;
public:
ValuesClass(std::initializer_list<OptionEnumValue> Options)
: Values(Options) {}
template <class Opt> void apply(Opt &O) const {
for (const auto &Value : Values)
O.getParser().addLiteralOption(Value.Name, Value.Value,
Value.Description);
}
};
/// Helper to build a ValuesClass by forwarding a variable number of arguments
/// as an initializer list to the ValuesClass constructor.
template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
return ValuesClass({Options...});
}
//===----------------------------------------------------------------------===//
// Parameterizable parser for different data types. By default, known data types
// (string, int, bool) have specialized parsers, that do what you would expect.
// The default parser, used for data types that are not built-in, uses a mapping
// table to map specific options to values, which is used, among other things,
// to handle enum types.
//--------------------------------------------------
// This class holds all the non-generic code that we do not need replicated for
// every instance of the generic parser. This also allows us to put stuff into
// CommandLine.cpp
//
class generic_parser_base {
protected:
class GenericOptionInfo {
public:
GenericOptionInfo(StringRef name, StringRef helpStr)
: Name(name), HelpStr(helpStr) {}
StringRef Name;
StringRef HelpStr;
};
public:
generic_parser_base(Option &O) : Owner(O) {}
virtual ~generic_parser_base() = default;
// Base class should have virtual-destructor
// Virtual function implemented by generic subclass to indicate how many
// entries are in Values.
//
virtual unsigned getNumOptions() const = 0;
// Return option name N.
virtual StringRef getOption(unsigned N) const = 0;
// Return description N
virtual StringRef getDescription(unsigned N) const = 0;
// Return the width of the option tag for printing...
virtual size_t getOptionWidth(const Option &O) const;
virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
// Print out information about this option. The to-be-maintained width is
// specified.
//
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
const GenericOptionValue &Default,
size_t GlobalWidth) const;
// Print the value of an option and it's default.
//
// Template definition ensures that the option and default have the same
// DataType (via the same AnyOptionValue).
template <class AnyOptionValue>
void printOptionDiff(const Option &O, const AnyOptionValue &V,
const AnyOptionValue &Default,
size_t GlobalWidth) const {
printGenericOptionDiff(O, V, Default, GlobalWidth);
}
void initialize() {}
void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
// If there has been no argstr specified, that means that we need to add an
// argument for every possible option. This ensures that our options are
// vectored to us.
if (!Owner.hasArgStr())
for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
OptionNames.push_back(getOption(i));
}
enum ValueExpected getValueExpectedFlagDefault() const {
// If there is an ArgStr specified, then we are of the form:
//
// -opt=O2 or -opt O2 or -optO2
//
// In which case, the value is required. Otherwise if an arg str has not
// been specified, we are of the form:
//
// -O2 or O2 or -la (where -l and -a are separate options)
//
// If this is the case, we cannot allow a value.
//
if (Owner.hasArgStr())
return ValueRequired;
else
return ValueDisallowed;
}
// Return the option number corresponding to the specified
// argument string. If the option is not found, getNumOptions() is returned.
//
unsigned findOption(StringRef Name);
protected:
Option &Owner;
};
// Default parser implementation - This implementation depends on having a
// mapping of recognized options to values of some sort. In addition to this,
// each entry in the mapping also tracks a help message that is printed with the
// command line option for -help. Because this is a simple mapping parser, the
// data type can be any unsupported type.
//
template <class DataType> class parser : public generic_parser_base {
protected:
class OptionInfo : public GenericOptionInfo {
public:
OptionInfo(StringRef name, DataType v, StringRef helpStr)
: GenericOptionInfo(name, helpStr), V(v) {}
OptionValue<DataType> V;
};
SmallVector<OptionInfo, 8> Values;
public:
parser(Option &O) : generic_parser_base(O) {}
using parser_data_type = DataType;
// Implement virtual functions needed by generic_parser_base
unsigned getNumOptions() const override { return unsigned(Values.size()); }
StringRef getOption(unsigned N) const override { return Values[N].Name; }
StringRef getDescription(unsigned N) const override {
return Values[N].HelpStr;
}
// Return the value of option name N.
const GenericOptionValue &getOptionValue(unsigned N) const override {
return Values[N].V;
}
// Return true on error.
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
StringRef ArgVal;
if (Owner.hasArgStr())
ArgVal = Arg;
else
ArgVal = ArgName;
for (size_t i = 0, e = Values.size(); i != e; ++i)
if (Values[i].Name == ArgVal) {
V = Values[i].V.getValue();
return false;
}
return O.error("Cannot find option named '" + ArgVal + "'!");
}
/// Add an entry to the mapping table.
///
template <class DT>
void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
assert(findOption(Name) == Values.size() && "Option already exists!");
OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
Values.push_back(X);
AddLiteralOption(Owner, Name);
}
/// Remove the specified option.
///
void removeLiteralOption(StringRef Name) {
unsigned N = findOption(Name);
assert(N != Values.size() && "Option not found!");
Values.erase(Values.begin() + N);
}
};
//--------------------------------------------------
// Super class of parsers to provide boilerplate code
//
class basic_parser_impl { // non-template implementation of basic_parser<t>
public:
basic_parser_impl(Option &) {}
virtual ~basic_parser_impl() = default;
enum ValueExpected getValueExpectedFlagDefault() const {
return ValueRequired;
}
void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
void initialize() {}
// Return the width of the option tag for printing...
size_t getOptionWidth(const Option &O) const;
// Print out information about this option. The to-be-maintained width is
// specified.
//
void printOptionInfo(const Option &O, size_t GlobalWidth) const;
// Print a placeholder for options that don't yet support printOptionDiff().
void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
// Overload in subclass to provide a better default value.
virtual StringRef getValueName() const { return "value"; }
// An out-of-line virtual method to provide a 'home' for this class.
virtual void anchor();
protected:
// A helper for basic_parser::printOptionDiff.
void printOptionName(const Option &O, size_t GlobalWidth) const;
};
// The real basic parser is just a template wrapper that provides a typedef for
// the provided data type.
//
template <class DataType> class basic_parser : public basic_parser_impl {
public:
using parser_data_type = DataType;
using OptVal = OptionValue<DataType>;
basic_parser(Option &O) : basic_parser_impl(O) {}
};
//--------------------------------------------------
extern template class basic_parser<bool>;
template <> class parser<bool> : public basic_parser<bool> {
public:
parser(Option &O) : basic_parser(O) {}
// Return true on error.
bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
void initialize() {}
enum ValueExpected getValueExpectedFlagDefault() const {
return ValueOptional;
}
// Do not print =<value> at all.
StringRef getValueName() const override { return StringRef(); }
void printOptionDiff(const Option &O, bool V, OptVal Default,
size_t GlobalWidth) const;
// An out-of-line virtual method to provide a 'home' for this class.
void anchor() override;
};
//--------------------------------------------------
extern template class basic_parser<boolOrDefault>;
template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
public:
parser(Option &O) : basic_parser(O) {}
// Return true on error.
bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
enum ValueExpected getValueExpectedFlagDefault() const {
return ValueOptional;
}
// Do not print =<value> at all.
StringRef getValueName() const override { return StringRef(); }
void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
size_t GlobalWidth) const;
// An out-of-line virtual method to provide a 'home' for this class.
void anchor() override;
};
//--------------------------------------------------
extern template class basic_parser<int>;
template <> class parser<int> : public basic_parser<int> {
public:
parser(Option &O) : basic_parser(O) {}
// Return true on error.
bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
// Overload in subclass to provide a better default value.
StringRef getValueName() const override { return "int"; }
void printOptionDiff(const Option &O, int V, OptVal Default,
size_t GlobalWidth) const;
// An out-of-line virtual method to provide a 'home' for this class.
void anchor() override;
};