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.
12 //
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
15 //
16 //===----------------------------------------------------------------------===//
17 
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;
45 
46 #define DEBUG_TYPE "commandline"
47 
48 //===----------------------------------------------------------------------===//
49 // Template instantiations and anchors.
50 //
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>;
63 
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>;
69 }
70 } // end namespace llvm::cl
71 
72 // Pin the vtables to this file.
anchor()73 void GenericOptionValue::anchor() {}
anchor()74 void OptionValue<boolOrDefault>::anchor() {}
anchor()75 void OptionValue<std::string>::anchor() {}
anchor()76 void Option::anchor() {}
anchor()77 void basic_parser_impl::anchor() {}
anchor()78 void parser<bool>::anchor() {}
anchor()79 void parser<boolOrDefault>::anchor() {}
anchor()80 void parser<int>::anchor() {}
anchor()81 void parser<unsigned>::anchor() {}
anchor()82 void parser<unsigned long>::anchor() {}
anchor()83 void parser<unsigned long long>::anchor() {}
anchor()84 void parser<double>::anchor() {}
anchor()85 void parser<float>::anchor() {}
anchor()86 void parser<std::string>::anchor() {}
anchor()87 void parser<char>::anchor() {}
88 
89 //===----------------------------------------------------------------------===//
90 
91 static StringRef ArgPrefix = "  -";
92 static StringRef ArgPrefixLong = "  --";
93 static StringRef ArgHelpPrefix = " - ";
94 
argPlusPrefixesSize(StringRef ArgName)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();
100 }
101 
argPrefix(StringRef ArgName)102 static StringRef argPrefix(StringRef ArgName) {
103   if (ArgName.size() == 1)
104     return ArgPrefix;
105   return ArgPrefixLong;
106 }
107 
108 // Option predicates...
isGrouping(const Option * O)109 static inline bool isGrouping(const Option *O) {
110   return O->getMiscFlags() & cl::Grouping;
111 }
isPrefixedOrGrouping(const Option * O)112 static inline bool isPrefixedOrGrouping(const Option *O) {
113   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
114          O->getFormattingFlag() == cl::AlwaysPrefix;
115 }
116 
117 
118 namespace {
119 
120 class PrintArg {
121   StringRef ArgName;
122 public:
PrintArg(StringRef ArgName)123   PrintArg(StringRef ArgName) : ArgName(ArgName) {}
124   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg&);
125 };
126 
operator <<(raw_ostream & OS,const PrintArg & Arg)127 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
128   OS << argPrefix(Arg.ArgName) << Arg.ArgName;
129   return OS;
130 }
131 
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;
138 
139   // This collects additional help to be printed.
140   std::vector<StringRef> MoreHelp;
141 
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;
146 
147   // This collects the different option categories that have been registered.
148   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
149 
150   // This collects the different subcommands that have been registered.
151   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
152 
CommandLineParser()153   CommandLineParser() : ActiveSubCommand(nullptr) {
154     registerSubCommand(&*TopLevelSubCommand);
155     registerSubCommand(&*AllSubCommands);
156   }
157 
158   void ResetAllOptionOccurrences();
159 
160   bool ParseCommandLineOptions(int argc, const char *const *argv,
161                                StringRef Overview, raw_ostream *Errs = nullptr,
162                                bool LongOptionsUseDoubleDash = false);
163 
addLiteralOption(Option & Opt,SubCommand * SC,StringRef Name)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");
171     }
172 
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);
180       }
181     }
182   }
183 
addLiteralOption(Option & Opt,StringRef 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);
190     }
191   }
192 
addOption(Option * O,SubCommand * SC)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;
200 
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;
206       }
207     }
208 
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;
218       }
219       SC->ConsumeAfterOpt = O;
220     }
221 
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");
228 
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);
236       }
237     }
238   }
239 
addOption(Option * O,bool ProcessDefaultOption=false)240   void addOption(Option *O, bool ProcessDefaultOption = false) {
241     if (!ProcessDefaultOption && O->isDefaultOption()) {
242       DefaultOptions.push_back(O);
243       return;
244     }
245 
246     if (O->Subs.empty()) {
247       addOption(O, &*TopLevelSubCommand);
248     } else {
249       for (auto SC : O->Subs)
250         addOption(O, SC);
251     }
252   }
253 
removeOption(Option * O,SubCommand * 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);
259 
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);
266       }
267 
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;
274         }
275       }
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;
281         }
282       }
283     else if (O == Sub.ConsumeAfterOpt)
284       Sub.ConsumeAfterOpt = nullptr;
285   }
286 
removeOption(Option * O)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);
297       }
298     }
299   }
300 
hasOptions(const SubCommand & Sub) const301   bool hasOptions(const SubCommand &Sub) const {
302     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
303             nullptr != Sub.ConsumeAfterOpt);
304   }
305 
hasOptions() const306   bool hasOptions() const {
307     for (const auto &S : RegisteredSubCommands) {
308       if (hasOptions(*S))
309         return true;
310     }
311     return false;
312   }
313 
getActiveSubCommand()314   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
315 
updateArgStr(Option * O,StringRef NewName,SubCommand * SC)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");
322     }
323     Sub.OptionsMap.erase(O->ArgStr);
324   }
325 
updateArgStr(Option * O,StringRef NewName)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);
336       }
337     }
338   }
339 
340   void printOptionValues();
341 
registerCategory(OptionCategory * cat)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");
348 
349     RegisteredOptionCategories.insert(cat);
350   }
351 
registerSubCommand(SubCommand * sub)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);
360 
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());
371       }
372     }
373   }
374 
unregisterSubCommand(SubCommand * sub)375   void unregisterSubCommand(SubCommand *sub) {
376     RegisteredSubCommands.erase(sub);
377   }
378 
379   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()380   getRegisteredSubcommands() {
381     return make_range(RegisteredSubCommands.begin(),
382                       RegisteredSubCommands.end());
383   }
384 
reset()385   void reset() {
386     ActiveSubCommand = nullptr;
387     ProgramName.clear();
388     ProgramOverview = StringRef();
389 
390     MoreHelp.clear();
391     RegisteredOptionCategories.clear();
392 
393     ResetAllOptionOccurrences();
394     RegisteredSubCommands.clear();
395 
396     TopLevelSubCommand->reset();
397     AllSubCommands->reset();
398     registerSubCommand(&*TopLevelSubCommand);
399     registerSubCommand(&*AllSubCommands);
400 
401     DefaultOptions.clear();
402   }
403 
404 private:
405   SubCommand *ActiveSubCommand;
406 
407   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
LookupLongOption(SubCommand & Sub,StringRef & Arg,StringRef & Value,bool LongOptionsUseDoubleDash,bool HaveDoubleDash)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;
414   }
415   SubCommand *LookupSubCommand(StringRef Name);
416 };
417 
418 } // namespace
419 
420 static ManagedStatic<CommandLineParser> GlobalParser;
421 
AddLiteralOption(Option & O,StringRef Name)422 void cl::AddLiteralOption(Option &O, StringRef Name) {
423   GlobalParser->addLiteralOption(O, Name);
424 }
425 
extrahelp(StringRef Help)426 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
427   GlobalParser->MoreHelp.push_back(Help);
428 }
429 
addArgument()430 void Option::addArgument() {
431   GlobalParser->addOption(this);
432   FullyInitialized = true;
433 }
434 
removeArgument()435 void Option::removeArgument() { GlobalParser->removeOption(this); }
436 
setArgStr(StringRef S)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);
444 }
445 
addCategory(OptionCategory & C)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);
455 }
456 
reset()457 void Option::reset() {
458   NumOccurrences = 0;
459   setDefault();
460   if (isDefaultOption())
461     removeArgument();
462 }
463 
464 // Initialise the general option category.
465 OptionCategory llvm::cl::GeneralCategory("General options");
466 
registerCategory()467 void OptionCategory::registerCategory() {
468   GlobalParser->registerCategory(this);
469 }
470 
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;
477 
478 // A special subcommand that can be used to put an option into all subcommands.
479 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
480 
registerSubCommand()481 void SubCommand::registerSubCommand() {
482   GlobalParser->registerSubCommand(this);
483 }
484 
unregisterSubCommand()485 void SubCommand::unregisterSubCommand() {
486   GlobalParser->unregisterSubCommand(this);
487 }
488 
reset()489 void SubCommand::reset() {
490   PositionalOpts.clear();
491   SinkOpts.clear();
492   OptionsMap.clear();
493 
494   ConsumeAfterOpt = nullptr;
495 }
496 
operator bool() const497 SubCommand::operator bool() const {
498   return (GlobalParser->getActiveSubCommand() == this);
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // Basic, shared command line option processing machinery.
503 //
504 
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.
LookupOption(SubCommand & Sub,StringRef & Arg,StringRef & Value)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);
514 
515   size_t EqualPos = Arg.find('=');
516 
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;
523 
524     return I != Sub.OptionsMap.end() ? I->second : nullptr;
525   }
526 
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;
533 
534   auto O = I->second;
535   if (O->getFormattingFlag() == cl::AlwaysPrefix)
536     return nullptr;
537 
538   Value = Arg.substr(EqualPos + 1);
539   Arg = Arg.substr(0, EqualPos);
540   return I->second;
541 }
542 
LookupSubCommand(StringRef Name)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;
551 
552     if (StringRef(S->getName()) == StringRef(Name))
553       return S;
554   }
555   return &*TopLevelSubCommand;
556 }
557 
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.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)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;
568 
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;
573 
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);
585 
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();
598       }
599     }
600   }
601 
602   return Best;
603 }
604 
605 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
606 /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)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(',');
615 
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(',');
624     }
625 
626     Value = Val;
627   }
628 
629   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
630 }
631 
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=).
ProvideOption(Option * Handler,StringRef ArgName,StringRef Value,int argc,const char * const * argv,int & i)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();
640 
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]);
652     }
653     break;
654   case ValueDisallowed:
655     if (NumAdditionalVals > 0)
656       return Handler->error("multi-valued option specified"
657                             " with ValueDisallowed modifier!");
658 
659     if (Value.data())
660       return Handler->error("does not allow a value! '" + Twine(Value) +
661                             "' specified.");
662     break;
663   case ValueOptional:
664     break;
665   }
666 
667   // If this isn't a multi-arg option, just run the handler.
668   if (NumAdditionalVals == 0)
669     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
670 
671   // If it is, run the handle several times.
672   bool MultiArg = false;
673 
674   if (Value.data()) {
675     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
676       return true;
677     --NumAdditionalVals;
678     MultiArg = true;
679   }
680 
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]);
686 
687     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
688       return true;
689     MultiArg = true;
690     --NumAdditionalVals;
691   }
692   return false;
693 }
694 
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)695 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
696   int Dummy = i;
697   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
698 }
699 
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.
705 //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)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();
712 
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();
721   }
722 
723   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
724     Length = Name.size();
725     return OMI->second; // Found one!
726   }
727   return nullptr; // No option found!
728 }
729 
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 *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)735 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
736                               bool &ErrorParsing,
737                               const StringMap<Option *> &OptionsMap) {
738   if (Arg.size() == 1)
739     return nullptr;
740 
741   // Do the lookup!
742   size_t Length = 0;
743   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
744   if (!PGOpt)
745     return nullptr;
746 
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);
752 
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;
759     }
760 
761     if (MaybeValue[0] == '=') {
762       Value = MaybeValue.substr(1);
763       return PGOpt;
764     }
765 
766     // This must be a grouped option.
767     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
768 
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;
773     }
774 
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);
779 
780     // Get the next grouping option.
781     Arg = MaybeValue;
782     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
783   } while (PGOpt);
784 
785   // We could not find a grouping option in the remainder of Arg.
786   return nullptr;
787 }
788 
RequiresValue(const Option * O)789 static bool RequiresValue(const Option *O) {
790   return O->getNumOccurrencesFlag() == cl::Required ||
791          O->getNumOccurrencesFlag() == cl::OneOrMore;
792 }
793 
EatsUnboundedNumberOfValues(const Option * O)794 static bool EatsUnboundedNumberOfValues(const Option *O) {
795   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
796          O->getNumOccurrencesFlag() == cl::OneOrMore;
797 }
798 
isWhitespace(char C)799 static bool isWhitespace(char C) {
800   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
801 }
802 
isWhitespaceOrNull(char C)803 static bool isWhitespaceOrNull(char C) {
804   return isWhitespace(C) || C == '\0';
805 }
806 
isQuote(char C)807 static bool isQuote(char C) { return C == '\"' || C == '\''; }
808 
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)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;
821       }
822       if (I == E)
823         break;
824     }
825 
826     char C = Src[I];
827 
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;
833     }
834 
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;
844       }
845       if (I == E)
846         break;
847       continue;
848     }
849 
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;
856     }
857 
858     // This is a normal character.  Append it.
859     Token.push_back(C);
860   }
861 
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);
868 }
869 
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.
874 ///
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.
880 ///
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.
885 ///
886 ///  * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)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] == '\\');
895 
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;
903   }
904   Token.append(BackslashCount, '\\');
905   return I - 1;
906 }
907 
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)908 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
909                                     SmallVectorImpl<const char *> &NewArgv,
910                                     bool MarkEOLs) {
911   SmallString<128> Token;
912 
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];
918 
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;
927       }
928       if (C == '"') {
929         State = QUOTED;
930         continue;
931       }
932       if (C == '\\') {
933         I = parseBackslash(Src, I, Token);
934         State = UNQUOTED;
935         continue;
936       }
937       Token.push_back(C);
938       State = UNQUOTED;
939       continue;
940     }
941 
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;
954       }
955       if (C == '"') {
956         State = QUOTED;
957         continue;
958       }
959       if (C == '\\') {
960         I = parseBackslash(Src, I, Token);
961         continue;
962       }
963       Token.push_back(C);
964       continue;
965     }
966 
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;
976         }
977         State = UNQUOTED;
978         continue;
979       }
980       if (C == '\\') {
981         I = parseBackslash(Src, I, Token);
982         continue;
983       }
984       Token.push_back(C);
985     }
986   }
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);
993 }
994 
tokenizeConfigFile(StringRef Source,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)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;
1005     }
1006     if (*Cur == '#') {
1007       while (Cur != Source.end() && *Cur != '\n')
1008         ++Cur;
1009       continue;
1010     }
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;
1023           }
1024         }
1025       } else if (*Cur == '\n')
1026         break;
1027     }
1028     // Tokenize line.
1029     Line.append(Start, Cur);
1030     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1031   }
1032 }
1033 
1034 // It is called byte order marker but the UTF-8 BOM is actually not affected
1035 // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)1036 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1037   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1038 }
1039 
ExpandResponseFile(StringRef FName,StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs,bool RelativeNames)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());
1050 
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);
1058   }
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);
1064 
1065   // Tokenize the contents into NewArgv.
1066   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1067 
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());
1084             }
1085             llvm::sys::path::append(
1086                 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
1087             NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
1088           }
1089         }
1090       }
1091 
1092   return true;
1093 }
1094 
1095 /// Expand response files on a command line recursively using the given
1096 /// StringSaver and tokenization strategy.
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv,bool MarkEOLs,bool RelativeNames)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;
1104   };
1105 
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;
1110 
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()});
1114 
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();
1121     }
1122 
1123     const char *Arg = Argv[I];
1124     // Check if it is an EOL marker
1125     if (Arg == nullptr) {
1126       ++I;
1127       continue;
1128     }
1129 
1130     if (Arg[0] != '@') {
1131       ++I;
1132       continue;
1133     }
1134 
1135     const char *FName = Arg + 1;
1136     auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
1137       return sys::fs::equivalent(RFile.File, FName);
1138     };
1139 
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;
1147     }
1148 
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;
1159     }
1160 
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;
1165     }
1166 
1167     FileStack.push_back({FName, I + ExpandedArgv.size()});
1168     Argv.erase(Argv.begin() + I);
1169     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1170   }
1171 
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;
1179 }
1180 
readConfigFile(StringRef CfgFile,StringSaver & Saver,SmallVectorImpl<const char * > & Argv)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);
1188 }
1189 
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).
1194 ///
ParseEnvironmentOptions(const char * progName,const char * envVar,const char * Overview)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");
1200 
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;
1205 
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());
1212 
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));
1218 }
1219 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,const char * EnvVar,bool LongOptionsUseDoubleDash)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]);
1228 
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);
1234   }
1235 
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());
1240 
1241   // Parse all options.
1242   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1243                                                Errs, LongOptionsUseDoubleDash);
1244 }
1245 
ResetAllOptionOccurrences()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();
1252   }
1253 }
1254 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,bool LongOptionsUseDoubleDash)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!");
1261 
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());
1272 
1273   // Copy the program name into ProgName, making sure not to overflow it.
1274   ProgramName = sys::path::filename(StringRef(argv[0]));
1275 
1276   ProgramOverview = Overview;
1277   bool IgnoreErrors = Errs;
1278   if (!Errs)
1279     Errs = &errs();
1280   bool ErrorParsing = false;
1281 
1282   // Check out the positional arguments to collect information about them.
1283   unsigned NumPositionalRequired = 0;
1284 
1285   // Determine whether or not there are an unlimited number of positionals
1286   bool HasUnlimitedPositionals = false;
1287 
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;
1296   }
1297   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1298 
1299   assert(ChosenSubCommand);
1300   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1301   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1302   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1303   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1304 
1305   for (auto O: DefaultOptions) {
1306     addOption(O, true);
1307   }
1308 
1309   if (ConsumeAfterOpt) {
1310     assert(PositionalOpts.size() > 0 &&
1311            "Cannot specify cl::ConsumeAfter without a positional argument!");
1312   }
1313   if (!PositionalOpts.empty()) {
1314 
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;
1330         }
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!
1335         //
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;
1345       }
1346       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1347     }
1348     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1349   }
1350 
1351   // PositionalVals - A vector of "positional" arguments we accumulate into
1352   // the process at the end.
1353   //
1354   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1355 
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;
1360 
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;
1370 
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.
1374     //
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!
1380       }
1381 
1382       if (!PositionalOpts.empty()) {
1383         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1384 
1385         // All of the positional arguments have been fulfulled, give the rest to
1386         // the consume after option... if it's specified...
1387         //
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...
1392         }
1393 
1394         // Delay processing positional arguments until the end...
1395         continue;
1396       }
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);
1411       }
1412 
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!
1418       }
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);
1425       }
1426 
1427       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1428                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1429 
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);
1434 
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);
1440     }
1441 
1442     if (!Handler) {
1443       if (SinkOpts.empty()) {
1444         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1445               << "'.  Try: '" << argv[0] << " --help'\n";
1446 
1447         if (NearestHandler) {
1448           // If we know a near match, report it as well.
1449           *Errs << ProgramName << ": Did you mean '"
1450                 << PrintArg(NearestHandlerString) << "'?\n";
1451         }
1452 
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]));
1459       }
1460       continue;
1461     }
1462 
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;
1471       }
1472       ActivePositionalArg = Handler;
1473     }
1474     else
1475       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1476   }
1477 
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";
1485 
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;
1493 
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...
1503       }
1504 
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.
1508       //
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!");
1525         }
1526       }
1527     }
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++;
1537       }
1538 
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.
1543     //
1544     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1545       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1546                                               PositionalVals[ValNo].first,
1547                                               PositionalVals[ValNo].second);
1548       ValNo++;
1549     }
1550 
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);
1557   }
1558 
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;
1567       }
1568       LLVM_FALLTHROUGH;
1569     default:
1570       break;
1571     }
1572   }
1573 
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';);
1580 
1581   // Free all of the memory allocated to the map.  Command line options may only
1582   // be processed once!
1583   MoreHelp.clear();
1584 
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;
1590   }
1591   return true;
1592 }
1593 
1594 //===----------------------------------------------------------------------===//
1595 // Option Base class implementation
1596 //
1597 
error(const Twine & Message,StringRef ArgName,raw_ostream & Errs)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);
1605 
1606   Errs << " option: " << Message << "\n";
1607   return true;
1608 }
1609 
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)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
1614 
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;
1628   }
1629 
1630   return handleOccurrence(pos, ArgName, Value);
1631 }
1632 
1633 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1634 // has been specified yet.
1635 //
getValueStr(const Option & O,StringRef DefaultMsg)1636 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1637   if (O.ValueStr.empty())
1638     return DefaultMsg;
1639   return O.ValueStr;
1640 }
1641 
1642 //===----------------------------------------------------------------------===//
1643 // cl::alias class implementation
1644 //
1645 
1646 // Return the width of the option tag for printing...
getOptionWidth() const1647 size_t alias::getOptionWidth() const {
1648   return argPlusPrefixesSize(ArgStr);
1649 }
1650 
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)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";
1660   }
1661 }
1662 
1663 // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1664 void alias::printOptionInfo(size_t GlobalWidth) const {
1665   outs() << PrintArg(ArgStr);
1666   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1667 }
1668 
1669 //===----------------------------------------------------------------------===//
1670 // Parser Implementation code...
1671 //
1672 
1673 // basic_parser implementation
1674 //
1675 
1676 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1677 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;
1685   }
1686 
1687   return Len;
1688 }
1689 
1690 // printOptionInfo - Print out information about this option.  The
1691 // to-be-maintained width is specified.
1692 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1693 void basic_parser_impl::printOptionInfo(const Option &O,
1694                                         size_t GlobalWidth) const {
1695   outs() << PrintArg(O.ArgStr);
1696 
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) << '>';
1703     }
1704   }
1705 
1706   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1707 }
1708 
printOptionName(const Option & O,size_t GlobalWidth) const1709 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());
1713 }
1714 
1715 // parser<bool> implementation
1716 //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)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;
1723   }
1724 
1725   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1726     Value = false;
1727     return false;
1728   }
1729   return O.error("'" + Arg +
1730                  "' is invalid value for boolean argument! Try 0 or 1");
1731 }
1732 
1733 // parser<boolOrDefault> implementation
1734 //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)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;
1741   }
1742   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1743     Value = BOU_FALSE;
1744     return false;
1745   }
1746 
1747   return O.error("'" + Arg +
1748                  "' is invalid value for boolean argument! Try 0 or 1");
1749 }
1750 
1751 // parser<int> implementation
1752 //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)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;
1758 }
1759 
1760 // parser<unsigned> implementation
1761 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)1762 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1763                              unsigned &Value) {
1764 
1765   if (Arg.getAsInteger(0, Value))
1766     return O.error("'" + Arg + "' value invalid for uint argument!");
1767   return false;
1768 }
1769 
1770 // parser<unsigned long> implementation
1771 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long & Value)1772 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1773                                   unsigned long &Value) {
1774 
1775   if (Arg.getAsInteger(0, Value))
1776     return O.error("'" + Arg + "' value invalid for ulong argument!");
1777   return false;
1778 }
1779 
1780 // parser<unsigned long long> implementation
1781 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)1782 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1783                                        StringRef Arg,
1784                                        unsigned long long &Value) {
1785 
1786   if (Arg.getAsInteger(0, Value))
1787     return O.error("'" + Arg + "' value invalid for ullong argument!");
1788   return false;
1789 }
1790 
1791 // parser<double>/parser<float> implementation
1792 //
parseDouble(Option & O,StringRef Arg,double & Value)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!");
1797 }
1798 
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)1799 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1800                            double &Val) {
1801   return parseDouble(O, Arg, Val);
1802 }
1803 
parse(Option & O,StringRef ArgName,StringRef Arg,float & 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;
1811 }
1812 
1813 // generic_parser_base implementation
1814 //
1815 
1816 // findOption - Return the option number corresponding to the specified
1817 // argument string.  If the option is not found, getNumOptions() is returned.
1818 //
findOption(StringRef Name)1819 unsigned generic_parser_base::findOption(StringRef Name) {
1820   unsigned e = getNumOptions();
1821 
1822   for (unsigned i = 0; i != e; ++i) {
1823     if (getOption(i) == Name)
1824       return i;
1825   }
1826   return e;
1827 }
1828 
1829 static StringRef EqValue = "=<value>";
1830 static StringRef EmptyOption = "<empty>";
1831 static StringRef OptionPrefix = "    =";
1832 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1833 
shouldPrintOption(StringRef Name,StringRef Description,const Option & O)1834 static bool shouldPrintOption(StringRef Name, StringRef Description,
1835                               const Option &O) {
1836   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1837          !Description.empty();
1838 }
1839 
1840 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1841 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);
1851     }
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;
1858   }
1859 }
1860 
1861 // printOptionInfo - Print out information about this option.  The
1862 // to-be-maintained width is specified.
1863 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1864 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;
1876         }
1877       }
1878     }
1879 
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();
1896       }
1897       if (!Description.empty())
1898         outs().indent(NumSpaces) << ArgHelpPrefix << "  " << Description;
1899       outs() << '\n';
1900     }
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);
1908     }
1909   }
1910 }
1911 
1912 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1913 
1914 // printGenericOptionDiff - Print the value of this option and it's default.
1915 //
1916 // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const1917 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());
1922 
1923   unsigned NumOpts = getNumOptions();
1924   for (unsigned i = 0; i != NumOpts; ++i) {
1925     if (Value.compare(getOptionValue(i)))
1926       continue;
1927 
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;
1937     }
1938     outs() << ")\n";
1939     return;
1940   }
1941   outs() << "= *unknown option value*\n";
1942 }
1943 
1944 // printOptionDiff - Specializations for printing basic value types.
1945 //
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;                                                           \
1951     {                                                                          \
1952       raw_string_ostream SS(Str);                                              \
1953       SS << V;                                                                 \
1954     }                                                                          \
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";                                                           \
1964   }
1965 
1966 PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)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)
1975 
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";
1988 }
1989 
1990 // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const1991 void basic_parser_impl::printOptionNoValue(const Option &O,
1992                                            size_t GlobalWidth) const {
1993   printOptionName(O, GlobalWidth);
1994   outs() << "= *cannot print option value*\n";
1995 }
1996 
1997 //===----------------------------------------------------------------------===//
1998 // -help and -help-hidden option implementation
1999 //
2000 
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)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);
2004 }
2005 
SubNameCompare(const std::pair<const char *,SubCommand * > * LHS,const std::pair<const char *,SubCommand * > * RHS)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);
2009 }
2010 
2011 // Copy Options into a vector so we can sort them as we like.
sortOpts(StringMap<Option * > & OptMap,SmallVectorImpl<std::pair<const char *,Option * >> & Opts,bool ShowHidden)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.
2016 
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;
2022 
2023     // Unless showhidden is set, ignore hidden flags.
2024     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2025       continue;
2026 
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;
2030 
2031     Opts.push_back(
2032         std::pair<const char *, Option *>(I->getKey().data(), I->second));
2033   }
2034 
2035   // Sort the options list alphabetically.
2036   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2037 }
2038 
2039 static void
sortSubCommands(const SmallPtrSetImpl<SubCommand * > & SubMap,SmallVectorImpl<std::pair<const char *,SubCommand * >> & Subs)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));
2046   }
2047   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2048 }
2049 
2050 namespace {
2051 
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.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)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);
2063   }
2064 
printSubCommands(StrSubCommandPairVector & Subs,size_t MaxSubLen)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();
2071       }
2072       outs() << "\n";
2073     }
2074   }
2075 
2076 public:
HelpPrinter(bool showHidden)2077   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
~HelpPrinter()2078   virtual ~HelpPrinter() {}
2079 
2080   // Invoke the printer.
operator =(bool Value)2081   void operator=(bool Value) {
2082     if (!Value)
2083       return;
2084     printHelp();
2085 
2086     // Halt the program since help information was printed
2087     exit(0);
2088   }
2089 
printHelp()2090   void printHelp() {
2091     SubCommand *Sub = GlobalParser->getActiveSubCommand();
2092     auto &OptionsMap = Sub->OptionsMap;
2093     auto &PositionalOpts = Sub->PositionalOpts;
2094     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2095 
2096     StrOptionPairVector Opts;
2097     sortOpts(OptionsMap, Opts, ShowHidden);
2098 
2099     StrSubCommandPairVector Subs;
2100     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2101 
2102     if (!GlobalParser->ProgramOverview.empty())
2103       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2104 
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";
2114       }
2115       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2116              << " [options]";
2117     }
2118 
2119     for (auto Opt : PositionalOpts) {
2120       if (Opt->hasArgStr())
2121         outs() << " --" << Opt->ArgStr;
2122       outs() << " " << Opt->HelpStr;
2123     }
2124 
2125     // Print the consume after option info if it exists...
2126     if (ConsumeAfterOpt)
2127       outs() << " " << ConsumeAfterOpt->HelpStr;
2128 
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));
2134 
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";
2142     }
2143 
2144     outs() << "\n\n";
2145 
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());
2150 
2151     outs() << "OPTIONS:\n";
2152     printOptions(Opts, MaxArgLen);
2153 
2154     // Print any extra help the user has declared.
2155     for (auto I : GlobalParser->MoreHelp)
2156       outs() << I;
2157     GlobalParser->MoreHelp.clear();
2158   }
2159 };
2160 
2161 class CategorizedHelpPrinter : public HelpPrinter {
2162 public:
CategorizedHelpPrinter(bool showHidden)2163   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2164 
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.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)2169   static int OptionCategoryCompare(OptionCategory *const *A,
2170                                    OptionCategory *const *B) {
2171     return (*A)->getName().compare((*B)->getName());
2172   }
2173 
2174   // Make sure we inherit our base class's operator=()
2175   using HelpPrinter::operator=;
2176 
2177 protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)2178   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2179     std::vector<OptionCategory *> SortedCategories;
2180     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2181 
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);
2188     }
2189 
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);
2194 
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 *>();
2201 
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);
2211       }
2212     }
2213 
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;
2224 
2225       // Print category information.
2226       outs() << "\n";
2227       outs() << (*Category)->getName() << ":\n";
2228 
2229       // Check if description is set.
2230       if (!(*Category)->getDescription().empty())
2231         outs() << (*Category)->getDescription() << "\n\n";
2232       else
2233         outs() << "\n";
2234 
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;
2240       }
2241       // Loop over the options in the category and print.
2242       for (const Option *Opt : CategoryOptions)
2243         Opt->printOptionInfo(MaxArgLen);
2244     }
2245   }
2246 };
2247 
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;
2254 
2255 public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)2256   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2257                               CategorizedHelpPrinter &CategorizedPrinter)
2258       : UncategorizedPrinter(UncategorizedPrinter),
2259         CategorizedPrinter(CategorizedPrinter) {}
2260 
2261   // Invoke the printer.
2262   void operator=(bool Value);
2263 };
2264 
2265 } // End anonymous namespace
2266 
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);
2273 
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);
2280 
2281 // Define a category for generic options that all tools should have.
2282 static cl::OptionCategory GenericCategory("Generic Options");
2283 
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));
2292 
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));
2298 
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));
2306 
2307 static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2308                       cl::DefaultOption);
2309 
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));
2314 
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));
2320 
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));
2325 
operator =(bool Value)2326 void HelpPrinterWrapper::operator=(bool Value) {
2327   if (!Value)
2328     return;
2329 
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);
2337 
2338     CategorizedPrinter = true; // Invoke categorized printer
2339   } else
2340     UncategorizedPrinter = true; // Invoke uncategorized printer
2341 }
2342 
2343 // Print the value of each option.
PrintOptionValues()2344 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2345 
printOptionValues()2346 void CommandLineParser::printOptionValues() {
2347   if (!PrintOptions && !PrintAllOptions)
2348     return;
2349 
2350   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2351   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2352 
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());
2357 
2358   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2359     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2360 }
2361 
2362 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2363 
2364 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2365 
2366 namespace {
2367 class VersionPrinter {
2368 public:
print()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';
2398   }
operator =(bool OptionWasSpecified)2399   void operator=(bool OptionWasSpecified) {
2400     if (!OptionWasSpecified)
2401       return;
2402 
2403     if (OverrideVersionPrinter != nullptr) {
2404       OverrideVersionPrinter(outs());
2405       exit(0);
2406     }
2407     print();
2408 
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());
2415     }
2416 
2417     exit(0);
2418   }
2419 };
2420 } // End anonymous namespace
2421 
2422 // Define the --version option that prints out the LLVM version for the tool
2423 static VersionPrinter VersionPrinterInstance;
2424 
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));
2429 
2430 // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)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();
2440 }
2441 
2442 /// Utility function for printing version number.
PrintVersionMessage()2443 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2444 
SetVersionPrinter(VersionPrinterTy func)2445 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2446 
AddExtraVersionPrinter(VersionPrinterTy func)2447 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2448   if (!ExtraVersionPrinters)
2449     ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2450 
2451   ExtraVersionPrinters->push_back(func);
2452 }
2453 
getRegisteredOptions(SubCommand & Sub)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;
2459 }
2460 
2461 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()2462 cl::getRegisteredSubcommands() {
2463   return GlobalParser->getRegisteredSubcommands();
2464 }
2465 
HideUnrelatedOptions(cl::OptionCategory & Category,SubCommand & Sub)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);
2472     }
2473   }
2474 }
2475 
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories,SubCommand & Sub)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);
2482     }
2483   }
2484 }
2485 
ResetCommandLineParser()2486 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
ResetAllOptionOccurrences()2487 void cl::ResetAllOptionOccurrences() {
2488   GlobalParser->ResetAllOptionOccurrences();
2489 }
2490 
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)2491 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2492                                  const char *Overview) {
2493   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2494                                     &llvm::nulls());
2495 }
2496