1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This class implements a command line argument processor that is useful when 10 // creating a tool. It provides a simple, minimalistic interface that is easily 11 // extensible and supports nonlocal (library) command line options. 12 // 13 // Note that rather than trying to figure out what this code does, you should 14 // read the library documentation located in docs/CommandLine.html or looks at 15 // the many example usages in tools/*/*.cpp 16 // 17 //===----------------------------------------------------------------------===// 18 19 #ifndef LLVM_SUPPORT_COMMANDLINE_H 20 #define LLVM_SUPPORT_COMMANDLINE_H 21 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringMap.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/ADT/iterator_range.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/StringSaver.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <cassert> 34 #include <climits> 35 #include <cstddef> 36 #include <functional> 37 #include <initializer_list> 38 #include <string> 39 #include <type_traits> 40 #include <vector> 41 42 namespace llvm { 43 44 namespace vfs { 45 class FileSystem; 46 } 47 48 class StringSaver; 49 50 /// This namespace contains all of the command line option processing machinery. 51 /// It is intentionally a short name to make qualified usage concise. 52 namespace cl { 53 54 //===----------------------------------------------------------------------===// 55 // Command line option processing entry point. 56 // 57 // Returns true on success. Otherwise, this will print the error message to 58 // stderr and exit if \p Errs is not set (nullptr by default), or print the 59 // error message to \p Errs and return false if \p Errs is provided. 60 // 61 // If EnvVar is not nullptr, command-line options are also parsed from the 62 // environment variable named by EnvVar. Precedence is given to occurrences 63 // from argv. This precedence is currently implemented by parsing argv after 64 // the environment variable, so it is only implemented correctly for options 65 // that give precedence to later occurrences. If your program supports options 66 // that give precedence to earlier occurrences, you will need to extend this 67 // function to support it correctly. 68 bool ParseCommandLineOptions(int argc, const char *const *argv, 69 StringRef Overview = "", 70 raw_ostream *Errs = nullptr, 71 const char *EnvVar = nullptr, 72 bool LongOptionsUseDoubleDash = false); 73 74 // Function pointer type for printing version information. 75 using VersionPrinterTy = std::function<void(raw_ostream &)>; 76 77 ///===---------------------------------------------------------------------===// 78 /// Override the default (LLVM specific) version printer used to print out the 79 /// version when --version is given on the command line. This allows other 80 /// systems using the CommandLine utilities to print their own version string. 81 void SetVersionPrinter(VersionPrinterTy func); 82 83 ///===---------------------------------------------------------------------===// 84 /// Add an extra printer to use in addition to the default one. This can be 85 /// called multiple times, and each time it adds a new function to the list 86 /// which will be called after the basic LLVM version printing is complete. 87 /// Each can then add additional information specific to the tool. 88 void AddExtraVersionPrinter(VersionPrinterTy func); 89 90 // Print option values. 91 // With -print-options print the difference between option values and defaults. 92 // With -print-all-options print all option values. 93 // (Currently not perfect, but best-effort.) 94 void PrintOptionValues(); 95 96 // Forward declaration - AddLiteralOption needs to be up here to make gcc happy. 97 class Option; 98 99 /// Adds a new option for parsing and provides the option it refers to. 100 /// 101 /// \param O pointer to the option 102 /// \param Name the string name for the option to handle during parsing 103 /// 104 /// Literal options are used by some parsers to register special option values. 105 /// This is how the PassNameParser registers pass names for opt. 106 void AddLiteralOption(Option &O, StringRef Name); 107 108 //===----------------------------------------------------------------------===// 109 // Flags permitted to be passed to command line arguments 110 // 111 112 enum NumOccurrencesFlag { // Flags for the number of occurrences allowed 113 Optional = 0x00, // Zero or One occurrence 114 ZeroOrMore = 0x01, // Zero or more occurrences allowed 115 Required = 0x02, // One occurrence required 116 OneOrMore = 0x03, // One or more occurrences required 117 118 // Indicates that this option is fed anything that follows the last positional 119 // argument required by the application (it is an error if there are zero 120 // positional arguments, and a ConsumeAfter option is used). 121 // Thus, for example, all arguments to LLI are processed until a filename is 122 // found. Once a filename is found, all of the succeeding arguments are 123 // passed, unprocessed, to the ConsumeAfter option. 124 // 125 ConsumeAfter = 0x04 126 }; 127 128 enum ValueExpected { // Is a value required for the option? 129 // zero reserved for the unspecified value 130 ValueOptional = 0x01, // The value can appear... or not 131 ValueRequired = 0x02, // The value is required to appear! 132 ValueDisallowed = 0x03 // A value may not be specified (for flags) 133 }; 134 135 enum OptionHidden { // Control whether -help shows this option 136 NotHidden = 0x00, // Option included in -help & -help-hidden 137 Hidden = 0x01, // -help doesn't, but -help-hidden does 138 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg 139 }; 140 141 // This controls special features that the option might have that cause it to be 142 // parsed differently... 143 // 144 // Prefix - This option allows arguments that are otherwise unrecognized to be 145 // matched by options that are a prefix of the actual value. This is useful for 146 // cases like a linker, where options are typically of the form '-lfoo' or 147 // '-L../../include' where -l or -L are the actual flags. When prefix is 148 // enabled, and used, the value for the flag comes from the suffix of the 149 // argument. 150 // 151 // AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject 152 // the Option=Value form. 153 // 154 155 enum FormattingFlags { 156 NormalFormatting = 0x00, // Nothing special 157 Positional = 0x01, // Is a positional argument, no '-' required 158 Prefix = 0x02, // Can this option directly prefix its value? 159 AlwaysPrefix = 0x03 // Can this option only directly prefix its value? 160 }; 161 162 enum MiscFlags { // Miscellaneous flags to adjust argument 163 CommaSeparated = 0x01, // Should this cl::list split between commas? 164 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args? 165 Sink = 0x04, // Should this cl::list eat all unknown options? 166 167 // Can this option group with other options? 168 // If this is enabled, multiple letter options are allowed to bunch together 169 // with only a single hyphen for the whole group. This allows emulation 170 // of the behavior that ls uses for example: ls -la === ls -l -a 171 Grouping = 0x08, 172 173 // Default option 174 DefaultOption = 0x10 175 }; 176 177 //===----------------------------------------------------------------------===// 178 // 179 class OptionCategory { 180 private: 181 StringRef const Name; 182 StringRef const Description; 183 184 void registerCategory(); 185 186 public: 187 OptionCategory(StringRef const Name, 188 StringRef const Description = "") 189 : Name(Name), Description(Description) { 190 registerCategory(); 191 } 192 193 StringRef getName() const { return Name; } 194 StringRef getDescription() const { return Description; } 195 }; 196 197 // The general Option Category (used as default category). 198 OptionCategory &getGeneralCategory(); 199 200 //===----------------------------------------------------------------------===// 201 // 202 class SubCommand { 203 private: 204 StringRef Name; 205 StringRef Description; 206 207 protected: 208 void registerSubCommand(); 209 void unregisterSubCommand(); 210 211 public: 212 SubCommand(StringRef Name, StringRef Description = "") 213 : Name(Name), Description(Description) { 214 registerSubCommand(); 215 } 216 SubCommand() = default; 217 218 // Get the special subcommand representing no subcommand. 219 static SubCommand &getTopLevel(); 220 221 // Get the special subcommand that can be used to put an option into all 222 // subcommands. 223 static SubCommand &getAll(); 224 225 void reset(); 226 227 explicit operator bool() const; 228 229 StringRef getName() const { return Name; } 230 StringRef getDescription() const { return Description; } 231 232 SmallVector<Option *, 4> PositionalOpts; 233 SmallVector<Option *, 4> SinkOpts; 234 StringMap<Option *> OptionsMap; 235 236 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists. 237 }; 238 239 class SubCommandGroup { 240 SmallVector<SubCommand *, 4> Subs; 241 242 public: 243 SubCommandGroup(std::initializer_list<SubCommand *> IL) : Subs(IL) {} 244 245 ArrayRef<SubCommand *> getSubCommands() const { return Subs; } 246 }; 247 248 //===----------------------------------------------------------------------===// 249 // 250 class Option { 251 friend class alias; 252 253 // Overriden by subclasses to handle the value passed into an argument. Should 254 // return true if there was an error processing the argument and the program 255 // should exit. 256 // 257 virtual bool handleOccurrence(unsigned pos, StringRef ArgName, 258 StringRef Arg) = 0; 259 260 virtual enum ValueExpected getValueExpectedFlagDefault() const { 261 return ValueOptional; 262 } 263 264 // Out of line virtual function to provide home for the class. 265 virtual void anchor(); 266 267 uint16_t NumOccurrences; // The number of times specified 268 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid 269 // problems with signed enums in bitfields. 270 uint16_t Occurrences : 3; // enum NumOccurrencesFlag 271 // not using the enum type for 'Value' because zero is an implementation 272 // detail representing the non-value 273 uint16_t Value : 2; 274 uint16_t HiddenFlag : 2; // enum OptionHidden 275 uint16_t Formatting : 2; // enum FormattingFlags 276 uint16_t Misc : 5; 277 uint16_t FullyInitialized : 1; // Has addArgument been called? 278 uint16_t Position; // Position of last occurrence of the option 279 uint16_t AdditionalVals; // Greater than 0 for multi-valued option. 280 281 public: 282 StringRef ArgStr; // The argument string itself (ex: "help", "o") 283 StringRef HelpStr; // The descriptive text message for -help 284 StringRef ValueStr; // String describing what the value of this option is 285 SmallVector<OptionCategory *, 1> 286 Categories; // The Categories this option belongs to 287 SmallPtrSet<SubCommand *, 1> Subs; // The subcommands this option belongs to. 288 289 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const { 290 return (enum NumOccurrencesFlag)Occurrences; 291 } 292 293 inline enum ValueExpected getValueExpectedFlag() const { 294 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault(); 295 } 296 297 inline enum OptionHidden getOptionHiddenFlag() const { 298 return (enum OptionHidden)HiddenFlag; 299 } 300 301 inline enum FormattingFlags getFormattingFlag() const { 302 return (enum FormattingFlags)Formatting; 303 } 304 305 inline unsigned getMiscFlags() const { return Misc; } 306 inline unsigned getPosition() const { return Position; } 307 inline unsigned getNumAdditionalVals() const { return AdditionalVals; } 308 309 // Return true if the argstr != "" 310 bool hasArgStr() const { return !ArgStr.empty(); } 311 bool isPositional() const { return getFormattingFlag() == cl::Positional; } 312 bool isSink() const { return getMiscFlags() & cl::Sink; } 313 bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; } 314 315 bool isConsumeAfter() const { 316 return getNumOccurrencesFlag() == cl::ConsumeAfter; 317 } 318 319 //-------------------------------------------------------------------------=== 320 // Accessor functions set by OptionModifiers 321 // 322 void setArgStr(StringRef S); 323 void setDescription(StringRef S) { HelpStr = S; } 324 void setValueStr(StringRef S) { ValueStr = S; } 325 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; } 326 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; } 327 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; } 328 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; } 329 void setMiscFlag(enum MiscFlags M) { Misc |= M; } 330 void setPosition(unsigned pos) { Position = pos; } 331 void addCategory(OptionCategory &C); 332 void addSubCommand(SubCommand &S) { Subs.insert(&S); } 333 334 protected: 335 explicit Option(enum NumOccurrencesFlag OccurrencesFlag, 336 enum OptionHidden Hidden) 337 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0), 338 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), 339 FullyInitialized(false), Position(0), AdditionalVals(0) { 340 Categories.push_back(&getGeneralCategory()); 341 } 342 343 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; } 344 345 public: 346 virtual ~Option() = default; 347 348 // Register this argument with the commandline system. 349 // 350 void addArgument(); 351 352 /// Unregisters this option from the CommandLine system. 353 /// 354 /// This option must have been the last option registered. 355 /// For testing purposes only. 356 void removeArgument(); 357 358 // Return the width of the option tag for printing... 359 virtual size_t getOptionWidth() const = 0; 360 361 // Print out information about this option. The to-be-maintained width is 362 // specified. 363 // 364 virtual void printOptionInfo(size_t GlobalWidth) const = 0; 365 366 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0; 367 368 virtual void setDefault() = 0; 369 370 // Prints the help string for an option. 371 // 372 // This maintains the Indent for multi-line descriptions. 373 // FirstLineIndentedBy is the count of chars of the first line 374 // i.e. the one containing the --<option name>. 375 static void printHelpStr(StringRef HelpStr, size_t Indent, 376 size_t FirstLineIndentedBy); 377 378 // Prints the help string for an enum value. 379 // 380 // This maintains the Indent for multi-line descriptions. 381 // FirstLineIndentedBy is the count of chars of the first line 382 // i.e. the one containing the =<value>. 383 static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, 384 size_t FirstLineIndentedBy); 385 386 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} 387 388 // Wrapper around handleOccurrence that enforces Flags. 389 // 390 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 391 bool MultiArg = false); 392 393 // Prints option name followed by message. Always returns true. 394 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs()); 395 bool error(const Twine &Message, raw_ostream &Errs) { 396 return error(Message, StringRef(), Errs); 397 } 398 399 inline int getNumOccurrences() const { return NumOccurrences; } 400 void reset(); 401 }; 402 403 //===----------------------------------------------------------------------===// 404 // Command line option modifiers that can be used to modify the behavior of 405 // command line option parsers... 406 // 407 408 // Modifier to set the description shown in the -help output... 409 struct desc { 410 StringRef Desc; 411 412 desc(StringRef Str) : Desc(Str) {} 413 414 void apply(Option &O) const { O.setDescription(Desc); } 415 }; 416 417 // Modifier to set the value description shown in the -help output... 418 struct value_desc { 419 StringRef Desc; 420 421 value_desc(StringRef Str) : Desc(Str) {} 422 423 void apply(Option &O) const { O.setValueStr(Desc); } 424 }; 425 426 // Specify a default (initial) value for the command line argument, if the 427 // default constructor for the argument type does not give you what you want. 428 // This is only valid on "opt" arguments, not on "list" arguments. 429 template <class Ty> struct initializer { 430 const Ty &Init; 431 initializer(const Ty &Val) : Init(Val) {} 432 433 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); } 434 }; 435 436 template <class Ty> struct list_initializer { 437 ArrayRef<Ty> Inits; 438 list_initializer(ArrayRef<Ty> Vals) : Inits(Vals) {} 439 440 template <class Opt> void apply(Opt &O) const { O.setInitialValues(Inits); } 441 }; 442 443 template <class Ty> initializer<Ty> init(const Ty &Val) { 444 return initializer<Ty>(Val); 445 } 446 447 template <class Ty> 448 list_initializer<Ty> list_init(ArrayRef<Ty> Vals) { 449 return list_initializer<Ty>(Vals); 450 } 451 452 // Allow the user to specify which external variable they want to store the 453 // results of the command line argument processing into, if they don't want to 454 // store it in the option itself. 455 template <class Ty> struct LocationClass { 456 Ty &Loc; 457 458 LocationClass(Ty &L) : Loc(L) {} 459 460 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); } 461 }; 462 463 template <class Ty> LocationClass<Ty> location(Ty &L) { 464 return LocationClass<Ty>(L); 465 } 466 467 // Specify the Option category for the command line argument to belong to. 468 struct cat { 469 OptionCategory &Category; 470 471 cat(OptionCategory &c) : Category(c) {} 472 473 template <class Opt> void apply(Opt &O) const { O.addCategory(Category); } 474 }; 475 476 // Specify the subcommand that this option belongs to. 477 struct sub { 478 SubCommand *Sub = nullptr; 479 SubCommandGroup *Group = nullptr; 480 481 sub(SubCommand &S) : Sub(&S) {} 482 sub(SubCommandGroup &G) : Group(&G) {} 483 484 template <class Opt> void apply(Opt &O) const { 485 if (Sub) 486 O.addSubCommand(*Sub); 487 else if (Group) 488 for (SubCommand *SC : Group->getSubCommands()) 489 O.addSubCommand(*SC); 490 } 491 }; 492 493 // Specify a callback function to be called when an option is seen. 494 // Can be used to set other options automatically. 495 template <typename R, typename Ty> struct cb { 496 std::function<R(Ty)> CB; 497 498 cb(std::function<R(Ty)> CB) : CB(CB) {} 499 500 template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); } 501 }; 502 503 namespace detail { 504 template <typename F> 505 struct callback_traits : public callback_traits<decltype(&F::operator())> {}; 506 507 template <typename R, typename C, typename... Args> 508 struct callback_traits<R (C::*)(Args...) const> { 509 using result_type = R; 510 using arg_type = std::tuple_element_t<0, std::tuple<Args...>>; 511 static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter"); 512 static_assert(std::is_same_v<result_type, void>, 513 "callback return type must be void"); 514 static_assert(std::is_lvalue_reference_v<arg_type> && 515 std::is_const_v<std::remove_reference_t<arg_type>>, 516 "callback arg_type must be a const lvalue reference"); 517 }; 518 } // namespace detail 519 520 template <typename F> 521 cb<typename detail::callback_traits<F>::result_type, 522 typename detail::callback_traits<F>::arg_type> 523 callback(F CB) { 524 using result_type = typename detail::callback_traits<F>::result_type; 525 using arg_type = typename detail::callback_traits<F>::arg_type; 526 return cb<result_type, arg_type>(CB); 527 } 528 529 //===----------------------------------------------------------------------===// 530 531 // Support value comparison outside the template. 532 struct GenericOptionValue { 533 virtual bool compare(const GenericOptionValue &V) const = 0; 534 535 protected: 536 GenericOptionValue() = default; 537 GenericOptionValue(const GenericOptionValue&) = default; 538 GenericOptionValue &operator=(const GenericOptionValue &) = default; 539 ~GenericOptionValue() = default; 540 541 private: 542 virtual void anchor(); 543 }; 544 545 template <class DataType> struct OptionValue; 546 547 // The default value safely does nothing. Option value printing is only 548 // best-effort. 549 template <class DataType, bool isClass> 550 struct OptionValueBase : public GenericOptionValue { 551 // Temporary storage for argument passing. 552 using WrapperType = OptionValue<DataType>; 553 554 bool hasValue() const { return false; } 555 556 const DataType &getValue() const { llvm_unreachable("no default value"); } 557 558 // Some options may take their value from a different data type. 559 template <class DT> void setValue(const DT & /*V*/) {} 560 561 // Returns whether this instance matches the argument. 562 bool compare(const DataType & /*V*/) const { return false; } 563 564 bool compare(const GenericOptionValue & /*V*/) const override { 565 return false; 566 } 567 568 protected: 569 ~OptionValueBase() = default; 570 }; 571 572 // Simple copy of the option value. 573 template <class DataType> class OptionValueCopy : public GenericOptionValue { 574 DataType Value; 575 bool Valid = false; 576 577 protected: 578 OptionValueCopy(const OptionValueCopy&) = default; 579 OptionValueCopy &operator=(const OptionValueCopy &) = default; 580 ~OptionValueCopy() = default; 581 582 public: 583 OptionValueCopy() = default; 584 585 bool hasValue() const { return Valid; } 586 587 const DataType &getValue() const { 588 assert(Valid && "invalid option value"); 589 return Value; 590 } 591 592 void setValue(const DataType &V) { 593 Valid = true; 594 Value = V; 595 } 596 597 // Returns whether this instance matches V. 598 bool compare(const DataType &V) const { return Valid && (Value == V); } 599 600 bool compare(const GenericOptionValue &V) const override { 601 const OptionValueCopy<DataType> &VC = 602 static_cast<const OptionValueCopy<DataType> &>(V); 603 if (!VC.hasValue()) 604 return false; 605 return compare(VC.getValue()); 606 } 607 }; 608 609 // Non-class option values. 610 template <class DataType> 611 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> { 612 using WrapperType = DataType; 613 614 protected: 615 OptionValueBase() = default; 616 OptionValueBase(const OptionValueBase&) = default; 617 OptionValueBase &operator=(const OptionValueBase &) = default; 618 ~OptionValueBase() = default; 619 }; 620 621 // Top-level option class. 622 template <class DataType> 623 struct OptionValue final 624 : OptionValueBase<DataType, std::is_class_v<DataType>> { 625 OptionValue() = default; 626 627 OptionValue(const DataType &V) { this->setValue(V); } 628 629 // Some options may take their value from a different data type. 630 template <class DT> OptionValue<DataType> &operator=(const DT &V) { 631 this->setValue(V); 632 return *this; 633 } 634 }; 635 636 // Other safe-to-copy-by-value common option types. 637 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE }; 638 template <> 639 struct OptionValue<cl::boolOrDefault> final 640 : OptionValueCopy<cl::boolOrDefault> { 641 using WrapperType = cl::boolOrDefault; 642 643 OptionValue() = default; 644 645 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); } 646 647 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) { 648 setValue(V); 649 return *this; 650 } 651 652 private: 653 void anchor() override; 654 }; 655 656 template <> 657 struct OptionValue<std::string> final : OptionValueCopy<std::string> { 658 using WrapperType = StringRef; 659 660 OptionValue() = default; 661 662 OptionValue(const std::string &V) { this->setValue(V); } 663 664 OptionValue<std::string> &operator=(const std::string &V) { 665 setValue(V); 666 return *this; 667 } 668 669 private: 670 void anchor() override; 671 }; 672 673 //===----------------------------------------------------------------------===// 674 // Enum valued command line option 675 // 676 677 // This represents a single enum value, using "int" as the underlying type. 678 struct OptionEnumValue { 679 StringRef Name; 680 int Value; 681 StringRef Description; 682 }; 683 684 #define clEnumVal(ENUMVAL, DESC) \ 685 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC } 686 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) \ 687 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC } 688 689 // For custom data types, allow specifying a group of values together as the 690 // values that go into the mapping that the option handler uses. 691 // 692 class ValuesClass { 693 // Use a vector instead of a map, because the lists should be short, 694 // the overhead is less, and most importantly, it keeps them in the order 695 // inserted so we can print our option out nicely. 696 SmallVector<OptionEnumValue, 4> Values; 697 698 public: 699 ValuesClass(std::initializer_list<OptionEnumValue> Options) 700 : Values(Options) {} 701 702 template <class Opt> void apply(Opt &O) const { 703 for (const auto &Value : Values) 704 O.getParser().addLiteralOption(Value.Name, Value.Value, 705 Value.Description); 706 } 707 }; 708 709 /// Helper to build a ValuesClass by forwarding a variable number of arguments 710 /// as an initializer list to the ValuesClass constructor. 711 template <typename... OptsTy> ValuesClass values(OptsTy... Options) { 712 return ValuesClass({Options...}); 713 } 714 715 //===----------------------------------------------------------------------===// 716 // Parameterizable parser for different data types. By default, known data types 717 // (string, int, bool) have specialized parsers, that do what you would expect. 718 // The default parser, used for data types that are not built-in, uses a mapping 719 // table to map specific options to values, which is used, among other things, 720 // to handle enum types. 721 722 //-------------------------------------------------- 723 // This class holds all the non-generic code that we do not need replicated for 724 // every instance of the generic parser. This also allows us to put stuff into 725 // CommandLine.cpp 726 // 727 class generic_parser_base { 728 protected: 729 class GenericOptionInfo { 730 public: 731 GenericOptionInfo(StringRef name, StringRef helpStr) 732 : Name(name), HelpStr(helpStr) {} 733 StringRef Name; 734 StringRef HelpStr; 735 }; 736 737 public: 738 generic_parser_base(Option &O) : Owner(O) {} 739 740 virtual ~generic_parser_base() = default; 741 // Base class should have virtual-destructor 742 743 // Virtual function implemented by generic subclass to indicate how many 744 // entries are in Values. 745 // 746 virtual unsigned getNumOptions() const = 0; 747 748 // Return option name N. 749 virtual StringRef getOption(unsigned N) const = 0; 750 751 // Return description N 752 virtual StringRef getDescription(unsigned N) const = 0; 753 754 // Return the width of the option tag for printing... 755 virtual size_t getOptionWidth(const Option &O) const; 756 757 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0; 758 759 // Print out information about this option. The to-be-maintained width is 760 // specified. 761 // 762 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const; 763 764 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, 765 const GenericOptionValue &Default, 766 size_t GlobalWidth) const; 767 768 // Print the value of an option and it's default. 769 // 770 // Template definition ensures that the option and default have the same 771 // DataType (via the same AnyOptionValue). 772 template <class AnyOptionValue> 773 void printOptionDiff(const Option &O, const AnyOptionValue &V, 774 const AnyOptionValue &Default, 775 size_t GlobalWidth) const { 776 printGenericOptionDiff(O, V, Default, GlobalWidth); 777 } 778 779 void initialize() {} 780 781 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) { 782 // If there has been no argstr specified, that means that we need to add an 783 // argument for every possible option. This ensures that our options are 784 // vectored to us. 785 if (!Owner.hasArgStr()) 786 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 787 OptionNames.push_back(getOption(i)); 788 } 789 790 enum ValueExpected getValueExpectedFlagDefault() const { 791 // If there is an ArgStr specified, then we are of the form: 792 // 793 // -opt=O2 or -opt O2 or -optO2 794 // 795 // In which case, the value is required. Otherwise if an arg str has not 796 // been specified, we are of the form: 797 // 798 // -O2 or O2 or -la (where -l and -a are separate options) 799 // 800 // If this is the case, we cannot allow a value. 801 // 802 if (Owner.hasArgStr()) 803 return ValueRequired; 804 else 805 return ValueDisallowed; 806 } 807 808 // Return the option number corresponding to the specified 809 // argument string. If the option is not found, getNumOptions() is returned. 810 // 811 unsigned findOption(StringRef Name); 812 813 protected: 814 Option &Owner; 815 }; 816 817 // Default parser implementation - This implementation depends on having a 818 // mapping of recognized options to values of some sort. In addition to this, 819 // each entry in the mapping also tracks a help message that is printed with the 820 // command line option for -help. Because this is a simple mapping parser, the 821 // data type can be any unsupported type. 822 // 823 template <class DataType> class parser : public generic_parser_base { 824 protected: 825 class OptionInfo : public GenericOptionInfo { 826 public: 827 OptionInfo(StringRef name, DataType v, StringRef helpStr) 828 : GenericOptionInfo(name, helpStr), V(v) {} 829 830 OptionValue<DataType> V; 831 }; 832 SmallVector<OptionInfo, 8> Values; 833 834 public: 835 parser(Option &O) : generic_parser_base(O) {} 836 837 using parser_data_type = DataType; 838 839 // Implement virtual functions needed by generic_parser_base 840 unsigned getNumOptions() const override { return unsigned(Values.size()); } 841 StringRef getOption(unsigned N) const override { return Values[N].Name; } 842 StringRef getDescription(unsigned N) const override { 843 return Values[N].HelpStr; 844 } 845 846 // Return the value of option name N. 847 const GenericOptionValue &getOptionValue(unsigned N) const override { 848 return Values[N].V; 849 } 850 851 // Return true on error. 852 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) { 853 StringRef ArgVal; 854 if (Owner.hasArgStr()) 855 ArgVal = Arg; 856 else 857 ArgVal = ArgName; 858 859 for (size_t i = 0, e = Values.size(); i != e; ++i) 860 if (Values[i].Name == ArgVal) { 861 V = Values[i].V.getValue(); 862 return false; 863 } 864 865 return O.error("Cannot find option named '" + ArgVal + "'!"); 866 } 867 868 /// Add an entry to the mapping table. 869 /// 870 template <class DT> 871 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) { 872 #ifndef NDEBUG 873 if (findOption(Name) != Values.size()) 874 report_fatal_error("Option '" + Name + "' already exists!"); 875 #endif 876 OptionInfo X(Name, static_cast<DataType>(V), HelpStr); 877 Values.push_back(X); 878 AddLiteralOption(Owner, Name); 879 } 880 881 /// Remove the specified option. 882 /// 883 void removeLiteralOption(StringRef Name) { 884 unsigned N = findOption(Name); 885 assert(N != Values.size() && "Option not found!"); 886 Values.erase(Values.begin() + N); 887 } 888 }; 889 890 //-------------------------------------------------- 891 // Super class of parsers to provide boilerplate code 892 // 893 class basic_parser_impl { // non-template implementation of basic_parser<t> 894 public: 895 basic_parser_impl(Option &) {} 896 897 virtual ~basic_parser_impl() = default; 898 899 enum ValueExpected getValueExpectedFlagDefault() const { 900 return ValueRequired; 901 } 902 903 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} 904 905 void initialize() {} 906 907 // Return the width of the option tag for printing... 908 size_t getOptionWidth(const Option &O) const; 909 910 // Print out information about this option. The to-be-maintained width is 911 // specified. 912 // 913 void printOptionInfo(const Option &O, size_t GlobalWidth) const; 914 915 // Print a placeholder for options that don't yet support printOptionDiff(). 916 void printOptionNoValue(const Option &O, size_t GlobalWidth) const; 917 918 // Overload in subclass to provide a better default value. 919 virtual StringRef getValueName() const { return "value"; } 920 921 // An out-of-line virtual method to provide a 'home' for this class. 922 virtual void anchor(); 923 924 protected: 925 // A helper for basic_parser::printOptionDiff. 926 void printOptionName(const Option &O, size_t GlobalWidth) const; 927 }; 928 929 // The real basic parser is just a template wrapper that provides a typedef for 930 // the provided data type. 931 // 932 template <class DataType> class basic_parser : public basic_parser_impl { 933 public: 934 using parser_data_type = DataType; 935 using OptVal = OptionValue<DataType>; 936 937 basic_parser(Option &O) : basic_parser_impl(O) {} 938 }; 939 940 //-------------------------------------------------- 941 942 extern template class basic_parser<bool>; 943 944 template <> class parser<bool> : public basic_parser<bool> { 945 public: 946 parser(Option &O) : basic_parser(O) {} 947 948 // Return true on error. 949 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val); 950 951 void initialize() {} 952 953 enum ValueExpected getValueExpectedFlagDefault() const { 954 return ValueOptional; 955 } 956 957 // Do not print =<value> at all. 958 StringRef getValueName() const override { return StringRef(); } 959 960 void printOptionDiff(const Option &O, bool V, OptVal Default, 961 size_t GlobalWidth) const; 962 963 // An out-of-line virtual method to provide a 'home' for this class. 964 void anchor() override; 965 }; 966 967 //-------------------------------------------------- 968 969 extern template class basic_parser<boolOrDefault>; 970 971 template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> { 972 public: 973 parser(Option &O) : basic_parser(O) {} 974 975 // Return true on error. 976 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val); 977 978 enum ValueExpected getValueExpectedFlagDefault() const { 979 return ValueOptional; 980 } 981 982 // Do not print =<value> at all. 983 StringRef getValueName() const override { return StringRef(); } 984 985 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default, 986 size_t GlobalWidth) const; 987 988 // An out-of-line virtual method to provide a 'home' for this class. 989 void anchor() override; 990 }; 991 992 //-------------------------------------------------- 993 994 extern template class basic_parser<int>; 995 996 template <> class parser<int> : public basic_parser<int> { 997 public: 998 parser(Option &O) : basic_parser(O) {} 999 1000 // Return true on error. 1001 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val); 1002 1003 // Overload in subclass to provide a better default value. 1004 StringRef getValueName() const override { return "int"; } 1005 1006 void printOptionDiff(const Option &O, int V, OptVal Default, 1007 size_t GlobalWidth) const; 1008 1009 // An out-of-line virtual method to provide a 'home' for this class. 1010 void anchor() override; 1011 }; 1012 1013 //-------------------------------------------------- 1014 1015 extern template class basic_parser<long>; 1016 1017 template <> class parser<long> final : public basic_parser<long> { 1018 public: 1019 parser(Option &O) : basic_parser(O) {} 1020 1021 // Return true on error. 1022 bool parse(Option &O, StringRef ArgName, StringRef Arg, long &Val); 1023 1024 // Overload in subclass to provide a better default value. 1025 StringRef getValueName() const override { return "long"; } 1026 1027 void printOptionDiff(const Option &O, long V, OptVal Default, 1028 size_t GlobalWidth) const; 1029 1030 // An out-of-line virtual method to provide a 'home' for this class. 1031 void anchor() override; 1032 }; 1033 1034 //-------------------------------------------------- 1035 1036 extern template class basic_parser<long long>; 1037 1038 template <> class parser<long long> : public basic_parser<long long> { 1039 public: 1040 parser(Option &O) : basic_parser(O) {} 1041 1042 // Return true on error. 1043 bool parse(Option &O, StringRef ArgName, StringRef Arg, long long &Val); 1044 1045 // Overload in subclass to provide a better default value. 1046 StringRef getValueName() const override { return "long"; } 1047 1048 void printOptionDiff(const Option &O, long long V, OptVal Default, 1049 size_t GlobalWidth) const; 1050 1051 // An out-of-line virtual method to provide a 'home' for this class. 1052 void anchor() override; 1053 }; 1054 1055 //-------------------------------------------------- 1056 1057 extern template class basic_parser<unsigned>; 1058 1059 template <> class parser<unsigned> : public basic_parser<unsigned> { 1060 public: 1061 parser(Option &O) : basic_parser(O) {} 1062 1063 // Return true on error. 1064 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val); 1065 1066 // Overload in subclass to provide a better default value. 1067 StringRef getValueName() const override { return "uint"; } 1068 1069 void printOptionDiff(const Option &O, unsigned V, OptVal Default, 1070 size_t GlobalWidth) const; 1071 1072 // An out-of-line virtual method to provide a 'home' for this class. 1073 void anchor() override; 1074 }; 1075 1076 //-------------------------------------------------- 1077 1078 extern template class basic_parser<unsigned long>; 1079 1080 template <> 1081 class parser<unsigned long> final : public basic_parser<unsigned long> { 1082 public: 1083 parser(Option &O) : basic_parser(O) {} 1084 1085 // Return true on error. 1086 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long &Val); 1087 1088 // Overload in subclass to provide a better default value. 1089 StringRef getValueName() const override { return "ulong"; } 1090 1091 void printOptionDiff(const Option &O, unsigned long V, OptVal Default, 1092 size_t GlobalWidth) const; 1093 1094 // An out-of-line virtual method to provide a 'home' for this class. 1095 void anchor() override; 1096 }; 1097 1098 //-------------------------------------------------- 1099 1100 extern template class basic_parser<unsigned long long>; 1101 1102 template <> 1103 class parser<unsigned long long> : public basic_parser<unsigned long long> { 1104 public: 1105 parser(Option &O) : basic_parser(O) {} 1106 1107 // Return true on error. 1108 bool parse(Option &O, StringRef ArgName, StringRef Arg, 1109 unsigned long long &Val); 1110 1111 // Overload in subclass to provide a better default value. 1112 StringRef getValueName() const override { return "ulong"; } 1113 1114 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default, 1115 size_t GlobalWidth) const; 1116 1117 // An out-of-line virtual method to provide a 'home' for this class. 1118 void anchor() override; 1119 }; 1120 1121 //-------------------------------------------------- 1122 1123 extern template class basic_parser<double>; 1124 1125 template <> class parser<double> : public basic_parser<double> { 1126 public: 1127 parser(Option &O) : basic_parser(O) {} 1128 1129 // Return true on error. 1130 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val); 1131 1132 // Overload in subclass to provide a better default value. 1133 StringRef getValueName() const override { return "number"; } 1134 1135 void printOptionDiff(const Option &O, double V, OptVal Default, 1136 size_t GlobalWidth) const; 1137 1138 // An out-of-line virtual method to provide a 'home' for this class. 1139 void anchor() override; 1140 }; 1141 1142 //-------------------------------------------------- 1143 1144 extern template class basic_parser<float>; 1145 1146 template <> class parser<float> : public basic_parser<float> { 1147 public: 1148 parser(Option &O) : basic_parser(O) {} 1149 1150 // Return true on error. 1151 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val); 1152 1153 // Overload in subclass to provide a better default value. 1154 StringRef getValueName() const override { return "number"; } 1155 1156 void printOptionDiff(const Option &O, float V, OptVal Default, 1157 size_t GlobalWidth) const; 1158 1159 // An out-of-line virtual method to provide a 'home' for this class. 1160 void anchor() override; 1161 }; 1162 1163 //-------------------------------------------------- 1164 1165 extern template class basic_parser<std::string>; 1166 1167 template <> class parser<std::string> : public basic_parser<std::string> { 1168 public: 1169 parser(Option &O) : basic_parser(O) {} 1170 1171 // Return true on error. 1172 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) { 1173 Value = Arg.str(); 1174 return false; 1175 } 1176 1177 // Overload in subclass to provide a better default value. 1178 StringRef getValueName() const override { return "string"; } 1179 1180 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default, 1181 size_t GlobalWidth) const; 1182 1183 // An out-of-line virtual method to provide a 'home' for this class. 1184 void anchor() override; 1185 }; 1186 1187 //-------------------------------------------------- 1188 1189 extern template class basic_parser<char>; 1190 1191 template <> class parser<char> : public basic_parser<char> { 1192 public: 1193 parser(Option &O) : basic_parser(O) {} 1194 1195 // Return true on error. 1196 bool parse(Option &, StringRef, StringRef Arg, char &Value) { 1197 Value = Arg[0]; 1198 return false; 1199 } 1200 1201 // Overload in subclass to provide a better default value. 1202 StringRef getValueName() const override { return "char"; } 1203 1204 void printOptionDiff(const Option &O, char V, OptVal Default, 1205 size_t GlobalWidth) const; 1206 1207 // An out-of-line virtual method to provide a 'home' for this class. 1208 void anchor() override; 1209 }; 1210 1211 //-------------------------------------------------- 1212 // This collection of wrappers is the intermediary between class opt and class 1213 // parser to handle all the template nastiness. 1214 1215 // This overloaded function is selected by the generic parser. 1216 template <class ParserClass, class DT> 1217 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, 1218 const OptionValue<DT> &Default, size_t GlobalWidth) { 1219 OptionValue<DT> OV = V; 1220 P.printOptionDiff(O, OV, Default, GlobalWidth); 1221 } 1222 1223 // This is instantiated for basic parsers when the parsed value has a different 1224 // type than the option value. e.g. HelpPrinter. 1225 template <class ParserDT, class ValDT> struct OptionDiffPrinter { 1226 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/, 1227 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) { 1228 P.printOptionNoValue(O, GlobalWidth); 1229 } 1230 }; 1231 1232 // This is instantiated for basic parsers when the parsed value has the same 1233 // type as the option value. 1234 template <class DT> struct OptionDiffPrinter<DT, DT> { 1235 void print(const Option &O, const parser<DT> &P, const DT &V, 1236 const OptionValue<DT> &Default, size_t GlobalWidth) { 1237 P.printOptionDiff(O, V, Default, GlobalWidth); 1238 } 1239 }; 1240 1241 // This overloaded function is selected by the basic parser, which may parse a 1242 // different type than the option type. 1243 template <class ParserClass, class ValDT> 1244 void printOptionDiff( 1245 const Option &O, 1246 const basic_parser<typename ParserClass::parser_data_type> &P, 1247 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) { 1248 1249 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer; 1250 printer.print(O, static_cast<const ParserClass &>(P), V, Default, 1251 GlobalWidth); 1252 } 1253 1254 //===----------------------------------------------------------------------===// 1255 // This class is used because we must use partial specialization to handle 1256 // literal string arguments specially (const char* does not correctly respond to 1257 // the apply method). Because the syntax to use this is a pain, we have the 1258 // 'apply' method below to handle the nastiness... 1259 // 1260 template <class Mod> struct applicator { 1261 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); } 1262 }; 1263 1264 // Handle const char* as a special case... 1265 template <unsigned n> struct applicator<char[n]> { 1266 template <class Opt> static void opt(StringRef Str, Opt &O) { 1267 O.setArgStr(Str); 1268 } 1269 }; 1270 template <unsigned n> struct applicator<const char[n]> { 1271 template <class Opt> static void opt(StringRef Str, Opt &O) { 1272 O.setArgStr(Str); 1273 } 1274 }; 1275 template <> struct applicator<StringRef > { 1276 template <class Opt> static void opt(StringRef Str, Opt &O) { 1277 O.setArgStr(Str); 1278 } 1279 }; 1280 1281 template <> struct applicator<NumOccurrencesFlag> { 1282 static void opt(NumOccurrencesFlag N, Option &O) { 1283 O.setNumOccurrencesFlag(N); 1284 } 1285 }; 1286 1287 template <> struct applicator<ValueExpected> { 1288 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); } 1289 }; 1290 1291 template <> struct applicator<OptionHidden> { 1292 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); } 1293 }; 1294 1295 template <> struct applicator<FormattingFlags> { 1296 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); } 1297 }; 1298 1299 template <> struct applicator<MiscFlags> { 1300 static void opt(MiscFlags MF, Option &O) { 1301 assert((MF != Grouping || O.ArgStr.size() == 1) && 1302 "cl::Grouping can only apply to single character Options."); 1303 O.setMiscFlag(MF); 1304 } 1305 }; 1306 1307 // Apply modifiers to an option in a type safe way. 1308 template <class Opt, class Mod, class... Mods> 1309 void apply(Opt *O, const Mod &M, const Mods &... Ms) { 1310 applicator<Mod>::opt(M, *O); 1311 apply(O, Ms...); 1312 } 1313 1314 template <class Opt, class Mod> void apply(Opt *O, const Mod &M) { 1315 applicator<Mod>::opt(M, *O); 1316 } 1317 1318 //===----------------------------------------------------------------------===// 1319 // Default storage class definition: external storage. This implementation 1320 // assumes the user will specify a variable to store the data into with the 1321 // cl::location(x) modifier. 1322 // 1323 template <class DataType, bool ExternalStorage, bool isClass> 1324 class opt_storage { 1325 DataType *Location = nullptr; // Where to store the object... 1326 OptionValue<DataType> Default; 1327 1328 void check_location() const { 1329 assert(Location && "cl::location(...) not specified for a command " 1330 "line option with external storage, " 1331 "or cl::init specified before cl::location()!!"); 1332 } 1333 1334 public: 1335 opt_storage() = default; 1336 1337 bool setLocation(Option &O, DataType &L) { 1338 if (Location) 1339 return O.error("cl::location(x) specified more than once!"); 1340 Location = &L; 1341 Default = L; 1342 return false; 1343 } 1344 1345 template <class T> void setValue(const T &V, bool initial = false) { 1346 check_location(); 1347 *Location = V; 1348 if (initial) 1349 Default = V; 1350 } 1351 1352 DataType &getValue() { 1353 check_location(); 1354 return *Location; 1355 } 1356 const DataType &getValue() const { 1357 check_location(); 1358 return *Location; 1359 } 1360 1361 operator DataType() const { return this->getValue(); } 1362 1363 const OptionValue<DataType> &getDefault() const { return Default; } 1364 }; 1365 1366 // Define how to hold a class type object, such as a string. Since we can 1367 // inherit from a class, we do so. This makes us exactly compatible with the 1368 // object in all cases that it is used. 1369 // 1370 template <class DataType> 1371 class opt_storage<DataType, false, true> : public DataType { 1372 public: 1373 OptionValue<DataType> Default; 1374 1375 template <class T> void setValue(const T &V, bool initial = false) { 1376 DataType::operator=(V); 1377 if (initial) 1378 Default = V; 1379 } 1380 1381 DataType &getValue() { return *this; } 1382 const DataType &getValue() const { return *this; } 1383 1384 const OptionValue<DataType> &getDefault() const { return Default; } 1385 }; 1386 1387 // Define a partial specialization to handle things we cannot inherit from. In 1388 // this case, we store an instance through containment, and overload operators 1389 // to get at the value. 1390 // 1391 template <class DataType> class opt_storage<DataType, false, false> { 1392 public: 1393 DataType Value; 1394 OptionValue<DataType> Default; 1395 1396 // Make sure we initialize the value with the default constructor for the 1397 // type. 1398 opt_storage() : Value(DataType()), Default() {} 1399 1400 template <class T> void setValue(const T &V, bool initial = false) { 1401 Value = V; 1402 if (initial) 1403 Default = V; 1404 } 1405 DataType &getValue() { return Value; } 1406 DataType getValue() const { return Value; } 1407 1408 const OptionValue<DataType> &getDefault() const { return Default; } 1409 1410 operator DataType() const { return getValue(); } 1411 1412 // If the datatype is a pointer, support -> on it. 1413 DataType operator->() const { return Value; } 1414 }; 1415 1416 //===----------------------------------------------------------------------===// 1417 // A scalar command line option. 1418 // 1419 template <class DataType, bool ExternalStorage = false, 1420 class ParserClass = parser<DataType>> 1421 class opt 1422 : public Option, 1423 public opt_storage<DataType, ExternalStorage, std::is_class_v<DataType>> { 1424 ParserClass Parser; 1425 1426 bool handleOccurrence(unsigned pos, StringRef ArgName, 1427 StringRef Arg) override { 1428 typename ParserClass::parser_data_type Val = 1429 typename ParserClass::parser_data_type(); 1430 if (Parser.parse(*this, ArgName, Arg, Val)) 1431 return true; // Parse error! 1432 this->setValue(Val); 1433 this->setPosition(pos); 1434 Callback(Val); 1435 return false; 1436 } 1437 1438 enum ValueExpected getValueExpectedFlagDefault() const override { 1439 return Parser.getValueExpectedFlagDefault(); 1440 } 1441 1442 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1443 return Parser.getExtraOptionNames(OptionNames); 1444 } 1445 1446 // Forward printing stuff to the parser... 1447 size_t getOptionWidth() const override { 1448 return Parser.getOptionWidth(*this); 1449 } 1450 1451 void printOptionInfo(size_t GlobalWidth) const override { 1452 Parser.printOptionInfo(*this, GlobalWidth); 1453 } 1454 1455 void printOptionValue(size_t GlobalWidth, bool Force) const override { 1456 if (Force || !this->getDefault().compare(this->getValue())) { 1457 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(), 1458 this->getDefault(), GlobalWidth); 1459 } 1460 } 1461 1462 template <class T, class = std::enable_if_t<std::is_assignable_v<T &, T>>> 1463 void setDefaultImpl() { 1464 const OptionValue<DataType> &V = this->getDefault(); 1465 if (V.hasValue()) 1466 this->setValue(V.getValue()); 1467 else 1468 this->setValue(T()); 1469 } 1470 1471 template <class T, class = std::enable_if_t<!std::is_assignable_v<T &, T>>> 1472 void setDefaultImpl(...) {} 1473 1474 void setDefault() override { setDefaultImpl<DataType>(); } 1475 1476 void done() { 1477 addArgument(); 1478 Parser.initialize(); 1479 } 1480 1481 public: 1482 // Command line options should not be copyable 1483 opt(const opt &) = delete; 1484 opt &operator=(const opt &) = delete; 1485 1486 // setInitialValue - Used by the cl::init modifier... 1487 void setInitialValue(const DataType &V) { this->setValue(V, true); } 1488 1489 ParserClass &getParser() { return Parser; } 1490 1491 template <class T> DataType &operator=(const T &Val) { 1492 this->setValue(Val); 1493 Callback(Val); 1494 return this->getValue(); 1495 } 1496 1497 template <class... Mods> 1498 explicit opt(const Mods &... Ms) 1499 : Option(llvm::cl::Optional, NotHidden), Parser(*this) { 1500 apply(this, Ms...); 1501 done(); 1502 } 1503 1504 void setCallback( 1505 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1506 Callback = CB; 1507 } 1508 1509 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1510 [](const typename ParserClass::parser_data_type &) {}; 1511 }; 1512 1513 extern template class opt<unsigned>; 1514 extern template class opt<int>; 1515 extern template class opt<std::string>; 1516 extern template class opt<char>; 1517 extern template class opt<bool>; 1518 1519 //===----------------------------------------------------------------------===// 1520 // Default storage class definition: external storage. This implementation 1521 // assumes the user will specify a variable to store the data into with the 1522 // cl::location(x) modifier. 1523 // 1524 template <class DataType, class StorageClass> class list_storage { 1525 StorageClass *Location = nullptr; // Where to store the object... 1526 std::vector<OptionValue<DataType>> Default = 1527 std::vector<OptionValue<DataType>>(); 1528 bool DefaultAssigned = false; 1529 1530 public: 1531 list_storage() = default; 1532 1533 void clear() {} 1534 1535 bool setLocation(Option &O, StorageClass &L) { 1536 if (Location) 1537 return O.error("cl::location(x) specified more than once!"); 1538 Location = &L; 1539 return false; 1540 } 1541 1542 template <class T> void addValue(const T &V, bool initial = false) { 1543 assert(Location != nullptr && 1544 "cl::location(...) not specified for a command " 1545 "line option with external storage!"); 1546 Location->push_back(V); 1547 if (initial) 1548 Default.push_back(V); 1549 } 1550 1551 const std::vector<OptionValue<DataType>> &getDefault() const { 1552 return Default; 1553 } 1554 1555 void assignDefault() { DefaultAssigned = true; } 1556 void overwriteDefault() { DefaultAssigned = false; } 1557 bool isDefaultAssigned() { return DefaultAssigned; } 1558 }; 1559 1560 // Define how to hold a class type object, such as a string. 1561 // Originally this code inherited from std::vector. In transitioning to a new 1562 // API for command line options we should change this. The new implementation 1563 // of this list_storage specialization implements the minimum subset of the 1564 // std::vector API required for all the current clients. 1565 // 1566 // FIXME: Reduce this API to a more narrow subset of std::vector 1567 // 1568 template <class DataType> class list_storage<DataType, bool> { 1569 std::vector<DataType> Storage; 1570 std::vector<OptionValue<DataType>> Default; 1571 bool DefaultAssigned = false; 1572 1573 public: 1574 using iterator = typename std::vector<DataType>::iterator; 1575 1576 iterator begin() { return Storage.begin(); } 1577 iterator end() { return Storage.end(); } 1578 1579 using const_iterator = typename std::vector<DataType>::const_iterator; 1580 1581 const_iterator begin() const { return Storage.begin(); } 1582 const_iterator end() const { return Storage.end(); } 1583 1584 using size_type = typename std::vector<DataType>::size_type; 1585 1586 size_type size() const { return Storage.size(); } 1587 1588 bool empty() const { return Storage.empty(); } 1589 1590 void push_back(const DataType &value) { Storage.push_back(value); } 1591 void push_back(DataType &&value) { Storage.push_back(value); } 1592 1593 using reference = typename std::vector<DataType>::reference; 1594 using const_reference = typename std::vector<DataType>::const_reference; 1595 1596 reference operator[](size_type pos) { return Storage[pos]; } 1597 const_reference operator[](size_type pos) const { return Storage[pos]; } 1598 1599 void clear() { 1600 Storage.clear(); 1601 } 1602 1603 iterator erase(const_iterator pos) { return Storage.erase(pos); } 1604 iterator erase(const_iterator first, const_iterator last) { 1605 return Storage.erase(first, last); 1606 } 1607 1608 iterator erase(iterator pos) { return Storage.erase(pos); } 1609 iterator erase(iterator first, iterator last) { 1610 return Storage.erase(first, last); 1611 } 1612 1613 iterator insert(const_iterator pos, const DataType &value) { 1614 return Storage.insert(pos, value); 1615 } 1616 iterator insert(const_iterator pos, DataType &&value) { 1617 return Storage.insert(pos, value); 1618 } 1619 1620 iterator insert(iterator pos, const DataType &value) { 1621 return Storage.insert(pos, value); 1622 } 1623 iterator insert(iterator pos, DataType &&value) { 1624 return Storage.insert(pos, value); 1625 } 1626 1627 reference front() { return Storage.front(); } 1628 const_reference front() const { return Storage.front(); } 1629 1630 operator std::vector<DataType> &() { return Storage; } 1631 operator ArrayRef<DataType>() const { return Storage; } 1632 std::vector<DataType> *operator&() { return &Storage; } 1633 const std::vector<DataType> *operator&() const { return &Storage; } 1634 1635 template <class T> void addValue(const T &V, bool initial = false) { 1636 Storage.push_back(V); 1637 if (initial) 1638 Default.push_back(OptionValue<DataType>(V)); 1639 } 1640 1641 const std::vector<OptionValue<DataType>> &getDefault() const { 1642 return Default; 1643 } 1644 1645 void assignDefault() { DefaultAssigned = true; } 1646 void overwriteDefault() { DefaultAssigned = false; } 1647 bool isDefaultAssigned() { return DefaultAssigned; } 1648 }; 1649 1650 //===----------------------------------------------------------------------===// 1651 // A list of command line options. 1652 // 1653 template <class DataType, class StorageClass = bool, 1654 class ParserClass = parser<DataType>> 1655 class list : public Option, public list_storage<DataType, StorageClass> { 1656 std::vector<unsigned> Positions; 1657 ParserClass Parser; 1658 1659 enum ValueExpected getValueExpectedFlagDefault() const override { 1660 return Parser.getValueExpectedFlagDefault(); 1661 } 1662 1663 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1664 return Parser.getExtraOptionNames(OptionNames); 1665 } 1666 1667 bool handleOccurrence(unsigned pos, StringRef ArgName, 1668 StringRef Arg) override { 1669 typename ParserClass::parser_data_type Val = 1670 typename ParserClass::parser_data_type(); 1671 if (list_storage<DataType, StorageClass>::isDefaultAssigned()) { 1672 clear(); 1673 list_storage<DataType, StorageClass>::overwriteDefault(); 1674 } 1675 if (Parser.parse(*this, ArgName, Arg, Val)) 1676 return true; // Parse Error! 1677 list_storage<DataType, StorageClass>::addValue(Val); 1678 setPosition(pos); 1679 Positions.push_back(pos); 1680 Callback(Val); 1681 return false; 1682 } 1683 1684 // Forward printing stuff to the parser... 1685 size_t getOptionWidth() const override { 1686 return Parser.getOptionWidth(*this); 1687 } 1688 1689 void printOptionInfo(size_t GlobalWidth) const override { 1690 Parser.printOptionInfo(*this, GlobalWidth); 1691 } 1692 1693 // Unimplemented: list options don't currently store their default value. 1694 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1695 } 1696 1697 void setDefault() override { 1698 Positions.clear(); 1699 list_storage<DataType, StorageClass>::clear(); 1700 for (auto &Val : list_storage<DataType, StorageClass>::getDefault()) 1701 list_storage<DataType, StorageClass>::addValue(Val.getValue()); 1702 } 1703 1704 void done() { 1705 addArgument(); 1706 Parser.initialize(); 1707 } 1708 1709 public: 1710 // Command line options should not be copyable 1711 list(const list &) = delete; 1712 list &operator=(const list &) = delete; 1713 1714 ParserClass &getParser() { return Parser; } 1715 1716 unsigned getPosition(unsigned optnum) const { 1717 assert(optnum < this->size() && "Invalid option index"); 1718 return Positions[optnum]; 1719 } 1720 1721 void clear() { 1722 Positions.clear(); 1723 list_storage<DataType, StorageClass>::clear(); 1724 } 1725 1726 // setInitialValues - Used by the cl::list_init modifier... 1727 void setInitialValues(ArrayRef<DataType> Vs) { 1728 assert(!(list_storage<DataType, StorageClass>::isDefaultAssigned()) && 1729 "Cannot have two default values"); 1730 list_storage<DataType, StorageClass>::assignDefault(); 1731 for (auto &Val : Vs) 1732 list_storage<DataType, StorageClass>::addValue(Val, true); 1733 } 1734 1735 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); } 1736 1737 template <class... Mods> 1738 explicit list(const Mods &... Ms) 1739 : Option(ZeroOrMore, NotHidden), Parser(*this) { 1740 apply(this, Ms...); 1741 done(); 1742 } 1743 1744 void setCallback( 1745 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1746 Callback = CB; 1747 } 1748 1749 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1750 [](const typename ParserClass::parser_data_type &) {}; 1751 }; 1752 1753 // Modifier to set the number of additional values. 1754 struct multi_val { 1755 unsigned AdditionalVals; 1756 explicit multi_val(unsigned N) : AdditionalVals(N) {} 1757 1758 template <typename D, typename S, typename P> 1759 void apply(list<D, S, P> &L) const { 1760 L.setNumAdditionalVals(AdditionalVals); 1761 } 1762 }; 1763 1764 //===----------------------------------------------------------------------===// 1765 // Default storage class definition: external storage. This implementation 1766 // assumes the user will specify a variable to store the data into with the 1767 // cl::location(x) modifier. 1768 // 1769 template <class DataType, class StorageClass> class bits_storage { 1770 unsigned *Location = nullptr; // Where to store the bits... 1771 1772 template <class T> static unsigned Bit(const T &V) { 1773 unsigned BitPos = static_cast<unsigned>(V); 1774 assert(BitPos < sizeof(unsigned) * CHAR_BIT && 1775 "enum exceeds width of bit vector!"); 1776 return 1 << BitPos; 1777 } 1778 1779 public: 1780 bits_storage() = default; 1781 1782 bool setLocation(Option &O, unsigned &L) { 1783 if (Location) 1784 return O.error("cl::location(x) specified more than once!"); 1785 Location = &L; 1786 return false; 1787 } 1788 1789 template <class T> void addValue(const T &V) { 1790 assert(Location != nullptr && 1791 "cl::location(...) not specified for a command " 1792 "line option with external storage!"); 1793 *Location |= Bit(V); 1794 } 1795 1796 unsigned getBits() { return *Location; } 1797 1798 void clear() { 1799 if (Location) 1800 *Location = 0; 1801 } 1802 1803 template <class T> bool isSet(const T &V) { 1804 return (*Location & Bit(V)) != 0; 1805 } 1806 }; 1807 1808 // Define how to hold bits. Since we can inherit from a class, we do so. 1809 // This makes us exactly compatible with the bits in all cases that it is used. 1810 // 1811 template <class DataType> class bits_storage<DataType, bool> { 1812 unsigned Bits{0}; // Where to store the bits... 1813 1814 template <class T> static unsigned Bit(const T &V) { 1815 unsigned BitPos = static_cast<unsigned>(V); 1816 assert(BitPos < sizeof(unsigned) * CHAR_BIT && 1817 "enum exceeds width of bit vector!"); 1818 return 1 << BitPos; 1819 } 1820 1821 public: 1822 template <class T> void addValue(const T &V) { Bits |= Bit(V); } 1823 1824 unsigned getBits() { return Bits; } 1825 1826 void clear() { Bits = 0; } 1827 1828 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; } 1829 }; 1830 1831 //===----------------------------------------------------------------------===// 1832 // A bit vector of command options. 1833 // 1834 template <class DataType, class Storage = bool, 1835 class ParserClass = parser<DataType>> 1836 class bits : public Option, public bits_storage<DataType, Storage> { 1837 std::vector<unsigned> Positions; 1838 ParserClass Parser; 1839 1840 enum ValueExpected getValueExpectedFlagDefault() const override { 1841 return Parser.getValueExpectedFlagDefault(); 1842 } 1843 1844 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { 1845 return Parser.getExtraOptionNames(OptionNames); 1846 } 1847 1848 bool handleOccurrence(unsigned pos, StringRef ArgName, 1849 StringRef Arg) override { 1850 typename ParserClass::parser_data_type Val = 1851 typename ParserClass::parser_data_type(); 1852 if (Parser.parse(*this, ArgName, Arg, Val)) 1853 return true; // Parse Error! 1854 this->addValue(Val); 1855 setPosition(pos); 1856 Positions.push_back(pos); 1857 Callback(Val); 1858 return false; 1859 } 1860 1861 // Forward printing stuff to the parser... 1862 size_t getOptionWidth() const override { 1863 return Parser.getOptionWidth(*this); 1864 } 1865 1866 void printOptionInfo(size_t GlobalWidth) const override { 1867 Parser.printOptionInfo(*this, GlobalWidth); 1868 } 1869 1870 // Unimplemented: bits options don't currently store their default values. 1871 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1872 } 1873 1874 void setDefault() override { bits_storage<DataType, Storage>::clear(); } 1875 1876 void done() { 1877 addArgument(); 1878 Parser.initialize(); 1879 } 1880 1881 public: 1882 // Command line options should not be copyable 1883 bits(const bits &) = delete; 1884 bits &operator=(const bits &) = delete; 1885 1886 ParserClass &getParser() { return Parser; } 1887 1888 unsigned getPosition(unsigned optnum) const { 1889 assert(optnum < this->size() && "Invalid option index"); 1890 return Positions[optnum]; 1891 } 1892 1893 template <class... Mods> 1894 explicit bits(const Mods &... Ms) 1895 : Option(ZeroOrMore, NotHidden), Parser(*this) { 1896 apply(this, Ms...); 1897 done(); 1898 } 1899 1900 void setCallback( 1901 std::function<void(const typename ParserClass::parser_data_type &)> CB) { 1902 Callback = CB; 1903 } 1904 1905 std::function<void(const typename ParserClass::parser_data_type &)> Callback = 1906 [](const typename ParserClass::parser_data_type &) {}; 1907 }; 1908 1909 //===----------------------------------------------------------------------===// 1910 // Aliased command line option (alias this name to a preexisting name) 1911 // 1912 1913 class alias : public Option { 1914 Option *AliasFor; 1915 1916 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/, 1917 StringRef Arg) override { 1918 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg); 1919 } 1920 1921 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value, 1922 bool MultiArg = false) override { 1923 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg); 1924 } 1925 1926 // Handle printing stuff... 1927 size_t getOptionWidth() const override; 1928 void printOptionInfo(size_t GlobalWidth) const override; 1929 1930 // Aliases do not need to print their values. 1931 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { 1932 } 1933 1934 void setDefault() override { AliasFor->setDefault(); } 1935 1936 ValueExpected getValueExpectedFlagDefault() const override { 1937 return AliasFor->getValueExpectedFlag(); 1938 } 1939 1940 void done() { 1941 if (!hasArgStr()) 1942 error("cl::alias must have argument name specified!"); 1943 if (!AliasFor) 1944 error("cl::alias must have an cl::aliasopt(option) specified!"); 1945 if (!Subs.empty()) 1946 error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!"); 1947 Subs = AliasFor->Subs; 1948 Categories = AliasFor->Categories; 1949 addArgument(); 1950 } 1951 1952 public: 1953 // Command line options should not be copyable 1954 alias(const alias &) = delete; 1955 alias &operator=(const alias &) = delete; 1956 1957 void setAliasFor(Option &O) { 1958 if (AliasFor) 1959 error("cl::alias must only have one cl::aliasopt(...) specified!"); 1960 AliasFor = &O; 1961 } 1962 1963 template <class... Mods> 1964 explicit alias(const Mods &... Ms) 1965 : Option(Optional, Hidden), AliasFor(nullptr) { 1966 apply(this, Ms...); 1967 done(); 1968 } 1969 }; 1970 1971 // Modifier to set the option an alias aliases. 1972 struct aliasopt { 1973 Option &Opt; 1974 1975 explicit aliasopt(Option &O) : Opt(O) {} 1976 1977 void apply(alias &A) const { A.setAliasFor(Opt); } 1978 }; 1979 1980 // Provide additional help at the end of the normal help output. All occurrences 1981 // of cl::extrahelp will be accumulated and printed to stderr at the end of the 1982 // regular help, just before exit is called. 1983 struct extrahelp { 1984 StringRef morehelp; 1985 1986 explicit extrahelp(StringRef help); 1987 }; 1988 1989 void PrintVersionMessage(); 1990 1991 /// This function just prints the help message, exactly the same way as if the 1992 /// -help or -help-hidden option had been given on the command line. 1993 /// 1994 /// \param Hidden if true will print hidden options 1995 /// \param Categorized if true print options in categories 1996 void PrintHelpMessage(bool Hidden = false, bool Categorized = false); 1997 1998 /// An array of optional enabled settings in the LLVM build configuration, 1999 /// which may be of interest to compiler developers. For example, includes 2000 /// "+assertions" if assertions are enabled. Used by printBuildConfig. 2001 ArrayRef<StringRef> getCompilerBuildConfig(); 2002 2003 /// Prints the compiler build configuration. 2004 /// Designed for compiler developers, not compiler end-users. 2005 /// Intended to be used in --version output when enabled. 2006 void printBuildConfig(raw_ostream &OS); 2007 2008 //===----------------------------------------------------------------------===// 2009 // Public interface for accessing registered options. 2010 // 2011 2012 /// Use this to get a StringMap to all registered named options 2013 /// (e.g. -help). 2014 /// 2015 /// \return A reference to the StringMap used by the cl APIs to parse options. 2016 /// 2017 /// Access to unnamed arguments (i.e. positional) are not provided because 2018 /// it is expected that the client already has access to these. 2019 /// 2020 /// Typical usage: 2021 /// \code 2022 /// main(int argc,char* argv[]) { 2023 /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions(); 2024 /// assert(opts.count("help") == 1) 2025 /// opts["help"]->setDescription("Show alphabetical help information") 2026 /// // More code 2027 /// llvm::cl::ParseCommandLineOptions(argc,argv); 2028 /// //More code 2029 /// } 2030 /// \endcode 2031 /// 2032 /// This interface is useful for modifying options in libraries that are out of 2033 /// the control of the client. The options should be modified before calling 2034 /// llvm::cl::ParseCommandLineOptions(). 2035 /// 2036 /// Hopefully this API can be deprecated soon. Any situation where options need 2037 /// to be modified by tools or libraries should be handled by sane APIs rather 2038 /// than just handing around a global list. 2039 StringMap<Option *> & 2040 getRegisteredOptions(SubCommand &Sub = SubCommand::getTopLevel()); 2041 2042 /// Use this to get all registered SubCommands from the provided parser. 2043 /// 2044 /// \return A range of all SubCommand pointers registered with the parser. 2045 /// 2046 /// Typical usage: 2047 /// \code 2048 /// main(int argc, char* argv[]) { 2049 /// llvm::cl::ParseCommandLineOptions(argc, argv); 2050 /// for (auto* S : llvm::cl::getRegisteredSubcommands()) { 2051 /// if (*S) { 2052 /// std::cout << "Executing subcommand: " << S->getName() << std::endl; 2053 /// // Execute some function based on the name... 2054 /// } 2055 /// } 2056 /// } 2057 /// \endcode 2058 /// 2059 /// This interface is useful for defining subcommands in libraries and 2060 /// the dispatch from a single point (like in the main function). 2061 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator> 2062 getRegisteredSubcommands(); 2063 2064 //===----------------------------------------------------------------------===// 2065 // Standalone command line processing utilities. 2066 // 2067 2068 /// Tokenizes a command line that can contain escapes and quotes. 2069 // 2070 /// The quoting rules match those used by GCC and other tools that use 2071 /// libiberty's buildargv() or expandargv() utilities, and do not match bash. 2072 /// They differ from buildargv() on treatment of backslashes that do not escape 2073 /// a special character to make it possible to accept most Windows file paths. 2074 /// 2075 /// \param [in] Source The string to be split on whitespace with quotes. 2076 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2077 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of 2078 /// lines and end of the response file to be marked with a nullptr string. 2079 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2080 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, 2081 SmallVectorImpl<const char *> &NewArgv, 2082 bool MarkEOLs = false); 2083 2084 /// Tokenizes a string of Windows command line arguments, which may contain 2085 /// quotes and escaped quotes. 2086 /// 2087 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules. 2088 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx 2089 /// 2090 /// For handling a full Windows command line including the executable name at 2091 /// the start, see TokenizeWindowsCommandLineFull below. 2092 /// 2093 /// \param [in] Source The string to be split on whitespace with quotes. 2094 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2095 /// \param [in] MarkEOLs true if tokenizing a response file and you want end of 2096 /// lines and end of the response file to be marked with a nullptr string. 2097 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2098 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, 2099 SmallVectorImpl<const char *> &NewArgv, 2100 bool MarkEOLs = false); 2101 2102 /// Tokenizes a Windows command line while attempting to avoid copies. If no 2103 /// quoting or escaping was used, this produces substrings of the original 2104 /// string. If a token requires unquoting, it will be allocated with the 2105 /// StringSaver. 2106 void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, 2107 SmallVectorImpl<StringRef> &NewArgv); 2108 2109 /// Tokenizes a Windows full command line, including command name at the start. 2110 /// 2111 /// This uses the same syntax rules as TokenizeWindowsCommandLine for all but 2112 /// the first token. But the first token is expected to be parsed as the 2113 /// executable file name in the way CreateProcess would do it, rather than the 2114 /// way the C library startup code would do it: CreateProcess does not consider 2115 /// that \ is ever an escape character (because " is not a valid filename char, 2116 /// hence there's never a need to escape it to be used literally). 2117 /// 2118 /// Parameters are the same as for TokenizeWindowsCommandLine. In particular, 2119 /// if you set MarkEOLs = true, then the first word of every line will be 2120 /// parsed using the special rules for command names, making this function 2121 /// suitable for parsing a file full of commands to execute. 2122 void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, 2123 SmallVectorImpl<const char *> &NewArgv, 2124 bool MarkEOLs = false); 2125 2126 /// String tokenization function type. Should be compatible with either 2127 /// Windows or Unix command line tokenizers. 2128 using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver, 2129 SmallVectorImpl<const char *> &NewArgv, 2130 bool MarkEOLs); 2131 2132 /// Tokenizes content of configuration file. 2133 /// 2134 /// \param [in] Source The string representing content of config file. 2135 /// \param [in] Saver Delegates back to the caller for saving parsed strings. 2136 /// \param [out] NewArgv All parsed strings are appended to NewArgv. 2137 /// \param [in] MarkEOLs Added for compatibility with TokenizerCallback. 2138 /// 2139 /// It works like TokenizeGNUCommandLine with ability to skip comment lines. 2140 /// 2141 void tokenizeConfigFile(StringRef Source, StringSaver &Saver, 2142 SmallVectorImpl<const char *> &NewArgv, 2143 bool MarkEOLs = false); 2144 2145 /// Contains options that control response file expansion. 2146 class ExpansionContext { 2147 /// Provides persistent storage for parsed strings. 2148 StringSaver Saver; 2149 2150 /// Tokenization strategy. Typically Unix or Windows. 2151 TokenizerCallback Tokenizer; 2152 2153 /// File system used for all file access when running the expansion. 2154 vfs::FileSystem *FS; 2155 2156 /// Path used to resolve relative rsp files. If empty, the file system 2157 /// current directory is used instead. 2158 StringRef CurrentDir; 2159 2160 /// Directories used for search of config files. 2161 ArrayRef<StringRef> SearchDirs; 2162 2163 /// True if names of nested response files must be resolved relative to 2164 /// including file. 2165 bool RelativeNames = false; 2166 2167 /// If true, mark end of lines and the end of the response file with nullptrs 2168 /// in the Argv vector. 2169 bool MarkEOLs = false; 2170 2171 /// If true, body of config file is expanded. 2172 bool InConfigFile = false; 2173 2174 llvm::Error expandResponseFile(StringRef FName, 2175 SmallVectorImpl<const char *> &NewArgv); 2176 2177 public: 2178 ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T); 2179 2180 ExpansionContext &setMarkEOLs(bool X) { 2181 MarkEOLs = X; 2182 return *this; 2183 } 2184 2185 ExpansionContext &setRelativeNames(bool X) { 2186 RelativeNames = X; 2187 return *this; 2188 } 2189 2190 ExpansionContext &setCurrentDir(StringRef X) { 2191 CurrentDir = X; 2192 return *this; 2193 } 2194 2195 ExpansionContext &setSearchDirs(ArrayRef<StringRef> X) { 2196 SearchDirs = X; 2197 return *this; 2198 } 2199 2200 ExpansionContext &setVFS(vfs::FileSystem *X) { 2201 FS = X; 2202 return *this; 2203 } 2204 2205 /// Looks for the specified configuration file. 2206 /// 2207 /// \param[in] FileName Name of the file to search for. 2208 /// \param[out] FilePath File absolute path, if it was found. 2209 /// \return True if file was found. 2210 /// 2211 /// If the specified file name contains a directory separator, it is searched 2212 /// for by its absolute path. Otherwise looks for file sequentially in 2213 /// directories specified by SearchDirs field. 2214 bool findConfigFile(StringRef FileName, SmallVectorImpl<char> &FilePath); 2215 2216 /// Reads command line options from the given configuration file. 2217 /// 2218 /// \param [in] CfgFile Path to configuration file. 2219 /// \param [out] Argv Array to which the read options are added. 2220 /// \return true if the file was successfully read. 2221 /// 2222 /// It reads content of the specified file, tokenizes it and expands "@file" 2223 /// commands resolving file names in them relative to the directory where 2224 /// CfgFilename resides. It also expands "<CFGDIR>" to the base path of the 2225 /// current config file. 2226 Error readConfigFile(StringRef CfgFile, SmallVectorImpl<const char *> &Argv); 2227 2228 /// Expands constructs "@file" in the provided array of arguments recursively. 2229 Error expandResponseFiles(SmallVectorImpl<const char *> &Argv); 2230 }; 2231 2232 /// A convenience helper which concatenates the options specified by the 2233 /// environment variable EnvVar and command line options, then expands 2234 /// response files recursively. 2235 /// \return true if all @files were expanded successfully or there were none. 2236 bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, 2237 SmallVectorImpl<const char *> &NewArgv); 2238 2239 /// A convenience helper which supports the typical use case of expansion 2240 /// function call. 2241 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 2242 SmallVectorImpl<const char *> &Argv); 2243 2244 /// A convenience helper which concatenates the options specified by the 2245 /// environment variable EnvVar and command line options, then expands response 2246 /// files recursively. The tokenizer is a predefined GNU or Windows one. 2247 /// \return true if all @files were expanded successfully or there were none. 2248 bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, 2249 StringSaver &Saver, 2250 SmallVectorImpl<const char *> &NewArgv); 2251 2252 /// Mark all options not part of this category as cl::ReallyHidden. 2253 /// 2254 /// \param Category the category of options to keep displaying 2255 /// 2256 /// Some tools (like clang-format) like to be able to hide all options that are 2257 /// not specific to the tool. This function allows a tool to specify a single 2258 /// option category to display in the -help output. 2259 void HideUnrelatedOptions(cl::OptionCategory &Category, 2260 SubCommand &Sub = SubCommand::getTopLevel()); 2261 2262 /// Mark all options not part of the categories as cl::ReallyHidden. 2263 /// 2264 /// \param Categories the categories of options to keep displaying. 2265 /// 2266 /// Some tools (like clang-format) like to be able to hide all options that are 2267 /// not specific to the tool. This function allows a tool to specify a single 2268 /// option category to display in the -help output. 2269 void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, 2270 SubCommand &Sub = SubCommand::getTopLevel()); 2271 2272 /// Reset all command line options to a state that looks as if they have 2273 /// never appeared on the command line. This is useful for being able to parse 2274 /// a command line multiple times (especially useful for writing tests). 2275 void ResetAllOptionOccurrences(); 2276 2277 /// Reset the command line parser back to its initial state. This 2278 /// removes 2279 /// all options, categories, and subcommands and returns the parser to a state 2280 /// where no options are supported. 2281 void ResetCommandLineParser(); 2282 2283 /// Parses `Arg` into the option handler `Handler`. 2284 bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i); 2285 2286 } // end namespace cl 2287 2288 } // end namespace llvm 2289 2290 #endif // LLVM_SUPPORT_COMMANDLINE_H 2291