1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements a command line argument processor that is useful when
11 // creating a tool.  It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
13 //
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringMap.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 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
49 namespace llvm {
50 // If LLVM_ENABLE_ABI_BREAKING_CHECKS is set the flag -mllvm -reverse-iterate
51 // can be used to toggle forward/reverse iteration of unordered containers.
52 // This will help uncover differences in codegen caused due to undefined
53 // iteration order.
54 static cl::opt<bool, true> ReverseIteration("reverse-iterate",
55   cl::location(ReverseIterate<bool>::value));
56 }
57 #endif
58 
59 //===----------------------------------------------------------------------===//
60 // Template instantiations and anchors.
61 //
62 namespace llvm {
63 namespace cl {
64 template class basic_parser<bool>;
65 template class basic_parser<boolOrDefault>;
66 template class basic_parser<int>;
67 template class basic_parser<unsigned>;
68 template class basic_parser<unsigned long long>;
69 template class basic_parser<double>;
70 template class basic_parser<float>;
71 template class basic_parser<std::string>;
72 template class basic_parser<char>;
73 
74 template class opt<unsigned>;
75 template class opt<int>;
76 template class opt<std::string>;
77 template class opt<char>;
78 template class opt<bool>;
79 }
80 } // end namespace llvm::cl
81 
82 // Pin the vtables to this file.
anchor()83 void GenericOptionValue::anchor() {}
anchor()84 void OptionValue<boolOrDefault>::anchor() {}
anchor()85 void OptionValue<std::string>::anchor() {}
anchor()86 void Option::anchor() {}
anchor()87 void basic_parser_impl::anchor() {}
anchor()88 void parser<bool>::anchor() {}
anchor()89 void parser<boolOrDefault>::anchor() {}
anchor()90 void parser<int>::anchor() {}
anchor()91 void parser<unsigned>::anchor() {}
anchor()92 void parser<unsigned long long>::anchor() {}
anchor()93 void parser<double>::anchor() {}
anchor()94 void parser<float>::anchor() {}
anchor()95 void parser<std::string>::anchor() {}
anchor()96 void parser<char>::anchor() {}
97 
98 //===----------------------------------------------------------------------===//
99 
100 namespace {
101 
102 class CommandLineParser {
103 public:
104   // Globals for name and overview of program.  Program name is not a string to
105   // avoid static ctor/dtor issues.
106   std::string ProgramName;
107   StringRef ProgramOverview;
108 
109   // This collects additional help to be printed.
110   std::vector<StringRef> MoreHelp;
111 
112   // This collects the different option categories that have been registered.
113   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
114 
115   // This collects the different subcommands that have been registered.
116   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
117 
CommandLineParser()118   CommandLineParser() : ActiveSubCommand(nullptr) {
119     registerSubCommand(&*TopLevelSubCommand);
120     registerSubCommand(&*AllSubCommands);
121   }
122 
123   void ResetAllOptionOccurrences();
124 
125   bool ParseCommandLineOptions(int argc, const char *const *argv,
126                                StringRef Overview, bool IgnoreErrors);
127 
addLiteralOption(Option & Opt,SubCommand * SC,StringRef Name)128   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
129     if (Opt.hasArgStr())
130       return;
131     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
132       errs() << ProgramName << ": CommandLine Error: Option '" << Name
133              << "' registered more than once!\n";
134       report_fatal_error("inconsistency in registered CommandLine options");
135     }
136 
137     // If we're adding this to all sub-commands, add it to the ones that have
138     // already been registered.
139     if (SC == &*AllSubCommands) {
140       for (const auto &Sub : RegisteredSubCommands) {
141         if (SC == Sub)
142           continue;
143         addLiteralOption(Opt, Sub, Name);
144       }
145     }
146   }
147 
addLiteralOption(Option & Opt,StringRef Name)148   void addLiteralOption(Option &Opt, StringRef Name) {
149     if (Opt.Subs.empty())
150       addLiteralOption(Opt, &*TopLevelSubCommand, Name);
151     else {
152       for (auto SC : Opt.Subs)
153         addLiteralOption(Opt, SC, Name);
154     }
155   }
156 
addOption(Option * O,SubCommand * SC)157   void addOption(Option *O, SubCommand *SC) {
158     bool HadErrors = false;
159     if (O->hasArgStr()) {
160       // Add argument to the argument map!
161       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
162         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
163                << "' registered more than once!\n";
164         HadErrors = true;
165       }
166     }
167 
168     // Remember information about positional options.
169     if (O->getFormattingFlag() == cl::Positional)
170       SC->PositionalOpts.push_back(O);
171     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
172       SC->SinkOpts.push_back(O);
173     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
174       if (SC->ConsumeAfterOpt) {
175         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
176         HadErrors = true;
177       }
178       SC->ConsumeAfterOpt = O;
179     }
180 
181     // Fail hard if there were errors. These are strictly unrecoverable and
182     // indicate serious issues such as conflicting option names or an
183     // incorrectly
184     // linked LLVM distribution.
185     if (HadErrors)
186       report_fatal_error("inconsistency in registered CommandLine options");
187 
188     // If we're adding this to all sub-commands, add it to the ones that have
189     // already been registered.
190     if (SC == &*AllSubCommands) {
191       for (const auto &Sub : RegisteredSubCommands) {
192         if (SC == Sub)
193           continue;
194         addOption(O, Sub);
195       }
196     }
197   }
198 
addOption(Option * O)199   void addOption(Option *O) {
200     if (O->Subs.empty()) {
201       addOption(O, &*TopLevelSubCommand);
202     } else {
203       for (auto SC : O->Subs)
204         addOption(O, SC);
205     }
206   }
207 
removeOption(Option * O,SubCommand * SC)208   void removeOption(Option *O, SubCommand *SC) {
209     SmallVector<StringRef, 16> OptionNames;
210     O->getExtraOptionNames(OptionNames);
211     if (O->hasArgStr())
212       OptionNames.push_back(O->ArgStr);
213 
214     SubCommand &Sub = *SC;
215     for (auto Name : OptionNames)
216       Sub.OptionsMap.erase(Name);
217 
218     if (O->getFormattingFlag() == cl::Positional)
219       for (auto Opt = Sub.PositionalOpts.begin();
220            Opt != Sub.PositionalOpts.end(); ++Opt) {
221         if (*Opt == O) {
222           Sub.PositionalOpts.erase(Opt);
223           break;
224         }
225       }
226     else if (O->getMiscFlags() & cl::Sink)
227       for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
228         if (*Opt == O) {
229           Sub.SinkOpts.erase(Opt);
230           break;
231         }
232       }
233     else if (O == Sub.ConsumeAfterOpt)
234       Sub.ConsumeAfterOpt = nullptr;
235   }
236 
removeOption(Option * O)237   void removeOption(Option *O) {
238     if (O->Subs.empty())
239       removeOption(O, &*TopLevelSubCommand);
240     else {
241       if (O->isInAllSubCommands()) {
242         for (auto SC : RegisteredSubCommands)
243           removeOption(O, SC);
244       } else {
245         for (auto SC : O->Subs)
246           removeOption(O, SC);
247       }
248     }
249   }
250 
hasOptions(const SubCommand & Sub) const251   bool hasOptions(const SubCommand &Sub) const {
252     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
253             nullptr != Sub.ConsumeAfterOpt);
254   }
255 
hasOptions() const256   bool hasOptions() const {
257     for (const auto &S : RegisteredSubCommands) {
258       if (hasOptions(*S))
259         return true;
260     }
261     return false;
262   }
263 
getActiveSubCommand()264   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
265 
updateArgStr(Option * O,StringRef NewName,SubCommand * SC)266   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
267     SubCommand &Sub = *SC;
268     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
269       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
270              << "' registered more than once!\n";
271       report_fatal_error("inconsistency in registered CommandLine options");
272     }
273     Sub.OptionsMap.erase(O->ArgStr);
274   }
275 
updateArgStr(Option * O,StringRef NewName)276   void updateArgStr(Option *O, StringRef NewName) {
277     if (O->Subs.empty())
278       updateArgStr(O, NewName, &*TopLevelSubCommand);
279     else {
280       for (auto SC : O->Subs)
281         updateArgStr(O, NewName, SC);
282     }
283   }
284 
285   void printOptionValues();
286 
registerCategory(OptionCategory * cat)287   void registerCategory(OptionCategory *cat) {
288     assert(count_if(RegisteredOptionCategories,
289                     [cat](const OptionCategory *Category) {
290              return cat->getName() == Category->getName();
291            }) == 0 &&
292            "Duplicate option categories");
293 
294     RegisteredOptionCategories.insert(cat);
295   }
296 
registerSubCommand(SubCommand * sub)297   void registerSubCommand(SubCommand *sub) {
298     assert(count_if(RegisteredSubCommands,
299                     [sub](const SubCommand *Sub) {
300                       return (!sub->getName().empty()) &&
301                              (Sub->getName() == sub->getName());
302                     }) == 0 &&
303            "Duplicate subcommands");
304     RegisteredSubCommands.insert(sub);
305 
306     // For all options that have been registered for all subcommands, add the
307     // option to this subcommand now.
308     if (sub != &*AllSubCommands) {
309       for (auto &E : AllSubCommands->OptionsMap) {
310         Option *O = E.second;
311         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
312             O->hasArgStr())
313           addOption(O, sub);
314         else
315           addLiteralOption(*O, sub, E.first());
316       }
317     }
318   }
319 
unregisterSubCommand(SubCommand * sub)320   void unregisterSubCommand(SubCommand *sub) {
321     RegisteredSubCommands.erase(sub);
322   }
323 
324   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()325   getRegisteredSubcommands() {
326     return make_range(RegisteredSubCommands.begin(),
327                       RegisteredSubCommands.end());
328   }
329 
reset()330   void reset() {
331     ActiveSubCommand = nullptr;
332     ProgramName.clear();
333     ProgramOverview = StringRef();
334 
335     MoreHelp.clear();
336     RegisteredOptionCategories.clear();
337 
338     ResetAllOptionOccurrences();
339     RegisteredSubCommands.clear();
340 
341     TopLevelSubCommand->reset();
342     AllSubCommands->reset();
343     registerSubCommand(&*TopLevelSubCommand);
344     registerSubCommand(&*AllSubCommands);
345   }
346 
347 private:
348   SubCommand *ActiveSubCommand;
349 
350   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
351   SubCommand *LookupSubCommand(StringRef Name);
352 };
353 
354 } // namespace
355 
356 static ManagedStatic<CommandLineParser> GlobalParser;
357 
AddLiteralOption(Option & O,StringRef Name)358 void cl::AddLiteralOption(Option &O, StringRef Name) {
359   GlobalParser->addLiteralOption(O, Name);
360 }
361 
extrahelp(StringRef Help)362 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
363   GlobalParser->MoreHelp.push_back(Help);
364 }
365 
addArgument()366 void Option::addArgument() {
367   GlobalParser->addOption(this);
368   FullyInitialized = true;
369 }
370 
removeArgument()371 void Option::removeArgument() { GlobalParser->removeOption(this); }
372 
setArgStr(StringRef S)373 void Option::setArgStr(StringRef S) {
374   if (FullyInitialized)
375     GlobalParser->updateArgStr(this, S);
376   ArgStr = S;
377 }
378 
379 // Initialise the general option category.
380 OptionCategory llvm::cl::GeneralCategory("General options");
381 
registerCategory()382 void OptionCategory::registerCategory() {
383   GlobalParser->registerCategory(this);
384 }
385 
386 // A special subcommand representing no subcommand. It is particularly important
387 // that this ManagedStatic uses constant initailization and not dynamic
388 // initialization because it is referenced from cl::opt constructors, which run
389 // dynamically in an arbitrary order.
390 LLVM_REQUIRE_CONSTANT_INITIALIZATION ManagedStatic<SubCommand>
391 llvm::cl::TopLevelSubCommand;
392 
393 // A special subcommand that can be used to put an option into all subcommands.
394 LLVM_REQUIRE_CONSTANT_INITIALIZATION ManagedStatic<SubCommand>
395 llvm::cl::AllSubCommands;
396 
registerSubCommand()397 void SubCommand::registerSubCommand() {
398   GlobalParser->registerSubCommand(this);
399 }
400 
unregisterSubCommand()401 void SubCommand::unregisterSubCommand() {
402   GlobalParser->unregisterSubCommand(this);
403 }
404 
reset()405 void SubCommand::reset() {
406   PositionalOpts.clear();
407   SinkOpts.clear();
408   OptionsMap.clear();
409 
410   ConsumeAfterOpt = nullptr;
411 }
412 
operator bool() const413 SubCommand::operator bool() const {
414   return (GlobalParser->getActiveSubCommand() == this);
415 }
416 
417 //===----------------------------------------------------------------------===//
418 // Basic, shared command line option processing machinery.
419 //
420 
421 /// LookupOption - Lookup the option specified by the specified option on the
422 /// command line.  If there is a value specified (after an equal sign) return
423 /// that as well.  This assumes that leading dashes have already been stripped.
LookupOption(SubCommand & Sub,StringRef & Arg,StringRef & Value)424 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
425                                         StringRef &Value) {
426   // Reject all dashes.
427   if (Arg.empty())
428     return nullptr;
429   assert(&Sub != &*AllSubCommands);
430 
431   size_t EqualPos = Arg.find('=');
432 
433   // If we have an equals sign, remember the value.
434   if (EqualPos == StringRef::npos) {
435     // Look up the option.
436     auto I = Sub.OptionsMap.find(Arg);
437     if (I == Sub.OptionsMap.end())
438       return nullptr;
439 
440     return I != Sub.OptionsMap.end() ? I->second : nullptr;
441   }
442 
443   // If the argument before the = is a valid option name, we match.  If not,
444   // return Arg unmolested.
445   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
446   if (I == Sub.OptionsMap.end())
447     return nullptr;
448 
449   Value = Arg.substr(EqualPos + 1);
450   Arg = Arg.substr(0, EqualPos);
451   return I->second;
452 }
453 
LookupSubCommand(StringRef Name)454 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
455   if (Name.empty())
456     return &*TopLevelSubCommand;
457   for (auto S : RegisteredSubCommands) {
458     if (S == &*AllSubCommands)
459       continue;
460     if (S->getName().empty())
461       continue;
462 
463     if (StringRef(S->getName()) == StringRef(Name))
464       return S;
465   }
466   return &*TopLevelSubCommand;
467 }
468 
469 /// LookupNearestOption - Lookup the closest match to the option specified by
470 /// the specified option on the command line.  If there is a value specified
471 /// (after an equal sign) return that as well.  This assumes that leading dashes
472 /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)473 static Option *LookupNearestOption(StringRef Arg,
474                                    const StringMap<Option *> &OptionsMap,
475                                    std::string &NearestString) {
476   // Reject all dashes.
477   if (Arg.empty())
478     return nullptr;
479 
480   // Split on any equal sign.
481   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
482   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
483   StringRef &RHS = SplitArg.second;
484 
485   // Find the closest match.
486   Option *Best = nullptr;
487   unsigned BestDistance = 0;
488   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
489                                            ie = OptionsMap.end();
490        it != ie; ++it) {
491     Option *O = it->second;
492     SmallVector<StringRef, 16> OptionNames;
493     O->getExtraOptionNames(OptionNames);
494     if (O->hasArgStr())
495       OptionNames.push_back(O->ArgStr);
496 
497     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
498     StringRef Flag = PermitValue ? LHS : Arg;
499     for (auto Name : OptionNames) {
500       unsigned Distance = StringRef(Name).edit_distance(
501           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
502       if (!Best || Distance < BestDistance) {
503         Best = O;
504         BestDistance = Distance;
505         if (RHS.empty() || !PermitValue)
506           NearestString = Name;
507         else
508           NearestString = (Twine(Name) + "=" + RHS).str();
509       }
510     }
511   }
512 
513   return Best;
514 }
515 
516 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
517 /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)518 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
519                                           StringRef ArgName, StringRef Value,
520                                           bool MultiArg = false) {
521   // Check to see if this option accepts a comma separated list of values.  If
522   // it does, we have to split up the value into multiple values.
523   if (Handler->getMiscFlags() & CommaSeparated) {
524     StringRef Val(Value);
525     StringRef::size_type Pos = Val.find(',');
526 
527     while (Pos != StringRef::npos) {
528       // Process the portion before the comma.
529       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
530         return true;
531       // Erase the portion before the comma, AND the comma.
532       Val = Val.substr(Pos + 1);
533       // Check for another comma.
534       Pos = Val.find(',');
535     }
536 
537     Value = Val;
538   }
539 
540   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
541 }
542 
543 /// ProvideOption - For Value, this differentiates between an empty value ("")
544 /// and a null value (StringRef()).  The later is accepted for arguments that
545 /// 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)546 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
547                                  StringRef Value, int argc,
548                                  const char *const *argv, int &i) {
549   // Is this a multi-argument option?
550   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
551 
552   // Enforce value requirements
553   switch (Handler->getValueExpectedFlag()) {
554   case ValueRequired:
555     if (!Value.data()) { // No value specified?
556       if (i + 1 >= argc)
557         return Handler->error("requires a value!");
558       // Steal the next argument, like for '-o filename'
559       assert(argv && "null check");
560       Value = StringRef(argv[++i]);
561     }
562     break;
563   case ValueDisallowed:
564     if (NumAdditionalVals > 0)
565       return Handler->error("multi-valued option specified"
566                             " with ValueDisallowed modifier!");
567 
568     if (Value.data())
569       return Handler->error("does not allow a value! '" + Twine(Value) +
570                             "' specified.");
571     break;
572   case ValueOptional:
573     break;
574   }
575 
576   // If this isn't a multi-arg option, just run the handler.
577   if (NumAdditionalVals == 0)
578     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
579 
580   // If it is, run the handle several times.
581   bool MultiArg = false;
582 
583   if (Value.data()) {
584     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
585       return true;
586     --NumAdditionalVals;
587     MultiArg = true;
588   }
589 
590   while (NumAdditionalVals > 0) {
591     if (i + 1 >= argc)
592       return Handler->error("not enough values!");
593     assert(argv && "null check");
594     Value = StringRef(argv[++i]);
595 
596     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
597       return true;
598     MultiArg = true;
599     --NumAdditionalVals;
600   }
601   return false;
602 }
603 
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)604 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
605   int Dummy = i;
606   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
607 }
608 
609 // Option predicates...
isGrouping(const Option * O)610 static inline bool isGrouping(const Option *O) {
611   return O->getFormattingFlag() == cl::Grouping;
612 }
isPrefixedOrGrouping(const Option * O)613 static inline bool isPrefixedOrGrouping(const Option *O) {
614   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
615 }
616 
617 // getOptionPred - Check to see if there are any options that satisfy the
618 // specified predicate with names that are the prefixes in Name.  This is
619 // checked by progressively stripping characters off of the name, checking to
620 // see if there options that satisfy the predicate.  If we find one, return it,
621 // otherwise return null.
622 //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)623 static Option *getOptionPred(StringRef Name, size_t &Length,
624                              bool (*Pred)(const Option *),
625                              const StringMap<Option *> &OptionsMap) {
626 
627   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
628 
629   // Loop while we haven't found an option and Name still has at least two
630   // characters in it (so that the next iteration will not be the empty
631   // string.
632   while (OMI == OptionsMap.end() && Name.size() > 1) {
633     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
634     OMI = OptionsMap.find(Name);
635   }
636 
637   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
638     Length = Name.size();
639     return OMI->second; // Found one!
640   }
641   return nullptr; // No option found!
642 }
643 
644 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
645 /// with at least one '-') does not fully match an available option.  Check to
646 /// see if this is a prefix or grouped option.  If so, split arg into output an
647 /// Arg/Value pair and return the Option to parse it with.
648 static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)649 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
650                               bool &ErrorParsing,
651                               const StringMap<Option *> &OptionsMap) {
652   if (Arg.size() == 1)
653     return nullptr;
654 
655   // Do the lookup!
656   size_t Length = 0;
657   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
658   if (!PGOpt)
659     return nullptr;
660 
661   // If the option is a prefixed option, then the value is simply the
662   // rest of the name...  so fall through to later processing, by
663   // setting up the argument name flags and value fields.
664   if (PGOpt->getFormattingFlag() == cl::Prefix) {
665     Value = Arg.substr(Length);
666     Arg = Arg.substr(0, Length);
667     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
668     return PGOpt;
669   }
670 
671   // This must be a grouped option... handle them now.  Grouping options can't
672   // have values.
673   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
674 
675   do {
676     // Move current arg name out of Arg into OneArgName.
677     StringRef OneArgName = Arg.substr(0, Length);
678     Arg = Arg.substr(Length);
679 
680     // Because ValueRequired is an invalid flag for grouped arguments,
681     // we don't need to pass argc/argv in.
682     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
683            "Option can not be cl::Grouping AND cl::ValueRequired!");
684     int Dummy = 0;
685     ErrorParsing |=
686         ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
687 
688     // Get the next grouping option.
689     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
690   } while (PGOpt && Length != Arg.size());
691 
692   // Return the last option with Arg cut down to just the last one.
693   return PGOpt;
694 }
695 
RequiresValue(const Option * O)696 static bool RequiresValue(const Option *O) {
697   return O->getNumOccurrencesFlag() == cl::Required ||
698          O->getNumOccurrencesFlag() == cl::OneOrMore;
699 }
700 
EatsUnboundedNumberOfValues(const Option * O)701 static bool EatsUnboundedNumberOfValues(const Option *O) {
702   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
703          O->getNumOccurrencesFlag() == cl::OneOrMore;
704 }
705 
isWhitespace(char C)706 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
707 
isQuote(char C)708 static bool isQuote(char C) { return C == '\"' || C == '\''; }
709 
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)710 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
711                                 SmallVectorImpl<const char *> &NewArgv,
712                                 bool MarkEOLs) {
713   SmallString<128> Token;
714   for (size_t I = 0, E = Src.size(); I != E; ++I) {
715     // Consume runs of whitespace.
716     if (Token.empty()) {
717       while (I != E && isWhitespace(Src[I])) {
718         // Mark the end of lines in response files
719         if (MarkEOLs && Src[I] == '\n')
720           NewArgv.push_back(nullptr);
721         ++I;
722       }
723       if (I == E)
724         break;
725     }
726 
727     // Backslash escapes the next character.
728     if (I + 1 < E && Src[I] == '\\') {
729       ++I; // Skip the escape.
730       Token.push_back(Src[I]);
731       continue;
732     }
733 
734     // Consume a quoted string.
735     if (isQuote(Src[I])) {
736       char Quote = Src[I++];
737       while (I != E && Src[I] != Quote) {
738         // Backslash escapes the next character.
739         if (Src[I] == '\\' && I + 1 != E)
740           ++I;
741         Token.push_back(Src[I]);
742         ++I;
743       }
744       if (I == E)
745         break;
746       continue;
747     }
748 
749     // End the token if this is whitespace.
750     if (isWhitespace(Src[I])) {
751       if (!Token.empty())
752         NewArgv.push_back(Saver.save(StringRef(Token)).data());
753       Token.clear();
754       continue;
755     }
756 
757     // This is a normal character.  Append it.
758     Token.push_back(Src[I]);
759   }
760 
761   // Append the last token after hitting EOF with no whitespace.
762   if (!Token.empty())
763     NewArgv.push_back(Saver.save(StringRef(Token)).data());
764   // Mark the end of response files
765   if (MarkEOLs)
766     NewArgv.push_back(nullptr);
767 }
768 
769 /// Backslashes are interpreted in a rather complicated way in the Windows-style
770 /// command line, because backslashes are used both to separate path and to
771 /// escape double quote. This method consumes runs of backslashes as well as the
772 /// following double quote if it's escaped.
773 ///
774 ///  * If an even number of backslashes is followed by a double quote, one
775 ///    backslash is output for every pair of backslashes, and the last double
776 ///    quote remains unconsumed. The double quote will later be interpreted as
777 ///    the start or end of a quoted string in the main loop outside of this
778 ///    function.
779 ///
780 ///  * If an odd number of backslashes is followed by a double quote, one
781 ///    backslash is output for every pair of backslashes, and a double quote is
782 ///    output for the last pair of backslash-double quote. The double quote is
783 ///    consumed in this case.
784 ///
785 ///  * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)786 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
787   size_t E = Src.size();
788   int BackslashCount = 0;
789   // Skip the backslashes.
790   do {
791     ++I;
792     ++BackslashCount;
793   } while (I != E && Src[I] == '\\');
794 
795   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
796   if (FollowedByDoubleQuote) {
797     Token.append(BackslashCount / 2, '\\');
798     if (BackslashCount % 2 == 0)
799       return I - 1;
800     Token.push_back('"');
801     return I;
802   }
803   Token.append(BackslashCount, '\\');
804   return I - 1;
805 }
806 
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)807 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
808                                     SmallVectorImpl<const char *> &NewArgv,
809                                     bool MarkEOLs) {
810   SmallString<128> Token;
811 
812   // This is a small state machine to consume characters until it reaches the
813   // end of the source string.
814   enum { INIT, UNQUOTED, QUOTED } State = INIT;
815   for (size_t I = 0, E = Src.size(); I != E; ++I) {
816     // INIT state indicates that the current input index is at the start of
817     // the string or between tokens.
818     if (State == INIT) {
819       if (isWhitespace(Src[I])) {
820         // Mark the end of lines in response files
821         if (MarkEOLs && Src[I] == '\n')
822           NewArgv.push_back(nullptr);
823         continue;
824       }
825       if (Src[I] == '"') {
826         State = QUOTED;
827         continue;
828       }
829       if (Src[I] == '\\') {
830         I = parseBackslash(Src, I, Token);
831         State = UNQUOTED;
832         continue;
833       }
834       Token.push_back(Src[I]);
835       State = UNQUOTED;
836       continue;
837     }
838 
839     // UNQUOTED state means that it's reading a token not quoted by double
840     // quotes.
841     if (State == UNQUOTED) {
842       // Whitespace means the end of the token.
843       if (isWhitespace(Src[I])) {
844         NewArgv.push_back(Saver.save(StringRef(Token)).data());
845         Token.clear();
846         State = INIT;
847         // Mark the end of lines in response files
848         if (MarkEOLs && Src[I] == '\n')
849           NewArgv.push_back(nullptr);
850         continue;
851       }
852       if (Src[I] == '"') {
853         State = QUOTED;
854         continue;
855       }
856       if (Src[I] == '\\') {
857         I = parseBackslash(Src, I, Token);
858         continue;
859       }
860       Token.push_back(Src[I]);
861       continue;
862     }
863 
864     // QUOTED state means that it's reading a token quoted by double quotes.
865     if (State == QUOTED) {
866       if (Src[I] == '"') {
867         State = UNQUOTED;
868         continue;
869       }
870       if (Src[I] == '\\') {
871         I = parseBackslash(Src, I, Token);
872         continue;
873       }
874       Token.push_back(Src[I]);
875     }
876   }
877   // Append the last token after hitting EOF with no whitespace.
878   if (!Token.empty())
879     NewArgv.push_back(Saver.save(StringRef(Token)).data());
880   // Mark the end of response files
881   if (MarkEOLs)
882     NewArgv.push_back(nullptr);
883 }
884 
885 // It is called byte order marker but the UTF-8 BOM is actually not affected
886 // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)887 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
888   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
889 }
890 
ExpandResponseFile(StringRef FName,StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs,bool RelativeNames)891 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
892                                TokenizerCallback Tokenizer,
893                                SmallVectorImpl<const char *> &NewArgv,
894                                bool MarkEOLs, bool RelativeNames) {
895   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
896       MemoryBuffer::getFile(FName);
897   if (!MemBufOrErr)
898     return false;
899   MemoryBuffer &MemBuf = *MemBufOrErr.get();
900   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
901 
902   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
903   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
904   std::string UTF8Buf;
905   if (hasUTF16ByteOrderMark(BufRef)) {
906     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
907       return false;
908     Str = StringRef(UTF8Buf);
909   }
910   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
911   // these bytes before parsing.
912   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
913   else if (hasUTF8ByteOrderMark(BufRef))
914     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
915 
916   // Tokenize the contents into NewArgv.
917   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
918 
919   // If names of nested response files should be resolved relative to including
920   // file, replace the included response file names with their full paths
921   // obtained by required resolution.
922   if (RelativeNames)
923     for (unsigned I = 0; I < NewArgv.size(); ++I)
924       if (NewArgv[I]) {
925         StringRef Arg = NewArgv[I];
926         if (Arg.front() == '@') {
927           StringRef FileName = Arg.drop_front();
928           if (llvm::sys::path::is_relative(FileName)) {
929             SmallString<128> ResponseFile;
930             ResponseFile.append(1, '@');
931             if (llvm::sys::path::is_relative(FName)) {
932               SmallString<128> curr_dir;
933               llvm::sys::fs::current_path(curr_dir);
934               ResponseFile.append(curr_dir.str());
935             }
936             llvm::sys::path::append(
937                 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
938             NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
939           }
940         }
941       }
942 
943   return true;
944 }
945 
946 /// \brief Expand response files on a command line recursively using the given
947 /// StringSaver and tokenization strategy.
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv,bool MarkEOLs,bool RelativeNames)948 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
949                              SmallVectorImpl<const char *> &Argv,
950                              bool MarkEOLs, bool RelativeNames) {
951   unsigned RspFiles = 0;
952   bool AllExpanded = true;
953 
954   // Don't cache Argv.size() because it can change.
955   for (unsigned I = 0; I != Argv.size();) {
956     const char *Arg = Argv[I];
957     // Check if it is an EOL marker
958     if (Arg == nullptr) {
959       ++I;
960       continue;
961     }
962     if (Arg[0] != '@') {
963       ++I;
964       continue;
965     }
966 
967     // If we have too many response files, leave some unexpanded.  This avoids
968     // crashing on self-referential response files.
969     if (RspFiles++ > 20)
970       return false;
971 
972     // Replace this response file argument with the tokenization of its
973     // contents.  Nested response files are expanded in subsequent iterations.
974     SmallVector<const char *, 0> ExpandedArgv;
975     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
976                             MarkEOLs, RelativeNames)) {
977       // We couldn't read this file, so we leave it in the argument stream and
978       // move on.
979       AllExpanded = false;
980       ++I;
981       continue;
982     }
983     Argv.erase(Argv.begin() + I);
984     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
985   }
986   return AllExpanded;
987 }
988 
989 /// ParseEnvironmentOptions - An alternative entry point to the
990 /// CommandLine library, which allows you to read the program's name
991 /// from the caller (as PROGNAME) and its command-line arguments from
992 /// an environment variable (whose name is given in ENVVAR).
993 ///
ParseEnvironmentOptions(const char * progName,const char * envVar,const char * Overview)994 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
995                                  const char *Overview) {
996   // Check args.
997   assert(progName && "Program name not specified");
998   assert(envVar && "Environment variable name missing");
999 
1000   // Get the environment variable they want us to parse options out of.
1001   llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1002   if (!envValue)
1003     return;
1004 
1005   // Get program's "name", which we wouldn't know without the caller
1006   // telling us.
1007   SmallVector<const char *, 20> newArgv;
1008   BumpPtrAllocator A;
1009   StringSaver Saver(A);
1010   newArgv.push_back(Saver.save(progName).data());
1011 
1012   // Parse the value of the environment variable into a "command line"
1013   // and hand it off to ParseCommandLineOptions().
1014   TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1015   int newArgc = static_cast<int>(newArgv.size());
1016   ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1017 }
1018 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,bool IgnoreErrors)1019 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1020                                  StringRef Overview, bool IgnoreErrors) {
1021   return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1022                                                IgnoreErrors);
1023 }
1024 
ResetAllOptionOccurrences()1025 void CommandLineParser::ResetAllOptionOccurrences() {
1026   // So that we can parse different command lines multiple times in succession
1027   // we reset all option values to look like they have never been seen before.
1028   for (auto SC : RegisteredSubCommands) {
1029     for (auto &O : SC->OptionsMap)
1030       O.second->reset();
1031   }
1032 }
1033 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,bool IgnoreErrors)1034 bool CommandLineParser::ParseCommandLineOptions(int argc,
1035                                                 const char *const *argv,
1036                                                 StringRef Overview,
1037                                                 bool IgnoreErrors) {
1038   assert(hasOptions() && "No options specified!");
1039 
1040   // Expand response files.
1041   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1042   BumpPtrAllocator A;
1043   StringSaver Saver(A);
1044   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
1045   argv = &newArgv[0];
1046   argc = static_cast<int>(newArgv.size());
1047 
1048   // Copy the program name into ProgName, making sure not to overflow it.
1049   ProgramName = sys::path::filename(StringRef(argv[0]));
1050 
1051   ProgramOverview = Overview;
1052   bool ErrorParsing = false;
1053 
1054   // Check out the positional arguments to collect information about them.
1055   unsigned NumPositionalRequired = 0;
1056 
1057   // Determine whether or not there are an unlimited number of positionals
1058   bool HasUnlimitedPositionals = false;
1059 
1060   int FirstArg = 1;
1061   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1062   if (argc >= 2 && argv[FirstArg][0] != '-') {
1063     // If the first argument specifies a valid subcommand, start processing
1064     // options from the second argument.
1065     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1066     if (ChosenSubCommand != &*TopLevelSubCommand)
1067       FirstArg = 2;
1068   }
1069   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1070 
1071   assert(ChosenSubCommand);
1072   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1073   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1074   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1075   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1076 
1077   if (ConsumeAfterOpt) {
1078     assert(PositionalOpts.size() > 0 &&
1079            "Cannot specify cl::ConsumeAfter without a positional argument!");
1080   }
1081   if (!PositionalOpts.empty()) {
1082 
1083     // Calculate how many positional values are _required_.
1084     bool UnboundedFound = false;
1085     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1086       Option *Opt = PositionalOpts[i];
1087       if (RequiresValue(Opt))
1088         ++NumPositionalRequired;
1089       else if (ConsumeAfterOpt) {
1090         // ConsumeAfter cannot be combined with "optional" positional options
1091         // unless there is only one positional argument...
1092         if (PositionalOpts.size() > 1) {
1093           if (!IgnoreErrors)
1094             Opt->error("error - this positional option will never be matched, "
1095                        "because it does not Require a value, and a "
1096                        "cl::ConsumeAfter option is active!");
1097           ErrorParsing = true;
1098         }
1099       } else if (UnboundedFound && !Opt->hasArgStr()) {
1100         // This option does not "require" a value...  Make sure this option is
1101         // not specified after an option that eats all extra arguments, or this
1102         // one will never get any!
1103         //
1104         if (!IgnoreErrors) {
1105           Opt->error("error - option can never match, because "
1106                      "another positional argument will match an "
1107                      "unbounded number of values, and this option"
1108                      " does not require a value!");
1109           errs() << ProgramName << ": CommandLine Error: Option '"
1110                  << Opt->ArgStr << "' is all messed up!\n";
1111           errs() << PositionalOpts.size();
1112         }
1113         ErrorParsing = true;
1114       }
1115       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1116     }
1117     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1118   }
1119 
1120   // PositionalVals - A vector of "positional" arguments we accumulate into
1121   // the process at the end.
1122   //
1123   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1124 
1125   // If the program has named positional arguments, and the name has been run
1126   // across, keep track of which positional argument was named.  Otherwise put
1127   // the positional args into the PositionalVals list...
1128   Option *ActivePositionalArg = nullptr;
1129 
1130   // Loop over all of the arguments... processing them.
1131   bool DashDashFound = false; // Have we read '--'?
1132   for (int i = FirstArg; i < argc; ++i) {
1133     Option *Handler = nullptr;
1134     Option *NearestHandler = nullptr;
1135     std::string NearestHandlerString;
1136     StringRef Value;
1137     StringRef ArgName = "";
1138 
1139     // Check to see if this is a positional argument.  This argument is
1140     // considered to be positional if it doesn't start with '-', if it is "-"
1141     // itself, or if we have seen "--" already.
1142     //
1143     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1144       // Positional argument!
1145       if (ActivePositionalArg) {
1146         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1147         continue; // We are done!
1148       }
1149 
1150       if (!PositionalOpts.empty()) {
1151         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1152 
1153         // All of the positional arguments have been fulfulled, give the rest to
1154         // the consume after option... if it's specified...
1155         //
1156         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1157           for (++i; i < argc; ++i)
1158             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1159           break; // Handle outside of the argument processing loop...
1160         }
1161 
1162         // Delay processing positional arguments until the end...
1163         continue;
1164       }
1165     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1166                !DashDashFound) {
1167       DashDashFound = true; // This is the mythical "--"?
1168       continue;             // Don't try to process it as an argument itself.
1169     } else if (ActivePositionalArg &&
1170                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1171       // If there is a positional argument eating options, check to see if this
1172       // option is another positional argument.  If so, treat it as an argument,
1173       // otherwise feed it to the eating positional.
1174       ArgName = StringRef(argv[i] + 1);
1175       // Eat leading dashes.
1176       while (!ArgName.empty() && ArgName[0] == '-')
1177         ArgName = ArgName.substr(1);
1178 
1179       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1180       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1181         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1182         continue; // We are done!
1183       }
1184 
1185     } else { // We start with a '-', must be an argument.
1186       ArgName = StringRef(argv[i] + 1);
1187       // Eat leading dashes.
1188       while (!ArgName.empty() && ArgName[0] == '-')
1189         ArgName = ArgName.substr(1);
1190 
1191       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1192 
1193       // Check to see if this "option" is really a prefixed or grouped argument.
1194       if (!Handler)
1195         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1196                                                 OptionsMap);
1197 
1198       // Otherwise, look for the closest available option to report to the user
1199       // in the upcoming error.
1200       if (!Handler && SinkOpts.empty())
1201         NearestHandler =
1202             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1203     }
1204 
1205     if (!Handler) {
1206       if (SinkOpts.empty()) {
1207         if (!IgnoreErrors) {
1208           errs() << ProgramName << ": Unknown command line argument '"
1209                  << argv[i] << "'.  Try: '" << argv[0] << " -help'\n";
1210 
1211           if (NearestHandler) {
1212             // If we know a near match, report it as well.
1213             errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
1214                    << "'?\n";
1215           }
1216         }
1217 
1218         ErrorParsing = true;
1219       } else {
1220         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1221                                                  E = SinkOpts.end();
1222              I != E; ++I)
1223           (*I)->addOccurrence(i, "", StringRef(argv[i]));
1224       }
1225       continue;
1226     }
1227 
1228     // If this is a named positional argument, just remember that it is the
1229     // active one...
1230     if (Handler->getFormattingFlag() == cl::Positional)
1231       ActivePositionalArg = Handler;
1232     else
1233       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1234   }
1235 
1236   // Check and handle positional arguments now...
1237   if (NumPositionalRequired > PositionalVals.size()) {
1238     if (!IgnoreErrors) {
1239       errs() << ProgramName
1240              << ": Not enough positional command line arguments specified!\n"
1241              << "Must specify at least " << NumPositionalRequired
1242              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1243              << ": See: " << argv[0] << " - help\n";
1244     }
1245 
1246     ErrorParsing = true;
1247   } else if (!HasUnlimitedPositionals &&
1248              PositionalVals.size() > PositionalOpts.size()) {
1249     if (!IgnoreErrors) {
1250       errs() << ProgramName << ": Too many positional arguments specified!\n"
1251              << "Can specify at most " << PositionalOpts.size()
1252              << " positional arguments: See: " << argv[0] << " -help\n";
1253     }
1254     ErrorParsing = true;
1255 
1256   } else if (!ConsumeAfterOpt) {
1257     // Positional args have already been handled if ConsumeAfter is specified.
1258     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1259     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1260       if (RequiresValue(PositionalOpts[i])) {
1261         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1262                                 PositionalVals[ValNo].second);
1263         ValNo++;
1264         --NumPositionalRequired; // We fulfilled our duty...
1265       }
1266 
1267       // If we _can_ give this option more arguments, do so now, as long as we
1268       // do not give it values that others need.  'Done' controls whether the
1269       // option even _WANTS_ any more.
1270       //
1271       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1272       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1273         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1274         case cl::Optional:
1275           Done = true; // Optional arguments want _at most_ one value
1276           LLVM_FALLTHROUGH;
1277         case cl::ZeroOrMore: // Zero or more will take all they can get...
1278         case cl::OneOrMore:  // One or more will take all they can get...
1279           ProvidePositionalOption(PositionalOpts[i],
1280                                   PositionalVals[ValNo].first,
1281                                   PositionalVals[ValNo].second);
1282           ValNo++;
1283           break;
1284         default:
1285           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1286                            "positional argument processing!");
1287         }
1288       }
1289     }
1290   } else {
1291     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1292     unsigned ValNo = 0;
1293     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1294       if (RequiresValue(PositionalOpts[j])) {
1295         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1296                                                 PositionalVals[ValNo].first,
1297                                                 PositionalVals[ValNo].second);
1298         ValNo++;
1299       }
1300 
1301     // Handle the case where there is just one positional option, and it's
1302     // optional.  In this case, we want to give JUST THE FIRST option to the
1303     // positional option and keep the rest for the consume after.  The above
1304     // loop would have assigned no values to positional options in this case.
1305     //
1306     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1307       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1308                                               PositionalVals[ValNo].first,
1309                                               PositionalVals[ValNo].second);
1310       ValNo++;
1311     }
1312 
1313     // Handle over all of the rest of the arguments to the
1314     // cl::ConsumeAfter command line option...
1315     for (; ValNo != PositionalVals.size(); ++ValNo)
1316       ErrorParsing |=
1317           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1318                                   PositionalVals[ValNo].second);
1319   }
1320 
1321   // Loop over args and make sure all required args are specified!
1322   for (const auto &Opt : OptionsMap) {
1323     switch (Opt.second->getNumOccurrencesFlag()) {
1324     case Required:
1325     case OneOrMore:
1326       if (Opt.second->getNumOccurrences() == 0) {
1327         Opt.second->error("must be specified at least once!");
1328         ErrorParsing = true;
1329       }
1330       LLVM_FALLTHROUGH;
1331     default:
1332       break;
1333     }
1334   }
1335 
1336   // Now that we know if -debug is specified, we can use it.
1337   // Note that if ReadResponseFiles == true, this must be done before the
1338   // memory allocated for the expanded command line is free()d below.
1339   DEBUG(dbgs() << "Args: ";
1340         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1341         dbgs() << '\n';);
1342 
1343   // Free all of the memory allocated to the map.  Command line options may only
1344   // be processed once!
1345   MoreHelp.clear();
1346 
1347   // If we had an error processing our arguments, don't let the program execute
1348   if (ErrorParsing) {
1349     if (!IgnoreErrors)
1350       exit(1);
1351     return false;
1352   }
1353   return true;
1354 }
1355 
1356 //===----------------------------------------------------------------------===//
1357 // Option Base class implementation
1358 //
1359 
error(const Twine & Message,StringRef ArgName)1360 bool Option::error(const Twine &Message, StringRef ArgName) {
1361   if (!ArgName.data())
1362     ArgName = ArgStr;
1363   if (ArgName.empty())
1364     errs() << HelpStr; // Be nice for positional arguments
1365   else
1366     errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1367 
1368   errs() << " option: " << Message << "\n";
1369   return true;
1370 }
1371 
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)1372 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1373                            bool MultiArg) {
1374   if (!MultiArg)
1375     NumOccurrences++; // Increment the number of times we have been seen
1376 
1377   switch (getNumOccurrencesFlag()) {
1378   case Optional:
1379     if (NumOccurrences > 1)
1380       return error("may only occur zero or one times!", ArgName);
1381     break;
1382   case Required:
1383     if (NumOccurrences > 1)
1384       return error("must occur exactly one time!", ArgName);
1385     LLVM_FALLTHROUGH;
1386   case OneOrMore:
1387   case ZeroOrMore:
1388   case ConsumeAfter:
1389     break;
1390   }
1391 
1392   return handleOccurrence(pos, ArgName, Value);
1393 }
1394 
1395 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1396 // has been specified yet.
1397 //
getValueStr(const Option & O,StringRef DefaultMsg)1398 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1399   if (O.ValueStr.empty())
1400     return DefaultMsg;
1401   return O.ValueStr;
1402 }
1403 
1404 //===----------------------------------------------------------------------===//
1405 // cl::alias class implementation
1406 //
1407 
1408 // Return the width of the option tag for printing...
getOptionWidth() const1409 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1410 
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)1411 static void printHelpStr(StringRef HelpStr, size_t Indent,
1412                          size_t FirstLineIndentedBy) {
1413   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1414   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1415   while (!Split.second.empty()) {
1416     Split = Split.second.split('\n');
1417     outs().indent(Indent) << Split.first << "\n";
1418   }
1419 }
1420 
1421 // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1422 void alias::printOptionInfo(size_t GlobalWidth) const {
1423   outs() << "  -" << ArgStr;
1424   printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1425 }
1426 
1427 //===----------------------------------------------------------------------===//
1428 // Parser Implementation code...
1429 //
1430 
1431 // basic_parser implementation
1432 //
1433 
1434 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1435 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1436   size_t Len = O.ArgStr.size();
1437   auto ValName = getValueName();
1438   if (!ValName.empty())
1439     Len += getValueStr(O, ValName).size() + 3;
1440 
1441   return Len + 6;
1442 }
1443 
1444 // printOptionInfo - Print out information about this option.  The
1445 // to-be-maintained width is specified.
1446 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1447 void basic_parser_impl::printOptionInfo(const Option &O,
1448                                         size_t GlobalWidth) const {
1449   outs() << "  -" << O.ArgStr;
1450 
1451   auto ValName = getValueName();
1452   if (!ValName.empty())
1453     outs() << "=<" << getValueStr(O, ValName) << '>';
1454 
1455   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1456 }
1457 
printOptionName(const Option & O,size_t GlobalWidth) const1458 void basic_parser_impl::printOptionName(const Option &O,
1459                                         size_t GlobalWidth) const {
1460   outs() << "  -" << O.ArgStr;
1461   outs().indent(GlobalWidth - O.ArgStr.size());
1462 }
1463 
1464 // parser<bool> implementation
1465 //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)1466 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1467                          bool &Value) {
1468   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1469       Arg == "1") {
1470     Value = true;
1471     return false;
1472   }
1473 
1474   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1475     Value = false;
1476     return false;
1477   }
1478   return O.error("'" + Arg +
1479                  "' is invalid value for boolean argument! Try 0 or 1");
1480 }
1481 
1482 // parser<boolOrDefault> implementation
1483 //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)1484 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1485                                   boolOrDefault &Value) {
1486   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1487       Arg == "1") {
1488     Value = BOU_TRUE;
1489     return false;
1490   }
1491   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1492     Value = BOU_FALSE;
1493     return false;
1494   }
1495 
1496   return O.error("'" + Arg +
1497                  "' is invalid value for boolean argument! Try 0 or 1");
1498 }
1499 
1500 // parser<int> implementation
1501 //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)1502 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1503                         int &Value) {
1504   if (Arg.getAsInteger(0, Value))
1505     return O.error("'" + Arg + "' value invalid for integer argument!");
1506   return false;
1507 }
1508 
1509 // parser<unsigned> implementation
1510 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)1511 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1512                              unsigned &Value) {
1513 
1514   if (Arg.getAsInteger(0, Value))
1515     return O.error("'" + Arg + "' value invalid for uint argument!");
1516   return false;
1517 }
1518 
1519 // parser<unsigned long long> implementation
1520 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)1521 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1522                                        StringRef Arg,
1523                                        unsigned long long &Value) {
1524 
1525   if (Arg.getAsInteger(0, Value))
1526     return O.error("'" + Arg + "' value invalid for uint argument!");
1527   return false;
1528 }
1529 
1530 // parser<double>/parser<float> implementation
1531 //
parseDouble(Option & O,StringRef Arg,double & Value)1532 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1533   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1534   const char *ArgStart = TmpStr.c_str();
1535   char *End;
1536   Value = strtod(ArgStart, &End);
1537   if (*End != 0)
1538     return O.error("'" + Arg + "' value invalid for floating point argument!");
1539   return false;
1540 }
1541 
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)1542 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1543                            double &Val) {
1544   return parseDouble(O, Arg, Val);
1545 }
1546 
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)1547 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1548                           float &Val) {
1549   double dVal;
1550   if (parseDouble(O, Arg, dVal))
1551     return true;
1552   Val = (float)dVal;
1553   return false;
1554 }
1555 
1556 // generic_parser_base implementation
1557 //
1558 
1559 // findOption - Return the option number corresponding to the specified
1560 // argument string.  If the option is not found, getNumOptions() is returned.
1561 //
findOption(StringRef Name)1562 unsigned generic_parser_base::findOption(StringRef Name) {
1563   unsigned e = getNumOptions();
1564 
1565   for (unsigned i = 0; i != e; ++i) {
1566     if (getOption(i) == Name)
1567       return i;
1568   }
1569   return e;
1570 }
1571 
1572 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1573 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1574   if (O.hasArgStr()) {
1575     size_t Size = O.ArgStr.size() + 6;
1576     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1577       Size = std::max(Size, getOption(i).size() + 8);
1578     return Size;
1579   } else {
1580     size_t BaseSize = 0;
1581     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1582       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1583     return BaseSize;
1584   }
1585 }
1586 
1587 // printOptionInfo - Print out information about this option.  The
1588 // to-be-maintained width is specified.
1589 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1590 void generic_parser_base::printOptionInfo(const Option &O,
1591                                           size_t GlobalWidth) const {
1592   if (O.hasArgStr()) {
1593     outs() << "  -" << O.ArgStr;
1594     printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1595 
1596     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1597       size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
1598       outs() << "    =" << getOption(i);
1599       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1600     }
1601   } else {
1602     if (!O.HelpStr.empty())
1603       outs() << "  " << O.HelpStr << '\n';
1604     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1605       auto Option = getOption(i);
1606       outs() << "    -" << Option;
1607       printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1608     }
1609   }
1610 }
1611 
1612 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1613 
1614 // printGenericOptionDiff - Print the value of this option and it's default.
1615 //
1616 // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const1617 void generic_parser_base::printGenericOptionDiff(
1618     const Option &O, const GenericOptionValue &Value,
1619     const GenericOptionValue &Default, size_t GlobalWidth) const {
1620   outs() << "  -" << O.ArgStr;
1621   outs().indent(GlobalWidth - O.ArgStr.size());
1622 
1623   unsigned NumOpts = getNumOptions();
1624   for (unsigned i = 0; i != NumOpts; ++i) {
1625     if (Value.compare(getOptionValue(i)))
1626       continue;
1627 
1628     outs() << "= " << getOption(i);
1629     size_t L = getOption(i).size();
1630     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1631     outs().indent(NumSpaces) << " (default: ";
1632     for (unsigned j = 0; j != NumOpts; ++j) {
1633       if (Default.compare(getOptionValue(j)))
1634         continue;
1635       outs() << getOption(j);
1636       break;
1637     }
1638     outs() << ")\n";
1639     return;
1640   }
1641   outs() << "= *unknown option value*\n";
1642 }
1643 
1644 // printOptionDiff - Specializations for printing basic value types.
1645 //
1646 #define PRINT_OPT_DIFF(T)                                                      \
1647   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1648                                   size_t GlobalWidth) const {                  \
1649     printOptionName(O, GlobalWidth);                                           \
1650     std::string Str;                                                           \
1651     {                                                                          \
1652       raw_string_ostream SS(Str);                                              \
1653       SS << V;                                                                 \
1654     }                                                                          \
1655     outs() << "= " << Str;                                                     \
1656     size_t NumSpaces =                                                         \
1657         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1658     outs().indent(NumSpaces) << " (default: ";                                 \
1659     if (D.hasValue())                                                          \
1660       outs() << D.getValue();                                                  \
1661     else                                                                       \
1662       outs() << "*no default*";                                                \
1663     outs() << ")\n";                                                           \
1664   }
1665 
1666 PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)1667 PRINT_OPT_DIFF(boolOrDefault)
1668 PRINT_OPT_DIFF(int)
1669 PRINT_OPT_DIFF(unsigned)
1670 PRINT_OPT_DIFF(unsigned long long)
1671 PRINT_OPT_DIFF(double)
1672 PRINT_OPT_DIFF(float)
1673 PRINT_OPT_DIFF(char)
1674 
1675 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1676                                           const OptionValue<std::string> &D,
1677                                           size_t GlobalWidth) const {
1678   printOptionName(O, GlobalWidth);
1679   outs() << "= " << V;
1680   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1681   outs().indent(NumSpaces) << " (default: ";
1682   if (D.hasValue())
1683     outs() << D.getValue();
1684   else
1685     outs() << "*no default*";
1686   outs() << ")\n";
1687 }
1688 
1689 // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const1690 void basic_parser_impl::printOptionNoValue(const Option &O,
1691                                            size_t GlobalWidth) const {
1692   printOptionName(O, GlobalWidth);
1693   outs() << "= *cannot print option value*\n";
1694 }
1695 
1696 //===----------------------------------------------------------------------===//
1697 // -help and -help-hidden option implementation
1698 //
1699 
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)1700 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1701                           const std::pair<const char *, Option *> *RHS) {
1702   return strcmp(LHS->first, RHS->first);
1703 }
1704 
SubNameCompare(const std::pair<const char *,SubCommand * > * LHS,const std::pair<const char *,SubCommand * > * RHS)1705 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1706                           const std::pair<const char *, SubCommand *> *RHS) {
1707   return strcmp(LHS->first, RHS->first);
1708 }
1709 
1710 // 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)1711 static void sortOpts(StringMap<Option *> &OptMap,
1712                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1713                      bool ShowHidden) {
1714   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1715 
1716   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1717        I != E; ++I) {
1718     // Ignore really-hidden options.
1719     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1720       continue;
1721 
1722     // Unless showhidden is set, ignore hidden flags.
1723     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1724       continue;
1725 
1726     // If we've already seen this option, don't add it to the list again.
1727     if (!OptionSet.insert(I->second).second)
1728       continue;
1729 
1730     Opts.push_back(
1731         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1732   }
1733 
1734   // Sort the options list alphabetically.
1735   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1736 }
1737 
1738 static void
sortSubCommands(const SmallPtrSetImpl<SubCommand * > & SubMap,SmallVectorImpl<std::pair<const char *,SubCommand * >> & Subs)1739 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1740                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1741   for (const auto &S : SubMap) {
1742     if (S->getName().empty())
1743       continue;
1744     Subs.push_back(std::make_pair(S->getName().data(), S));
1745   }
1746   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1747 }
1748 
1749 namespace {
1750 
1751 class HelpPrinter {
1752 protected:
1753   const bool ShowHidden;
1754   typedef SmallVector<std::pair<const char *, Option *>, 128>
1755       StrOptionPairVector;
1756   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1757       StrSubCommandPairVector;
1758   // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1759   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1760     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1761       Opts[i].second->printOptionInfo(MaxArgLen);
1762   }
1763 
printSubCommands(StrSubCommandPairVector & Subs,size_t MaxSubLen)1764   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1765     for (const auto &S : Subs) {
1766       outs() << "  " << S.first;
1767       if (!S.second->getDescription().empty()) {
1768         outs().indent(MaxSubLen - strlen(S.first));
1769         outs() << " - " << S.second->getDescription();
1770       }
1771       outs() << "\n";
1772     }
1773   }
1774 
1775 public:
HelpPrinter(bool showHidden)1776   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
~HelpPrinter()1777   virtual ~HelpPrinter() {}
1778 
1779   // Invoke the printer.
operator =(bool Value)1780   void operator=(bool Value) {
1781     if (!Value)
1782       return;
1783 
1784     SubCommand *Sub = GlobalParser->getActiveSubCommand();
1785     auto &OptionsMap = Sub->OptionsMap;
1786     auto &PositionalOpts = Sub->PositionalOpts;
1787     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1788 
1789     StrOptionPairVector Opts;
1790     sortOpts(OptionsMap, Opts, ShowHidden);
1791 
1792     StrSubCommandPairVector Subs;
1793     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1794 
1795     if (!GlobalParser->ProgramOverview.empty())
1796       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1797 
1798     if (Sub == &*TopLevelSubCommand) {
1799       outs() << "USAGE: " << GlobalParser->ProgramName;
1800       if (Subs.size() > 2)
1801         outs() << " [subcommand]";
1802       outs() << " [options]";
1803     } else {
1804       if (!Sub->getDescription().empty()) {
1805         outs() << "SUBCOMMAND '" << Sub->getName()
1806                << "': " << Sub->getDescription() << "\n\n";
1807       }
1808       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1809              << " [options]";
1810     }
1811 
1812     for (auto Opt : PositionalOpts) {
1813       if (Opt->hasArgStr())
1814         outs() << " --" << Opt->ArgStr;
1815       outs() << " " << Opt->HelpStr;
1816     }
1817 
1818     // Print the consume after option info if it exists...
1819     if (ConsumeAfterOpt)
1820       outs() << " " << ConsumeAfterOpt->HelpStr;
1821 
1822     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1823       // Compute the maximum subcommand length...
1824       size_t MaxSubLen = 0;
1825       for (size_t i = 0, e = Subs.size(); i != e; ++i)
1826         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1827 
1828       outs() << "\n\n";
1829       outs() << "SUBCOMMANDS:\n\n";
1830       printSubCommands(Subs, MaxSubLen);
1831       outs() << "\n";
1832       outs() << "  Type \"" << GlobalParser->ProgramName
1833              << " <subcommand> -help\" to get more help on a specific "
1834                 "subcommand";
1835     }
1836 
1837     outs() << "\n\n";
1838 
1839     // Compute the maximum argument length...
1840     size_t MaxArgLen = 0;
1841     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1842       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1843 
1844     outs() << "OPTIONS:\n";
1845     printOptions(Opts, MaxArgLen);
1846 
1847     // Print any extra help the user has declared.
1848     for (auto I : GlobalParser->MoreHelp)
1849       outs() << I;
1850     GlobalParser->MoreHelp.clear();
1851 
1852     // Halt the program since help information was printed
1853     exit(0);
1854   }
1855 };
1856 
1857 class CategorizedHelpPrinter : public HelpPrinter {
1858 public:
CategorizedHelpPrinter(bool showHidden)1859   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1860 
1861   // Helper function for printOptions().
1862   // It shall return a negative value if A's name should be lexicographically
1863   // ordered before B's name. It returns a value greater equal zero otherwise.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)1864   static int OptionCategoryCompare(OptionCategory *const *A,
1865                                    OptionCategory *const *B) {
1866     return (*A)->getName() == (*B)->getName();
1867   }
1868 
1869   // Make sure we inherit our base class's operator=()
1870   using HelpPrinter::operator=;
1871 
1872 protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1873   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1874     std::vector<OptionCategory *> SortedCategories;
1875     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1876 
1877     // Collect registered option categories into vector in preparation for
1878     // sorting.
1879     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1880               E = GlobalParser->RegisteredOptionCategories.end();
1881          I != E; ++I) {
1882       SortedCategories.push_back(*I);
1883     }
1884 
1885     // Sort the different option categories alphabetically.
1886     assert(SortedCategories.size() > 0 && "No option categories registered!");
1887     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1888                    OptionCategoryCompare);
1889 
1890     // Create map to empty vectors.
1891     for (std::vector<OptionCategory *>::const_iterator
1892              I = SortedCategories.begin(),
1893              E = SortedCategories.end();
1894          I != E; ++I)
1895       CategorizedOptions[*I] = std::vector<Option *>();
1896 
1897     // Walk through pre-sorted options and assign into categories.
1898     // Because the options are already alphabetically sorted the
1899     // options within categories will also be alphabetically sorted.
1900     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1901       Option *Opt = Opts[I].second;
1902       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1903              "Option has an unregistered category");
1904       CategorizedOptions[Opt->Category].push_back(Opt);
1905     }
1906 
1907     // Now do printing.
1908     for (std::vector<OptionCategory *>::const_iterator
1909              Category = SortedCategories.begin(),
1910              E = SortedCategories.end();
1911          Category != E; ++Category) {
1912       // Hide empty categories for -help, but show for -help-hidden.
1913       const auto &CategoryOptions = CategorizedOptions[*Category];
1914       bool IsEmptyCategory = CategoryOptions.empty();
1915       if (!ShowHidden && IsEmptyCategory)
1916         continue;
1917 
1918       // Print category information.
1919       outs() << "\n";
1920       outs() << (*Category)->getName() << ":\n";
1921 
1922       // Check if description is set.
1923       if (!(*Category)->getDescription().empty())
1924         outs() << (*Category)->getDescription() << "\n\n";
1925       else
1926         outs() << "\n";
1927 
1928       // When using -help-hidden explicitly state if the category has no
1929       // options associated with it.
1930       if (IsEmptyCategory) {
1931         outs() << "  This option category has no options.\n";
1932         continue;
1933       }
1934       // Loop over the options in the category and print.
1935       for (const Option *Opt : CategoryOptions)
1936         Opt->printOptionInfo(MaxArgLen);
1937     }
1938   }
1939 };
1940 
1941 // This wraps the Uncategorizing and Categorizing printers and decides
1942 // at run time which should be invoked.
1943 class HelpPrinterWrapper {
1944 private:
1945   HelpPrinter &UncategorizedPrinter;
1946   CategorizedHelpPrinter &CategorizedPrinter;
1947 
1948 public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)1949   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1950                               CategorizedHelpPrinter &CategorizedPrinter)
1951       : UncategorizedPrinter(UncategorizedPrinter),
1952         CategorizedPrinter(CategorizedPrinter) {}
1953 
1954   // Invoke the printer.
1955   void operator=(bool Value);
1956 };
1957 
1958 } // End anonymous namespace
1959 
1960 // Declare the four HelpPrinter instances that are used to print out help, or
1961 // help-hidden as an uncategorized list or in categories.
1962 static HelpPrinter UncategorizedNormalPrinter(false);
1963 static HelpPrinter UncategorizedHiddenPrinter(true);
1964 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1965 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1966 
1967 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1968 // a categorizing help printer
1969 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1970                                                CategorizedNormalPrinter);
1971 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1972                                                CategorizedHiddenPrinter);
1973 
1974 // Define a category for generic options that all tools should have.
1975 static cl::OptionCategory GenericCategory("Generic Options");
1976 
1977 // Define uncategorized help printers.
1978 // -help-list is hidden by default because if Option categories are being used
1979 // then -help behaves the same as -help-list.
1980 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1981     "help-list",
1982     cl::desc("Display list of available options (-help-list-hidden for more)"),
1983     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1984     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1985 
1986 static cl::opt<HelpPrinter, true, parser<bool>>
1987     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1988           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1989           cl::ValueDisallowed, cl::cat(GenericCategory),
1990           cl::sub(*AllSubCommands));
1991 
1992 // Define uncategorized/categorized help printers. These printers change their
1993 // behaviour at runtime depending on whether one or more Option categories have
1994 // been declared.
1995 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1996     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1997         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1998         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
1999 
2000 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2001     HHOp("help-hidden", cl::desc("Display all available options"),
2002          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2003          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2004 
2005 static cl::opt<bool> PrintOptions(
2006     "print-options",
2007     cl::desc("Print non-default options after command line parsing"),
2008     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2009     cl::sub(*AllSubCommands));
2010 
2011 static cl::opt<bool> PrintAllOptions(
2012     "print-all-options",
2013     cl::desc("Print all option values after command line parsing"), cl::Hidden,
2014     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2015 
operator =(bool Value)2016 void HelpPrinterWrapper::operator=(bool Value) {
2017   if (!Value)
2018     return;
2019 
2020   // Decide which printer to invoke. If more than one option category is
2021   // registered then it is useful to show the categorized help instead of
2022   // uncategorized help.
2023   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2024     // unhide -help-list option so user can have uncategorized output if they
2025     // want it.
2026     HLOp.setHiddenFlag(NotHidden);
2027 
2028     CategorizedPrinter = true; // Invoke categorized printer
2029   } else
2030     UncategorizedPrinter = true; // Invoke uncategorized printer
2031 }
2032 
2033 // Print the value of each option.
PrintOptionValues()2034 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2035 
printOptionValues()2036 void CommandLineParser::printOptionValues() {
2037   if (!PrintOptions && !PrintAllOptions)
2038     return;
2039 
2040   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2041   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2042 
2043   // Compute the maximum argument length...
2044   size_t MaxArgLen = 0;
2045   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2046     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2047 
2048   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2049     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2050 }
2051 
2052 static void (*OverrideVersionPrinter)() = nullptr;
2053 
2054 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
2055 
2056 // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)2057 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2058   // This looks weird, but it actually prints the help message. The Printers are
2059   // types of HelpPrinter and the help gets printed when its operator= is
2060   // invoked. That's because the "normal" usages of the help printer is to be
2061   // assigned true/false depending on whether -help or -help-hidden was given or
2062   // not.  Since we're circumventing that we have to make it look like -help or
2063   // -help-hidden were given, so we assign true.
2064 
2065   if (!Hidden && !Categorized)
2066     UncategorizedNormalPrinter = true;
2067   else if (!Hidden && Categorized)
2068     CategorizedNormalPrinter = true;
2069   else if (Hidden && !Categorized)
2070     UncategorizedHiddenPrinter = true;
2071   else
2072     CategorizedHiddenPrinter = true;
2073 }
2074 
SetVersionPrinter(void (* func)())2075 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
2076 
AddExtraVersionPrinter(void (* func)())2077 void cl::AddExtraVersionPrinter(void (*func)()) {
2078   if (!ExtraVersionPrinters)
2079     ExtraVersionPrinters = new std::vector<void (*)()>;
2080 
2081   ExtraVersionPrinters->push_back(func);
2082 }
2083 
getRegisteredOptions(SubCommand & Sub)2084 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2085   auto &Subs = GlobalParser->RegisteredSubCommands;
2086   (void)Subs;
2087   assert(is_contained(Subs, &Sub));
2088   return Sub.OptionsMap;
2089 }
2090 
2091 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()2092 cl::getRegisteredSubcommands() {
2093   return GlobalParser->getRegisteredSubcommands();
2094 }
2095 
HideUnrelatedOptions(cl::OptionCategory & Category,SubCommand & Sub)2096 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2097   for (auto &I : Sub.OptionsMap) {
2098     if (I.second->Category != &Category &&
2099         I.second->Category != &GenericCategory)
2100       I.second->setHiddenFlag(cl::ReallyHidden);
2101   }
2102 }
2103 
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories,SubCommand & Sub)2104 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2105                               SubCommand &Sub) {
2106   auto CategoriesBegin = Categories.begin();
2107   auto CategoriesEnd = Categories.end();
2108   for (auto &I : Sub.OptionsMap) {
2109     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2110             CategoriesEnd &&
2111         I.second->Category != &GenericCategory)
2112       I.second->setHiddenFlag(cl::ReallyHidden);
2113   }
2114 }
2115 
ResetCommandLineParser()2116 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
ResetAllOptionOccurrences()2117 void cl::ResetAllOptionOccurrences() {
2118   GlobalParser->ResetAllOptionOccurrences();
2119 }
2120 
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)2121 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2122                                  const char *Overview) {
2123   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), true);
2124 }
2125