1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class implements a command line argument processor that is useful when
10 // creating a tool. It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
12 //
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/config.h"
31 #include "llvm/Support/ConvertUTF.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Error.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/StringSaver.h"
42 #include "llvm/Support/VirtualFileSystem.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <cstdlib>
45 #include <map>
46 #include <string>
47 using namespace llvm;
48 using namespace cl;
49
50 #define DEBUG_TYPE "commandline"
51
52 //===----------------------------------------------------------------------===//
53 // Template instantiations and anchors.
54 //
55 namespace llvm {
56 namespace cl {
57 template class basic_parser<bool>;
58 template class basic_parser<boolOrDefault>;
59 template class basic_parser<int>;
60 template class basic_parser<long>;
61 template class basic_parser<long long>;
62 template class basic_parser<unsigned>;
63 template class basic_parser<unsigned long>;
64 template class basic_parser<unsigned long long>;
65 template class basic_parser<double>;
66 template class basic_parser<float>;
67 template class basic_parser<std::string>;
68 template class basic_parser<char>;
69
70 template class opt<unsigned>;
71 template class opt<int>;
72 template class opt<std::string>;
73 template class opt<char>;
74 template class opt<bool>;
75 }
76 } // end namespace llvm::cl
77
78 // Pin the vtables to this file.
anchor()79 void GenericOptionValue::anchor() {}
anchor()80 void OptionValue<boolOrDefault>::anchor() {}
anchor()81 void OptionValue<std::string>::anchor() {}
anchor()82 void Option::anchor() {}
anchor()83 void basic_parser_impl::anchor() {}
anchor()84 void parser<bool>::anchor() {}
anchor()85 void parser<boolOrDefault>::anchor() {}
anchor()86 void parser<int>::anchor() {}
anchor()87 void parser<long>::anchor() {}
anchor()88 void parser<long long>::anchor() {}
anchor()89 void parser<unsigned>::anchor() {}
anchor()90 void parser<unsigned long>::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 const static size_t DefaultPad = 2;
100
101 static StringRef ArgPrefix = "-";
102 static StringRef ArgPrefixLong = "--";
103 static StringRef ArgHelpPrefix = " - ";
104
argPlusPrefixesSize(StringRef ArgName,size_t Pad=DefaultPad)105 static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
106 size_t Len = ArgName.size();
107 if (Len == 1)
108 return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
109 return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
110 }
111
argPrefix(StringRef ArgName,size_t Pad=DefaultPad)112 static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
113 SmallString<8> Prefix;
114 for (size_t I = 0; I < Pad; ++I) {
115 Prefix.push_back(' ');
116 }
117 Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
118 return Prefix;
119 }
120
121 // Option predicates...
isGrouping(const Option * O)122 static inline bool isGrouping(const Option *O) {
123 return O->getMiscFlags() & cl::Grouping;
124 }
isPrefixedOrGrouping(const Option * O)125 static inline bool isPrefixedOrGrouping(const Option *O) {
126 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
127 O->getFormattingFlag() == cl::AlwaysPrefix;
128 }
129
130
131 namespace {
132
133 class PrintArg {
134 StringRef ArgName;
135 size_t Pad;
136 public:
PrintArg(StringRef ArgName,size_t Pad=DefaultPad)137 PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
138 friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
139 };
140
operator <<(raw_ostream & OS,const PrintArg & Arg)141 raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
142 OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
143 return OS;
144 }
145
146 class CommandLineParser {
147 public:
148 // Globals for name and overview of program. Program name is not a string to
149 // avoid static ctor/dtor issues.
150 std::string ProgramName;
151 StringRef ProgramOverview;
152
153 // This collects additional help to be printed.
154 std::vector<StringRef> MoreHelp;
155
156 // This collects Options added with the cl::DefaultOption flag. Since they can
157 // be overridden, they are not added to the appropriate SubCommands until
158 // ParseCommandLineOptions actually runs.
159 SmallVector<Option*, 4> DefaultOptions;
160
161 // This collects the different option categories that have been registered.
162 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
163
164 // This collects the different subcommands that have been registered.
165 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
166
CommandLineParser()167 CommandLineParser() : ActiveSubCommand(nullptr) {
168 registerSubCommand(&*TopLevelSubCommand);
169 registerSubCommand(&*AllSubCommands);
170 }
171
172 void ResetAllOptionOccurrences();
173
174 bool ParseCommandLineOptions(int argc, const char *const *argv,
175 StringRef Overview, raw_ostream *Errs = nullptr,
176 bool LongOptionsUseDoubleDash = false);
177
addLiteralOption(Option & Opt,SubCommand * SC,StringRef Name)178 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
179 if (Opt.hasArgStr())
180 return;
181 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
182 errs() << ProgramName << ": CommandLine Error: Option '" << Name
183 << "' registered more than once!\n";
184 report_fatal_error("inconsistency in registered CommandLine options");
185 }
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 addLiteralOption(Opt, Sub, Name);
194 }
195 }
196 }
197
addLiteralOption(Option & Opt,StringRef Name)198 void addLiteralOption(Option &Opt, StringRef Name) {
199 if (Opt.Subs.empty())
200 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
201 else {
202 for (auto SC : Opt.Subs)
203 addLiteralOption(Opt, SC, Name);
204 }
205 }
206
addOption(Option * O,SubCommand * SC)207 void addOption(Option *O, SubCommand *SC) {
208 bool HadErrors = false;
209 if (O->hasArgStr()) {
210 // If it's a DefaultOption, check to make sure it isn't already there.
211 if (O->isDefaultOption() &&
212 SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
213 return;
214
215 // Add argument to the argument map!
216 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
217 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
218 << "' registered more than once!\n";
219 HadErrors = true;
220 }
221 }
222
223 // Remember information about positional options.
224 if (O->getFormattingFlag() == cl::Positional)
225 SC->PositionalOpts.push_back(O);
226 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
227 SC->SinkOpts.push_back(O);
228 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
229 if (SC->ConsumeAfterOpt) {
230 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
231 HadErrors = true;
232 }
233 SC->ConsumeAfterOpt = O;
234 }
235
236 // Fail hard if there were errors. These are strictly unrecoverable and
237 // indicate serious issues such as conflicting option names or an
238 // incorrectly
239 // linked LLVM distribution.
240 if (HadErrors)
241 report_fatal_error("inconsistency in registered CommandLine options");
242
243 // If we're adding this to all sub-commands, add it to the ones that have
244 // already been registered.
245 if (SC == &*AllSubCommands) {
246 for (auto *Sub : RegisteredSubCommands) {
247 if (SC == Sub)
248 continue;
249 addOption(O, Sub);
250 }
251 }
252 }
253
addOption(Option * O,bool ProcessDefaultOption=false)254 void addOption(Option *O, bool ProcessDefaultOption = false) {
255 if (!ProcessDefaultOption && O->isDefaultOption()) {
256 DefaultOptions.push_back(O);
257 return;
258 }
259
260 if (O->Subs.empty()) {
261 addOption(O, &*TopLevelSubCommand);
262 } else {
263 for (auto SC : O->Subs)
264 addOption(O, SC);
265 }
266 }
267
removeOption(Option * O,SubCommand * SC)268 void removeOption(Option *O, SubCommand *SC) {
269 SmallVector<StringRef, 16> OptionNames;
270 O->getExtraOptionNames(OptionNames);
271 if (O->hasArgStr())
272 OptionNames.push_back(O->ArgStr);
273
274 SubCommand &Sub = *SC;
275 auto End = Sub.OptionsMap.end();
276 for (auto Name : OptionNames) {
277 auto I = Sub.OptionsMap.find(Name);
278 if (I != End && I->getValue() == O)
279 Sub.OptionsMap.erase(I);
280 }
281
282 if (O->getFormattingFlag() == cl::Positional)
283 for (auto Opt = Sub.PositionalOpts.begin();
284 Opt != Sub.PositionalOpts.end(); ++Opt) {
285 if (*Opt == O) {
286 Sub.PositionalOpts.erase(Opt);
287 break;
288 }
289 }
290 else if (O->getMiscFlags() & cl::Sink)
291 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
292 if (*Opt == O) {
293 Sub.SinkOpts.erase(Opt);
294 break;
295 }
296 }
297 else if (O == Sub.ConsumeAfterOpt)
298 Sub.ConsumeAfterOpt = nullptr;
299 }
300
removeOption(Option * O)301 void removeOption(Option *O) {
302 if (O->Subs.empty())
303 removeOption(O, &*TopLevelSubCommand);
304 else {
305 if (O->isInAllSubCommands()) {
306 for (auto SC : RegisteredSubCommands)
307 removeOption(O, SC);
308 } else {
309 for (auto SC : O->Subs)
310 removeOption(O, SC);
311 }
312 }
313 }
314
hasOptions(const SubCommand & Sub) const315 bool hasOptions(const SubCommand &Sub) const {
316 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
317 nullptr != Sub.ConsumeAfterOpt);
318 }
319
hasOptions() const320 bool hasOptions() const {
321 for (const auto *S : RegisteredSubCommands) {
322 if (hasOptions(*S))
323 return true;
324 }
325 return false;
326 }
327
getActiveSubCommand()328 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
329
updateArgStr(Option * O,StringRef NewName,SubCommand * SC)330 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
331 SubCommand &Sub = *SC;
332 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
333 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
334 << "' registered more than once!\n";
335 report_fatal_error("inconsistency in registered CommandLine options");
336 }
337 Sub.OptionsMap.erase(O->ArgStr);
338 }
339
updateArgStr(Option * O,StringRef NewName)340 void updateArgStr(Option *O, StringRef NewName) {
341 if (O->Subs.empty())
342 updateArgStr(O, NewName, &*TopLevelSubCommand);
343 else {
344 if (O->isInAllSubCommands()) {
345 for (auto SC : RegisteredSubCommands)
346 updateArgStr(O, NewName, SC);
347 } else {
348 for (auto SC : O->Subs)
349 updateArgStr(O, NewName, SC);
350 }
351 }
352 }
353
354 void printOptionValues();
355
registerCategory(OptionCategory * cat)356 void registerCategory(OptionCategory *cat) {
357 assert(count_if(RegisteredOptionCategories,
358 [cat](const OptionCategory *Category) {
359 return cat->getName() == Category->getName();
360 }) == 0 &&
361 "Duplicate option categories");
362
363 RegisteredOptionCategories.insert(cat);
364 }
365
registerSubCommand(SubCommand * sub)366 void registerSubCommand(SubCommand *sub) {
367 assert(count_if(RegisteredSubCommands,
368 [sub](const SubCommand *Sub) {
369 return (!sub->getName().empty()) &&
370 (Sub->getName() == sub->getName());
371 }) == 0 &&
372 "Duplicate subcommands");
373 RegisteredSubCommands.insert(sub);
374
375 // For all options that have been registered for all subcommands, add the
376 // option to this subcommand now.
377 if (sub != &*AllSubCommands) {
378 for (auto &E : AllSubCommands->OptionsMap) {
379 Option *O = E.second;
380 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
381 O->hasArgStr())
382 addOption(O, sub);
383 else
384 addLiteralOption(*O, sub, E.first());
385 }
386 }
387 }
388
unregisterSubCommand(SubCommand * sub)389 void unregisterSubCommand(SubCommand *sub) {
390 RegisteredSubCommands.erase(sub);
391 }
392
393 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()394 getRegisteredSubcommands() {
395 return make_range(RegisteredSubCommands.begin(),
396 RegisteredSubCommands.end());
397 }
398
reset()399 void reset() {
400 ActiveSubCommand = nullptr;
401 ProgramName.clear();
402 ProgramOverview = StringRef();
403
404 MoreHelp.clear();
405 RegisteredOptionCategories.clear();
406
407 ResetAllOptionOccurrences();
408 RegisteredSubCommands.clear();
409
410 TopLevelSubCommand->reset();
411 AllSubCommands->reset();
412 registerSubCommand(&*TopLevelSubCommand);
413 registerSubCommand(&*AllSubCommands);
414
415 DefaultOptions.clear();
416 }
417
418 private:
419 SubCommand *ActiveSubCommand;
420
421 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
LookupLongOption(SubCommand & Sub,StringRef & Arg,StringRef & Value,bool LongOptionsUseDoubleDash,bool HaveDoubleDash)422 Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
423 bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
424 Option *Opt = LookupOption(Sub, Arg, Value);
425 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
426 return nullptr;
427 return Opt;
428 }
429 SubCommand *LookupSubCommand(StringRef Name);
430 };
431
432 } // namespace
433
434 static ManagedStatic<CommandLineParser> GlobalParser;
435
AddLiteralOption(Option & O,StringRef Name)436 void cl::AddLiteralOption(Option &O, StringRef Name) {
437 GlobalParser->addLiteralOption(O, Name);
438 }
439
extrahelp(StringRef Help)440 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
441 GlobalParser->MoreHelp.push_back(Help);
442 }
443
addArgument()444 void Option::addArgument() {
445 GlobalParser->addOption(this);
446 FullyInitialized = true;
447 }
448
removeArgument()449 void Option::removeArgument() { GlobalParser->removeOption(this); }
450
setArgStr(StringRef S)451 void Option::setArgStr(StringRef S) {
452 if (FullyInitialized)
453 GlobalParser->updateArgStr(this, S);
454 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
455 ArgStr = S;
456 if (ArgStr.size() == 1)
457 setMiscFlag(Grouping);
458 }
459
addCategory(OptionCategory & C)460 void Option::addCategory(OptionCategory &C) {
461 assert(!Categories.empty() && "Categories cannot be empty.");
462 // Maintain backward compatibility by replacing the default GeneralCategory
463 // if it's still set. Otherwise, just add the new one. The GeneralCategory
464 // must be explicitly added if you want multiple categories that include it.
465 if (&C != &GeneralCategory && Categories[0] == &GeneralCategory)
466 Categories[0] = &C;
467 else if (find(Categories, &C) == Categories.end())
468 Categories.push_back(&C);
469 }
470
reset()471 void Option::reset() {
472 NumOccurrences = 0;
473 setDefault();
474 if (isDefaultOption())
475 removeArgument();
476 }
477
478 // Initialise the general option category.
479 OptionCategory llvm::cl::GeneralCategory("General options");
480
registerCategory()481 void OptionCategory::registerCategory() {
482 GlobalParser->registerCategory(this);
483 }
484
485 // A special subcommand representing no subcommand. It is particularly important
486 // that this ManagedStatic uses constant initailization and not dynamic
487 // initialization because it is referenced from cl::opt constructors, which run
488 // dynamically in an arbitrary order.
489 LLVM_REQUIRE_CONSTANT_INITIALIZATION
490 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
491
492 // A special subcommand that can be used to put an option into all subcommands.
493 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
494
registerSubCommand()495 void SubCommand::registerSubCommand() {
496 GlobalParser->registerSubCommand(this);
497 }
498
unregisterSubCommand()499 void SubCommand::unregisterSubCommand() {
500 GlobalParser->unregisterSubCommand(this);
501 }
502
reset()503 void SubCommand::reset() {
504 PositionalOpts.clear();
505 SinkOpts.clear();
506 OptionsMap.clear();
507
508 ConsumeAfterOpt = nullptr;
509 }
510
operator bool() const511 SubCommand::operator bool() const {
512 return (GlobalParser->getActiveSubCommand() == this);
513 }
514
515 //===----------------------------------------------------------------------===//
516 // Basic, shared command line option processing machinery.
517 //
518
519 /// LookupOption - Lookup the option specified by the specified option on the
520 /// command line. If there is a value specified (after an equal sign) return
521 /// that as well. This assumes that leading dashes have already been stripped.
LookupOption(SubCommand & Sub,StringRef & Arg,StringRef & Value)522 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
523 StringRef &Value) {
524 // Reject all dashes.
525 if (Arg.empty())
526 return nullptr;
527 assert(&Sub != &*AllSubCommands);
528
529 size_t EqualPos = Arg.find('=');
530
531 // If we have an equals sign, remember the value.
532 if (EqualPos == StringRef::npos) {
533 // Look up the option.
534 auto I = Sub.OptionsMap.find(Arg);
535 if (I == Sub.OptionsMap.end())
536 return nullptr;
537
538 return I != Sub.OptionsMap.end() ? I->second : nullptr;
539 }
540
541 // If the argument before the = is a valid option name and the option allows
542 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
543 // failure by returning nullptr.
544 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
545 if (I == Sub.OptionsMap.end())
546 return nullptr;
547
548 auto O = I->second;
549 if (O->getFormattingFlag() == cl::AlwaysPrefix)
550 return nullptr;
551
552 Value = Arg.substr(EqualPos + 1);
553 Arg = Arg.substr(0, EqualPos);
554 return I->second;
555 }
556
LookupSubCommand(StringRef Name)557 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
558 if (Name.empty())
559 return &*TopLevelSubCommand;
560 for (auto S : RegisteredSubCommands) {
561 if (S == &*AllSubCommands)
562 continue;
563 if (S->getName().empty())
564 continue;
565
566 if (StringRef(S->getName()) == StringRef(Name))
567 return S;
568 }
569 return &*TopLevelSubCommand;
570 }
571
572 /// LookupNearestOption - Lookup the closest match to the option specified by
573 /// the specified option on the command line. If there is a value specified
574 /// (after an equal sign) return that as well. This assumes that leading dashes
575 /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)576 static Option *LookupNearestOption(StringRef Arg,
577 const StringMap<Option *> &OptionsMap,
578 std::string &NearestString) {
579 // Reject all dashes.
580 if (Arg.empty())
581 return nullptr;
582
583 // Split on any equal sign.
584 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
585 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
586 StringRef &RHS = SplitArg.second;
587
588 // Find the closest match.
589 Option *Best = nullptr;
590 unsigned BestDistance = 0;
591 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
592 ie = OptionsMap.end();
593 it != ie; ++it) {
594 Option *O = it->second;
595 // Do not suggest really hidden options (not shown in any help).
596 if (O->getOptionHiddenFlag() == ReallyHidden)
597 continue;
598
599 SmallVector<StringRef, 16> OptionNames;
600 O->getExtraOptionNames(OptionNames);
601 if (O->hasArgStr())
602 OptionNames.push_back(O->ArgStr);
603
604 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
605 StringRef Flag = PermitValue ? LHS : Arg;
606 for (auto Name : OptionNames) {
607 unsigned Distance = StringRef(Name).edit_distance(
608 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
609 if (!Best || Distance < BestDistance) {
610 Best = O;
611 BestDistance = Distance;
612 if (RHS.empty() || !PermitValue)
613 NearestString = std::string(Name);
614 else
615 NearestString = (Twine(Name) + "=" + RHS).str();
616 }
617 }
618 }
619
620 return Best;
621 }
622
623 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
624 /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)625 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
626 StringRef ArgName, StringRef Value,
627 bool MultiArg = false) {
628 // Check to see if this option accepts a comma separated list of values. If
629 // it does, we have to split up the value into multiple values.
630 if (Handler->getMiscFlags() & CommaSeparated) {
631 StringRef Val(Value);
632 StringRef::size_type Pos = Val.find(',');
633
634 while (Pos != StringRef::npos) {
635 // Process the portion before the comma.
636 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
637 return true;
638 // Erase the portion before the comma, AND the comma.
639 Val = Val.substr(Pos + 1);
640 // Check for another comma.
641 Pos = Val.find(',');
642 }
643
644 Value = Val;
645 }
646
647 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
648 }
649
650 /// ProvideOption - For Value, this differentiates between an empty value ("")
651 /// and a null value (StringRef()). The later is accepted for arguments that
652 /// 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)653 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
654 StringRef Value, int argc,
655 const char *const *argv, int &i) {
656 // Is this a multi-argument option?
657 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
658
659 // Enforce value requirements
660 switch (Handler->getValueExpectedFlag()) {
661 case ValueRequired:
662 if (!Value.data()) { // No value specified?
663 // If no other argument or the option only supports prefix form, we
664 // cannot look at the next argument.
665 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
666 return Handler->error("requires a value!");
667 // Steal the next argument, like for '-o filename'
668 assert(argv && "null check");
669 Value = StringRef(argv[++i]);
670 }
671 break;
672 case ValueDisallowed:
673 if (NumAdditionalVals > 0)
674 return Handler->error("multi-valued option specified"
675 " with ValueDisallowed modifier!");
676
677 if (Value.data())
678 return Handler->error("does not allow a value! '" + Twine(Value) +
679 "' specified.");
680 break;
681 case ValueOptional:
682 break;
683 }
684
685 // If this isn't a multi-arg option, just run the handler.
686 if (NumAdditionalVals == 0)
687 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
688
689 // If it is, run the handle several times.
690 bool MultiArg = false;
691
692 if (Value.data()) {
693 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
694 return true;
695 --NumAdditionalVals;
696 MultiArg = true;
697 }
698
699 while (NumAdditionalVals > 0) {
700 if (i + 1 >= argc)
701 return Handler->error("not enough values!");
702 assert(argv && "null check");
703 Value = StringRef(argv[++i]);
704
705 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
706 return true;
707 MultiArg = true;
708 --NumAdditionalVals;
709 }
710 return false;
711 }
712
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)713 bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
714 int Dummy = i;
715 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
716 }
717
718 // getOptionPred - Check to see if there are any options that satisfy the
719 // specified predicate with names that are the prefixes in Name. This is
720 // checked by progressively stripping characters off of the name, checking to
721 // see if there options that satisfy the predicate. If we find one, return it,
722 // otherwise return null.
723 //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)724 static Option *getOptionPred(StringRef Name, size_t &Length,
725 bool (*Pred)(const Option *),
726 const StringMap<Option *> &OptionsMap) {
727 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
728 if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
729 OMI = OptionsMap.end();
730
731 // Loop while we haven't found an option and Name still has at least two
732 // characters in it (so that the next iteration will not be the empty
733 // string.
734 while (OMI == OptionsMap.end() && Name.size() > 1) {
735 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
736 OMI = OptionsMap.find(Name);
737 if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
738 OMI = OptionsMap.end();
739 }
740
741 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
742 Length = Name.size();
743 return OMI->second; // Found one!
744 }
745 return nullptr; // No option found!
746 }
747
748 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
749 /// with at least one '-') does not fully match an available option. Check to
750 /// see if this is a prefix or grouped option. If so, split arg into output an
751 /// Arg/Value pair and return the Option to parse it with.
752 static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)753 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
754 bool &ErrorParsing,
755 const StringMap<Option *> &OptionsMap) {
756 if (Arg.size() == 1)
757 return nullptr;
758
759 // Do the lookup!
760 size_t Length = 0;
761 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
762 if (!PGOpt)
763 return nullptr;
764
765 do {
766 StringRef MaybeValue =
767 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
768 Arg = Arg.substr(0, Length);
769 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
770
771 // cl::Prefix options do not preserve '=' when used separately.
772 // The behavior for them with grouped options should be the same.
773 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
774 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
775 Value = MaybeValue;
776 return PGOpt;
777 }
778
779 if (MaybeValue[0] == '=') {
780 Value = MaybeValue.substr(1);
781 return PGOpt;
782 }
783
784 // This must be a grouped option.
785 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
786
787 // Grouping options inside a group can't have values.
788 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
789 ErrorParsing |= PGOpt->error("may not occur within a group!");
790 return nullptr;
791 }
792
793 // Because the value for the option is not required, we don't need to pass
794 // argc/argv in.
795 int Dummy = 0;
796 ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
797
798 // Get the next grouping option.
799 Arg = MaybeValue;
800 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
801 } while (PGOpt);
802
803 // We could not find a grouping option in the remainder of Arg.
804 return nullptr;
805 }
806
RequiresValue(const Option * O)807 static bool RequiresValue(const Option *O) {
808 return O->getNumOccurrencesFlag() == cl::Required ||
809 O->getNumOccurrencesFlag() == cl::OneOrMore;
810 }
811
EatsUnboundedNumberOfValues(const Option * O)812 static bool EatsUnboundedNumberOfValues(const Option *O) {
813 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
814 O->getNumOccurrencesFlag() == cl::OneOrMore;
815 }
816
isWhitespace(char C)817 static bool isWhitespace(char C) {
818 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
819 }
820
isWhitespaceOrNull(char C)821 static bool isWhitespaceOrNull(char C) {
822 return isWhitespace(C) || C == '\0';
823 }
824
isQuote(char C)825 static bool isQuote(char C) { return C == '\"' || C == '\''; }
826
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)827 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
828 SmallVectorImpl<const char *> &NewArgv,
829 bool MarkEOLs) {
830 SmallString<128> Token;
831 for (size_t I = 0, E = Src.size(); I != E; ++I) {
832 // Consume runs of whitespace.
833 if (Token.empty()) {
834 while (I != E && isWhitespace(Src[I])) {
835 // Mark the end of lines in response files.
836 if (MarkEOLs && Src[I] == '\n')
837 NewArgv.push_back(nullptr);
838 ++I;
839 }
840 if (I == E)
841 break;
842 }
843
844 char C = Src[I];
845
846 // Backslash escapes the next character.
847 if (I + 1 < E && C == '\\') {
848 ++I; // Skip the escape.
849 Token.push_back(Src[I]);
850 continue;
851 }
852
853 // Consume a quoted string.
854 if (isQuote(C)) {
855 ++I;
856 while (I != E && Src[I] != C) {
857 // Backslash escapes the next character.
858 if (Src[I] == '\\' && I + 1 != E)
859 ++I;
860 Token.push_back(Src[I]);
861 ++I;
862 }
863 if (I == E)
864 break;
865 continue;
866 }
867
868 // End the token if this is whitespace.
869 if (isWhitespace(C)) {
870 if (!Token.empty())
871 NewArgv.push_back(Saver.save(StringRef(Token)).data());
872 // Mark the end of lines in response files.
873 if (MarkEOLs && C == '\n')
874 NewArgv.push_back(nullptr);
875 Token.clear();
876 continue;
877 }
878
879 // This is a normal character. Append it.
880 Token.push_back(C);
881 }
882
883 // Append the last token after hitting EOF with no whitespace.
884 if (!Token.empty())
885 NewArgv.push_back(Saver.save(StringRef(Token)).data());
886 }
887
888 /// Backslashes are interpreted in a rather complicated way in the Windows-style
889 /// command line, because backslashes are used both to separate path and to
890 /// escape double quote. This method consumes runs of backslashes as well as the
891 /// following double quote if it's escaped.
892 ///
893 /// * If an even number of backslashes is followed by a double quote, one
894 /// backslash is output for every pair of backslashes, and the last double
895 /// quote remains unconsumed. The double quote will later be interpreted as
896 /// the start or end of a quoted string in the main loop outside of this
897 /// function.
898 ///
899 /// * If an odd number of backslashes is followed by a double quote, one
900 /// backslash is output for every pair of backslashes, and a double quote is
901 /// output for the last pair of backslash-double quote. The double quote is
902 /// consumed in this case.
903 ///
904 /// * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)905 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
906 size_t E = Src.size();
907 int BackslashCount = 0;
908 // Skip the backslashes.
909 do {
910 ++I;
911 ++BackslashCount;
912 } while (I != E && Src[I] == '\\');
913
914 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
915 if (FollowedByDoubleQuote) {
916 Token.append(BackslashCount / 2, '\\');
917 if (BackslashCount % 2 == 0)
918 return I - 1;
919 Token.push_back('"');
920 return I;
921 }
922 Token.append(BackslashCount, '\\');
923 return I - 1;
924 }
925
926 // Windows treats whitespace, double quotes, and backslashes specially.
isWindowsSpecialChar(char C)927 static bool isWindowsSpecialChar(char C) {
928 return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
929 }
930
931 // Windows tokenization implementation. The implementation is designed to be
932 // inlined and specialized for the two user entry points.
933 static inline void
tokenizeWindowsCommandLineImpl(StringRef Src,StringSaver & Saver,function_ref<void (StringRef)> AddToken,bool AlwaysCopy,function_ref<void ()> MarkEOL)934 tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver,
935 function_ref<void(StringRef)> AddToken,
936 bool AlwaysCopy, function_ref<void()> MarkEOL) {
937 SmallString<128> Token;
938
939 // Try to do as much work inside the state machine as possible.
940 enum { INIT, UNQUOTED, QUOTED } State = INIT;
941 for (size_t I = 0, E = Src.size(); I < E; ++I) {
942 switch (State) {
943 case INIT: {
944 assert(Token.empty() && "token should be empty in initial state");
945 // Eat whitespace before a token.
946 while (I < E && isWhitespaceOrNull(Src[I])) {
947 if (Src[I] == '\n')
948 MarkEOL();
949 ++I;
950 }
951 // Stop if this was trailing whitespace.
952 if (I >= E)
953 break;
954 size_t Start = I;
955 while (I < E && !isWindowsSpecialChar(Src[I]))
956 ++I;
957 StringRef NormalChars = Src.slice(Start, I);
958 if (I >= E || isWhitespaceOrNull(Src[I])) {
959 // No special characters: slice out the substring and start the next
960 // token. Copy the string if the caller asks us to.
961 AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
962 if (I < E && Src[I] == '\n')
963 MarkEOL();
964 } else if (Src[I] == '\"') {
965 Token += NormalChars;
966 State = QUOTED;
967 } else if (Src[I] == '\\') {
968 Token += NormalChars;
969 I = parseBackslash(Src, I, Token);
970 State = UNQUOTED;
971 } else {
972 llvm_unreachable("unexpected special character");
973 }
974 break;
975 }
976
977 case UNQUOTED:
978 if (isWhitespaceOrNull(Src[I])) {
979 // Whitespace means the end of the token. If we are in this state, the
980 // token must have contained a special character, so we must copy the
981 // token.
982 AddToken(Saver.save(Token.str()));
983 Token.clear();
984 if (Src[I] == '\n')
985 MarkEOL();
986 State = INIT;
987 } else if (Src[I] == '\"') {
988 State = QUOTED;
989 } else if (Src[I] == '\\') {
990 I = parseBackslash(Src, I, Token);
991 } else {
992 Token.push_back(Src[I]);
993 }
994 break;
995
996 case QUOTED:
997 if (Src[I] == '\"') {
998 if (I < (E - 1) && Src[I + 1] == '"') {
999 // Consecutive double-quotes inside a quoted string implies one
1000 // double-quote.
1001 Token.push_back('"');
1002 ++I;
1003 } else {
1004 // Otherwise, end the quoted portion and return to the unquoted state.
1005 State = UNQUOTED;
1006 }
1007 } else if (Src[I] == '\\') {
1008 I = parseBackslash(Src, I, Token);
1009 } else {
1010 Token.push_back(Src[I]);
1011 }
1012 break;
1013 }
1014 }
1015
1016 if (State == UNQUOTED)
1017 AddToken(Saver.save(Token.str()));
1018 }
1019
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)1020 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
1021 SmallVectorImpl<const char *> &NewArgv,
1022 bool MarkEOLs) {
1023 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1024 auto OnEOL = [&]() {
1025 if (MarkEOLs)
1026 NewArgv.push_back(nullptr);
1027 };
1028 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1029 /*AlwaysCopy=*/true, OnEOL);
1030 }
1031
TokenizeWindowsCommandLineNoCopy(StringRef Src,StringSaver & Saver,SmallVectorImpl<StringRef> & NewArgv)1032 void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
1033 SmallVectorImpl<StringRef> &NewArgv) {
1034 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1035 auto OnEOL = []() {};
1036 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1037 OnEOL);
1038 }
1039
tokenizeConfigFile(StringRef Source,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)1040 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1041 SmallVectorImpl<const char *> &NewArgv,
1042 bool MarkEOLs) {
1043 for (const char *Cur = Source.begin(); Cur != Source.end();) {
1044 SmallString<128> Line;
1045 // Check for comment line.
1046 if (isWhitespace(*Cur)) {
1047 while (Cur != Source.end() && isWhitespace(*Cur))
1048 ++Cur;
1049 continue;
1050 }
1051 if (*Cur == '#') {
1052 while (Cur != Source.end() && *Cur != '\n')
1053 ++Cur;
1054 continue;
1055 }
1056 // Find end of the current line.
1057 const char *Start = Cur;
1058 for (const char *End = Source.end(); Cur != End; ++Cur) {
1059 if (*Cur == '\\') {
1060 if (Cur + 1 != End) {
1061 ++Cur;
1062 if (*Cur == '\n' ||
1063 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1064 Line.append(Start, Cur - 1);
1065 if (*Cur == '\r')
1066 ++Cur;
1067 Start = Cur + 1;
1068 }
1069 }
1070 } else if (*Cur == '\n')
1071 break;
1072 }
1073 // Tokenize line.
1074 Line.append(Start, Cur);
1075 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1076 }
1077 }
1078
1079 // It is called byte order marker but the UTF-8 BOM is actually not affected
1080 // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)1081 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1082 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1083 }
1084
1085 // FName must be an absolute path.
ExpandResponseFile(StringRef FName,StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs,bool RelativeNames,llvm::vfs::FileSystem & FS)1086 static llvm::Error ExpandResponseFile(
1087 StringRef FName, StringSaver &Saver, TokenizerCallback Tokenizer,
1088 SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs, bool RelativeNames,
1089 llvm::vfs::FileSystem &FS) {
1090 assert(sys::path::is_absolute(FName));
1091 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1092 FS.getBufferForFile(FName);
1093 if (!MemBufOrErr)
1094 return llvm::errorCodeToError(MemBufOrErr.getError());
1095 MemoryBuffer &MemBuf = *MemBufOrErr.get();
1096 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1097
1098 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1099 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1100 std::string UTF8Buf;
1101 if (hasUTF16ByteOrderMark(BufRef)) {
1102 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1103 return llvm::createStringError(std::errc::illegal_byte_sequence,
1104 "Could not convert UTF16 to UTF8");
1105 Str = StringRef(UTF8Buf);
1106 }
1107 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1108 // these bytes before parsing.
1109 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1110 else if (hasUTF8ByteOrderMark(BufRef))
1111 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1112
1113 // Tokenize the contents into NewArgv.
1114 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1115
1116 if (!RelativeNames)
1117 return Error::success();
1118 llvm::StringRef BasePath = llvm::sys::path::parent_path(FName);
1119 // If names of nested response files should be resolved relative to including
1120 // file, replace the included response file names with their full paths
1121 // obtained by required resolution.
1122 for (auto &Arg : NewArgv) {
1123 // Skip non-rsp file arguments.
1124 if (!Arg || Arg[0] != '@')
1125 continue;
1126
1127 StringRef FileName(Arg + 1);
1128 // Skip if non-relative.
1129 if (!llvm::sys::path::is_relative(FileName))
1130 continue;
1131
1132 SmallString<128> ResponseFile;
1133 ResponseFile.push_back('@');
1134 ResponseFile.append(BasePath);
1135 llvm::sys::path::append(ResponseFile, FileName);
1136 Arg = Saver.save(ResponseFile.c_str()).data();
1137 }
1138 return Error::success();
1139 }
1140
1141 /// Expand response files on a command line recursively using the given
1142 /// StringSaver and tokenization strategy.
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv,bool MarkEOLs,bool RelativeNames,llvm::vfs::FileSystem & FS,llvm::Optional<llvm::StringRef> CurrentDir)1143 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1144 SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
1145 bool RelativeNames, llvm::vfs::FileSystem &FS,
1146 llvm::Optional<llvm::StringRef> CurrentDir) {
1147 bool AllExpanded = true;
1148 struct ResponseFileRecord {
1149 std::string File;
1150 size_t End;
1151 };
1152
1153 // To detect recursive response files, we maintain a stack of files and the
1154 // position of the last argument in the file. This position is updated
1155 // dynamically as we recursively expand files.
1156 SmallVector<ResponseFileRecord, 3> FileStack;
1157
1158 // Push a dummy entry that represents the initial command line, removing
1159 // the need to check for an empty list.
1160 FileStack.push_back({"", Argv.size()});
1161
1162 // Don't cache Argv.size() because it can change.
1163 for (unsigned I = 0; I != Argv.size();) {
1164 while (I == FileStack.back().End) {
1165 // Passing the end of a file's argument list, so we can remove it from the
1166 // stack.
1167 FileStack.pop_back();
1168 }
1169
1170 const char *Arg = Argv[I];
1171 // Check if it is an EOL marker
1172 if (Arg == nullptr) {
1173 ++I;
1174 continue;
1175 }
1176
1177 if (Arg[0] != '@') {
1178 ++I;
1179 continue;
1180 }
1181
1182 const char *FName = Arg + 1;
1183 // Note that CurrentDir is only used for top-level rsp files, the rest will
1184 // always have an absolute path deduced from the containing file.
1185 SmallString<128> CurrDir;
1186 if (llvm::sys::path::is_relative(FName)) {
1187 if (!CurrentDir)
1188 llvm::sys::fs::current_path(CurrDir);
1189 else
1190 CurrDir = *CurrentDir;
1191 llvm::sys::path::append(CurrDir, FName);
1192 FName = CurrDir.c_str();
1193 }
1194 auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
1195 llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
1196 if (!LHS) {
1197 // TODO: The error should be propagated up the stack.
1198 llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
1199 return false;
1200 }
1201 llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
1202 if (!RHS) {
1203 // TODO: The error should be propagated up the stack.
1204 llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
1205 return false;
1206 }
1207 return LHS->equivalent(*RHS);
1208 };
1209
1210 // Check for recursive response files.
1211 if (std::any_of(FileStack.begin() + 1, FileStack.end(), IsEquivalent)) {
1212 // This file is recursive, so we leave it in the argument stream and
1213 // move on.
1214 AllExpanded = false;
1215 ++I;
1216 continue;
1217 }
1218
1219 // Replace this response file argument with the tokenization of its
1220 // contents. Nested response files are expanded in subsequent iterations.
1221 SmallVector<const char *, 0> ExpandedArgv;
1222 if (llvm::Error Err =
1223 ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
1224 RelativeNames, FS)) {
1225 // We couldn't read this file, so we leave it in the argument stream and
1226 // move on.
1227 // TODO: The error should be propagated up the stack.
1228 llvm::consumeError(std::move(Err));
1229 AllExpanded = false;
1230 ++I;
1231 continue;
1232 }
1233
1234 for (ResponseFileRecord &Record : FileStack) {
1235 // Increase the end of all active records by the number of newly expanded
1236 // arguments, minus the response file itself.
1237 Record.End += ExpandedArgv.size() - 1;
1238 }
1239
1240 FileStack.push_back({FName, I + ExpandedArgv.size()});
1241 Argv.erase(Argv.begin() + I);
1242 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1243 }
1244
1245 // If successful, the top of the file stack will mark the end of the Argv
1246 // stream. A failure here indicates a bug in the stack popping logic above.
1247 // Note that FileStack may have more than one element at this point because we
1248 // don't have a chance to pop the stack when encountering recursive files at
1249 // the end of the stream, so seeing that doesn't indicate a bug.
1250 assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1251 return AllExpanded;
1252 }
1253
expandResponseFiles(int Argc,const char * const * Argv,const char * EnvVar,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv)1254 bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1255 const char *EnvVar, StringSaver &Saver,
1256 SmallVectorImpl<const char *> &NewArgv) {
1257 auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
1258 ? cl::TokenizeWindowsCommandLine
1259 : cl::TokenizeGNUCommandLine;
1260 // The environment variable specifies initial options.
1261 if (EnvVar)
1262 if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1263 Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1264
1265 // Command line options can override the environment variable.
1266 NewArgv.append(Argv + 1, Argv + Argc);
1267 return ExpandResponseFiles(Saver, Tokenize, NewArgv);
1268 }
1269
readConfigFile(StringRef CfgFile,StringSaver & Saver,SmallVectorImpl<const char * > & Argv)1270 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1271 SmallVectorImpl<const char *> &Argv) {
1272 SmallString<128> AbsPath;
1273 if (sys::path::is_relative(CfgFile)) {
1274 llvm::sys::fs::current_path(AbsPath);
1275 llvm::sys::path::append(AbsPath, CfgFile);
1276 CfgFile = AbsPath.str();
1277 }
1278 if (llvm::Error Err =
1279 ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1280 /*MarkEOLs*/ false, /*RelativeNames*/ true,
1281 *llvm::vfs::getRealFileSystem())) {
1282 // TODO: The error should be propagated up the stack.
1283 llvm::consumeError(std::move(Err));
1284 return false;
1285 }
1286 return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1287 /*MarkEOLs*/ false, /*RelativeNames*/ true);
1288 }
1289
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,const char * EnvVar,bool LongOptionsUseDoubleDash)1290 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1291 StringRef Overview, raw_ostream *Errs,
1292 const char *EnvVar,
1293 bool LongOptionsUseDoubleDash) {
1294 SmallVector<const char *, 20> NewArgv;
1295 BumpPtrAllocator A;
1296 StringSaver Saver(A);
1297 NewArgv.push_back(argv[0]);
1298
1299 // Parse options from environment variable.
1300 if (EnvVar) {
1301 if (llvm::Optional<std::string> EnvValue =
1302 sys::Process::GetEnv(StringRef(EnvVar)))
1303 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1304 }
1305
1306 // Append options from command line.
1307 for (int I = 1; I < argc; ++I)
1308 NewArgv.push_back(argv[I]);
1309 int NewArgc = static_cast<int>(NewArgv.size());
1310
1311 // Parse all options.
1312 return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1313 Errs, LongOptionsUseDoubleDash);
1314 }
1315
ResetAllOptionOccurrences()1316 void CommandLineParser::ResetAllOptionOccurrences() {
1317 // So that we can parse different command lines multiple times in succession
1318 // we reset all option values to look like they have never been seen before.
1319 for (auto SC : RegisteredSubCommands) {
1320 for (auto &O : SC->OptionsMap)
1321 O.second->reset();
1322 }
1323 }
1324
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,bool LongOptionsUseDoubleDash)1325 bool CommandLineParser::ParseCommandLineOptions(int argc,
1326 const char *const *argv,
1327 StringRef Overview,
1328 raw_ostream *Errs,
1329 bool LongOptionsUseDoubleDash) {
1330 assert(hasOptions() && "No options specified!");
1331
1332 // Expand response files.
1333 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1334 BumpPtrAllocator A;
1335 StringSaver Saver(A);
1336 ExpandResponseFiles(Saver,
1337 Triple(sys::getProcessTriple()).isOSWindows() ?
1338 cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1339 newArgv);
1340 argv = &newArgv[0];
1341 argc = static_cast<int>(newArgv.size());
1342
1343 // Copy the program name into ProgName, making sure not to overflow it.
1344 ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1345
1346 ProgramOverview = Overview;
1347 bool IgnoreErrors = Errs;
1348 if (!Errs)
1349 Errs = &errs();
1350 bool ErrorParsing = false;
1351
1352 // Check out the positional arguments to collect information about them.
1353 unsigned NumPositionalRequired = 0;
1354
1355 // Determine whether or not there are an unlimited number of positionals
1356 bool HasUnlimitedPositionals = false;
1357
1358 int FirstArg = 1;
1359 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1360 if (argc >= 2 && argv[FirstArg][0] != '-') {
1361 // If the first argument specifies a valid subcommand, start processing
1362 // options from the second argument.
1363 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1364 if (ChosenSubCommand != &*TopLevelSubCommand)
1365 FirstArg = 2;
1366 }
1367 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1368
1369 assert(ChosenSubCommand);
1370 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1371 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1372 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1373 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1374
1375 for (auto O: DefaultOptions) {
1376 addOption(O, true);
1377 }
1378
1379 if (ConsumeAfterOpt) {
1380 assert(PositionalOpts.size() > 0 &&
1381 "Cannot specify cl::ConsumeAfter without a positional argument!");
1382 }
1383 if (!PositionalOpts.empty()) {
1384
1385 // Calculate how many positional values are _required_.
1386 bool UnboundedFound = false;
1387 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1388 Option *Opt = PositionalOpts[i];
1389 if (RequiresValue(Opt))
1390 ++NumPositionalRequired;
1391 else if (ConsumeAfterOpt) {
1392 // ConsumeAfter cannot be combined with "optional" positional options
1393 // unless there is only one positional argument...
1394 if (PositionalOpts.size() > 1) {
1395 if (!IgnoreErrors)
1396 Opt->error("error - this positional option will never be matched, "
1397 "because it does not Require a value, and a "
1398 "cl::ConsumeAfter option is active!");
1399 ErrorParsing = true;
1400 }
1401 } else if (UnboundedFound && !Opt->hasArgStr()) {
1402 // This option does not "require" a value... Make sure this option is
1403 // not specified after an option that eats all extra arguments, or this
1404 // one will never get any!
1405 //
1406 if (!IgnoreErrors)
1407 Opt->error("error - option can never match, because "
1408 "another positional argument will match an "
1409 "unbounded number of values, and this option"
1410 " does not require a value!");
1411 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1412 << "' is all messed up!\n";
1413 *Errs << PositionalOpts.size();
1414 ErrorParsing = true;
1415 }
1416 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1417 }
1418 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1419 }
1420
1421 // PositionalVals - A vector of "positional" arguments we accumulate into
1422 // the process at the end.
1423 //
1424 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1425
1426 // If the program has named positional arguments, and the name has been run
1427 // across, keep track of which positional argument was named. Otherwise put
1428 // the positional args into the PositionalVals list...
1429 Option *ActivePositionalArg = nullptr;
1430
1431 // Loop over all of the arguments... processing them.
1432 bool DashDashFound = false; // Have we read '--'?
1433 for (int i = FirstArg; i < argc; ++i) {
1434 Option *Handler = nullptr;
1435 Option *NearestHandler = nullptr;
1436 std::string NearestHandlerString;
1437 StringRef Value;
1438 StringRef ArgName = "";
1439 bool HaveDoubleDash = false;
1440
1441 // Check to see if this is a positional argument. This argument is
1442 // considered to be positional if it doesn't start with '-', if it is "-"
1443 // itself, or if we have seen "--" already.
1444 //
1445 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1446 // Positional argument!
1447 if (ActivePositionalArg) {
1448 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1449 continue; // We are done!
1450 }
1451
1452 if (!PositionalOpts.empty()) {
1453 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1454
1455 // All of the positional arguments have been fulfulled, give the rest to
1456 // the consume after option... if it's specified...
1457 //
1458 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1459 for (++i; i < argc; ++i)
1460 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1461 break; // Handle outside of the argument processing loop...
1462 }
1463
1464 // Delay processing positional arguments until the end...
1465 continue;
1466 }
1467 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1468 !DashDashFound) {
1469 DashDashFound = true; // This is the mythical "--"?
1470 continue; // Don't try to process it as an argument itself.
1471 } else if (ActivePositionalArg &&
1472 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1473 // If there is a positional argument eating options, check to see if this
1474 // option is another positional argument. If so, treat it as an argument,
1475 // otherwise feed it to the eating positional.
1476 ArgName = StringRef(argv[i] + 1);
1477 // Eat second dash.
1478 if (!ArgName.empty() && ArgName[0] == '-') {
1479 HaveDoubleDash = true;
1480 ArgName = ArgName.substr(1);
1481 }
1482
1483 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1484 LongOptionsUseDoubleDash, HaveDoubleDash);
1485 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1486 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1487 continue; // We are done!
1488 }
1489 } else { // We start with a '-', must be an argument.
1490 ArgName = StringRef(argv[i] + 1);
1491 // Eat second dash.
1492 if (!ArgName.empty() && ArgName[0] == '-') {
1493 HaveDoubleDash = true;
1494 ArgName = ArgName.substr(1);
1495 }
1496
1497 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1498 LongOptionsUseDoubleDash, HaveDoubleDash);
1499
1500 // Check to see if this "option" is really a prefixed or grouped argument.
1501 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1502 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1503 OptionsMap);
1504
1505 // Otherwise, look for the closest available option to report to the user
1506 // in the upcoming error.
1507 if (!Handler && SinkOpts.empty())
1508 NearestHandler =
1509 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1510 }
1511
1512 if (!Handler) {
1513 if (SinkOpts.empty()) {
1514 *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1515 << "'. Try: '" << argv[0] << " --help'\n";
1516
1517 if (NearestHandler) {
1518 // If we know a near match, report it as well.
1519 *Errs << ProgramName << ": Did you mean '"
1520 << PrintArg(NearestHandlerString, 0) << "'?\n";
1521 }
1522
1523 ErrorParsing = true;
1524 } else {
1525 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1526 E = SinkOpts.end();
1527 I != E; ++I)
1528 (*I)->addOccurrence(i, "", StringRef(argv[i]));
1529 }
1530 continue;
1531 }
1532
1533 // If this is a named positional argument, just remember that it is the
1534 // active one...
1535 if (Handler->getFormattingFlag() == cl::Positional) {
1536 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1537 Handler->error("This argument does not take a value.\n"
1538 "\tInstead, it consumes any positional arguments until "
1539 "the next recognized option.", *Errs);
1540 ErrorParsing = true;
1541 }
1542 ActivePositionalArg = Handler;
1543 }
1544 else
1545 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1546 }
1547
1548 // Check and handle positional arguments now...
1549 if (NumPositionalRequired > PositionalVals.size()) {
1550 *Errs << ProgramName
1551 << ": Not enough positional command line arguments specified!\n"
1552 << "Must specify at least " << NumPositionalRequired
1553 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1554 << ": See: " << argv[0] << " --help\n";
1555
1556 ErrorParsing = true;
1557 } else if (!HasUnlimitedPositionals &&
1558 PositionalVals.size() > PositionalOpts.size()) {
1559 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1560 << "Can specify at most " << PositionalOpts.size()
1561 << " positional arguments: See: " << argv[0] << " --help\n";
1562 ErrorParsing = true;
1563
1564 } else if (!ConsumeAfterOpt) {
1565 // Positional args have already been handled if ConsumeAfter is specified.
1566 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1567 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1568 if (RequiresValue(PositionalOpts[i])) {
1569 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1570 PositionalVals[ValNo].second);
1571 ValNo++;
1572 --NumPositionalRequired; // We fulfilled our duty...
1573 }
1574
1575 // If we _can_ give this option more arguments, do so now, as long as we
1576 // do not give it values that others need. 'Done' controls whether the
1577 // option even _WANTS_ any more.
1578 //
1579 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1580 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1581 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1582 case cl::Optional:
1583 Done = true; // Optional arguments want _at most_ one value
1584 LLVM_FALLTHROUGH;
1585 case cl::ZeroOrMore: // Zero or more will take all they can get...
1586 case cl::OneOrMore: // One or more will take all they can get...
1587 ProvidePositionalOption(PositionalOpts[i],
1588 PositionalVals[ValNo].first,
1589 PositionalVals[ValNo].second);
1590 ValNo++;
1591 break;
1592 default:
1593 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1594 "positional argument processing!");
1595 }
1596 }
1597 }
1598 } else {
1599 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1600 unsigned ValNo = 0;
1601 for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
1602 if (RequiresValue(PositionalOpts[J])) {
1603 ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
1604 PositionalVals[ValNo].first,
1605 PositionalVals[ValNo].second);
1606 ValNo++;
1607 }
1608
1609 // Handle the case where there is just one positional option, and it's
1610 // optional. In this case, we want to give JUST THE FIRST option to the
1611 // positional option and keep the rest for the consume after. The above
1612 // loop would have assigned no values to positional options in this case.
1613 //
1614 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1615 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1616 PositionalVals[ValNo].first,
1617 PositionalVals[ValNo].second);
1618 ValNo++;
1619 }
1620
1621 // Handle over all of the rest of the arguments to the
1622 // cl::ConsumeAfter command line option...
1623 for (; ValNo != PositionalVals.size(); ++ValNo)
1624 ErrorParsing |=
1625 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1626 PositionalVals[ValNo].second);
1627 }
1628
1629 // Loop over args and make sure all required args are specified!
1630 for (const auto &Opt : OptionsMap) {
1631 switch (Opt.second->getNumOccurrencesFlag()) {
1632 case Required:
1633 case OneOrMore:
1634 if (Opt.second->getNumOccurrences() == 0) {
1635 Opt.second->error("must be specified at least once!");
1636 ErrorParsing = true;
1637 }
1638 LLVM_FALLTHROUGH;
1639 default:
1640 break;
1641 }
1642 }
1643
1644 // Now that we know if -debug is specified, we can use it.
1645 // Note that if ReadResponseFiles == true, this must be done before the
1646 // memory allocated for the expanded command line is free()d below.
1647 LLVM_DEBUG(dbgs() << "Args: ";
1648 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1649 dbgs() << '\n';);
1650
1651 // Free all of the memory allocated to the map. Command line options may only
1652 // be processed once!
1653 MoreHelp.clear();
1654
1655 // If we had an error processing our arguments, don't let the program execute
1656 if (ErrorParsing) {
1657 if (!IgnoreErrors)
1658 exit(1);
1659 return false;
1660 }
1661 return true;
1662 }
1663
1664 //===----------------------------------------------------------------------===//
1665 // Option Base class implementation
1666 //
1667
error(const Twine & Message,StringRef ArgName,raw_ostream & Errs)1668 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1669 if (!ArgName.data())
1670 ArgName = ArgStr;
1671 if (ArgName.empty())
1672 Errs << HelpStr; // Be nice for positional arguments
1673 else
1674 Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1675
1676 Errs << " option: " << Message << "\n";
1677 return true;
1678 }
1679
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)1680 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1681 bool MultiArg) {
1682 if (!MultiArg)
1683 NumOccurrences++; // Increment the number of times we have been seen
1684
1685 switch (getNumOccurrencesFlag()) {
1686 case Optional:
1687 if (NumOccurrences > 1)
1688 return error("may only occur zero or one times!", ArgName);
1689 break;
1690 case Required:
1691 if (NumOccurrences > 1)
1692 return error("must occur exactly one time!", ArgName);
1693 LLVM_FALLTHROUGH;
1694 case OneOrMore:
1695 case ZeroOrMore:
1696 case ConsumeAfter:
1697 break;
1698 }
1699
1700 return handleOccurrence(pos, ArgName, Value);
1701 }
1702
1703 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1704 // has been specified yet.
1705 //
getValueStr(const Option & O,StringRef DefaultMsg)1706 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1707 if (O.ValueStr.empty())
1708 return DefaultMsg;
1709 return O.ValueStr;
1710 }
1711
1712 //===----------------------------------------------------------------------===//
1713 // cl::alias class implementation
1714 //
1715
1716 // Return the width of the option tag for printing...
getOptionWidth() const1717 size_t alias::getOptionWidth() const {
1718 return argPlusPrefixesSize(ArgStr);
1719 }
1720
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)1721 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1722 size_t FirstLineIndentedBy) {
1723 assert(Indent >= FirstLineIndentedBy);
1724 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1725 outs().indent(Indent - FirstLineIndentedBy)
1726 << ArgHelpPrefix << Split.first << "\n";
1727 while (!Split.second.empty()) {
1728 Split = Split.second.split('\n');
1729 outs().indent(Indent) << Split.first << "\n";
1730 }
1731 }
1732
1733 // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1734 void alias::printOptionInfo(size_t GlobalWidth) const {
1735 outs() << PrintArg(ArgStr);
1736 printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1737 }
1738
1739 //===----------------------------------------------------------------------===//
1740 // Parser Implementation code...
1741 //
1742
1743 // basic_parser implementation
1744 //
1745
1746 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1747 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1748 size_t Len = argPlusPrefixesSize(O.ArgStr);
1749 auto ValName = getValueName();
1750 if (!ValName.empty()) {
1751 size_t FormattingLen = 3;
1752 if (O.getMiscFlags() & PositionalEatsArgs)
1753 FormattingLen = 6;
1754 Len += getValueStr(O, ValName).size() + FormattingLen;
1755 }
1756
1757 return Len;
1758 }
1759
1760 // printOptionInfo - Print out information about this option. The
1761 // to-be-maintained width is specified.
1762 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1763 void basic_parser_impl::printOptionInfo(const Option &O,
1764 size_t GlobalWidth) const {
1765 outs() << PrintArg(O.ArgStr);
1766
1767 auto ValName = getValueName();
1768 if (!ValName.empty()) {
1769 if (O.getMiscFlags() & PositionalEatsArgs) {
1770 outs() << " <" << getValueStr(O, ValName) << ">...";
1771 } else if (O.getValueExpectedFlag() == ValueOptional)
1772 outs() << "[=<" << getValueStr(O, ValName) << ">]";
1773 else
1774 outs() << "=<" << getValueStr(O, ValName) << '>';
1775 }
1776
1777 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1778 }
1779
printOptionName(const Option & O,size_t GlobalWidth) const1780 void basic_parser_impl::printOptionName(const Option &O,
1781 size_t GlobalWidth) const {
1782 outs() << PrintArg(O.ArgStr);
1783 outs().indent(GlobalWidth - O.ArgStr.size());
1784 }
1785
1786 // parser<bool> implementation
1787 //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)1788 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1789 bool &Value) {
1790 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1791 Arg == "1") {
1792 Value = true;
1793 return false;
1794 }
1795
1796 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1797 Value = false;
1798 return false;
1799 }
1800 return O.error("'" + Arg +
1801 "' is invalid value for boolean argument! Try 0 or 1");
1802 }
1803
1804 // parser<boolOrDefault> implementation
1805 //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)1806 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1807 boolOrDefault &Value) {
1808 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1809 Arg == "1") {
1810 Value = BOU_TRUE;
1811 return false;
1812 }
1813 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1814 Value = BOU_FALSE;
1815 return false;
1816 }
1817
1818 return O.error("'" + Arg +
1819 "' is invalid value for boolean argument! Try 0 or 1");
1820 }
1821
1822 // parser<int> implementation
1823 //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)1824 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1825 int &Value) {
1826 if (Arg.getAsInteger(0, Value))
1827 return O.error("'" + Arg + "' value invalid for integer argument!");
1828 return false;
1829 }
1830
1831 // parser<long> implementation
1832 //
parse(Option & O,StringRef ArgName,StringRef Arg,long & Value)1833 bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1834 long &Value) {
1835 if (Arg.getAsInteger(0, Value))
1836 return O.error("'" + Arg + "' value invalid for long argument!");
1837 return false;
1838 }
1839
1840 // parser<long long> implementation
1841 //
parse(Option & O,StringRef ArgName,StringRef Arg,long long & Value)1842 bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1843 long long &Value) {
1844 if (Arg.getAsInteger(0, Value))
1845 return O.error("'" + Arg + "' value invalid for llong argument!");
1846 return false;
1847 }
1848
1849 // parser<unsigned> implementation
1850 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)1851 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1852 unsigned &Value) {
1853
1854 if (Arg.getAsInteger(0, Value))
1855 return O.error("'" + Arg + "' value invalid for uint argument!");
1856 return false;
1857 }
1858
1859 // parser<unsigned long> implementation
1860 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long & Value)1861 bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
1862 unsigned long &Value) {
1863
1864 if (Arg.getAsInteger(0, Value))
1865 return O.error("'" + Arg + "' value invalid for ulong argument!");
1866 return false;
1867 }
1868
1869 // parser<unsigned long long> implementation
1870 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)1871 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1872 StringRef Arg,
1873 unsigned long long &Value) {
1874
1875 if (Arg.getAsInteger(0, Value))
1876 return O.error("'" + Arg + "' value invalid for ullong argument!");
1877 return false;
1878 }
1879
1880 // parser<double>/parser<float> implementation
1881 //
parseDouble(Option & O,StringRef Arg,double & Value)1882 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1883 if (to_float(Arg, Value))
1884 return false;
1885 return O.error("'" + Arg + "' value invalid for floating point argument!");
1886 }
1887
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)1888 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1889 double &Val) {
1890 return parseDouble(O, Arg, Val);
1891 }
1892
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)1893 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1894 float &Val) {
1895 double dVal;
1896 if (parseDouble(O, Arg, dVal))
1897 return true;
1898 Val = (float)dVal;
1899 return false;
1900 }
1901
1902 // generic_parser_base implementation
1903 //
1904
1905 // findOption - Return the option number corresponding to the specified
1906 // argument string. If the option is not found, getNumOptions() is returned.
1907 //
findOption(StringRef Name)1908 unsigned generic_parser_base::findOption(StringRef Name) {
1909 unsigned e = getNumOptions();
1910
1911 for (unsigned i = 0; i != e; ++i) {
1912 if (getOption(i) == Name)
1913 return i;
1914 }
1915 return e;
1916 }
1917
1918 static StringRef EqValue = "=<value>";
1919 static StringRef EmptyOption = "<empty>";
1920 static StringRef OptionPrefix = " =";
1921 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1922
shouldPrintOption(StringRef Name,StringRef Description,const Option & O)1923 static bool shouldPrintOption(StringRef Name, StringRef Description,
1924 const Option &O) {
1925 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1926 !Description.empty();
1927 }
1928
1929 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1930 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1931 if (O.hasArgStr()) {
1932 size_t Size =
1933 argPlusPrefixesSize(O.ArgStr) + EqValue.size();
1934 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1935 StringRef Name = getOption(i);
1936 if (!shouldPrintOption(Name, getDescription(i), O))
1937 continue;
1938 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1939 Size = std::max(Size, NameSize + OptionPrefixesSize);
1940 }
1941 return Size;
1942 } else {
1943 size_t BaseSize = 0;
1944 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1945 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1946 return BaseSize;
1947 }
1948 }
1949
1950 // printOptionInfo - Print out information about this option. The
1951 // to-be-maintained width is specified.
1952 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1953 void generic_parser_base::printOptionInfo(const Option &O,
1954 size_t GlobalWidth) const {
1955 if (O.hasArgStr()) {
1956 // When the value is optional, first print a line just describing the
1957 // option without values.
1958 if (O.getValueExpectedFlag() == ValueOptional) {
1959 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1960 if (getOption(i).empty()) {
1961 outs() << PrintArg(O.ArgStr);
1962 Option::printHelpStr(O.HelpStr, GlobalWidth,
1963 argPlusPrefixesSize(O.ArgStr));
1964 break;
1965 }
1966 }
1967 }
1968
1969 outs() << PrintArg(O.ArgStr) << EqValue;
1970 Option::printHelpStr(O.HelpStr, GlobalWidth,
1971 EqValue.size() +
1972 argPlusPrefixesSize(O.ArgStr));
1973 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1974 StringRef OptionName = getOption(i);
1975 StringRef Description = getDescription(i);
1976 if (!shouldPrintOption(OptionName, Description, O))
1977 continue;
1978 assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1979 size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1980 outs() << OptionPrefix << OptionName;
1981 if (OptionName.empty()) {
1982 outs() << EmptyOption;
1983 assert(NumSpaces >= EmptyOption.size());
1984 NumSpaces -= EmptyOption.size();
1985 }
1986 if (!Description.empty())
1987 outs().indent(NumSpaces) << ArgHelpPrefix << " " << Description;
1988 outs() << '\n';
1989 }
1990 } else {
1991 if (!O.HelpStr.empty())
1992 outs() << " " << O.HelpStr << '\n';
1993 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1994 StringRef Option = getOption(i);
1995 outs() << " " << PrintArg(Option);
1996 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1997 }
1998 }
1999 }
2000
2001 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2002
2003 // printGenericOptionDiff - Print the value of this option and it's default.
2004 //
2005 // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const2006 void generic_parser_base::printGenericOptionDiff(
2007 const Option &O, const GenericOptionValue &Value,
2008 const GenericOptionValue &Default, size_t GlobalWidth) const {
2009 outs() << " " << PrintArg(O.ArgStr);
2010 outs().indent(GlobalWidth - O.ArgStr.size());
2011
2012 unsigned NumOpts = getNumOptions();
2013 for (unsigned i = 0; i != NumOpts; ++i) {
2014 if (Value.compare(getOptionValue(i)))
2015 continue;
2016
2017 outs() << "= " << getOption(i);
2018 size_t L = getOption(i).size();
2019 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2020 outs().indent(NumSpaces) << " (default: ";
2021 for (unsigned j = 0; j != NumOpts; ++j) {
2022 if (Default.compare(getOptionValue(j)))
2023 continue;
2024 outs() << getOption(j);
2025 break;
2026 }
2027 outs() << ")\n";
2028 return;
2029 }
2030 outs() << "= *unknown option value*\n";
2031 }
2032
2033 // printOptionDiff - Specializations for printing basic value types.
2034 //
2035 #define PRINT_OPT_DIFF(T) \
2036 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2037 size_t GlobalWidth) const { \
2038 printOptionName(O, GlobalWidth); \
2039 std::string Str; \
2040 { \
2041 raw_string_ostream SS(Str); \
2042 SS << V; \
2043 } \
2044 outs() << "= " << Str; \
2045 size_t NumSpaces = \
2046 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2047 outs().indent(NumSpaces) << " (default: "; \
2048 if (D.hasValue()) \
2049 outs() << D.getValue(); \
2050 else \
2051 outs() << "*no default*"; \
2052 outs() << ")\n"; \
2053 }
2054
2055 PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)2056 PRINT_OPT_DIFF(boolOrDefault)
2057 PRINT_OPT_DIFF(int)
2058 PRINT_OPT_DIFF(long)
2059 PRINT_OPT_DIFF(long long)
2060 PRINT_OPT_DIFF(unsigned)
2061 PRINT_OPT_DIFF(unsigned long)
2062 PRINT_OPT_DIFF(unsigned long long)
2063 PRINT_OPT_DIFF(double)
2064 PRINT_OPT_DIFF(float)
2065 PRINT_OPT_DIFF(char)
2066
2067 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2068 const OptionValue<std::string> &D,
2069 size_t GlobalWidth) const {
2070 printOptionName(O, GlobalWidth);
2071 outs() << "= " << V;
2072 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2073 outs().indent(NumSpaces) << " (default: ";
2074 if (D.hasValue())
2075 outs() << D.getValue();
2076 else
2077 outs() << "*no default*";
2078 outs() << ")\n";
2079 }
2080
2081 // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const2082 void basic_parser_impl::printOptionNoValue(const Option &O,
2083 size_t GlobalWidth) const {
2084 printOptionName(O, GlobalWidth);
2085 outs() << "= *cannot print option value*\n";
2086 }
2087
2088 //===----------------------------------------------------------------------===//
2089 // -help and -help-hidden option implementation
2090 //
2091
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)2092 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2093 const std::pair<const char *, Option *> *RHS) {
2094 return strcmp(LHS->first, RHS->first);
2095 }
2096
SubNameCompare(const std::pair<const char *,SubCommand * > * LHS,const std::pair<const char *,SubCommand * > * RHS)2097 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2098 const std::pair<const char *, SubCommand *> *RHS) {
2099 return strcmp(LHS->first, RHS->first);
2100 }
2101
2102 // 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)2103 static void sortOpts(StringMap<Option *> &OptMap,
2104 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2105 bool ShowHidden) {
2106 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2107
2108 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
2109 I != E; ++I) {
2110 // Ignore really-hidden options.
2111 if (I->second->getOptionHiddenFlag() == ReallyHidden)
2112 continue;
2113
2114 // Unless showhidden is set, ignore hidden flags.
2115 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2116 continue;
2117
2118 // If we've already seen this option, don't add it to the list again.
2119 if (!OptionSet.insert(I->second).second)
2120 continue;
2121
2122 Opts.push_back(
2123 std::pair<const char *, Option *>(I->getKey().data(), I->second));
2124 }
2125
2126 // Sort the options list alphabetically.
2127 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2128 }
2129
2130 static void
sortSubCommands(const SmallPtrSetImpl<SubCommand * > & SubMap,SmallVectorImpl<std::pair<const char *,SubCommand * >> & Subs)2131 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2132 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2133 for (auto *S : SubMap) {
2134 if (S->getName().empty())
2135 continue;
2136 Subs.push_back(std::make_pair(S->getName().data(), S));
2137 }
2138 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2139 }
2140
2141 namespace {
2142
2143 class HelpPrinter {
2144 protected:
2145 const bool ShowHidden;
2146 typedef SmallVector<std::pair<const char *, Option *>, 128>
2147 StrOptionPairVector;
2148 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
2149 StrSubCommandPairVector;
2150 // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)2151 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2152 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2153 Opts[i].second->printOptionInfo(MaxArgLen);
2154 }
2155
printSubCommands(StrSubCommandPairVector & Subs,size_t MaxSubLen)2156 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2157 for (const auto &S : Subs) {
2158 outs() << " " << S.first;
2159 if (!S.second->getDescription().empty()) {
2160 outs().indent(MaxSubLen - strlen(S.first));
2161 outs() << " - " << S.second->getDescription();
2162 }
2163 outs() << "\n";
2164 }
2165 }
2166
2167 public:
HelpPrinter(bool showHidden)2168 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
~HelpPrinter()2169 virtual ~HelpPrinter() {}
2170
2171 // Invoke the printer.
operator =(bool Value)2172 void operator=(bool Value) {
2173 if (!Value)
2174 return;
2175 printHelp();
2176
2177 // Halt the program since help information was printed
2178 exit(0);
2179 }
2180
printHelp()2181 void printHelp() {
2182 SubCommand *Sub = GlobalParser->getActiveSubCommand();
2183 auto &OptionsMap = Sub->OptionsMap;
2184 auto &PositionalOpts = Sub->PositionalOpts;
2185 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2186
2187 StrOptionPairVector Opts;
2188 sortOpts(OptionsMap, Opts, ShowHidden);
2189
2190 StrSubCommandPairVector Subs;
2191 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2192
2193 if (!GlobalParser->ProgramOverview.empty())
2194 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2195
2196 if (Sub == &*TopLevelSubCommand) {
2197 outs() << "USAGE: " << GlobalParser->ProgramName;
2198 if (Subs.size() > 2)
2199 outs() << " [subcommand]";
2200 outs() << " [options]";
2201 } else {
2202 if (!Sub->getDescription().empty()) {
2203 outs() << "SUBCOMMAND '" << Sub->getName()
2204 << "': " << Sub->getDescription() << "\n\n";
2205 }
2206 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2207 << " [options]";
2208 }
2209
2210 for (auto Opt : PositionalOpts) {
2211 if (Opt->hasArgStr())
2212 outs() << " --" << Opt->ArgStr;
2213 outs() << " " << Opt->HelpStr;
2214 }
2215
2216 // Print the consume after option info if it exists...
2217 if (ConsumeAfterOpt)
2218 outs() << " " << ConsumeAfterOpt->HelpStr;
2219
2220 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
2221 // Compute the maximum subcommand length...
2222 size_t MaxSubLen = 0;
2223 for (size_t i = 0, e = Subs.size(); i != e; ++i)
2224 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
2225
2226 outs() << "\n\n";
2227 outs() << "SUBCOMMANDS:\n\n";
2228 printSubCommands(Subs, MaxSubLen);
2229 outs() << "\n";
2230 outs() << " Type \"" << GlobalParser->ProgramName
2231 << " <subcommand> --help\" to get more help on a specific "
2232 "subcommand";
2233 }
2234
2235 outs() << "\n\n";
2236
2237 // Compute the maximum argument length...
2238 size_t MaxArgLen = 0;
2239 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2240 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2241
2242 outs() << "OPTIONS:\n";
2243 printOptions(Opts, MaxArgLen);
2244
2245 // Print any extra help the user has declared.
2246 for (auto I : GlobalParser->MoreHelp)
2247 outs() << I;
2248 GlobalParser->MoreHelp.clear();
2249 }
2250 };
2251
2252 class CategorizedHelpPrinter : public HelpPrinter {
2253 public:
CategorizedHelpPrinter(bool showHidden)2254 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2255
2256 // Helper function for printOptions().
2257 // It shall return a negative value if A's name should be lexicographically
2258 // ordered before B's name. It returns a value greater than zero if B's name
2259 // should be ordered before A's name, and it returns 0 otherwise.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)2260 static int OptionCategoryCompare(OptionCategory *const *A,
2261 OptionCategory *const *B) {
2262 return (*A)->getName().compare((*B)->getName());
2263 }
2264
2265 // Make sure we inherit our base class's operator=()
2266 using HelpPrinter::operator=;
2267
2268 protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)2269 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2270 std::vector<OptionCategory *> SortedCategories;
2271 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2272
2273 // Collect registered option categories into vector in preparation for
2274 // sorting.
2275 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2276 E = GlobalParser->RegisteredOptionCategories.end();
2277 I != E; ++I) {
2278 SortedCategories.push_back(*I);
2279 }
2280
2281 // Sort the different option categories alphabetically.
2282 assert(SortedCategories.size() > 0 && "No option categories registered!");
2283 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2284 OptionCategoryCompare);
2285
2286 // Create map to empty vectors.
2287 for (std::vector<OptionCategory *>::const_iterator
2288 I = SortedCategories.begin(),
2289 E = SortedCategories.end();
2290 I != E; ++I)
2291 CategorizedOptions[*I] = std::vector<Option *>();
2292
2293 // Walk through pre-sorted options and assign into categories.
2294 // Because the options are already alphabetically sorted the
2295 // options within categories will also be alphabetically sorted.
2296 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2297 Option *Opt = Opts[I].second;
2298 for (auto &Cat : Opt->Categories) {
2299 assert(CategorizedOptions.count(Cat) > 0 &&
2300 "Option has an unregistered category");
2301 CategorizedOptions[Cat].push_back(Opt);
2302 }
2303 }
2304
2305 // Now do printing.
2306 for (std::vector<OptionCategory *>::const_iterator
2307 Category = SortedCategories.begin(),
2308 E = SortedCategories.end();
2309 Category != E; ++Category) {
2310 // Hide empty categories for --help, but show for --help-hidden.
2311 const auto &CategoryOptions = CategorizedOptions[*Category];
2312 bool IsEmptyCategory = CategoryOptions.empty();
2313 if (!ShowHidden && IsEmptyCategory)
2314 continue;
2315
2316 // Print category information.
2317 outs() << "\n";
2318 outs() << (*Category)->getName() << ":\n";
2319
2320 // Check if description is set.
2321 if (!(*Category)->getDescription().empty())
2322 outs() << (*Category)->getDescription() << "\n\n";
2323 else
2324 outs() << "\n";
2325
2326 // When using --help-hidden explicitly state if the category has no
2327 // options associated with it.
2328 if (IsEmptyCategory) {
2329 outs() << " This option category has no options.\n";
2330 continue;
2331 }
2332 // Loop over the options in the category and print.
2333 for (const Option *Opt : CategoryOptions)
2334 Opt->printOptionInfo(MaxArgLen);
2335 }
2336 }
2337 };
2338
2339 // This wraps the Uncategorizing and Categorizing printers and decides
2340 // at run time which should be invoked.
2341 class HelpPrinterWrapper {
2342 private:
2343 HelpPrinter &UncategorizedPrinter;
2344 CategorizedHelpPrinter &CategorizedPrinter;
2345
2346 public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)2347 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2348 CategorizedHelpPrinter &CategorizedPrinter)
2349 : UncategorizedPrinter(UncategorizedPrinter),
2350 CategorizedPrinter(CategorizedPrinter) {}
2351
2352 // Invoke the printer.
2353 void operator=(bool Value);
2354 };
2355
2356 } // End anonymous namespace
2357
2358 // Declare the four HelpPrinter instances that are used to print out help, or
2359 // help-hidden as an uncategorized list or in categories.
2360 static HelpPrinter UncategorizedNormalPrinter(false);
2361 static HelpPrinter UncategorizedHiddenPrinter(true);
2362 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2363 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2364
2365 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2366 // a categorizing help printer
2367 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2368 CategorizedNormalPrinter);
2369 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2370 CategorizedHiddenPrinter);
2371
2372 // Define a category for generic options that all tools should have.
2373 static cl::OptionCategory GenericCategory("Generic Options");
2374
2375 // Define uncategorized help printers.
2376 // --help-list is hidden by default because if Option categories are being used
2377 // then --help behaves the same as --help-list.
2378 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2379 "help-list",
2380 cl::desc("Display list of available options (--help-list-hidden for more)"),
2381 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2382 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2383
2384 static cl::opt<HelpPrinter, true, parser<bool>>
2385 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2386 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2387 cl::ValueDisallowed, cl::cat(GenericCategory),
2388 cl::sub(*AllSubCommands));
2389
2390 // Define uncategorized/categorized help printers. These printers change their
2391 // behaviour at runtime depending on whether one or more Option categories have
2392 // been declared.
2393 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2394 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
2395 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2396 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2397
2398 static cl::alias HOpA("h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2399 cl::DefaultOption);
2400
2401 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2402 HHOp("help-hidden", cl::desc("Display all available options"),
2403 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2404 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2405
2406 static cl::opt<bool> PrintOptions(
2407 "print-options",
2408 cl::desc("Print non-default options after command line parsing"),
2409 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2410 cl::sub(*AllSubCommands));
2411
2412 static cl::opt<bool> PrintAllOptions(
2413 "print-all-options",
2414 cl::desc("Print all option values after command line parsing"), cl::Hidden,
2415 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2416
operator =(bool Value)2417 void HelpPrinterWrapper::operator=(bool Value) {
2418 if (!Value)
2419 return;
2420
2421 // Decide which printer to invoke. If more than one option category is
2422 // registered then it is useful to show the categorized help instead of
2423 // uncategorized help.
2424 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2425 // unhide --help-list option so user can have uncategorized output if they
2426 // want it.
2427 HLOp.setHiddenFlag(NotHidden);
2428
2429 CategorizedPrinter = true; // Invoke categorized printer
2430 } else
2431 UncategorizedPrinter = true; // Invoke uncategorized printer
2432 }
2433
2434 // Print the value of each option.
PrintOptionValues()2435 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2436
printOptionValues()2437 void CommandLineParser::printOptionValues() {
2438 if (!PrintOptions && !PrintAllOptions)
2439 return;
2440
2441 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2442 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2443
2444 // Compute the maximum argument length...
2445 size_t MaxArgLen = 0;
2446 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2447 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2448
2449 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2450 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2451 }
2452
2453 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2454
2455 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2456
2457 #if defined(__GNUC__)
2458 // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2459 // enabled.
2460 # if defined(__OPTIMIZE__)
2461 # define LLVM_IS_DEBUG_BUILD 0
2462 # else
2463 # define LLVM_IS_DEBUG_BUILD 1
2464 # endif
2465 #elif defined(_MSC_VER)
2466 // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2467 // Use _DEBUG instead. This macro actually corresponds to the choice between
2468 // debug and release CRTs, but it is a reasonable proxy.
2469 # if defined(_DEBUG)
2470 # define LLVM_IS_DEBUG_BUILD 1
2471 # else
2472 # define LLVM_IS_DEBUG_BUILD 0
2473 # endif
2474 #else
2475 // Otherwise, for an unknown compiler, assume this is an optimized build.
2476 # define LLVM_IS_DEBUG_BUILD 0
2477 #endif
2478
2479 namespace {
2480 class VersionPrinter {
2481 public:
print()2482 void print() {
2483 raw_ostream &OS = outs();
2484 #ifdef PACKAGE_VENDOR
2485 OS << PACKAGE_VENDOR << " ";
2486 #else
2487 OS << "LLVM (http://llvm.org/):\n ";
2488 #endif
2489 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2490 #ifdef LLVM_VERSION_INFO
2491 OS << " " << LLVM_VERSION_INFO;
2492 #endif
2493 OS << "\n ";
2494 #if LLVM_IS_DEBUG_BUILD
2495 OS << "DEBUG build";
2496 #else
2497 OS << "Optimized build";
2498 #endif
2499 #ifndef NDEBUG
2500 OS << " with assertions";
2501 #endif
2502 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2503 std::string CPU = std::string(sys::getHostCPUName());
2504 if (CPU == "generic")
2505 CPU = "(unknown)";
2506 OS << ".\n"
2507 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
2508 << " Host CPU: " << CPU;
2509 #endif
2510 OS << '\n';
2511 }
operator =(bool OptionWasSpecified)2512 void operator=(bool OptionWasSpecified) {
2513 if (!OptionWasSpecified)
2514 return;
2515
2516 if (OverrideVersionPrinter != nullptr) {
2517 OverrideVersionPrinter(outs());
2518 exit(0);
2519 }
2520 print();
2521
2522 // Iterate over any registered extra printers and call them to add further
2523 // information.
2524 if (ExtraVersionPrinters != nullptr) {
2525 outs() << '\n';
2526 for (const auto &I : *ExtraVersionPrinters)
2527 I(outs());
2528 }
2529
2530 exit(0);
2531 }
2532 };
2533 } // End anonymous namespace
2534
2535 // Define the --version option that prints out the LLVM version for the tool
2536 static VersionPrinter VersionPrinterInstance;
2537
2538 static cl::opt<VersionPrinter, true, parser<bool>>
2539 VersOp("version", cl::desc("Display the version of this program"),
2540 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2541 cl::cat(GenericCategory));
2542
2543 // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)2544 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2545 if (!Hidden && !Categorized)
2546 UncategorizedNormalPrinter.printHelp();
2547 else if (!Hidden && Categorized)
2548 CategorizedNormalPrinter.printHelp();
2549 else if (Hidden && !Categorized)
2550 UncategorizedHiddenPrinter.printHelp();
2551 else
2552 CategorizedHiddenPrinter.printHelp();
2553 }
2554
2555 /// Utility function for printing version number.
PrintVersionMessage()2556 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2557
SetVersionPrinter(VersionPrinterTy func)2558 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2559
AddExtraVersionPrinter(VersionPrinterTy func)2560 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2561 if (!ExtraVersionPrinters)
2562 ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2563
2564 ExtraVersionPrinters->push_back(func);
2565 }
2566
getRegisteredOptions(SubCommand & Sub)2567 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2568 auto &Subs = GlobalParser->RegisteredSubCommands;
2569 (void)Subs;
2570 assert(is_contained(Subs, &Sub));
2571 return Sub.OptionsMap;
2572 }
2573
2574 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()2575 cl::getRegisteredSubcommands() {
2576 return GlobalParser->getRegisteredSubcommands();
2577 }
2578
HideUnrelatedOptions(cl::OptionCategory & Category,SubCommand & Sub)2579 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2580 for (auto &I : Sub.OptionsMap) {
2581 for (auto &Cat : I.second->Categories) {
2582 if (Cat != &Category &&
2583 Cat != &GenericCategory)
2584 I.second->setHiddenFlag(cl::ReallyHidden);
2585 }
2586 }
2587 }
2588
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories,SubCommand & Sub)2589 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2590 SubCommand &Sub) {
2591 for (auto &I : Sub.OptionsMap) {
2592 for (auto &Cat : I.second->Categories) {
2593 if (find(Categories, Cat) == Categories.end() && Cat != &GenericCategory)
2594 I.second->setHiddenFlag(cl::ReallyHidden);
2595 }
2596 }
2597 }
2598
ResetCommandLineParser()2599 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
ResetAllOptionOccurrences()2600 void cl::ResetAllOptionOccurrences() {
2601 GlobalParser->ResetAllOptionOccurrences();
2602 }
2603
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)2604 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2605 const char *Overview) {
2606 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2607 &llvm::nulls());
2608 }
2609