[llvm-objdump] - Import the test/Object/X86/no-start-symbol.test test case and rewrit...
[llvm-complete.git] / lib / Support / CommandLine.cpp
blob25510fa58ff54335eb54c1b7e87b0d2702fd575b
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
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.
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/Support/ConvertUTF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/StringSaver.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cstdlib>
42 #include <map>
43 using namespace llvm;
44 using namespace cl;
46 #define DEBUG_TYPE "commandline"
48 //===----------------------------------------------------------------------===//
49 // Template instantiations and anchors.
51 namespace llvm {
52 namespace cl {
53 template class basic_parser<bool>;
54 template class basic_parser<boolOrDefault>;
55 template class basic_parser<int>;
56 template class basic_parser<unsigned>;
57 template class basic_parser<unsigned long>;
58 template class basic_parser<unsigned long long>;
59 template class basic_parser<double>;
60 template class basic_parser<float>;
61 template class basic_parser<std::string>;
62 template class basic_parser<char>;
64 template class opt<unsigned>;
65 template class opt<int>;
66 template class opt<std::string>;
67 template class opt<char>;
68 template class opt<bool>;
70 } // end namespace llvm::cl
72 // Pin the vtables to this file.
73 void GenericOptionValue::anchor() {}
74 void OptionValue<boolOrDefault>::anchor() {}
75 void OptionValue<std::string>::anchor() {}
76 void Option::anchor() {}
77 void basic_parser_impl::anchor() {}
78 void parser<bool>::anchor() {}
79 void parser<boolOrDefault>::anchor() {}
80 void parser<int>::anchor() {}
81 void parser<unsigned>::anchor() {}
82 void parser<unsigned long>::anchor() {}
83 void parser<unsigned long long>::anchor() {}
84 void parser<double>::anchor() {}
85 void parser<float>::anchor() {}
86 void parser<std::string>::anchor() {}
87 void parser<char>::anchor() {}
89 //===----------------------------------------------------------------------===//
91 static StringRef ArgPrefix = " -";
92 static StringRef ArgPrefixLong = " --";
93 static StringRef ArgHelpPrefix = " - ";
95 static size_t argPlusPrefixesSize(StringRef ArgName) {
96 size_t Len = ArgName.size();
97 if (Len == 1)
98 return Len + ArgPrefix.size() + ArgHelpPrefix.size();
99 return Len + ArgPrefixLong.size() + ArgHelpPrefix.size();
102 static StringRef argPrefix(StringRef ArgName) {
103 if (ArgName.size() == 1)
104 return ArgPrefix;
105 return ArgPrefixLong;
108 // Option predicates...
109 static inline bool isGrouping(const Option *O) {
110 return O->getMiscFlags() & cl::Grouping;
112 static inline bool isPrefixedOrGrouping(const Option *O) {
113 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
114 O->getFormattingFlag() == cl::AlwaysPrefix;
118 namespace {
120 class PrintArg {
121 StringRef ArgName;
122 public:
123 PrintArg(StringRef ArgName) : ArgName(ArgName) {}
124 friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg&);
127 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
128 OS << argPrefix(Arg.ArgName) << Arg.ArgName;
129 return OS;
132 class CommandLineParser {
133 public:
134 // Globals for name and overview of program. Program name is not a string to
135 // avoid static ctor/dtor issues.
136 std::string ProgramName;
137 StringRef ProgramOverview;
139 // This collects additional help to be printed.
140 std::vector<StringRef> MoreHelp;
142 // This collects Options added with the cl::DefaultOption flag. Since they can
143 // be overridden, they are not added to the appropriate SubCommands until
144 // ParseCommandLineOptions actually runs.
145 SmallVector<Option*, 4> DefaultOptions;
147 // This collects the different option categories that have been registered.
148 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
150 // This collects the different subcommands that have been registered.
151 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
153 CommandLineParser() : ActiveSubCommand(nullptr) {
154 registerSubCommand(&*TopLevelSubCommand);
155 registerSubCommand(&*AllSubCommands);
158 void ResetAllOptionOccurrences();
160 bool ParseCommandLineOptions(int argc, const char *const *argv,
161 StringRef Overview, raw_ostream *Errs = nullptr,
162 bool LongOptionsUseDoubleDash = false);
164 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
165 if (Opt.hasArgStr())
166 return;
167 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
168 errs() << ProgramName << ": CommandLine Error: Option '" << Name
169 << "' registered more than once!\n";
170 report_fatal_error("inconsistency in registered CommandLine options");
173 // If we're adding this to all sub-commands, add it to the ones that have
174 // already been registered.
175 if (SC == &*AllSubCommands) {
176 for (const auto &Sub : RegisteredSubCommands) {
177 if (SC == Sub)
178 continue;
179 addLiteralOption(Opt, Sub, Name);
184 void addLiteralOption(Option &Opt, StringRef Name) {
185 if (Opt.Subs.empty())
186 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
187 else {
188 for (auto SC : Opt.Subs)
189 addLiteralOption(Opt, SC, Name);
193 void addOption(Option *O, SubCommand *SC) {
194 bool HadErrors = false;
195 if (O->hasArgStr()) {
196 // If it's a DefaultOption, check to make sure it isn't already there.
197 if (O->isDefaultOption() &&
198 SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
199 return;
201 // Add argument to the argument map!
202 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
203 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
204 << "' registered more than once!\n";
205 HadErrors = true;
209 // Remember information about positional options.
210 if (O->getFormattingFlag() == cl::Positional)
211 SC->PositionalOpts.push_back(O);
212 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
213 SC->SinkOpts.push_back(O);
214 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
215 if (SC->ConsumeAfterOpt) {
216 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
217 HadErrors = true;
219 SC->ConsumeAfterOpt = O;
222 // Fail hard if there were errors. These are strictly unrecoverable and
223 // indicate serious issues such as conflicting option names or an
224 // incorrectly
225 // linked LLVM distribution.
226 if (HadErrors)
227 report_fatal_error("inconsistency in registered CommandLine options");
229 // If we're adding this to all sub-commands, add it to the ones that have
230 // already been registered.
231 if (SC == &*AllSubCommands) {
232 for (const auto &Sub : RegisteredSubCommands) {
233 if (SC == Sub)
234 continue;
235 addOption(O, Sub);
240 void addOption(Option *O, bool ProcessDefaultOption = false) {
241 if (!ProcessDefaultOption && O->isDefaultOption()) {
242 DefaultOptions.push_back(O);
243 return;
246 if (O->Subs.empty()) {
247 addOption(O, &*TopLevelSubCommand);
248 } else {
249 for (auto SC : O->Subs)
250 addOption(O, SC);
254 void removeOption(Option *O, SubCommand *SC) {
255 SmallVector<StringRef, 16> OptionNames;
256 O->getExtraOptionNames(OptionNames);
257 if (O->hasArgStr())
258 OptionNames.push_back(O->ArgStr);
260 SubCommand &Sub = *SC;
261 auto End = Sub.OptionsMap.end();
262 for (auto Name : OptionNames) {
263 auto I = Sub.OptionsMap.find(Name);
264 if (I != End && I->getValue() == O)
265 Sub.OptionsMap.erase(I);
268 if (O->getFormattingFlag() == cl::Positional)
269 for (auto Opt = Sub.PositionalOpts.begin();
270 Opt != Sub.PositionalOpts.end(); ++Opt) {
271 if (*Opt == O) {
272 Sub.PositionalOpts.erase(Opt);
273 break;
276 else if (O->getMiscFlags() & cl::Sink)
277 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
278 if (*Opt == O) {
279 Sub.SinkOpts.erase(Opt);
280 break;
283 else if (O == Sub.ConsumeAfterOpt)
284 Sub.ConsumeAfterOpt = nullptr;
287 void removeOption(Option *O) {
288 if (O->Subs.empty())
289 removeOption(O, &*TopLevelSubCommand);
290 else {
291 if (O->isInAllSubCommands()) {
292 for (auto SC : RegisteredSubCommands)
293 removeOption(O, SC);
294 } else {
295 for (auto SC : O->Subs)
296 removeOption(O, SC);
301 bool hasOptions(const SubCommand &Sub) const {
302 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
303 nullptr != Sub.ConsumeAfterOpt);
306 bool hasOptions() const {
307 for (const auto &S : RegisteredSubCommands) {
308 if (hasOptions(*S))
309 return true;
311 return false;
314 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
316 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
317 SubCommand &Sub = *SC;
318 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
319 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
320 << "' registered more than once!\n";
321 report_fatal_error("inconsistency in registered CommandLine options");
323 Sub.OptionsMap.erase(O->ArgStr);
326 void updateArgStr(Option *O, StringRef NewName) {
327 if (O->Subs.empty())
328 updateArgStr(O, NewName, &*TopLevelSubCommand);
329 else {
330 if (O->isInAllSubCommands()) {
331 for (auto SC : RegisteredSubCommands)
332 updateArgStr(O, NewName, SC);
333 } else {
334 for (auto SC : O->Subs)
335 updateArgStr(O, NewName, SC);
340 void printOptionValues();
342 void registerCategory(OptionCategory *cat) {
343 assert(count_if(RegisteredOptionCategories,
344 [cat](const OptionCategory *Category) {
345 return cat->getName() == Category->getName();
346 }) == 0 &&
347 "Duplicate option categories");
349 RegisteredOptionCategories.insert(cat);
352 void registerSubCommand(SubCommand *sub) {
353 assert(count_if(RegisteredSubCommands,
354 [sub](const SubCommand *Sub) {
355 return (!sub->getName().empty()) &&
356 (Sub->getName() == sub->getName());
357 }) == 0 &&
358 "Duplicate subcommands");
359 RegisteredSubCommands.insert(sub);
361 // For all options that have been registered for all subcommands, add the
362 // option to this subcommand now.
363 if (sub != &*AllSubCommands) {
364 for (auto &E : AllSubCommands->OptionsMap) {
365 Option *O = E.second;
366 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
367 O->hasArgStr())
368 addOption(O, sub);
369 else
370 addLiteralOption(*O, sub, E.first());
375 void unregisterSubCommand(SubCommand *sub) {
376 RegisteredSubCommands.erase(sub);
379 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
380 getRegisteredSubcommands() {
381 return make_range(RegisteredSubCommands.begin(),
382 RegisteredSubCommands.end());
385 void reset() {
386 ActiveSubCommand = nullptr;
387 ProgramName.clear();
388 ProgramOverview = StringRef();
390 MoreHelp.clear();
391 RegisteredOptionCategories.clear();
393 ResetAllOptionOccurrences();
394 RegisteredSubCommands.clear();
396 TopLevelSubCommand->reset();
397 AllSubCommands->reset();
398 registerSubCommand(&*TopLevelSubCommand);
399 registerSubCommand(&*AllSubCommands);
401 DefaultOptions.clear();
404 private:
405 SubCommand *ActiveSubCommand;
407 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
408 Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
409 bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
410 Option *Opt = LookupOption(Sub, Arg, Value);
411 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
412 return nullptr;
413 return Opt;
415 SubCommand *LookupSubCommand(StringRef Name);
418 } // namespace
420 static ManagedStatic<CommandLineParser> GlobalParser;
422 void cl::AddLiteralOption(Option &O, StringRef Name) {
423 GlobalParser->addLiteralOption(O, Name);
426 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
427 GlobalParser->MoreHelp.push_back(Help);
430 void Option::addArgument() {
431 GlobalParser->addOption(this);
432 FullyInitialized = true;
435 void Option::removeArgument() { GlobalParser->removeOption(this); }
437 void Option::setArgStr(StringRef S) {
438 if (FullyInitialized)
439 GlobalParser->updateArgStr(this, S);
440 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
441 ArgStr = S;
442 if (ArgStr.size() == 1)
443 setMiscFlag(Grouping);
446 void Option::addCategory(OptionCategory &C) {
447 assert(!Categories.empty() && "Categories cannot be empty.");
448 // Maintain backward compatibility by replacing the default GeneralCategory
449 // if it's still set. Otherwise, just add the new one. The GeneralCategory
450 // must be explicitly added if you want multiple categories that include it.
451 if (&C != &GeneralCategory && Categories[0] == &GeneralCategory)
452 Categories[0] = &C;
453 else if (find(Categories, &C) == Categories.end())
454 Categories.push_back(&C);
457 void Option::reset() {
458 NumOccurrences = 0;
459 setDefault();
460 if (isDefaultOption())
461 removeArgument();
464 // Initialise the general option category.
465 OptionCategory llvm::cl::GeneralCategory("General options");
467 void OptionCategory::registerCategory() {
468 GlobalParser->registerCategory(this);
471 // A special subcommand representing no subcommand. It is particularly important
472 // that this ManagedStatic uses constant initailization and not dynamic
473 // initialization because it is referenced from cl::opt constructors, which run
474 // dynamically in an arbitrary order.
475 LLVM_REQUIRE_CONSTANT_INITIALIZATION
476 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
478 // A special subcommand that can be used to put an option into all subcommands.
479 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
481 void SubCommand::registerSubCommand() {
482 GlobalParser->registerSubCommand(this);
485 void SubCommand::unregisterSubCommand() {
486 GlobalParser->unregisterSubCommand(this);
489 void SubCommand::reset() {
490 PositionalOpts.clear();
491 SinkOpts.clear();
492 OptionsMap.clear();
494 ConsumeAfterOpt = nullptr;
497 SubCommand::operator bool() const {
498 return (GlobalParser->getActiveSubCommand() == this);
501 //===----------------------------------------------------------------------===//
502 // Basic, shared command line option processing machinery.
505 /// LookupOption - Lookup the option specified by the specified option on the
506 /// command line. If there is a value specified (after an equal sign) return
507 /// that as well. This assumes that leading dashes have already been stripped.
508 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
509 StringRef &Value) {
510 // Reject all dashes.
511 if (Arg.empty())
512 return nullptr;
513 assert(&Sub != &*AllSubCommands);
515 size_t EqualPos = Arg.find('=');
517 // If we have an equals sign, remember the value.
518 if (EqualPos == StringRef::npos) {
519 // Look up the option.
520 auto I = Sub.OptionsMap.find(Arg);
521 if (I == Sub.OptionsMap.end())
522 return nullptr;
524 return I != Sub.OptionsMap.end() ? I->second : nullptr;
527 // If the argument before the = is a valid option name and the option allows
528 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
529 // failure by returning nullptr.
530 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
531 if (I == Sub.OptionsMap.end())
532 return nullptr;
534 auto O = I->second;
535 if (O->getFormattingFlag() == cl::AlwaysPrefix)
536 return nullptr;
538 Value = Arg.substr(EqualPos + 1);
539 Arg = Arg.substr(0, EqualPos);
540 return I->second;
543 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
544 if (Name.empty())
545 return &*TopLevelSubCommand;
546 for (auto S : RegisteredSubCommands) {
547 if (S == &*AllSubCommands)
548 continue;
549 if (S->getName().empty())
550 continue;
552 if (StringRef(S->getName()) == StringRef(Name))
553 return S;
555 return &*TopLevelSubCommand;
558 /// LookupNearestOption - Lookup the closest match to the option specified by
559 /// the specified option on the command line. If there is a value specified
560 /// (after an equal sign) return that as well. This assumes that leading dashes
561 /// have already been stripped.
562 static Option *LookupNearestOption(StringRef Arg,
563 const StringMap<Option *> &OptionsMap,
564 std::string &NearestString) {
565 // Reject all dashes.
566 if (Arg.empty())
567 return nullptr;
569 // Split on any equal sign.
570 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
571 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
572 StringRef &RHS = SplitArg.second;
574 // Find the closest match.
575 Option *Best = nullptr;
576 unsigned BestDistance = 0;
577 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
578 ie = OptionsMap.end();
579 it != ie; ++it) {
580 Option *O = it->second;
581 SmallVector<StringRef, 16> OptionNames;
582 O->getExtraOptionNames(OptionNames);
583 if (O->hasArgStr())
584 OptionNames.push_back(O->ArgStr);
586 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
587 StringRef Flag = PermitValue ? LHS : Arg;
588 for (auto Name : OptionNames) {
589 unsigned Distance = StringRef(Name).edit_distance(
590 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
591 if (!Best || Distance < BestDistance) {
592 Best = O;
593 BestDistance = Distance;
594 if (RHS.empty() || !PermitValue)
595 NearestString = Name;
596 else
597 NearestString = (Twine(Name) + "=" + RHS).str();
602 return Best;
605 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
606 /// that does special handling of cl::CommaSeparated options.
607 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
608 StringRef ArgName, StringRef Value,
609 bool MultiArg = false) {
610 // Check to see if this option accepts a comma separated list of values. If
611 // it does, we have to split up the value into multiple values.
612 if (Handler->getMiscFlags() & CommaSeparated) {
613 StringRef Val(Value);
614 StringRef::size_type Pos = Val.find(',');
616 while (Pos != StringRef::npos) {
617 // Process the portion before the comma.
618 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
619 return true;
620 // Erase the portion before the comma, AND the comma.
621 Val = Val.substr(Pos + 1);
622 // Check for another comma.
623 Pos = Val.find(',');
626 Value = Val;
629 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
632 /// ProvideOption - For Value, this differentiates between an empty value ("")
633 /// and a null value (StringRef()). The later is accepted for arguments that
634 /// don't allow a value (-foo) the former is rejected (-foo=).
635 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
636 StringRef Value, int argc,
637 const char *const *argv, int &i) {
638 // Is this a multi-argument option?
639 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
641 // Enforce value requirements
642 switch (Handler->getValueExpectedFlag()) {
643 case ValueRequired:
644 if (!Value.data()) { // No value specified?
645 // If no other argument or the option only supports prefix form, we
646 // cannot look at the next argument.
647 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
648 return Handler->error("requires a value!");
649 // Steal the next argument, like for '-o filename'
650 assert(argv && "null check");
651 Value = StringRef(argv[++i]);
653 break;
654 case ValueDisallowed:
655 if (NumAdditionalVals > 0)
656 return Handler->error("multi-valued option specified"
657 " with ValueDisallowed modifier!");
659 if (Value.data())
660 return Handler->error("does not allow a value! '" + Twine(Value) +
661 "' specified.");
662 break;
663 case ValueOptional:
664 break;
667 // If this isn't a multi-arg option, just run the handler.
668 if (NumAdditionalVals == 0)
669 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
671 // If it is, run the handle several times.
672 bool MultiArg = false;
674 if (Value.data()) {
675 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
676 return true;
677 --NumAdditionalVals;
678 MultiArg = true;
681 while (NumAdditionalVals > 0) {
682 if (i + 1 >= argc)
683 return Handler->error("not enough values!");
684 assert(argv && "null check");
685 Value = StringRef(argv[++i]);
687 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
688 return true;
689 MultiArg = true;
690 --NumAdditionalVals;
692 return false;
695 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
696 int Dummy = i;
697 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
700 // getOptionPred - Check to see if there are any options that satisfy the
701 // specified predicate with names that are the prefixes in Name. This is
702 // checked by progressively stripping characters off of the name, checking to
703 // see if there options that satisfy the predicate. If we find one, return it,
704 // otherwise return null.
706 static Option *getOptionPred(StringRef Name, size_t &Length,
707 bool (*Pred)(const Option *),
708 const StringMap<Option *> &OptionsMap) {
709 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
710 if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
711 OMI = OptionsMap.end();
713 // Loop while we haven't found an option and Name still has at least two
714 // characters in it (so that the next iteration will not be the empty
715 // string.
716 while (OMI == OptionsMap.end() && Name.size() > 1) {
717 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
718 OMI = OptionsMap.find(Name);
719 if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
720 OMI = OptionsMap.end();
723 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
724 Length = Name.size();
725 return OMI->second; // Found one!
727 return nullptr; // No option found!
730 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
731 /// with at least one '-') does not fully match an available option. Check to
732 /// see if this is a prefix or grouped option. If so, split arg into output an
733 /// Arg/Value pair and return the Option to parse it with.
734 static Option *
735 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
736 bool &ErrorParsing,
737 const StringMap<Option *> &OptionsMap) {
738 if (Arg.size() == 1)
739 return nullptr;
741 // Do the lookup!
742 size_t Length = 0;
743 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
744 if (!PGOpt)
745 return nullptr;
747 do {
748 StringRef MaybeValue =
749 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
750 Arg = Arg.substr(0, Length);
751 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
753 // cl::Prefix options do not preserve '=' when used separately.
754 // The behavior for them with grouped options should be the same.
755 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
756 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
757 Value = MaybeValue;
758 return PGOpt;
761 if (MaybeValue[0] == '=') {
762 Value = MaybeValue.substr(1);
763 return PGOpt;
766 // This must be a grouped option.
767 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
769 // Grouping options inside a group can't have values.
770 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
771 ErrorParsing |= PGOpt->error("may not occur within a group!");
772 return nullptr;
775 // Because the value for the option is not required, we don't need to pass
776 // argc/argv in.
777 int Dummy = 0;
778 ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
780 // Get the next grouping option.
781 Arg = MaybeValue;
782 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
783 } while (PGOpt);
785 // We could not find a grouping option in the remainder of Arg.
786 return nullptr;
789 static bool RequiresValue(const Option *O) {
790 return O->getNumOccurrencesFlag() == cl::Required ||
791 O->getNumOccurrencesFlag() == cl::OneOrMore;
794 static bool EatsUnboundedNumberOfValues(const Option *O) {
795 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
796 O->getNumOccurrencesFlag() == cl::OneOrMore;
799 static bool isWhitespace(char C) {
800 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
803 static bool isWhitespaceOrNull(char C) {
804 return isWhitespace(C) || C == '\0';
807 static bool isQuote(char C) { return C == '\"' || C == '\''; }
809 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
810 SmallVectorImpl<const char *> &NewArgv,
811 bool MarkEOLs) {
812 SmallString<128> Token;
813 for (size_t I = 0, E = Src.size(); I != E; ++I) {
814 // Consume runs of whitespace.
815 if (Token.empty()) {
816 while (I != E && isWhitespace(Src[I])) {
817 // Mark the end of lines in response files
818 if (MarkEOLs && Src[I] == '\n')
819 NewArgv.push_back(nullptr);
820 ++I;
822 if (I == E)
823 break;
826 char C = Src[I];
828 // Backslash escapes the next character.
829 if (I + 1 < E && C == '\\') {
830 ++I; // Skip the escape.
831 Token.push_back(Src[I]);
832 continue;
835 // Consume a quoted string.
836 if (isQuote(C)) {
837 ++I;
838 while (I != E && Src[I] != C) {
839 // Backslash escapes the next character.
840 if (Src[I] == '\\' && I + 1 != E)
841 ++I;
842 Token.push_back(Src[I]);
843 ++I;
845 if (I == E)
846 break;
847 continue;
850 // End the token if this is whitespace.
851 if (isWhitespace(C)) {
852 if (!Token.empty())
853 NewArgv.push_back(Saver.save(StringRef(Token)).data());
854 Token.clear();
855 continue;
858 // This is a normal character. Append it.
859 Token.push_back(C);
862 // Append the last token after hitting EOF with no whitespace.
863 if (!Token.empty())
864 NewArgv.push_back(Saver.save(StringRef(Token)).data());
865 // Mark the end of response files
866 if (MarkEOLs)
867 NewArgv.push_back(nullptr);
870 /// Backslashes are interpreted in a rather complicated way in the Windows-style
871 /// command line, because backslashes are used both to separate path and to
872 /// escape double quote. This method consumes runs of backslashes as well as the
873 /// following double quote if it's escaped.
875 /// * If an even number of backslashes is followed by a double quote, one
876 /// backslash is output for every pair of backslashes, and the last double
877 /// quote remains unconsumed. The double quote will later be interpreted as
878 /// the start or end of a quoted string in the main loop outside of this
879 /// function.
881 /// * If an odd number of backslashes is followed by a double quote, one
882 /// backslash is output for every pair of backslashes, and a double quote is
883 /// output for the last pair of backslash-double quote. The double quote is
884 /// consumed in this case.
886 /// * Otherwise, backslashes are interpreted literally.
887 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
888 size_t E = Src.size();
889 int BackslashCount = 0;
890 // Skip the backslashes.
891 do {
892 ++I;
893 ++BackslashCount;
894 } while (I != E && Src[I] == '\\');
896 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
897 if (FollowedByDoubleQuote) {
898 Token.append(BackslashCount / 2, '\\');
899 if (BackslashCount % 2 == 0)
900 return I - 1;
901 Token.push_back('"');
902 return I;
904 Token.append(BackslashCount, '\\');
905 return I - 1;
908 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
909 SmallVectorImpl<const char *> &NewArgv,
910 bool MarkEOLs) {
911 SmallString<128> Token;
913 // This is a small state machine to consume characters until it reaches the
914 // end of the source string.
915 enum { INIT, UNQUOTED, QUOTED } State = INIT;
916 for (size_t I = 0, E = Src.size(); I != E; ++I) {
917 char C = Src[I];
919 // INIT state indicates that the current input index is at the start of
920 // the string or between tokens.
921 if (State == INIT) {
922 if (isWhitespaceOrNull(C)) {
923 // Mark the end of lines in response files
924 if (MarkEOLs && C == '\n')
925 NewArgv.push_back(nullptr);
926 continue;
928 if (C == '"') {
929 State = QUOTED;
930 continue;
932 if (C == '\\') {
933 I = parseBackslash(Src, I, Token);
934 State = UNQUOTED;
935 continue;
937 Token.push_back(C);
938 State = UNQUOTED;
939 continue;
942 // UNQUOTED state means that it's reading a token not quoted by double
943 // quotes.
944 if (State == UNQUOTED) {
945 // Whitespace means the end of the token.
946 if (isWhitespaceOrNull(C)) {
947 NewArgv.push_back(Saver.save(StringRef(Token)).data());
948 Token.clear();
949 State = INIT;
950 // Mark the end of lines in response files
951 if (MarkEOLs && C == '\n')
952 NewArgv.push_back(nullptr);
953 continue;
955 if (C == '"') {
956 State = QUOTED;
957 continue;
959 if (C == '\\') {
960 I = parseBackslash(Src, I, Token);
961 continue;
963 Token.push_back(C);
964 continue;
967 // QUOTED state means that it's reading a token quoted by double quotes.
968 if (State == QUOTED) {
969 if (C == '"') {
970 if (I < (E - 1) && Src[I + 1] == '"') {
971 // Consecutive double-quotes inside a quoted string implies one
972 // double-quote.
973 Token.push_back('"');
974 I = I + 1;
975 continue;
977 State = UNQUOTED;
978 continue;
980 if (C == '\\') {
981 I = parseBackslash(Src, I, Token);
982 continue;
984 Token.push_back(C);
987 // Append the last token after hitting EOF with no whitespace.
988 if (!Token.empty())
989 NewArgv.push_back(Saver.save(StringRef(Token)).data());
990 // Mark the end of response files
991 if (MarkEOLs)
992 NewArgv.push_back(nullptr);
995 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
996 SmallVectorImpl<const char *> &NewArgv,
997 bool MarkEOLs) {
998 for (const char *Cur = Source.begin(); Cur != Source.end();) {
999 SmallString<128> Line;
1000 // Check for comment line.
1001 if (isWhitespace(*Cur)) {
1002 while (Cur != Source.end() && isWhitespace(*Cur))
1003 ++Cur;
1004 continue;
1006 if (*Cur == '#') {
1007 while (Cur != Source.end() && *Cur != '\n')
1008 ++Cur;
1009 continue;
1011 // Find end of the current line.
1012 const char *Start = Cur;
1013 for (const char *End = Source.end(); Cur != End; ++Cur) {
1014 if (*Cur == '\\') {
1015 if (Cur + 1 != End) {
1016 ++Cur;
1017 if (*Cur == '\n' ||
1018 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1019 Line.append(Start, Cur - 1);
1020 if (*Cur == '\r')
1021 ++Cur;
1022 Start = Cur + 1;
1025 } else if (*Cur == '\n')
1026 break;
1028 // Tokenize line.
1029 Line.append(Start, Cur);
1030 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1034 // It is called byte order marker but the UTF-8 BOM is actually not affected
1035 // by the host system's endianness.
1036 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1037 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1040 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
1041 TokenizerCallback Tokenizer,
1042 SmallVectorImpl<const char *> &NewArgv,
1043 bool MarkEOLs, bool RelativeNames) {
1044 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1045 MemoryBuffer::getFile(FName);
1046 if (!MemBufOrErr)
1047 return false;
1048 MemoryBuffer &MemBuf = *MemBufOrErr.get();
1049 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1051 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1052 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1053 std::string UTF8Buf;
1054 if (hasUTF16ByteOrderMark(BufRef)) {
1055 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1056 return false;
1057 Str = StringRef(UTF8Buf);
1059 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1060 // these bytes before parsing.
1061 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1062 else if (hasUTF8ByteOrderMark(BufRef))
1063 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1065 // Tokenize the contents into NewArgv.
1066 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1068 // If names of nested response files should be resolved relative to including
1069 // file, replace the included response file names with their full paths
1070 // obtained by required resolution.
1071 if (RelativeNames)
1072 for (unsigned I = 0; I < NewArgv.size(); ++I)
1073 if (NewArgv[I]) {
1074 StringRef Arg = NewArgv[I];
1075 if (Arg.front() == '@') {
1076 StringRef FileName = Arg.drop_front();
1077 if (llvm::sys::path::is_relative(FileName)) {
1078 SmallString<128> ResponseFile;
1079 ResponseFile.append(1, '@');
1080 if (llvm::sys::path::is_relative(FName)) {
1081 SmallString<128> curr_dir;
1082 llvm::sys::fs::current_path(curr_dir);
1083 ResponseFile.append(curr_dir.str());
1085 llvm::sys::path::append(
1086 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
1087 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
1092 return true;
1095 /// Expand response files on a command line recursively using the given
1096 /// StringSaver and tokenization strategy.
1097 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1098 SmallVectorImpl<const char *> &Argv,
1099 bool MarkEOLs, bool RelativeNames) {
1100 bool AllExpanded = true;
1101 struct ResponseFileRecord {
1102 const char *File;
1103 size_t End;
1106 // To detect recursive response files, we maintain a stack of files and the
1107 // position of the last argument in the file. This position is updated
1108 // dynamically as we recursively expand files.
1109 SmallVector<ResponseFileRecord, 3> FileStack;
1111 // Push a dummy entry that represents the initial command line, removing
1112 // the need to check for an empty list.
1113 FileStack.push_back({"", Argv.size()});
1115 // Don't cache Argv.size() because it can change.
1116 for (unsigned I = 0; I != Argv.size();) {
1117 while (I == FileStack.back().End) {
1118 // Passing the end of a file's argument list, so we can remove it from the
1119 // stack.
1120 FileStack.pop_back();
1123 const char *Arg = Argv[I];
1124 // Check if it is an EOL marker
1125 if (Arg == nullptr) {
1126 ++I;
1127 continue;
1130 if (Arg[0] != '@') {
1131 ++I;
1132 continue;
1135 const char *FName = Arg + 1;
1136 auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
1137 return sys::fs::equivalent(RFile.File, FName);
1140 // Check for recursive response files.
1141 if (std::any_of(FileStack.begin() + 1, FileStack.end(), IsEquivalent)) {
1142 // This file is recursive, so we leave it in the argument stream and
1143 // move on.
1144 AllExpanded = false;
1145 ++I;
1146 continue;
1149 // Replace this response file argument with the tokenization of its
1150 // contents. Nested response files are expanded in subsequent iterations.
1151 SmallVector<const char *, 0> ExpandedArgv;
1152 if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1153 RelativeNames)) {
1154 // We couldn't read this file, so we leave it in the argument stream and
1155 // move on.
1156 AllExpanded = false;
1157 ++I;
1158 continue;
1161 for (ResponseFileRecord &Record : FileStack) {
1162 // Increase the end of all active records by the number of newly expanded
1163 // arguments, minus the response file itself.
1164 Record.End += ExpandedArgv.size() - 1;
1167 FileStack.push_back({FName, I + ExpandedArgv.size()});
1168 Argv.erase(Argv.begin() + I);
1169 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1172 // If successful, the top of the file stack will mark the end of the Argv
1173 // stream. A failure here indicates a bug in the stack popping logic above.
1174 // Note that FileStack may have more than one element at this point because we
1175 // don't have a chance to pop the stack when encountering recursive files at
1176 // the end of the stream, so seeing that doesn't indicate a bug.
1177 assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1178 return AllExpanded;
1181 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1182 SmallVectorImpl<const char *> &Argv) {
1183 if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1184 /*MarkEOLs*/ false, /*RelativeNames*/ true))
1185 return false;
1186 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1187 /*MarkEOLs*/ false, /*RelativeNames*/ true);
1190 /// ParseEnvironmentOptions - An alternative entry point to the
1191 /// CommandLine library, which allows you to read the program's name
1192 /// from the caller (as PROGNAME) and its command-line arguments from
1193 /// an environment variable (whose name is given in ENVVAR).
1195 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1196 const char *Overview) {
1197 // Check args.
1198 assert(progName && "Program name not specified");
1199 assert(envVar && "Environment variable name missing");
1201 // Get the environment variable they want us to parse options out of.
1202 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1203 if (!envValue)
1204 return;
1206 // Get program's "name", which we wouldn't know without the caller
1207 // telling us.
1208 SmallVector<const char *, 20> newArgv;
1209 BumpPtrAllocator A;
1210 StringSaver Saver(A);
1211 newArgv.push_back(Saver.save(progName).data());
1213 // Parse the value of the environment variable into a "command line"
1214 // and hand it off to ParseCommandLineOptions().
1215 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1216 int newArgc = static_cast<int>(newArgv.size());
1217 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1220 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1221 StringRef Overview, raw_ostream *Errs,
1222 const char *EnvVar,
1223 bool LongOptionsUseDoubleDash) {
1224 SmallVector<const char *, 20> NewArgv;
1225 BumpPtrAllocator A;
1226 StringSaver Saver(A);
1227 NewArgv.push_back(argv[0]);
1229 // Parse options from environment variable.
1230 if (EnvVar) {
1231 if (llvm::Optional<std::string> EnvValue =
1232 sys::Process::GetEnv(StringRef(EnvVar)))
1233 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1236 // Append options from command line.
1237 for (int I = 1; I < argc; ++I)
1238 NewArgv.push_back(argv[I]);
1239 int NewArgc = static_cast<int>(NewArgv.size());
1241 // Parse all options.
1242 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1243 Errs, LongOptionsUseDoubleDash);
1246 void CommandLineParser::ResetAllOptionOccurrences() {
1247 // So that we can parse different command lines multiple times in succession
1248 // we reset all option values to look like they have never been seen before.
1249 for (auto SC : RegisteredSubCommands) {
1250 for (auto &O : SC->OptionsMap)
1251 O.second->reset();
1255 bool CommandLineParser::ParseCommandLineOptions(int argc,
1256 const char *const *argv,
1257 StringRef Overview,
1258 raw_ostream *Errs,
1259 bool LongOptionsUseDoubleDash) {
1260 assert(hasOptions() && "No options specified!");
1262 // Expand response files.
1263 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1264 BumpPtrAllocator A;
1265 StringSaver Saver(A);
1266 ExpandResponseFiles(Saver,
1267 Triple(sys::getProcessTriple()).isOSWindows() ?
1268 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1269 newArgv);
1270 argv = &newArgv[0];
1271 argc = static_cast<int>(newArgv.size());
1273 // Copy the program name into ProgName, making sure not to overflow it.
1274 ProgramName = sys::path::filename(StringRef(argv[0]));
1276 ProgramOverview = Overview;
1277 bool IgnoreErrors = Errs;
1278 if (!Errs)
1279 Errs = &errs();
1280 bool ErrorParsing = false;
1282 // Check out the positional arguments to collect information about them.
1283 unsigned NumPositionalRequired = 0;
1285 // Determine whether or not there are an unlimited number of positionals
1286 bool HasUnlimitedPositionals = false;
1288 int FirstArg = 1;
1289 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1290 if (argc >= 2 && argv[FirstArg][0] != '-') {
1291 // If the first argument specifies a valid subcommand, start processing
1292 // options from the second argument.
1293 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1294 if (ChosenSubCommand != &*TopLevelSubCommand)
1295 FirstArg = 2;
1297 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1299 assert(ChosenSubCommand);
1300 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1301 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1302 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1303 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1305 for (auto O: DefaultOptions) {
1306 addOption(O, true);
1309 if (ConsumeAfterOpt) {
1310 assert(PositionalOpts.size() > 0 &&
1311 "Cannot specify cl::ConsumeAfter without a positional argument!");
1313 if (!PositionalOpts.empty()) {
1315 // Calculate how many positional values are _required_.
1316 bool UnboundedFound = false;
1317 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1318 Option *Opt = PositionalOpts[i];
1319 if (RequiresValue(Opt))
1320 ++NumPositionalRequired;
1321 else if (ConsumeAfterOpt) {
1322 // ConsumeAfter cannot be combined with "optional" positional options
1323 // unless there is only one positional argument...
1324 if (PositionalOpts.size() > 1) {
1325 if (!IgnoreErrors)
1326 Opt->error("error - this positional option will never be matched, "
1327 "because it does not Require a value, and a "
1328 "cl::ConsumeAfter option is active!");
1329 ErrorParsing = true;
1331 } else if (UnboundedFound && !Opt->hasArgStr()) {
1332 // This option does not "require" a value... Make sure this option is
1333 // not specified after an option that eats all extra arguments, or this
1334 // one will never get any!
1336 if (!IgnoreErrors)
1337 Opt->error("error - option can never match, because "
1338 "another positional argument will match an "
1339 "unbounded number of values, and this option"
1340 " does not require a value!");
1341 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1342 << "' is all messed up!\n";
1343 *Errs << PositionalOpts.size();
1344 ErrorParsing = true;
1346 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1348 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1351 // PositionalVals - A vector of "positional" arguments we accumulate into
1352 // the process at the end.
1354 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1356 // If the program has named positional arguments, and the name has been run
1357 // across, keep track of which positional argument was named. Otherwise put
1358 // the positional args into the PositionalVals list...
1359 Option *ActivePositionalArg = nullptr;
1361 // Loop over all of the arguments... processing them.
1362 bool DashDashFound = false; // Have we read '--'?
1363 for (int i = FirstArg; i < argc; ++i) {
1364 Option *Handler = nullptr;
1365 Option *NearestHandler = nullptr;
1366 std::string NearestHandlerString;
1367 StringRef Value;
1368 StringRef ArgName = "";
1369 bool HaveDoubleDash = false;
1371 // Check to see if this is a positional argument. This argument is
1372 // considered to be positional if it doesn't start with '-', if it is "-"
1373 // itself, or if we have seen "--" already.
1375 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1376 // Positional argument!
1377 if (ActivePositionalArg) {
1378 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1379 continue; // We are done!
1382 if (!PositionalOpts.empty()) {
1383 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1385 // All of the positional arguments have been fulfulled, give the rest to
1386 // the consume after option... if it's specified...
1388 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1389 for (++i; i < argc; ++i)
1390 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1391 break; // Handle outside of the argument processing loop...
1394 // Delay processing positional arguments until the end...
1395 continue;
1397 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1398 !DashDashFound) {
1399 DashDashFound = true; // This is the mythical "--"?
1400 continue; // Don't try to process it as an argument itself.
1401 } else if (ActivePositionalArg &&
1402 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1403 // If there is a positional argument eating options, check to see if this
1404 // option is another positional argument. If so, treat it as an argument,
1405 // otherwise feed it to the eating positional.
1406 ArgName = StringRef(argv[i] + 1);
1407 // Eat second dash.
1408 if (!ArgName.empty() && ArgName[0] == '-') {
1409 HaveDoubleDash = true;
1410 ArgName = ArgName.substr(1);
1413 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1414 LongOptionsUseDoubleDash, HaveDoubleDash);
1415 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1416 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1417 continue; // We are done!
1419 } else { // We start with a '-', must be an argument.
1420 ArgName = StringRef(argv[i] + 1);
1421 // Eat second dash.
1422 if (!ArgName.empty() && ArgName[0] == '-') {
1423 HaveDoubleDash = true;
1424 ArgName = ArgName.substr(1);
1427 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1428 LongOptionsUseDoubleDash, HaveDoubleDash);
1430 // Check to see if this "option" is really a prefixed or grouped argument.
1431 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1432 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1433 OptionsMap);
1435 // Otherwise, look for the closest available option to report to the user
1436 // in the upcoming error.
1437 if (!Handler && SinkOpts.empty())
1438 NearestHandler =
1439 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1442 if (!Handler) {
1443 if (SinkOpts.empty()) {
1444 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1445 << "'. Try: '" << argv[0] << " --help'\n";
1447 if (NearestHandler) {
1448 // If we know a near match, report it as well.
1449 *Errs << ProgramName << ": Did you mean '"
1450 << PrintArg(NearestHandlerString) << "'?\n";
1453 ErrorParsing = true;
1454 } else {
1455 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1456 E = SinkOpts.end();
1457 I != E; ++I)
1458 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1460 continue;
1463 // If this is a named positional argument, just remember that it is the
1464 // active one...
1465 if (Handler->getFormattingFlag() == cl::Positional) {
1466 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1467 Handler->error("This argument does not take a value.\n"
1468 "\tInstead, it consumes any positional arguments until "
1469 "the next recognized option.", *Errs);
1470 ErrorParsing = true;
1472 ActivePositionalArg = Handler;
1474 else
1475 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1478 // Check and handle positional arguments now...
1479 if (NumPositionalRequired > PositionalVals.size()) {
1480 *Errs << ProgramName
1481 << ": Not enough positional command line arguments specified!\n"
1482 << "Must specify at least " << NumPositionalRequired
1483 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1484 << ": See: " << argv[0] << " --help\n";
1486 ErrorParsing = true;
1487 } else if (!HasUnlimitedPositionals &&
1488 PositionalVals.size() > PositionalOpts.size()) {
1489 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1490 << "Can specify at most " << PositionalOpts.size()
1491 << " positional arguments: See: " << argv[0] << " --help\n";
1492 ErrorParsing = true;
1494 } else if (!ConsumeAfterOpt) {
1495 // Positional args have already been handled if ConsumeAfter is specified.
1496 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1497 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1498 if (RequiresValue(PositionalOpts[i])) {
1499 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1500 PositionalVals[ValNo].second);
1501 ValNo++;
1502 --NumPositionalRequired; // We fulfilled our duty...
1505 // If we _can_ give this option more arguments, do so now, as long as we
1506 // do not give it values that others need. 'Done' controls whether the
1507 // option even _WANTS_ any more.
1509 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1510 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1511 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1512 case cl::Optional:
1513 Done = true; // Optional arguments want _at most_ one value
1514 LLVM_FALLTHROUGH;
1515 case cl::ZeroOrMore: // Zero or more will take all they can get...
1516 case cl::OneOrMore: // One or more will take all they can get...
1517 ProvidePositionalOption(PositionalOpts[i],
1518 PositionalVals[ValNo].first,
1519 PositionalVals[ValNo].second);
1520 ValNo++;
1521 break;
1522 default:
1523 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1524 "positional argument processing!");
1528 } else {
1529 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1530 unsigned ValNo = 0;
1531 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1532 if (RequiresValue(PositionalOpts[j])) {
1533 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1534 PositionalVals[ValNo].first,
1535 PositionalVals[ValNo].second);
1536 ValNo++;
1539 // Handle the case where there is just one positional option, and it's
1540 // optional. In this case, we want to give JUST THE FIRST option to the
1541 // positional option and keep the rest for the consume after. The above
1542 // loop would have assigned no values to positional options in this case.
1544 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1545 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1546 PositionalVals[ValNo].first,
1547 PositionalVals[ValNo].second);
1548 ValNo++;
1551 // Handle over all of the rest of the arguments to the
1552 // cl::ConsumeAfter command line option...
1553 for (; ValNo != PositionalVals.size(); ++ValNo)
1554 ErrorParsing |=
1555 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1556 PositionalVals[ValNo].second);
1559 // Loop over args and make sure all required args are specified!
1560 for (const auto &Opt : OptionsMap) {
1561 switch (Opt.second->getNumOccurrencesFlag()) {
1562 case Required:
1563 case OneOrMore:
1564 if (Opt.second->getNumOccurrences() == 0) {
1565 Opt.second->error("must be specified at least once!");
1566 ErrorParsing = true;
1568 LLVM_FALLTHROUGH;
1569 default:
1570 break;
1574 // Now that we know if -debug is specified, we can use it.
1575 // Note that if ReadResponseFiles == true, this must be done before the
1576 // memory allocated for the expanded command line is free()d below.
1577 LLVM_DEBUG(dbgs() << "Args: ";
1578 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1579 dbgs() << '\n';);
1581 // Free all of the memory allocated to the map. Command line options may only
1582 // be processed once!
1583 MoreHelp.clear();
1585 // If we had an error processing our arguments, don't let the program execute
1586 if (ErrorParsing) {
1587 if (!IgnoreErrors)
1588 exit(1);
1589 return false;
1591 return true;
1594 //===----------------------------------------------------------------------===//
1595 // Option Base class implementation
1598 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1599 if (!ArgName.data())
1600 ArgName = ArgStr;
1601 if (ArgName.empty())
1602 Errs << HelpStr; // Be nice for positional arguments
1603 else
1604 Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName);
1606 Errs << " option: " << Message << "\n";
1607 return true;
1610 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1611 bool MultiArg) {
1612 if (!MultiArg)
1613 NumOccurrences++; // Increment the number of times we have been seen
1615 switch (getNumOccurrencesFlag()) {
1616 case Optional:
1617 if (NumOccurrences > 1)
1618 return error("may only occur zero or one times!", ArgName);
1619 break;
1620 case Required:
1621 if (NumOccurrences > 1)
1622 return error("must occur exactly one time!", ArgName);
1623 LLVM_FALLTHROUGH;
1624 case OneOrMore:
1625 case ZeroOrMore:
1626 case ConsumeAfter:
1627 break;
1630 return handleOccurrence(pos, ArgName, Value);
1633 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1634 // has been specified yet.
1636 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1637 if (O.ValueStr.empty())
1638 return DefaultMsg;
1639 return O.ValueStr;
1642 //===----------------------------------------------------------------------===//
1643 // cl::alias class implementation
1646 // Return the width of the option tag for printing...
1647 size_t alias::getOptionWidth() const {
1648 return argPlusPrefixesSize(ArgStr);
1651 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1652 size_t FirstLineIndentedBy) {
1653 assert(Indent >= FirstLineIndentedBy);
1654 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1655 outs().indent(Indent - FirstLineIndentedBy)
1656 << ArgHelpPrefix << Split.first << "\n";
1657 while (!Split.second.empty()) {
1658 Split = Split.second.split('\n');
1659 outs().indent(Indent) << Split.first << "\n";
1663 // Print out the option for the alias.
1664 void alias::printOptionInfo(size_t GlobalWidth) const {
1665 outs() << PrintArg(ArgStr);
1666 printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1669 //===----------------------------------------------------------------------===//
1670 // Parser Implementation code...
1673 // basic_parser implementation
1676 // Return the width of the option tag for printing...
1677 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1678 size_t Len = argPlusPrefixesSize(O.ArgStr);
1679 auto ValName = getValueName();
1680 if (!ValName.empty()) {
1681 size_t FormattingLen = 3;
1682 if (O.getMiscFlags() & PositionalEatsArgs)
1683 FormattingLen = 6;
1684 Len += getValueStr(O, ValName).size() + FormattingLen;
1687 return Len;
1690 // printOptionInfo - Print out information about this option. The
1691 // to-be-maintained width is specified.
1693 void basic_parser_impl::printOptionInfo(const Option &O,
1694 size_t GlobalWidth) const {
1695 outs() << PrintArg(O.ArgStr);
1697 auto ValName = getValueName();
1698 if (!ValName.empty()) {
1699 if (O.getMiscFlags() & PositionalEatsArgs) {
1700 outs() << " <" << getValueStr(O, ValName) << ">...";
1701 } else {
1702 outs() << "=<" << getValueStr(O, ValName) << '>';
1706 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1709 void basic_parser_impl::printOptionName(const Option &O,
1710 size_t GlobalWidth) const {
1711 outs() << PrintArg(O.ArgStr);
1712 outs().indent(GlobalWidth - O.ArgStr.size());
1715 // parser<bool> implementation
1717 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1718 bool &Value) {
1719 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1720 Arg == "1") {
1721 Value = true;
1722 return false;
1725 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1726 Value = false;
1727 return false;
1729 return O.error("'" + Arg +
1730 "' is invalid value for boolean argument! Try 0 or 1");
1733 // parser<boolOrDefault> implementation
1735 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1736 boolOrDefault &Value) {
1737 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1738 Arg == "1") {
1739 Value = BOU_TRUE;
1740 return false;
1742 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1743 Value = BOU_FALSE;
1744 return false;
1747 return O.error("'" + Arg +
1748 "' is invalid value for boolean argument! Try 0 or 1");
1751 // parser<int> implementation
1753 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1754 int &Value) {
1755 if (Arg.getAsInteger(0, Value))
1756 return O.error("'" + Arg + "' value invalid for integer argument!");
1757 return false;
1760 // parser<unsigned> implementation
1762 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1763 unsigned &Value) {
1765 if (Arg.getAsInteger(0, Value))
1766 return O.error("'" + Arg + "' value invalid for uint argument!");
1767 return false;
1770 // parser<unsigned long> implementation
1772 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1773 unsigned long &Value) {
1775 if (Arg.getAsInteger(0, Value))
1776 return O.error("'" + Arg + "' value invalid for ulong argument!");
1777 return false;
1780 // parser<unsigned long long> implementation
1782 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1783 StringRef Arg,
1784 unsigned long long &Value) {
1786 if (Arg.getAsInteger(0, Value))
1787 return O.error("'" + Arg + "' value invalid for ullong argument!");
1788 return false;
1791 // parser<double>/parser<float> implementation
1793 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1794 if (to_float(Arg, Value))
1795 return false;
1796 return O.error("'" + Arg + "' value invalid for floating point argument!");
1799 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1800 double &Val) {
1801 return parseDouble(O, Arg, Val);
1804 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1805 float &Val) {
1806 double dVal;
1807 if (parseDouble(O, Arg, dVal))
1808 return true;
1809 Val = (float)dVal;
1810 return false;
1813 // generic_parser_base implementation
1816 // findOption - Return the option number corresponding to the specified
1817 // argument string. If the option is not found, getNumOptions() is returned.
1819 unsigned generic_parser_base::findOption(StringRef Name) {
1820 unsigned e = getNumOptions();
1822 for (unsigned i = 0; i != e; ++i) {
1823 if (getOption(i) == Name)
1824 return i;
1826 return e;
1829 static StringRef EqValue = "=<value>";
1830 static StringRef EmptyOption = "<empty>";
1831 static StringRef OptionPrefix = " =";
1832 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1834 static bool shouldPrintOption(StringRef Name, StringRef Description,
1835 const Option &O) {
1836 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1837 !Description.empty();
1840 // Return the width of the option tag for printing...
1841 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1842 if (O.hasArgStr()) {
1843 size_t Size =
1844 argPlusPrefixesSize(O.ArgStr) + EqValue.size();
1845 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1846 StringRef Name = getOption(i);
1847 if (!shouldPrintOption(Name, getDescription(i), O))
1848 continue;
1849 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1850 Size = std::max(Size, NameSize + OptionPrefixesSize);
1852 return Size;
1853 } else {
1854 size_t BaseSize = 0;
1855 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1856 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1857 return BaseSize;
1861 // printOptionInfo - Print out information about this option. The
1862 // to-be-maintained width is specified.
1864 void generic_parser_base::printOptionInfo(const Option &O,
1865 size_t GlobalWidth) const {
1866 if (O.hasArgStr()) {
1867 // When the value is optional, first print a line just describing the
1868 // option without values.
1869 if (O.getValueExpectedFlag() == ValueOptional) {
1870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1871 if (getOption(i).empty()) {
1872 outs() << PrintArg(O.ArgStr);
1873 Option::printHelpStr(O.HelpStr, GlobalWidth,
1874 argPlusPrefixesSize(O.ArgStr));
1875 break;
1880 outs() << PrintArg(O.ArgStr) << EqValue;
1881 Option::printHelpStr(O.HelpStr, GlobalWidth,
1882 EqValue.size() +
1883 argPlusPrefixesSize(O.ArgStr));
1884 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1885 StringRef OptionName = getOption(i);
1886 StringRef Description = getDescription(i);
1887 if (!shouldPrintOption(OptionName, Description, O))
1888 continue;
1889 assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1890 size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1891 outs() << OptionPrefix << OptionName;
1892 if (OptionName.empty()) {
1893 outs() << EmptyOption;
1894 assert(NumSpaces >= EmptyOption.size());
1895 NumSpaces -= EmptyOption.size();
1897 if (!Description.empty())
1898 outs().indent(NumSpaces) << ArgHelpPrefix << " " << Description;
1899 outs() << '\n';
1901 } else {
1902 if (!O.HelpStr.empty())
1903 outs() << " " << O.HelpStr << '\n';
1904 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1905 StringRef Option = getOption(i);
1906 outs() << " " << PrintArg(Option);
1907 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1912 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1914 // printGenericOptionDiff - Print the value of this option and it's default.
1916 // "Generic" options have each value mapped to a name.
1917 void generic_parser_base::printGenericOptionDiff(
1918 const Option &O, const GenericOptionValue &Value,
1919 const GenericOptionValue &Default, size_t GlobalWidth) const {
1920 outs() << " " << PrintArg(O.ArgStr);
1921 outs().indent(GlobalWidth - O.ArgStr.size());
1923 unsigned NumOpts = getNumOptions();
1924 for (unsigned i = 0; i != NumOpts; ++i) {
1925 if (Value.compare(getOptionValue(i)))
1926 continue;
1928 outs() << "= " << getOption(i);
1929 size_t L = getOption(i).size();
1930 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1931 outs().indent(NumSpaces) << " (default: ";
1932 for (unsigned j = 0; j != NumOpts; ++j) {
1933 if (Default.compare(getOptionValue(j)))
1934 continue;
1935 outs() << getOption(j);
1936 break;
1938 outs() << ")\n";
1939 return;
1941 outs() << "= *unknown option value*\n";
1944 // printOptionDiff - Specializations for printing basic value types.
1946 #define PRINT_OPT_DIFF(T) \
1947 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1948 size_t GlobalWidth) const { \
1949 printOptionName(O, GlobalWidth); \
1950 std::string Str; \
1952 raw_string_ostream SS(Str); \
1953 SS << V; \
1955 outs() << "= " << Str; \
1956 size_t NumSpaces = \
1957 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1958 outs().indent(NumSpaces) << " (default: "; \
1959 if (D.hasValue()) \
1960 outs() << D.getValue(); \
1961 else \
1962 outs() << "*no default*"; \
1963 outs() << ")\n"; \
1966 PRINT_OPT_DIFF(bool)
1967 PRINT_OPT_DIFF(boolOrDefault)
1968 PRINT_OPT_DIFF(int)
1969 PRINT_OPT_DIFF(unsigned)
1970 PRINT_OPT_DIFF(unsigned long)
1971 PRINT_OPT_DIFF(unsigned long long)
1972 PRINT_OPT_DIFF(double)
1973 PRINT_OPT_DIFF(float)
1974 PRINT_OPT_DIFF(char)
1976 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1977 const OptionValue<std::string> &D,
1978 size_t GlobalWidth) const {
1979 printOptionName(O, GlobalWidth);
1980 outs() << "= " << V;
1981 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1982 outs().indent(NumSpaces) << " (default: ";
1983 if (D.hasValue())
1984 outs() << D.getValue();
1985 else
1986 outs() << "*no default*";
1987 outs() << ")\n";
1990 // Print a placeholder for options that don't yet support printOptionDiff().
1991 void basic_parser_impl::printOptionNoValue(const Option &O,
1992 size_t GlobalWidth) const {
1993 printOptionName(O, GlobalWidth);
1994 outs() << "= *cannot print option value*\n";
1997 //===----------------------------------------------------------------------===//
1998 // -help and -help-hidden option implementation
2001 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2002 const std::pair<const char *, Option *> *RHS) {
2003 return strcmp(LHS->first, RHS->first);
2006 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2007 const std::pair<const char *, SubCommand *> *RHS) {
2008 return strcmp(LHS->first, RHS->first);
2011 // Copy Options into a vector so we can sort them as we like.
2012 static void sortOpts(StringMap<Option *> &OptMap,
2013 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2014 bool ShowHidden) {
2015 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2017 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2018 I != E; ++I) {
2019 // Ignore really-hidden options.
2020 if (I->second->getOptionHiddenFlag() == ReallyHidden)
2021 continue;
2023 // Unless showhidden is set, ignore hidden flags.
2024 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2025 continue;
2027 // If we've already seen this option, don't add it to the list again.
2028 if (!OptionSet.insert(I->second).second)
2029 continue;
2031 Opts.push_back(
2032 std::pair<const char *, Option *>(I->getKey().data(), I->second));
2035 // Sort the options list alphabetically.
2036 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2039 static void
2040 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2041 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2042 for (const auto &S : SubMap) {
2043 if (S->getName().empty())
2044 continue;
2045 Subs.push_back(std::make_pair(S->getName().data(), S));
2047 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2050 namespace {
2052 class HelpPrinter {
2053 protected:
2054 const bool ShowHidden;
2055 typedef SmallVector<std::pair<const char *, Option *>, 128>
2056 StrOptionPairVector;
2057 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2058 StrSubCommandPairVector;
2059 // Print the options. Opts is assumed to be alphabetically sorted.
2060 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2061 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2062 Opts[i].second->printOptionInfo(MaxArgLen);
2065 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2066 for (const auto &S : Subs) {
2067 outs() << " " << S.first;
2068 if (!S.second->getDescription().empty()) {
2069 outs().indent(MaxSubLen - strlen(S.first));
2070 outs() << " - " << S.second->getDescription();
2072 outs() << "\n";
2076 public:
2077 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2078 virtual ~HelpPrinter() {}
2080 // Invoke the printer.
2081 void operator=(bool Value) {
2082 if (!Value)
2083 return;
2084 printHelp();
2086 // Halt the program since help information was printed
2087 exit(0);
2090 void printHelp() {
2091 SubCommand *Sub = GlobalParser->getActiveSubCommand();
2092 auto &OptionsMap = Sub->OptionsMap;
2093 auto &PositionalOpts = Sub->PositionalOpts;
2094 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2096 StrOptionPairVector Opts;
2097 sortOpts(OptionsMap, Opts, ShowHidden);
2099 StrSubCommandPairVector Subs;
2100 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2102 if (!GlobalParser->ProgramOverview.empty())
2103 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2105 if (Sub == &*TopLevelSubCommand) {
2106 outs() << "USAGE: " << GlobalParser->ProgramName;
2107 if (Subs.size() > 2)
2108 outs() << " [subcommand]";
2109 outs() << " [options]";
2110 } else {
2111 if (!Sub->getDescription().empty()) {
2112 outs() << "SUBCOMMAND '" << Sub->getName()
2113 << "': " << Sub->getDescription() << "\n\n";
2115 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2116 << " [options]";
2119 for (auto Opt : PositionalOpts) {
2120 if (Opt->hasArgStr())
2121 outs() << " --" << Opt->ArgStr;
2122 outs() << " " << Opt->HelpStr;
2125 // Print the consume after option info if it exists...
2126 if (ConsumeAfterOpt)
2127 outs() << " " << ConsumeAfterOpt->HelpStr;
2129 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2130 // Compute the maximum subcommand length...
2131 size_t MaxSubLen = 0;
2132 for (size_t i = 0, e = Subs.size(); i != e; ++i)
2133 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2135 outs() << "\n\n";
2136 outs() << "SUBCOMMANDS:\n\n";
2137 printSubCommands(Subs, MaxSubLen);
2138 outs() << "\n";
2139 outs() << " Type \"" << GlobalParser->ProgramName
2140 << " <subcommand> --help\" to get more help on a specific "
2141 "subcommand";
2144 outs() << "\n\n";
2146 // Compute the maximum argument length...
2147 size_t MaxArgLen = 0;
2148 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2149 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2151 outs() << "OPTIONS:\n";
2152 printOptions(Opts, MaxArgLen);
2154 // Print any extra help the user has declared.
2155 for (auto I : GlobalParser->MoreHelp)
2156 outs() << I;
2157 GlobalParser->MoreHelp.clear();
2161 class CategorizedHelpPrinter : public HelpPrinter {
2162 public:
2163 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2165 // Helper function for printOptions().
2166 // It shall return a negative value if A's name should be lexicographically
2167 // ordered before B's name. It returns a value greater than zero if B's name
2168 // should be ordered before A's name, and it returns 0 otherwise.
2169 static int OptionCategoryCompare(OptionCategory *const *A,
2170 OptionCategory *const *B) {
2171 return (*A)->getName().compare((*B)->getName());
2174 // Make sure we inherit our base class's operator=()
2175 using HelpPrinter::operator=;
2177 protected:
2178 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2179 std::vector<OptionCategory *> SortedCategories;
2180 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2182 // Collect registered option categories into vector in preparation for
2183 // sorting.
2184 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2185 E = GlobalParser->RegisteredOptionCategories.end();
2186 I != E; ++I) {
2187 SortedCategories.push_back(*I);
2190 // Sort the different option categories alphabetically.
2191 assert(SortedCategories.size() > 0 && "No option categories registered!");
2192 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2193 OptionCategoryCompare);
2195 // Create map to empty vectors.
2196 for (std::vector<OptionCategory *>::const_iterator
2197 I = SortedCategories.begin(),
2198 E = SortedCategories.end();
2199 I != E; ++I)
2200 CategorizedOptions[*I] = std::vector<Option *>();
2202 // Walk through pre-sorted options and assign into categories.
2203 // Because the options are already alphabetically sorted the
2204 // options within categories will also be alphabetically sorted.
2205 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2206 Option *Opt = Opts[I].second;
2207 for (auto &Cat : Opt->Categories) {
2208 assert(CategorizedOptions.count(Cat) > 0 &&
2209 "Option has an unregistered category");
2210 CategorizedOptions[Cat].push_back(Opt);
2214 // Now do printing.
2215 for (std::vector<OptionCategory *>::const_iterator
2216 Category = SortedCategories.begin(),
2217 E = SortedCategories.end();
2218 Category != E; ++Category) {
2219 // Hide empty categories for --help, but show for --help-hidden.
2220 const auto &CategoryOptions = CategorizedOptions[*Category];
2221 bool IsEmptyCategory = CategoryOptions.empty();
2222 if (!ShowHidden && IsEmptyCategory)
2223 continue;
2225 // Print category information.
2226 outs() << "\n";
2227 outs() << (*Category)->getName() << ":\n";
2229 // Check if description is set.
2230 if (!(*Category)->getDescription().empty())
2231 outs() << (*Category)->getDescription() << "\n\n";
2232 else
2233 outs() << "\n";
2235 // When using --help-hidden explicitly state if the category has no
2236 // options associated with it.
2237 if (IsEmptyCategory) {
2238 outs() << " This option category has no options.\n";
2239 continue;
2241 // Loop over the options in the category and print.
2242 for (const Option *Opt : CategoryOptions)
2243 Opt->printOptionInfo(MaxArgLen);
2248 // This wraps the Uncategorizing and Categorizing printers and decides
2249 // at run time which should be invoked.
2250 class HelpPrinterWrapper {
2251 private:
2252 HelpPrinter &UncategorizedPrinter;
2253 CategorizedHelpPrinter &CategorizedPrinter;
2255 public:
2256 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2257 CategorizedHelpPrinter &CategorizedPrinter)
2258 : UncategorizedPrinter(UncategorizedPrinter),
2259 CategorizedPrinter(CategorizedPrinter) {}
2261 // Invoke the printer.
2262 void operator=(bool Value);
2265 } // End anonymous namespace
2267 // Declare the four HelpPrinter instances that are used to print out help, or
2268 // help-hidden as an uncategorized list or in categories.
2269 static HelpPrinter UncategorizedNormalPrinter(false);
2270 static HelpPrinter UncategorizedHiddenPrinter(true);
2271 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2272 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2274 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2275 // a categorizing help printer
2276 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2277 CategorizedNormalPrinter);
2278 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2279 CategorizedHiddenPrinter);
2281 // Define a category for generic options that all tools should have.
2282 static cl::OptionCategory GenericCategory("Generic Options");
2284 // Define uncategorized help printers.
2285 // --help-list is hidden by default because if Option categories are being used
2286 // then --help behaves the same as --help-list.
2287 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2288 "help-list",
2289 cl::desc("Display list of available options (--help-list-hidden for more)"),
2290 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2291 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2293 static cl::opt<HelpPrinter, true, parser<bool>>
2294 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2295 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2296 cl::ValueDisallowed, cl::cat(GenericCategory),
2297 cl::sub(*AllSubCommands));
2299 // Define uncategorized/categorized help printers. These printers change their
2300 // behaviour at runtime depending on whether one or more Option categories have
2301 // been declared.
2302 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2303 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
2304 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2305 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2307 static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2308 cl::DefaultOption);
2310 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2311 HHOp("help-hidden", cl::desc("Display all available options"),
2312 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2313 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2315 static cl::opt<bool> PrintOptions(
2316 "print-options",
2317 cl::desc("Print non-default options after command line parsing"),
2318 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2319 cl::sub(*AllSubCommands));
2321 static cl::opt<bool> PrintAllOptions(
2322 "print-all-options",
2323 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2324 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2326 void HelpPrinterWrapper::operator=(bool Value) {
2327 if (!Value)
2328 return;
2330 // Decide which printer to invoke. If more than one option category is
2331 // registered then it is useful to show the categorized help instead of
2332 // uncategorized help.
2333 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2334 // unhide --help-list option so user can have uncategorized output if they
2335 // want it.
2336 HLOp.setHiddenFlag(NotHidden);
2338 CategorizedPrinter = true; // Invoke categorized printer
2339 } else
2340 UncategorizedPrinter = true; // Invoke uncategorized printer
2343 // Print the value of each option.
2344 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2346 void CommandLineParser::printOptionValues() {
2347 if (!PrintOptions && !PrintAllOptions)
2348 return;
2350 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2351 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2353 // Compute the maximum argument length...
2354 size_t MaxArgLen = 0;
2355 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2356 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2358 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2359 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2362 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2364 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2366 namespace {
2367 class VersionPrinter {
2368 public:
2369 void print() {
2370 raw_ostream &OS = outs();
2371 #ifdef PACKAGE_VENDOR
2372 OS << PACKAGE_VENDOR << " ";
2373 #else
2374 OS << "LLVM (http://llvm.org/):\n ";
2375 #endif
2376 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2377 #ifdef LLVM_VERSION_INFO
2378 OS << " " << LLVM_VERSION_INFO;
2379 #endif
2380 OS << "\n ";
2381 #ifndef __OPTIMIZE__
2382 OS << "DEBUG build";
2383 #else
2384 OS << "Optimized build";
2385 #endif
2386 #ifndef NDEBUG
2387 OS << " with assertions";
2388 #endif
2389 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2390 std::string CPU = sys::getHostCPUName();
2391 if (CPU == "generic")
2392 CPU = "(unknown)";
2393 OS << ".\n"
2394 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2395 << " Host CPU: " << CPU;
2396 #endif
2397 OS << '\n';
2399 void operator=(bool OptionWasSpecified) {
2400 if (!OptionWasSpecified)
2401 return;
2403 if (OverrideVersionPrinter != nullptr) {
2404 OverrideVersionPrinter(outs());
2405 exit(0);
2407 print();
2409 // Iterate over any registered extra printers and call them to add further
2410 // information.
2411 if (ExtraVersionPrinters != nullptr) {
2412 outs() << '\n';
2413 for (auto I : *ExtraVersionPrinters)
2414 I(outs());
2417 exit(0);
2420 } // End anonymous namespace
2422 // Define the --version option that prints out the LLVM version for the tool
2423 static VersionPrinter VersionPrinterInstance;
2425 static cl::opt<VersionPrinter, true, parser<bool>>
2426 VersOp("version", cl::desc("Display the version of this program"),
2427 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2428 cl::cat(GenericCategory));
2430 // Utility function for printing the help message.
2431 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2432 if (!Hidden && !Categorized)
2433 UncategorizedNormalPrinter.printHelp();
2434 else if (!Hidden && Categorized)
2435 CategorizedNormalPrinter.printHelp();
2436 else if (Hidden && !Categorized)
2437 UncategorizedHiddenPrinter.printHelp();
2438 else
2439 CategorizedHiddenPrinter.printHelp();
2442 /// Utility function for printing version number.
2443 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2445 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2447 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2448 if (!ExtraVersionPrinters)
2449 ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2451 ExtraVersionPrinters->push_back(func);
2454 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2455 auto &Subs = GlobalParser->RegisteredSubCommands;
2456 (void)Subs;
2457 assert(is_contained(Subs, &Sub));
2458 return Sub.OptionsMap;
2461 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2462 cl::getRegisteredSubcommands() {
2463 return GlobalParser->getRegisteredSubcommands();
2466 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2467 for (auto &I : Sub.OptionsMap) {
2468 for (auto &Cat : I.second->Categories) {
2469 if (Cat != &Category &&
2470 Cat != &GenericCategory)
2471 I.second->setHiddenFlag(cl::ReallyHidden);
2476 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2477 SubCommand &Sub) {
2478 for (auto &I : Sub.OptionsMap) {
2479 for (auto &Cat : I.second->Categories) {
2480 if (find(Categories, Cat) == Categories.end() && Cat != &GenericCategory)
2481 I.second->setHiddenFlag(cl::ReallyHidden);
2486 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2487 void cl::ResetAllOptionOccurrences() {
2488 GlobalParser->ResetAllOptionOccurrences();
2491 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2492 const char *Overview) {
2493 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2494 &llvm::nulls());