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