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