Bug Summary

File:src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/lib/Support/CommandLine.cpp
Warning:line 665, column 25
Array access (from variable 'argv') results in a null pointer dereference

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CommandLine.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVMSupport/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/../include -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/obj -I /usr/src/gnu/usr.bin/clang/libLLVMSupport/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVMSupport/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/lib/Support/CommandLine.cpp

/usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/lib/Support/CommandLine.cpp

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

/usr/src/gnu/usr.bin/clang/libLLVMSupport/../../../llvm/llvm/include/llvm/Support/CommandLine.h

1//===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
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 should
14// read the library documentation located in docs/CommandLine.html or looks at
15// the many example usages in tools/*/*.cpp
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_SUPPORT_COMMANDLINE_H
20#define LLVM_SUPPORT_COMMANDLINE_H
21
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/ADT/iterator_range.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/ManagedStatic.h"
34#include "llvm/Support/raw_ostream.h"
35#include <cassert>
36#include <climits>
37#include <cstddef>
38#include <functional>
39#include <initializer_list>
40#include <string>
41#include <type_traits>
42#include <vector>
43
44namespace llvm {
45
46namespace vfs {
47class FileSystem;
48}
49
50class StringSaver;
51
52/// cl Namespace - This namespace contains all of the command line option
53/// processing machinery. It is intentionally a short name to make qualified
54/// usage concise.
55namespace cl {
56
57//===----------------------------------------------------------------------===//
58// ParseCommandLineOptions - Command line option processing entry point.
59//
60// Returns true on success. Otherwise, this will print the error message to
61// stderr and exit if \p Errs is not set (nullptr by default), or print the
62// error message to \p Errs and return false if \p Errs is provided.
63//
64// If EnvVar is not nullptr, command-line options are also parsed from the
65// environment variable named by EnvVar. Precedence is given to occurrences
66// from argv. This precedence is currently implemented by parsing argv after
67// the environment variable, so it is only implemented correctly for options
68// that give precedence to later occurrences. If your program supports options
69// that give precedence to earlier occurrences, you will need to extend this
70// function to support it correctly.
71bool ParseCommandLineOptions(int argc, const char *const *argv,
72 StringRef Overview = "",
73 raw_ostream *Errs = nullptr,
74 const char *EnvVar = nullptr,
75 bool LongOptionsUseDoubleDash = false);
76
77// Function pointer type for printing version information.
78using VersionPrinterTy = std::function<void(raw_ostream &)>;
79
80///===---------------------------------------------------------------------===//
81/// SetVersionPrinter - Override the default (LLVM specific) version printer
82/// used to print out the version when --version is given
83/// on the command line. This allows other systems using the
84/// CommandLine utilities to print their own version string.
85void SetVersionPrinter(VersionPrinterTy func);
86
87///===---------------------------------------------------------------------===//
88/// AddExtraVersionPrinter - Add an extra printer to use in addition to the
89/// default one. This can be called multiple times,
90/// and each time it adds a new function to the list
91/// which will be called after the basic LLVM version
92/// printing is complete. Each can then add additional
93/// information specific to the tool.
94void AddExtraVersionPrinter(VersionPrinterTy func);
95
96// PrintOptionValues - Print option values.
97// With -print-options print the difference between option values and defaults.
98// With -print-all-options print all option values.
99// (Currently not perfect, but best-effort.)
100void PrintOptionValues();
101
102// Forward declaration - AddLiteralOption needs to be up here to make gcc happy.
103class Option;
104
105/// Adds a new option for parsing and provides the option it refers to.
106///
107/// \param O pointer to the option
108/// \param Name the string name for the option to handle during parsing
109///
110/// Literal options are used by some parsers to register special option values.
111/// This is how the PassNameParser registers pass names for opt.
112void AddLiteralOption(Option &O, StringRef Name);
113
114//===----------------------------------------------------------------------===//
115// Flags permitted to be passed to command line arguments
116//
117
118enum NumOccurrencesFlag { // Flags for the number of occurrences allowed
119 Optional = 0x00, // Zero or One occurrence
120 ZeroOrMore = 0x01, // Zero or more occurrences allowed
121 Required = 0x02, // One occurrence required
122 OneOrMore = 0x03, // One or more occurrences required
123
124 // ConsumeAfter - Indicates that this option is fed anything that follows the
125 // last positional argument required by the application (it is an error if
126 // there are zero positional arguments, and a ConsumeAfter option is used).
127 // Thus, for example, all arguments to LLI are processed until a filename is
128 // found. Once a filename is found, all of the succeeding arguments are
129 // passed, unprocessed, to the ConsumeAfter option.
130 //
131 ConsumeAfter = 0x04
132};
133
134enum ValueExpected { // Is a value required for the option?
135 // zero reserved for the unspecified value
136 ValueOptional = 0x01, // The value can appear... or not
137 ValueRequired = 0x02, // The value is required to appear!
138 ValueDisallowed = 0x03 // A value may not be specified (for flags)
139};
140
141enum OptionHidden { // Control whether -help shows this option
142 NotHidden = 0x00, // Option included in -help & -help-hidden
143 Hidden = 0x01, // -help doesn't, but -help-hidden does
144 ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg
145};
146
147// Formatting flags - This controls special features that the option might have
148// that cause it to be parsed differently...
149//
150// Prefix - This option allows arguments that are otherwise unrecognized to be
151// matched by options that are a prefix of the actual value. This is useful for
152// cases like a linker, where options are typically of the form '-lfoo' or
153// '-L../../include' where -l or -L are the actual flags. When prefix is
154// enabled, and used, the value for the flag comes from the suffix of the
155// argument.
156//
157// AlwaysPrefix - Only allow the behavior enabled by the Prefix flag and reject
158// the Option=Value form.
159//
160
161enum FormattingFlags {
162 NormalFormatting = 0x00, // Nothing special
163 Positional = 0x01, // Is a positional argument, no '-' required
164 Prefix = 0x02, // Can this option directly prefix its value?
165 AlwaysPrefix = 0x03 // Can this option only directly prefix its value?
166};
167
168enum MiscFlags { // Miscellaneous flags to adjust argument
169 CommaSeparated = 0x01, // Should this cl::list split between commas?
170 PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args?
171 Sink = 0x04, // Should this cl::list eat all unknown options?
172
173 // Grouping - Can this option group with other options?
174 // If this is enabled, multiple letter options are allowed to bunch together
175 // with only a single hyphen for the whole group. This allows emulation
176 // of the behavior that ls uses for example: ls -la === ls -l -a
177 Grouping = 0x08,
178
179 // Default option
180 DefaultOption = 0x10
181};
182
183//===----------------------------------------------------------------------===//
184// Option Category class
185//
186class OptionCategory {
187private:
188 StringRef const Name;
189 StringRef const Description;
190
191 void registerCategory();
192
193public:
194 OptionCategory(StringRef const Name,
195 StringRef const Description = "")
196 : Name(Name), Description(Description) {
197 registerCategory();
198 }
199
200 StringRef getName() const { return Name; }
201 StringRef getDescription() const { return Description; }
202};
203
204// The general Option Category (used as default category).
205OptionCategory &getGeneralCategory();
206
207//===----------------------------------------------------------------------===//
208// SubCommand class
209//
210class SubCommand {
211private:
212 StringRef Name;
213 StringRef Description;
214
215protected:
216 void registerSubCommand();
217 void unregisterSubCommand();
218
219public:
220 SubCommand(StringRef Name, StringRef Description = "")
221 : Name(Name), Description(Description) {
222 registerSubCommand();
223 }
224 SubCommand() = default;
225
226 void reset();
227
228 explicit operator bool() const;
229
230 StringRef getName() const { return Name; }
231 StringRef getDescription() const { return Description; }
232
233 SmallVector<Option *, 4> PositionalOpts;
234 SmallVector<Option *, 4> SinkOpts;
235 StringMap<Option *> OptionsMap;
236
237 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
238};
239
240// A special subcommand representing no subcommand
241extern ManagedStatic<SubCommand> TopLevelSubCommand;
242
243// A special subcommand that can be used to put an option into all subcommands.
244extern ManagedStatic<SubCommand> AllSubCommands;
245
246//===----------------------------------------------------------------------===//
247// Option Base class
248//
249class Option {
250 friend class alias;
251
252 // handleOccurrences - Overriden by subclasses to handle the value passed into
253 // an argument. Should return true if there was an error processing the
254 // argument and the program should exit.
255 //
256 virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
257 StringRef Arg) = 0;
258
259 virtual enum ValueExpected getValueExpectedFlagDefault() const {
260 return ValueOptional;
261 }
262
263 // Out of line virtual function to provide home for the class.
264 virtual void anchor();
265
266 uint16_t NumOccurrences; // The number of times specified
267 // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
268 // problems with signed enums in bitfields.
269 uint16_t Occurrences : 3; // enum NumOccurrencesFlag
270 // not using the enum type for 'Value' because zero is an implementation
271 // detail representing the non-value
272 uint16_t Value : 2;
273 uint16_t HiddenFlag : 2; // enum OptionHidden
274 uint16_t Formatting : 2; // enum FormattingFlags
275 uint16_t Misc : 5;
276 uint16_t FullyInitialized : 1; // Has addArgument been called?
277 uint16_t Position; // Position of last occurrence of the option
278 uint16_t AdditionalVals; // Greater than 0 for multi-valued option.
279
280public:
281 StringRef ArgStr; // The argument string itself (ex: "help", "o")
282 StringRef HelpStr; // The descriptive text message for -help
283 StringRef ValueStr; // String describing what the value of this option is
284 SmallVector<OptionCategory *, 1>
285 Categories; // The Categories this option belongs to
286 SmallPtrSet<SubCommand *, 1> Subs; // The subcommands this option belongs to.
287
288 inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
289 return (enum NumOccurrencesFlag)Occurrences;
290 }
291
292 inline enum ValueExpected getValueExpectedFlag() const {
293 return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
27
Assuming field 'Value' is not equal to 0, which participates in a condition later
28
'?' condition is true
29
Returning value, which participates in a condition later
294 }
295
296 inline enum OptionHidden getOptionHiddenFlag() const {
297 return (enum OptionHidden)HiddenFlag;
298 }
299
300 inline enum FormattingFlags getFormattingFlag() const {
301 return (enum FormattingFlags)Formatting;
302 }
303
304 inline unsigned getMiscFlags() const { return Misc; }
305 inline unsigned getPosition() const { return Position; }
306 inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
307
308 // hasArgStr - Return true if the argstr != ""
309 bool hasArgStr() const { return !ArgStr.empty(); }
310 bool isPositional() const { return getFormattingFlag() == cl::Positional; }
311 bool isSink() const { return getMiscFlags() & cl::Sink; }
312 bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; }
313
314 bool isConsumeAfter() const {
315 return getNumOccurrencesFlag() == cl::ConsumeAfter;
316 }
317
318 bool isInAllSubCommands() const {
319 return any_of(Subs, [](const SubCommand *SC) {
320 return SC == &*AllSubCommands;
321 });
322 }
323
324 //-------------------------------------------------------------------------===
325 // Accessor functions set by OptionModifiers
326 //
327 void setArgStr(StringRef S);
328 void setDescription(StringRef S) { HelpStr = S; }
329 void setValueStr(StringRef S) { ValueStr = S; }
330 void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
331 void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
332 void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
333 void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
334 void setMiscFlag(enum MiscFlags M) { Misc |= M; }
335 void setPosition(unsigned pos) { Position = pos; }
336 void addCategory(OptionCategory &C);
337 void addSubCommand(SubCommand &S) { Subs.insert(&S); }
338
339protected:
340 explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
341 enum OptionHidden Hidden)
342 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
343 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
344 FullyInitialized(false), Position(0), AdditionalVals(0) {
345 Categories.push_back(&getGeneralCategory());
346 }
347
348 inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
349
350public:
351 virtual ~Option() = default;
352
353 // addArgument - Register this argument with the commandline system.
354 //
355 void addArgument();
356
357 /// Unregisters this option from the CommandLine system.
358 ///
359 /// This option must have been the last option registered.
360 /// For testing purposes only.
361 void removeArgument();
362
363 // Return the width of the option tag for printing...
364 virtual size_t getOptionWidth() const = 0;
365
366 // printOptionInfo - Print out information about this option. The
367 // to-be-maintained width is specified.
368 //
369 virtual void printOptionInfo(size_t GlobalWidth) const = 0;
370
371 virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
372
373 virtual void setDefault() = 0;
374
375 // Prints the help string for an option.
376 //
377 // This maintains the Indent for multi-line descriptions.
378 // FirstLineIndentedBy is the count of chars of the first line
379 // i.e. the one containing the --<option name>.
380 static void printHelpStr(StringRef HelpStr, size_t Indent,
381 size_t FirstLineIndentedBy);
382
383 // Prints the help string for an enum value.
384 //
385 // This maintains the Indent for multi-line descriptions.
386 // FirstLineIndentedBy is the count of chars of the first line
387 // i.e. the one containing the =<value>.
388 static void printEnumValHelpStr(StringRef HelpStr, size_t Indent,
389 size_t FirstLineIndentedBy);
390
391 virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
392
393 // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
394 //
395 virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
396 bool MultiArg = false);
397
398 // Prints option name followed by message. Always returns true.
399 bool error(const Twine &Message, StringRef ArgName = StringRef(), raw_ostream &Errs = llvm::errs());
400 bool error(const Twine &Message, raw_ostream &Errs) {
401 return error(Message, StringRef(), Errs);
402 }
403
404 inline int getNumOccurrences() const { return NumOccurrences; }
405 void reset();
406};
407
408//===----------------------------------------------------------------------===//
409// Command line option modifiers that can be used to modify the behavior of
410// command line option parsers...
411//
412
413// desc - Modifier to set the description shown in the -help output...
414struct desc {
415 StringRef Desc;
416
417 desc(StringRef Str) : Desc(Str) {}
418
419 void apply(Option &O) const { O.setDescription(Desc); }
420};
421
422// value_desc - Modifier to set the value description shown in the -help
423// output...
424struct value_desc {
425 StringRef Desc;
426
427 value_desc(StringRef Str) : Desc(Str) {}
428
429 void apply(Option &O) const { O.setValueStr(Desc); }
430};
431
432// init - Specify a default (initial) value for the command line argument, if
433// the default constructor for the argument type does not give you what you
434// want. This is only valid on "opt" arguments, not on "list" arguments.
435//
436template <class Ty> struct initializer {
437 const Ty &Init;
438 initializer(const Ty &Val) : Init(Val) {}
439
440 template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
441};
442
443template <class Ty> initializer<Ty> init(const Ty &Val) {
444 return initializer<Ty>(Val);
445}
446
447// location - Allow the user to specify which external variable they want to
448// store the results of the command line argument processing into, if they don't
449// want to store it in the option itself.
450//
451template <class Ty> struct LocationClass {
452 Ty &Loc;
453
454 LocationClass(Ty &L) : Loc(L) {}
455
456 template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
457};
458
459template <class Ty> LocationClass<Ty> location(Ty &L) {
460 return LocationClass<Ty>(L);
461}
462
463// cat - Specifiy the Option category for the command line argument to belong
464// to.
465struct cat {
466 OptionCategory &Category;
467
468 cat(OptionCategory &c) : Category(c) {}
469
470 template <class Opt> void apply(Opt &O) const { O.addCategory(Category); }
471};
472
473// sub - Specify the subcommand that this option belongs to.
474struct sub {
475 SubCommand &Sub;
476
477 sub(SubCommand &S) : Sub(S) {}
478
479 template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); }
480};
481
482// Specify a callback function to be called when an option is seen.
483// Can be used to set other options automatically.
484template <typename R, typename Ty> struct cb {
485 std::function<R(Ty)> CB;
486
487 cb(std::function<R(Ty)> CB) : CB(CB) {}
488
489 template <typename Opt> void apply(Opt &O) const { O.setCallback(CB); }
490};
491
492namespace detail {
493template <typename F>
494struct callback_traits : public callback_traits<decltype(&F::operator())> {};
495
496template <typename R, typename C, typename... Args>
497struct callback_traits<R (C::*)(Args...) const> {
498 using result_type = R;
499 using arg_type = std::tuple_element_t<0, std::tuple<Args...>>;
500 static_assert(sizeof...(Args) == 1, "callback function must have one and only one parameter");
501 static_assert(std::is_same<result_type, void>::value,
502 "callback return type must be void");
503 static_assert(std::is_lvalue_reference<arg_type>::value &&
504 std::is_const<std::remove_reference_t<arg_type>>::value,
505 "callback arg_type must be a const lvalue reference");
506};
507} // namespace detail
508
509template <typename F>
510cb<typename detail::callback_traits<F>::result_type,
511 typename detail::callback_traits<F>::arg_type>
512callback(F CB) {
513 using result_type = typename detail::callback_traits<F>::result_type;
514 using arg_type = typename detail::callback_traits<F>::arg_type;
515 return cb<result_type, arg_type>(CB);
516}
517
518//===----------------------------------------------------------------------===//
519// OptionValue class
520
521// Support value comparison outside the template.
522struct GenericOptionValue {
523 virtual bool compare(const GenericOptionValue &V) const = 0;
524
525protected:
526 GenericOptionValue() = default;
527 GenericOptionValue(const GenericOptionValue&) = default;
528 GenericOptionValue &operator=(const GenericOptionValue &) = default;
529 ~GenericOptionValue() = default;
530
531private:
532 virtual void anchor();
533};
534
535template <class DataType> struct OptionValue;
536
537// The default value safely does nothing. Option value printing is only
538// best-effort.
539template <class DataType, bool isClass>
540struct OptionValueBase : public GenericOptionValue {
541 // Temporary storage for argument passing.
542 using WrapperType = OptionValue<DataType>;
543
544 bool hasValue() const { return false; }
545
546 const DataType &getValue() const { llvm_unreachable("no default value")__builtin_unreachable(); }
547
548 // Some options may take their value from a different data type.
549 template <class DT> void setValue(const DT & /*V*/) {}
550
551 bool compare(const DataType & /*V*/) const { return false; }
552
553 bool compare(const GenericOptionValue & /*V*/) const override {
554 return false;
555 }
556
557protected:
558 ~OptionValueBase() = default;
559};
560
561// Simple copy of the option value.
562template <class DataType> class OptionValueCopy : public GenericOptionValue {
563 DataType Value;
564 bool Valid = false;
565
566protected:
567 OptionValueCopy(const OptionValueCopy&) = default;
568 OptionValueCopy &operator=(const OptionValueCopy &) = default;
569 ~OptionValueCopy() = default;
570
571public:
572 OptionValueCopy() = default;
573
574 bool hasValue() const { return Valid; }
575
576 const DataType &getValue() const {
577 assert(Valid && "invalid option value")((void)0);
578 return Value;
579 }
580
581 void setValue(const DataType &V) {
582 Valid = true;
583 Value = V;
584 }
585
586 bool compare(const DataType &V) const { return Valid && (Value != V); }
587
588 bool compare(const GenericOptionValue &V) const override {
589 const OptionValueCopy<DataType> &VC =
590 static_cast<const OptionValueCopy<DataType> &>(V);
591 if (!VC.hasValue())
592 return false;
593 return compare(VC.getValue());
594 }
595};
596
597// Non-class option values.
598template <class DataType>
599struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
600 using WrapperType = DataType;
601
602protected:
603 OptionValueBase() = default;
604 OptionValueBase(const OptionValueBase&) = default;
605 OptionValueBase &operator=(const OptionValueBase &) = default;
606 ~OptionValueBase() = default;
607};
608
609// Top-level option class.
610template <class DataType>
611struct OptionValue final
612 : OptionValueBase<DataType, std::is_class<DataType>::value> {
613 OptionValue() = default;
614
615 OptionValue(const DataType &V) { this->setValue(V); }
616
617 // Some options may take their value from a different data type.
618 template <class DT> OptionValue<DataType> &operator=(const DT &V) {
619 this->setValue(V);
620 return *this;
621 }
622};
623
624// Other safe-to-copy-by-value common option types.
625enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
626template <>
627struct OptionValue<cl::boolOrDefault> final
628 : OptionValueCopy<cl::boolOrDefault> {
629 using WrapperType = cl::boolOrDefault;
630
631 OptionValue() = default;
632
633 OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
634
635 OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
636 setValue(V);
637 return *this;
638 }
639
640private:
641 void anchor() override;
642};
643
644template <>
645struct OptionValue<std::string> final : OptionValueCopy<std::string> {
646 using WrapperType = StringRef;
647
648 OptionValue() = default;
649
650 OptionValue(const std::string &V) { this->setValue(V); }
651
652 OptionValue<std::string> &operator=(const std::string &V) {
653 setValue(V);
654 return *this;
655 }
656
657private:
658 void anchor() override;
659};
660
661//===----------------------------------------------------------------------===//
662// Enum valued command line option
663//
664
665// This represents a single enum value, using "int" as the underlying type.
666struct OptionEnumValue {
667 StringRef Name;
668 int Value;
669 StringRef Description;
670};
671
672#define clEnumVal(ENUMVAL, DESC)llvm::cl::OptionEnumValue { "ENUMVAL", int(ENUMVAL), DESC } \
673 llvm::cl::OptionEnumValue { #ENUMVAL, int(ENUMVAL), DESC }
674#define clEnumValN(ENUMVAL, FLAGNAME, DESC)llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC } \
675 llvm::cl::OptionEnumValue { FLAGNAME, int(ENUMVAL), DESC }
676
677// values - For custom data types, allow specifying a group of values together
678// as the values that go into the mapping that the option handler uses.
679//
680class ValuesClass {
681 // Use a vector instead of a map, because the lists should be short,
682 // the overhead is less, and most importantly, it keeps them in the order
683 // inserted so we can print our option out nicely.
684 SmallVector<OptionEnumValue, 4> Values;
685
686public:
687 ValuesClass(std::initializer_list<OptionEnumValue> Options)
688 : Values(Options) {}
689
690 template <class Opt> void apply(Opt &O) const {
691 for (const auto &Value : Values)
692 O.getParser().addLiteralOption(Value.Name, Value.Value,
693 Value.Description);
694 }
695};
696
697/// Helper to build a ValuesClass by forwarding a variable number of arguments
698/// as an initializer list to the ValuesClass constructor.
699template <typename... OptsTy> ValuesClass values(OptsTy... Options) {
700 return ValuesClass({Options...});
701}
702
703//===----------------------------------------------------------------------===//
704// parser class - Parameterizable parser for different data types. By default,
705// known data types (string, int, bool) have specialized parsers, that do what
706// you would expect. The default parser, used for data types that are not
707// built-in, uses a mapping table to map specific options to values, which is
708// used, among other things, to handle enum types.
709
710//--------------------------------------------------
711// generic_parser_base - This class holds all the non-generic code that we do
712// not need replicated for every instance of the generic parser. This also
713// allows us to put stuff into CommandLine.cpp
714//
715class generic_parser_base {
716protected:
717 class GenericOptionInfo {
718 public:
719 GenericOptionInfo(StringRef name, StringRef helpStr)
720 : Name(name), HelpStr(helpStr) {}
721 StringRef Name;
722 StringRef HelpStr;
723 };
724
725public:
726 generic_parser_base(Option &O) : Owner(O) {}
727
728 virtual ~generic_parser_base() = default;
729 // Base class should have virtual-destructor
730
731 // getNumOptions - Virtual function implemented by generic subclass to
732 // indicate how many entries are in Values.
733 //
734 virtual unsigned getNumOptions() const = 0;
735
736 // getOption - Return option name N.
737 virtual StringRef getOption(unsigned N) const = 0;
738
739 // getDescription - Return description N
740 virtual StringRef getDescription(unsigned N) const = 0;
741
742 // Return the width of the option tag for printing...
743 virtual size_t getOptionWidth(const Option &O) const;
744
745 virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
746
747 // printOptionInfo - Print out information about this option. The
748 // to-be-maintained width is specified.
749 //
750 virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
751
752 void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
753 const GenericOptionValue &Default,
754 size_t GlobalWidth) const;
755
756 // printOptionDiff - print the value of an option and it's default.
757 //
758 // Template definition ensures that the option and default have the same
759 // DataType (via the same AnyOptionValue).
760 template <class AnyOptionValue>
761 void printOptionDiff(const Option &O, const AnyOptionValue &V,
762 const AnyOptionValue &Default,
763 size_t GlobalWidth) const {
764 printGenericOptionDiff(O, V, Default, GlobalWidth);
765 }
766
767 void initialize() {}
768
769 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
770 // If there has been no argstr specified, that means that we need to add an
771 // argument for every possible option. This ensures that our options are
772 // vectored to us.
773 if (!Owner.hasArgStr())
774 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
775 OptionNames.push_back(getOption(i));
776 }
777
778 enum ValueExpected getValueExpectedFlagDefault() const {
779 // If there is an ArgStr specified, then we are of the form:
780 //
781 // -opt=O2 or -opt O2 or -optO2
782 //
783 // In which case, the value is required. Otherwise if an arg str has not
784 // been specified, we are of the form:
785 //
786 // -O2 or O2 or -la (where -l and -a are separate options)
787 //
788 // If this is the case, we cannot allow a value.
789 //
790 if (Owner.hasArgStr())
791 return ValueRequired;
792 else
793 return ValueDisallowed;
794 }
795
796 // findOption - Return the option number corresponding to the specified
797 // argument string. If the option is not found, getNumOptions() is returned.
798 //
799 unsigned findOption(StringRef Name);
800
801protected:
802 Option &Owner;
803};
804
805// Default parser implementation - This implementation depends on having a
806// mapping of recognized options to values of some sort. In addition to this,
807// each entry in the mapping also tracks a help message that is printed with the
808// command line option for -help. Because this is a simple mapping parser, the
809// data type can be any unsupported type.
810//
811template <class DataType> class parser : public generic_parser_base {
812protected:
813 class OptionInfo : public GenericOptionInfo {
814 public:
815 OptionInfo(StringRef name, DataType v, StringRef helpStr)
816 : GenericOptionInfo(name, helpStr), V(v) {}
817
818 OptionValue<DataType> V;
819 };
820 SmallVector<OptionInfo, 8> Values;
821
822public:
823 parser(Option &O) : generic_parser_base(O) {}
824
825 using parser_data_type = DataType;
826
827 // Implement virtual functions needed by generic_parser_base
828 unsigned getNumOptions() const override { return unsigned(Values.size()); }
829 StringRef getOption(unsigned N) const override { return Values[N].Name; }
830 StringRef getDescription(unsigned N) const override {
831 return Values[N].HelpStr;
832 }
833
834 // getOptionValue - Return the value of option name N.
835 const GenericOptionValue &getOptionValue(unsigned N) const override {
836 return Values[N].V;
837 }
838
839 // parse - Return true on error.
840 bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
841 StringRef ArgVal;
842 if (Owner.hasArgStr())
843 ArgVal = Arg;
844 else
845 ArgVal = ArgName;
846
847 for (size_t i = 0, e = Values.size(); i != e; ++i)
848 if (Values[i].Name == ArgVal) {
849 V = Values[i].V.getValue();
850 return false;
851 }
852
853 return O.error("Cannot find option named '" + ArgVal + "'!");
854 }
855
856 /// addLiteralOption - Add an entry to the mapping table.
857 ///
858 template <class DT>
859 void addLiteralOption(StringRef Name, const DT &V, StringRef HelpStr) {
860 assert(findOption(Name) == Values.size() && "Option already exists!")((void)0);
861 OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
862 Values.push_back(X);
863 AddLiteralOption(Owner, Name);
864 }
865
866 /// removeLiteralOption - Remove the specified option.
867 ///
868 void removeLiteralOption(StringRef Name) {
869 unsigned N = findOption(Name);
870 assert(N != Values.size() && "Option not found!")((void)0);
871 Values.erase(Values.begin() + N);
872 }
873};
874
875//--------------------------------------------------
876// basic_parser - Super class of parsers to provide boilerplate code
877//
878class basic_parser_impl { // non-template implementation of basic_parser<t>
879public:
880 basic_parser_impl(Option &) {}
881
882 virtual ~basic_parser_impl() {}
883
884 enum ValueExpected getValueExpectedFlagDefault() const {
885 return ValueRequired;
886 }
887
888 void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
889
890 void initialize() {}
891
892 // Return the width of the option tag for printing...
893 size_t getOptionWidth(const Option &O) const;
894
895 // printOptionInfo - Print out information about this option. The
896 // to-be-maintained width is specified.
897 //
898 void printOptionInfo(const Option &O, size_t GlobalWidth) const;
899
900 // printOptionNoValue - Print a placeholder for options that don't yet support
901 // printOptionDiff().
902 void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
903
904 // getValueName - Overload in subclass to provide a better default value.
905 virtual StringRef getValueName() const { return "value"; }
906
907 // An out-of-line virtual method to provide a 'home' for this class.
908 virtual void anchor();
909
910protected:
911 // A helper for basic_parser::printOptionDiff.
912 void printOptionName(const Option &O, size_t GlobalWidth) const;
913};
914
915// basic_parser - The real basic parser is just a template wrapper that provides
916// a typedef for the provided data type.
917//
918template <class DataType> class basic_parser : public basic_parser_impl {
919public:
920 using parser_data_type = DataType;
921 using OptVal = OptionValue<DataType>;
922
923 basic_parser(Option &O) : basic_parser_impl(O) {}
924};
925
926//--------------------------------------------------
927// parser<bool>
928//
929template <> class parser<bool> : public basic_parser<bool> {
930public:
931 parser(Option &O) : basic_parser(O) {}
932
933 // parse - Return true on error.
934 bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
935
936 void initialize() {}
937
938 enum ValueExpected getValueExpectedFlagDefault() const {
939 return ValueOptional;
940 }
941
942 // getValueName - Do not print =<value> at all.
943 StringRef getValueName() const override { return StringRef(); }
944
945 void printOptionDiff(const Option &O, bool V, OptVal Default,
946 size_t GlobalWidth) const;
947
948 // An out-of-line virtual method to provide a 'home' for this class.
949 void anchor() override;
950};
951
952extern template class basic_parser<bool>;
953
954//--------------------------------------------------
955// parser<boolOrDefault>
956template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
957public:
958 parser(Option &O) : basic_parser(O) {}
959
960 // parse - Return true on error.
961 bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
962
963 enum ValueExpected getValueExpectedFlagDefault() const {
964 return ValueOptional;
965 }
966
967 // getValueName - Do not print =<value> at all.
968 StringRef getValueName() const override { return StringRef(); }
969
970 void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
971 size_t GlobalWidth) const;
972
973 // An out-of-line virtual method to provide a 'home' for this class.
974 void anchor() override;
975};
976
977extern template class basic_parser<boolOrDefault>;
978
979//--------------------------------------------------
980// parser<int>
981//
982template <> class parser<int> : public basic_parser<int> {
983public:
984 parser(Option &O) : basic_parser(O) {}
985
986 // parse - Return true on error.
987 bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
988
989 // getValueName - Overload in subclass to provide a better default value.
990 StringRef getValueName() const override { return "int"; }
991
992 void printOptionDiff(const Option &O, int V, OptVal Default,
993 size_t GlobalWidth) const;
994
995 // An out-of-line virtual method to provide a 'home' for this class.
996 void anchor() override;
997};
998
999extern template class basic_parser<int>;
1000
1001//--------------------------------------------------
1002// parser<long>
1003//
1004template <> class parser<long> final : public basic_parser<long> {
1005public:
1006 parser(Option &O) : basic_parser(O) {}
1007
1008 // parse - Return true on error.
1009 bool parse(Option &O, StringRef ArgName, StringRef Arg, long &Val);
1010
1011 // getValueName - Overload in subclass to provide a better default value.
1012 StringRef getValueName() const override { return "long"; }
1013
1014 void printOptionDiff(const Option &O, long V, OptVal Default,
1015 size_t GlobalWidth) const;
1016
1017 // An out-of-line virtual method to provide a 'home' for this class.
1018 void anchor() override;
1019};
1020
1021extern template class basic_parser<long>;
1022
1023//--------------------------------------------------
1024// parser<long long>
1025//
1026template <> class parser<long long> : public basic_parser<long long> {
1027public:
1028 parser(Option &O) : basic_parser(O) {}
1029
1030 // parse - Return true on error.
1031 bool parse(Option &O, StringRef ArgName, StringRef Arg, long long &Val);
1032
1033 // getValueName - Overload in subclass to provide a better default value.
1034 StringRef getValueName() const override { return "long"; }
1035
1036 void printOptionDiff(const Option &O, long long V, OptVal Default,
1037 size_t GlobalWidth) const;
1038
1039 // An out-of-line virtual method to provide a 'home' for this class.
1040 void anchor() override;
1041};
1042
1043extern template class basic_parser<long long>;
1044
1045//--------------------------------------------------
1046// parser<unsigned>
1047//
1048template <> class parser<unsigned> : public basic_parser<unsigned> {
1049public:
1050 parser(Option &O) : basic_parser(O) {}
1051
1052 // parse - Return true on error.
1053 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
1054
1055 // getValueName - Overload in subclass to provide a better default value.
1056 StringRef getValueName() const override { return "uint"; }
1057
1058 void printOptionDiff(const Option &O, unsigned V, OptVal Default,
1059 size_t GlobalWidth) const;
1060
1061 // An out-of-line virtual method to provide a 'home' for this class.
1062 void anchor() override;
1063};
1064
1065extern template class basic_parser<unsigned>;
1066
1067//--------------------------------------------------
1068// parser<unsigned long>
1069//
1070template <>
1071class parser<unsigned long> final : public basic_parser<unsigned long> {
1072public:
1073 parser(Option &O) : basic_parser(O) {}
1074
1075 // parse - Return true on error.
1076 bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long &Val);
1077
1078 // getValueName - Overload in subclass to provide a better default value.
1079 StringRef getValueName() const override { return "ulong"; }
1080
1081 void printOptionDiff(const Option &O, unsigned long V, OptVal Default,
1082 size_t GlobalWidth) const;
1083
1084 // An out-of-line virtual method to provide a 'home' for this class.
1085 void anchor() override;
1086};
1087
1088extern template class basic_parser<unsigned long>;
1089
1090//--------------------------------------------------
1091// parser<unsigned long long>
1092//
1093template <>
1094class parser<unsigned long long> : public basic_parser<unsigned long long> {
1095public:
1096 parser(Option &O) : basic_parser(O) {}
1097
1098 // parse - Return true on error.
1099 bool parse(Option &O, StringRef ArgName, StringRef Arg,
1100 unsigned long long &Val);
1101
1102 // getValueName - Overload in subclass to provide a better default value.
1103 StringRef getValueName() const override { return "ulong"; }
1104
1105 void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
1106 size_t GlobalWidth) const;
1107
1108 // An out-of-line virtual method to provide a 'home' for this class.
1109 void anchor() override;
1110};
1111
1112extern template class basic_parser<unsigned long long>;
1113
1114//--------------------------------------------------
1115// parser<double>
1116//
1117template <> class parser<double> : public basic_parser<double> {
1118public:
1119 parser(Option &O) : basic_parser(O) {}
1120
1121 // parse - Return true on error.
1122 bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
1123
1124 // getValueName - Overload in subclass to provide a better default value.
1125 StringRef getValueName() const override { return "number"; }
1126
1127 void printOptionDiff(const Option &O, double V, OptVal Default,
1128 size_t GlobalWidth) const;
1129
1130 // An out-of-line virtual method to provide a 'home' for this class.
1131 void anchor() override;
1132};
1133
1134extern template class basic_parser<double>;
1135
1136//--------------------------------------------------
1137// parser<float>
1138//
1139template <> class parser<float> : public basic_parser<float> {
1140public:
1141 parser(Option &O) : basic_parser(O) {}
1142
1143 // parse - Return true on error.
1144 bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
1145
1146 // getValueName - Overload in subclass to provide a better default value.
1147 StringRef getValueName() const override { return "number"; }
1148
1149 void printOptionDiff(const Option &O, float V, OptVal Default,
1150 size_t GlobalWidth) const;
1151
1152 // An out-of-line virtual method to provide a 'home' for this class.
1153 void anchor() override;
1154};
1155
1156extern template class basic_parser<float>;
1157
1158//--------------------------------------------------
1159// parser<std::string>
1160//
1161template <> class parser<std::string> : public basic_parser<std::string> {
1162public:
1163 parser(Option &O) : basic_parser(O) {}
1164
1165 // parse - Return true on error.
1166 bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
1167 Value = Arg.str();
1168 return false;
1169 }
1170
1171 // getValueName - Overload in subclass to provide a better default value.
1172 StringRef getValueName() const override { return "string"; }
1173
1174 void printOptionDiff(const Option &O, StringRef V, const OptVal &Default,
1175 size_t GlobalWidth) const;
1176
1177 // An out-of-line virtual method to provide a 'home' for this class.
1178 void anchor() override;
1179};
1180
1181extern template class basic_parser<std::string>;
1182
1183//--------------------------------------------------
1184// parser<char>
1185//
1186template <> class parser<char> : public basic_parser<char> {
1187public:
1188 parser(Option &O) : basic_parser(O) {}
1189
1190 // parse - Return true on error.
1191 bool parse(Option &, StringRef, StringRef Arg, char &Value) {
1192 Value = Arg[0];
1193 return false;
1194 }
1195
1196 // getValueName - Overload in subclass to provide a better default value.
1197 StringRef getValueName() const override { return "char"; }
1198
1199 void printOptionDiff(const Option &O, char V, OptVal Default,
1200 size_t GlobalWidth) const;
1201
1202 // An out-of-line virtual method to provide a 'home' for this class.
1203 void anchor() override;
1204};
1205
1206extern template class basic_parser<char>;
1207
1208//--------------------------------------------------
1209// PrintOptionDiff
1210//
1211// This collection of wrappers is the intermediary between class opt and class
1212// parser to handle all the template nastiness.
1213
1214// This overloaded function is selected by the generic parser.
1215template <class ParserClass, class DT>
1216void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
1217 const OptionValue<DT> &Default, size_t GlobalWidth) {
1218 OptionValue<DT> OV = V;
1219 P.printOptionDiff(O, OV, Default, GlobalWidth);
1220}
1221
1222// This is instantiated for basic parsers when the parsed value has a different
1223// type than the option value. e.g. HelpPrinter.
1224template <class ParserDT, class ValDT> struct OptionDiffPrinter {
1225 void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
1226 const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
1227 P.printOptionNoValue(O, GlobalWidth);
1228 }
1229};
1230
1231// This is instantiated for basic parsers when the parsed value has the same
1232// type as the option value.
1233template <class DT> struct OptionDiffPrinter<DT, DT> {
1234 void print(const Option &O, const parser<DT> &P, const DT &V,
1235 const OptionValue<DT> &Default, size_t GlobalWidth) {
1236 P.printOptionDiff(O, V, Default, GlobalWidth);
1237 }
1238};
1239
1240// This overloaded function is selected by the basic parser, which may parse a
1241// different type than the option type.
1242template <class ParserClass, class ValDT>
1243void printOptionDiff(
1244 const Option &O,
1245 const basic_parser<typename ParserClass::parser_data_type> &P,
1246 const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
1247
1248 OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
1249 printer.print(O, static_cast<const ParserClass &>(P), V, Default,
1250 GlobalWidth);
1251}
1252
1253//===----------------------------------------------------------------------===//
1254// applicator class - This class is used because we must use partial
1255// specialization to handle literal string arguments specially (const char* does
1256// not correctly respond to the apply method). Because the syntax to use this
1257// is a pain, we have the 'apply' method below to handle the nastiness...
1258//
1259template <class Mod> struct applicator {
1260 template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
1261};
1262
1263// Handle const char* as a special case...
1264template <unsigned n> struct applicator<char[n]> {
1265 template <class Opt> static void opt(StringRef Str, Opt &O) {
1266 O.setArgStr(Str);
1267 }
1268};
1269template <unsigned n> struct applicator<const char[n]> {
1270 template <class Opt> static void opt(StringRef Str, Opt &O) {
1271 O.setArgStr(Str);
1272 }
1273};
1274template <> struct applicator<StringRef > {
1275 template <class Opt> static void opt(StringRef Str, Opt &O) {
1276 O.setArgStr(Str);
1277 }
1278};
1279
1280template <> struct applicator<NumOccurrencesFlag> {
1281 static void opt(NumOccurrencesFlag N, Option &O) {
1282 O.setNumOccurrencesFlag(N);
1283 }
1284};
1285
1286template <> struct applicator<ValueExpected> {
1287 static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1288};
1289
1290template <> struct applicator<OptionHidden> {
1291 static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1292};
1293
1294template <> struct applicator<FormattingFlags> {
1295 static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1296};
1297
1298template <> struct applicator<MiscFlags> {
1299 static void opt(MiscFlags MF, Option &O) {
1300 assert((MF != Grouping || O.ArgStr.size() == 1) &&((void)0)
1301 "cl::Grouping can only apply to single charater Options.")((void)0);
1302 O.setMiscFlag(MF);
1303 }
1304};
1305
1306// apply method - Apply modifiers to an option in a type safe way.
1307template <class Opt, class Mod, class... Mods>
1308void apply(Opt *O, const Mod &M, const Mods &... Ms) {
1309 applicator<Mod>::opt(M, *O);
1310 apply(O, Ms...);
1311}
1312
1313template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
1314 applicator<Mod>::opt(M, *O);
1315}
1316
1317//===----------------------------------------------------------------------===//
1318// opt_storage class
1319
1320// Default storage class definition: external storage. This implementation
1321// assumes the user will specify a variable to store the data into with the
1322// cl::location(x) modifier.
1323//
1324template <class DataType, bool ExternalStorage, bool isClass>
1325class opt_storage {
1326 DataType *Location = nullptr; // Where to store the object...
1327 OptionValue<DataType> Default;
1328
1329 void check_location() const {
1330 assert(Location && "cl::location(...) not specified for a command "((void)0)
1331 "line option with external storage, "((void)0)
1332 "or cl::init specified before cl::location()!!")((void)0);
1333 }
1334
1335public:
1336 opt_storage() = default;
1337
1338 bool setLocation(Option &O, DataType &L) {
1339 if (Location)
1340 return O.error("cl::location(x) specified more than once!");
1341 Location = &L;
1342 Default = L;
1343 return false;
1344 }
1345
1346 template <class T> void setValue(const T &V, bool initial = false) {
1347 check_location();
1348 *Location = V;
1349 if (initial)
1350 Default = V;
1351 }
1352
1353 DataType &getValue() {
1354 check_location();
1355 return *Location;
1356 }
1357 const DataType &getValue() const {
1358 check_location();
1359 return *Location;
1360 }
1361
1362 operator DataType() const { return this->getValue(); }
1363
1364 const OptionValue<DataType> &getDefault() const { return Default; }
1365};
1366
1367// Define how to hold a class type object, such as a string. Since we can
1368// inherit from a class, we do so. This makes us exactly compatible with the
1369// object in all cases that it is used.
1370//
1371template <class DataType>
1372class opt_storage<DataType, false, true> : public DataType {
1373public:
1374 OptionValue<DataType> Default;
1375
1376 template <class T> void setValue(const T &V, bool initial = false) {
1377 DataType::operator=(V);
1378 if (initial)
1379 Default = V;
1380 }
1381
1382 DataType &getValue() { return *this; }
1383 const DataType &getValue() const { return *this; }
1384
1385 const OptionValue<DataType> &getDefault() const { return Default; }
1386};
1387
1388// Define a partial specialization to handle things we cannot inherit from. In
1389// this case, we store an instance through containment, and overload operators
1390// to get at the value.
1391//
1392template <class DataType> class opt_storage<DataType, false, false> {
1393public:
1394 DataType Value;
1395 OptionValue<DataType> Default;
1396
1397 // Make sure we initialize the value with the default constructor for the
1398 // type.
1399 opt_storage() : Value(DataType()), Default(DataType()) {}
1400
1401 template <class T> void setValue(const T &V, bool initial = false) {
1402 Value = V;
1403 if (initial)
1404 Default = V;
1405 }
1406 DataType &getValue() { return Value; }
1407 DataType getValue() const { return Value; }
1408
1409 const OptionValue<DataType> &getDefault() const { return Default; }
1410
1411 operator DataType() const { return getValue(); }
1412
1413 // If the datatype is a pointer, support -> on it.
1414 DataType operator->() const { return Value; }
1415};
1416
1417//===----------------------------------------------------------------------===//
1418// opt - A scalar command line option.
1419//
1420template <class DataType, bool ExternalStorage = false,
1421 class ParserClass = parser<DataType>>
1422class opt : public Option,
1423 public opt_storage<DataType, ExternalStorage,
1424 std::is_class<DataType>::value> {
1425 ParserClass Parser;
1426
1427 bool handleOccurrence(unsigned pos, StringRef ArgName,
1428 StringRef Arg) override {
1429 typename ParserClass::parser_data_type Val =
1430 typename ParserClass::parser_data_type();
1431 if (Parser.parse(*this, ArgName, Arg, Val))
1432 return true; // Parse error!
1433 this->setValue(Val);
1434 this->setPosition(pos);
1435 Callback(Val);
1436 return false;
1437 }
1438
1439 enum ValueExpected getValueExpectedFlagDefault() const override {
1440 return Parser.getValueExpectedFlagDefault();
1441 }
1442
1443 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1444 return Parser.getExtraOptionNames(OptionNames);
1445 }
1446
1447 // Forward printing stuff to the parser...
1448 size_t getOptionWidth() const override {
1449 return Parser.getOptionWidth(*this);
1450 }
1451
1452 void printOptionInfo(size_t GlobalWidth) const override {
1453 Parser.printOptionInfo(*this, GlobalWidth);
1454 }
1455
1456 void printOptionValue(size_t GlobalWidth, bool Force) const override {
1457 if (Force || this->getDefault().compare(this->getValue())) {
1458 cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(),
1459 this->getDefault(), GlobalWidth);
1460 }
1461 }
1462
1463 template <class T,
1464 class = std::enable_if_t<std::is_assignable<T &, T>::value>>
1465 void setDefaultImpl() {
1466 const OptionValue<DataType> &V = this->getDefault();
1467 if (V.hasValue())
1468 this->setValue(V.getValue());
1469 }
1470
1471 template <class T,
1472 class = std::enable_if_t<!std::is_assignable<T &, T>::value>>
1473 void setDefaultImpl(...) {}
1474
1475 void setDefault() override { setDefaultImpl<DataType>(); }
1476
1477 void done() {
1478 addArgument();
1479 Parser.initialize();
1480 }
1481
1482public:
1483 // Command line options should not be copyable
1484 opt(const opt &) = delete;
1485 opt &operator=(const opt &) = delete;
1486
1487 // setInitialValue - Used by the cl::init modifier...
1488 void setInitialValue(const DataType &V) { this->setValue(V, true); }
1489
1490 ParserClass &getParser() { return Parser; }
1491
1492 template <class T> DataType &operator=(const T &Val) {
1493 this->setValue(Val);
1494 Callback(Val);
1495 return this->getValue();
1496 }
1497
1498 template <class... Mods>
1499 explicit opt(const Mods &... Ms)
1500 : Option(llvm::cl::Optional, NotHidden), Parser(*this) {
1501 apply(this, Ms...);
1502 done();
1503 }
1504
1505 void setCallback(
1506 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1507 Callback = CB;
1508 }
1509
1510 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1511 [](const typename ParserClass::parser_data_type &) {};
1512};
1513
1514extern template class opt<unsigned>;
1515extern template class opt<int>;
1516extern template class opt<std::string>;
1517extern template class opt<char>;
1518extern template class opt<bool>;
1519
1520//===----------------------------------------------------------------------===//
1521// list_storage class
1522
1523// Default storage class definition: external storage. This implementation
1524// assumes the user will specify a variable to store the data into with the
1525// cl::location(x) modifier.
1526//
1527template <class DataType, class StorageClass> class list_storage {
1528 StorageClass *Location = nullptr; // Where to store the object...
1529
1530public:
1531 list_storage() = default;
1532
1533 void clear() {}
1534
1535 bool setLocation(Option &O, StorageClass &L) {
1536 if (Location)
1537 return O.error("cl::location(x) specified more than once!");
1538 Location = &L;
1539 return false;
1540 }
1541
1542 template <class T> void addValue(const T &V) {
1543 assert(Location != 0 && "cl::location(...) not specified for a command "((void)0)
1544 "line option with external storage!")((void)0);
1545 Location->push_back(V);
1546 }
1547};
1548
1549// Define how to hold a class type object, such as a string.
1550// Originally this code inherited from std::vector. In transitioning to a new
1551// API for command line options we should change this. The new implementation
1552// of this list_storage specialization implements the minimum subset of the
1553// std::vector API required for all the current clients.
1554//
1555// FIXME: Reduce this API to a more narrow subset of std::vector
1556//
1557template <class DataType> class list_storage<DataType, bool> {
1558 std::vector<DataType> Storage;
1559
1560public:
1561 using iterator = typename std::vector<DataType>::iterator;
1562
1563 iterator begin() { return Storage.begin(); }
1564 iterator end() { return Storage.end(); }
1565
1566 using const_iterator = typename std::vector<DataType>::const_iterator;
1567
1568 const_iterator begin() const { return Storage.begin(); }
1569 const_iterator end() const { return Storage.end(); }
1570
1571 using size_type = typename std::vector<DataType>::size_type;
1572
1573 size_type size() const { return Storage.size(); }
1574
1575 bool empty() const { return Storage.empty(); }
1576
1577 void push_back(const DataType &value) { Storage.push_back(value); }
1578 void push_back(DataType &&value) { Storage.push_back(value); }
1579
1580 using reference = typename std::vector<DataType>::reference;
1581 using const_reference = typename std::vector<DataType>::const_reference;
1582
1583 reference operator[](size_type pos) { return Storage[pos]; }
1584 const_reference operator[](size_type pos) const { return Storage[pos]; }
1585
1586 void clear() {
1587 Storage.clear();
1588 }
1589
1590 iterator erase(const_iterator pos) { return Storage.erase(pos); }
1591 iterator erase(const_iterator first, const_iterator last) {
1592 return Storage.erase(first, last);
1593 }
1594
1595 iterator erase(iterator pos) { return Storage.erase(pos); }
1596 iterator erase(iterator first, iterator last) {
1597 return Storage.erase(first, last);
1598 }
1599
1600 iterator insert(const_iterator pos, const DataType &value) {
1601 return Storage.insert(pos, value);
1602 }
1603 iterator insert(const_iterator pos, DataType &&value) {
1604 return Storage.insert(pos, value);
1605 }
1606
1607 iterator insert(iterator pos, const DataType &value) {
1608 return Storage.insert(pos, value);
1609 }
1610 iterator insert(iterator pos, DataType &&value) {
1611 return Storage.insert(pos, value);
1612 }
1613
1614 reference front() { return Storage.front(); }
1615 const_reference front() const { return Storage.front(); }
1616
1617 operator std::vector<DataType> &() { return Storage; }
1618 operator ArrayRef<DataType>() const { return Storage; }
1619 std::vector<DataType> *operator&() { return &Storage; }
1620 const std::vector<DataType> *operator&() const { return &Storage; }
1621
1622 template <class T> void addValue(const T &V) { Storage.push_back(V); }
1623};
1624
1625//===----------------------------------------------------------------------===//
1626// list - A list of command line options.
1627//
1628template <class DataType, class StorageClass = bool,
1629 class ParserClass = parser<DataType>>
1630class list : public Option, public list_storage<DataType, StorageClass> {
1631 std::vector<unsigned> Positions;
1632 ParserClass Parser;
1633
1634 enum ValueExpected getValueExpectedFlagDefault() const override {
1635 return Parser.getValueExpectedFlagDefault();
1636 }
1637
1638 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1639 return Parser.getExtraOptionNames(OptionNames);
1640 }
1641
1642 bool handleOccurrence(unsigned pos, StringRef ArgName,
1643 StringRef Arg) override {
1644 typename ParserClass::parser_data_type Val =
1645 typename ParserClass::parser_data_type();
1646 if (Parser.parse(*this, ArgName, Arg, Val))
1647 return true; // Parse Error!
1648 list_storage<DataType, StorageClass>::addValue(Val);
1649 setPosition(pos);
1650 Positions.push_back(pos);
1651 Callback(Val);
1652 return false;
1653 }
1654
1655 // Forward printing stuff to the parser...
1656 size_t getOptionWidth() const override {
1657 return Parser.getOptionWidth(*this);
1658 }
1659
1660 void printOptionInfo(size_t GlobalWidth) const override {
1661 Parser.printOptionInfo(*this, GlobalWidth);
1662 }
1663
1664 // Unimplemented: list options don't currently store their default value.
1665 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1666 }
1667
1668 void setDefault() override {
1669 Positions.clear();
1670 list_storage<DataType, StorageClass>::clear();
1671 }
1672
1673 void done() {
1674 addArgument();
1675 Parser.initialize();
1676 }
1677
1678public:
1679 // Command line options should not be copyable
1680 list(const list &) = delete;
1681 list &operator=(const list &) = delete;
1682
1683 ParserClass &getParser() { return Parser; }
1684
1685 unsigned getPosition(unsigned optnum) const {
1686 assert(optnum < this->size() && "Invalid option index")((void)0);
1687 return Positions[optnum];
1688 }
1689
1690 void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
1691
1692 template <class... Mods>
1693 explicit list(const Mods &... Ms)
1694 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1695 apply(this, Ms...);
1696 done();
1697 }
1698
1699 void setCallback(
1700 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1701 Callback = CB;
1702 }
1703
1704 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1705 [](const typename ParserClass::parser_data_type &) {};
1706};
1707
1708// multi_val - Modifier to set the number of additional values.
1709struct multi_val {
1710 unsigned AdditionalVals;
1711 explicit multi_val(unsigned N) : AdditionalVals(N) {}
1712
1713 template <typename D, typename S, typename P>
1714 void apply(list<D, S, P> &L) const {
1715 L.setNumAdditionalVals(AdditionalVals);
1716 }
1717};
1718
1719//===----------------------------------------------------------------------===//
1720// bits_storage class
1721
1722// Default storage class definition: external storage. This implementation
1723// assumes the user will specify a variable to store the data into with the
1724// cl::location(x) modifier.
1725//
1726template <class DataType, class StorageClass> class bits_storage {
1727 unsigned *Location = nullptr; // Where to store the bits...
1728
1729 template <class T> static unsigned Bit(const T &V) {
1730 unsigned BitPos = reinterpret_cast<unsigned>(V);
1731 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&((void)0)
1732 "enum exceeds width of bit vector!")((void)0);
1733 return 1 << BitPos;
1734 }
1735
1736public:
1737 bits_storage() = default;
1738
1739 bool setLocation(Option &O, unsigned &L) {
1740 if (Location)
1741 return O.error("cl::location(x) specified more than once!");
1742 Location = &L;
1743 return false;
1744 }
1745
1746 template <class T> void addValue(const T &V) {
1747 assert(Location != 0 && "cl::location(...) not specified for a command "((void)0)
1748 "line option with external storage!")((void)0);
1749 *Location |= Bit(V);
1750 }
1751
1752 unsigned getBits() { return *Location; }
1753
1754 template <class T> bool isSet(const T &V) {
1755 return (*Location & Bit(V)) != 0;
1756 }
1757};
1758
1759// Define how to hold bits. Since we can inherit from a class, we do so.
1760// This makes us exactly compatible with the bits in all cases that it is used.
1761//
1762template <class DataType> class bits_storage<DataType, bool> {
1763 unsigned Bits; // Where to store the bits...
1764
1765 template <class T> static unsigned Bit(const T &V) {
1766 unsigned BitPos = (unsigned)V;
1767 assert(BitPos < sizeof(unsigned) * CHAR_BIT &&((void)0)
1768 "enum exceeds width of bit vector!")((void)0);
1769 return 1 << BitPos;
1770 }
1771
1772public:
1773 template <class T> void addValue(const T &V) { Bits |= Bit(V); }
1774
1775 unsigned getBits() { return Bits; }
1776
1777 template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
1778};
1779
1780//===----------------------------------------------------------------------===//
1781// bits - A bit vector of command options.
1782//
1783template <class DataType, class Storage = bool,
1784 class ParserClass = parser<DataType>>
1785class bits : public Option, public bits_storage<DataType, Storage> {
1786 std::vector<unsigned> Positions;
1787 ParserClass Parser;
1788
1789 enum ValueExpected getValueExpectedFlagDefault() const override {
1790 return Parser.getValueExpectedFlagDefault();
1791 }
1792
1793 void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
1794 return Parser.getExtraOptionNames(OptionNames);
1795 }
1796
1797 bool handleOccurrence(unsigned pos, StringRef ArgName,
1798 StringRef Arg) override {
1799 typename ParserClass::parser_data_type Val =
1800 typename ParserClass::parser_data_type();
1801 if (Parser.parse(*this, ArgName, Arg, Val))
1802 return true; // Parse Error!
1803 this->addValue(Val);
1804 setPosition(pos);
1805 Positions.push_back(pos);
1806 Callback(Val);
1807 return false;
1808 }
1809
1810 // Forward printing stuff to the parser...
1811 size_t getOptionWidth() const override {
1812 return Parser.getOptionWidth(*this);
1813 }
1814
1815 void printOptionInfo(size_t GlobalWidth) const override {
1816 Parser.printOptionInfo(*this, GlobalWidth);
1817 }
1818
1819 // Unimplemented: bits options don't currently store their default values.
1820 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1821 }
1822
1823 void setDefault() override {}
1824
1825 void done() {
1826 addArgument();
1827 Parser.initialize();
1828 }
1829
1830public:
1831 // Command line options should not be copyable
1832 bits(const bits &) = delete;
1833 bits &operator=(const bits &) = delete;
1834
1835 ParserClass &getParser() { return Parser; }
1836
1837 unsigned getPosition(unsigned optnum) const {
1838 assert(optnum < this->size() && "Invalid option index")((void)0);
1839 return Positions[optnum];
1840 }
1841
1842 template <class... Mods>
1843 explicit bits(const Mods &... Ms)
1844 : Option(ZeroOrMore, NotHidden), Parser(*this) {
1845 apply(this, Ms...);
1846 done();
1847 }
1848
1849 void setCallback(
1850 std::function<void(const typename ParserClass::parser_data_type &)> CB) {
1851 Callback = CB;
1852 }
1853
1854 std::function<void(const typename ParserClass::parser_data_type &)> Callback =
1855 [](const typename ParserClass::parser_data_type &) {};
1856};
1857
1858//===----------------------------------------------------------------------===//
1859// Aliased command line option (alias this name to a preexisting name)
1860//
1861
1862class alias : public Option {
1863 Option *AliasFor;
1864
1865 bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1866 StringRef Arg) override {
1867 return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1868 }
1869
1870 bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
1871 bool MultiArg = false) override {
1872 return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
1873 }
1874
1875 // Handle printing stuff...
1876 size_t getOptionWidth() const override;
1877 void printOptionInfo(size_t GlobalWidth) const override;
1878
1879 // Aliases do not need to print their values.
1880 void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
1881 }
1882
1883 void setDefault() override { AliasFor->setDefault(); }
1884
1885 ValueExpected getValueExpectedFlagDefault() const override {
1886 return AliasFor->getValueExpectedFlag();
1887 }
1888
1889 void done() {
1890 if (!hasArgStr())
1891 error("cl::alias must have argument name specified!");
1892 if (!AliasFor)
1893 error("cl::alias must have an cl::aliasopt(option) specified!");
1894 if (!Subs.empty())
1895 error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!");
1896 Subs = AliasFor->Subs;
1897 Categories = AliasFor->Categories;
1898 addArgument();
1899 }
1900
1901public:
1902 // Command line options should not be copyable
1903 alias(const alias &) = delete;
1904 alias &operator=(const alias &) = delete;
1905
1906 void setAliasFor(Option &O) {
1907 if (AliasFor)
1908 error("cl::alias must only have one cl::aliasopt(...) specified!");
1909 AliasFor = &O;
1910 }
1911
1912 template <class... Mods>
1913 explicit alias(const Mods &... Ms)
1914 : Option(Optional, Hidden), AliasFor(nullptr) {
1915 apply(this, Ms...);
1916 done();
1917 }
1918};
1919
1920// aliasfor - Modifier to set the option an alias aliases.
1921struct aliasopt {
1922 Option &Opt;
1923
1924 explicit aliasopt(Option &O) : Opt(O) {}
1925
1926 void apply(alias &A) const { A.setAliasFor(Opt); }
1927};
1928
1929// extrahelp - provide additional help at the end of the normal help
1930// output. All occurrences of cl::extrahelp will be accumulated and
1931// printed to stderr at the end of the regular help, just before
1932// exit is called.
1933struct extrahelp {
1934 StringRef morehelp;
1935
1936 explicit extrahelp(StringRef help);
1937};
1938
1939void PrintVersionMessage();
1940
1941/// This function just prints the help message, exactly the same way as if the
1942/// -help or -help-hidden option had been given on the command line.
1943///
1944/// \param Hidden if true will print hidden options
1945/// \param Categorized if true print options in categories
1946void PrintHelpMessage(bool Hidden = false, bool Categorized = false);
1947
1948//===----------------------------------------------------------------------===//
1949// Public interface for accessing registered options.
1950//
1951
1952/// Use this to get a StringMap to all registered named options
1953/// (e.g. -help).
1954///
1955/// \return A reference to the StringMap used by the cl APIs to parse options.
1956///
1957/// Access to unnamed arguments (i.e. positional) are not provided because
1958/// it is expected that the client already has access to these.
1959///
1960/// Typical usage:
1961/// \code
1962/// main(int argc,char* argv[]) {
1963/// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions();
1964/// assert(opts.count("help") == 1)
1965/// opts["help"]->setDescription("Show alphabetical help information")
1966/// // More code
1967/// llvm::cl::ParseCommandLineOptions(argc,argv);
1968/// //More code
1969/// }
1970/// \endcode
1971///
1972/// This interface is useful for modifying options in libraries that are out of
1973/// the control of the client. The options should be modified before calling
1974/// llvm::cl::ParseCommandLineOptions().
1975///
1976/// Hopefully this API can be deprecated soon. Any situation where options need
1977/// to be modified by tools or libraries should be handled by sane APIs rather
1978/// than just handing around a global list.
1979StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand);
1980
1981/// Use this to get all registered SubCommands from the provided parser.
1982///
1983/// \return A range of all SubCommand pointers registered with the parser.
1984///
1985/// Typical usage:
1986/// \code
1987/// main(int argc, char* argv[]) {
1988/// llvm::cl::ParseCommandLineOptions(argc, argv);
1989/// for (auto* S : llvm::cl::getRegisteredSubcommands()) {
1990/// if (*S) {
1991/// std::cout << "Executing subcommand: " << S->getName() << std::endl;
1992/// // Execute some function based on the name...
1993/// }
1994/// }
1995/// }
1996/// \endcode
1997///
1998/// This interface is useful for defining subcommands in libraries and
1999/// the dispatch from a single point (like in the main function).
2000iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2001getRegisteredSubcommands();
2002
2003//===----------------------------------------------------------------------===//
2004// Standalone command line processing utilities.
2005//
2006
2007/// Tokenizes a command line that can contain escapes and quotes.
2008//
2009/// The quoting rules match those used by GCC and other tools that use
2010/// libiberty's buildargv() or expandargv() utilities, and do not match bash.
2011/// They differ from buildargv() on treatment of backslashes that do not escape
2012/// a special character to make it possible to accept most Windows file paths.
2013///
2014/// \param [in] Source The string to be split on whitespace with quotes.
2015/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2016/// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2017/// lines and end of the response file to be marked with a nullptr string.
2018/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2019void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
2020 SmallVectorImpl<const char *> &NewArgv,
2021 bool MarkEOLs = false);
2022
2023/// Tokenizes a Windows command line which may contain quotes and escaped
2024/// quotes.
2025///
2026/// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
2027/// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
2028///
2029/// \param [in] Source The string to be split on whitespace with quotes.
2030/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2031/// \param [in] MarkEOLs true if tokenizing a response file and you want end of
2032/// lines and end of the response file to be marked with a nullptr string.
2033/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2034void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
2035 SmallVectorImpl<const char *> &NewArgv,
2036 bool MarkEOLs = false);
2037
2038/// Tokenizes a Windows command line while attempting to avoid copies. If no
2039/// quoting or escaping was used, this produces substrings of the original
2040/// string. If a token requires unquoting, it will be allocated with the
2041/// StringSaver.
2042void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver,
2043 SmallVectorImpl<StringRef> &NewArgv);
2044
2045/// String tokenization function type. Should be compatible with either
2046/// Windows or Unix command line tokenizers.
2047using TokenizerCallback = void (*)(StringRef Source, StringSaver &Saver,
2048 SmallVectorImpl<const char *> &NewArgv,
2049 bool MarkEOLs);
2050
2051/// Tokenizes content of configuration file.
2052///
2053/// \param [in] Source The string representing content of config file.
2054/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2055/// \param [out] NewArgv All parsed strings are appended to NewArgv.
2056/// \param [in] MarkEOLs Added for compatibility with TokenizerCallback.
2057///
2058/// It works like TokenizeGNUCommandLine with ability to skip comment lines.
2059///
2060void tokenizeConfigFile(StringRef Source, StringSaver &Saver,
2061 SmallVectorImpl<const char *> &NewArgv,
2062 bool MarkEOLs = false);
2063
2064/// Reads command line options from the given configuration file.
2065///
2066/// \param [in] CfgFileName Path to configuration file.
2067/// \param [in] Saver Objects that saves allocated strings.
2068/// \param [out] Argv Array to which the read options are added.
2069/// \return true if the file was successfully read.
2070///
2071/// It reads content of the specified file, tokenizes it and expands "@file"
2072/// commands resolving file names in them relative to the directory where
2073/// CfgFilename resides.
2074///
2075bool readConfigFile(StringRef CfgFileName, StringSaver &Saver,
2076 SmallVectorImpl<const char *> &Argv);
2077
2078/// Expand response files on a command line recursively using the given
2079/// StringSaver and tokenization strategy. Argv should contain the command line
2080/// before expansion and will be modified in place. If requested, Argv will
2081/// also be populated with nullptrs indicating where each response file line
2082/// ends, which is useful for the "/link" argument that needs to consume all
2083/// remaining arguments only until the next end of line, when in a response
2084/// file.
2085///
2086/// \param [in] Saver Delegates back to the caller for saving parsed strings.
2087/// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
2088/// \param [in,out] Argv Command line into which to expand response files.
2089/// \param [in] MarkEOLs Mark end of lines and the end of the response file
2090/// with nullptrs in the Argv vector.
2091/// \param [in] RelativeNames true if names of nested response files must be
2092/// resolved relative to including file.
2093/// \param [in] FS File system used for all file access when running the tool.
2094/// \param [in] CurrentDir Path used to resolve relative rsp files. If set to
2095/// None, process' cwd is used instead.
2096/// \return true if all @files were expanded successfully or there were none.
2097bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
2098 SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
2099 bool RelativeNames,
2100 llvm::Optional<llvm::StringRef> CurrentDir,
2101 llvm::vfs::FileSystem &FS);
2102
2103/// An overload of ExpandResponseFiles() that uses
2104/// llvm::vfs::getRealFileSystem().
2105bool ExpandResponseFiles(
2106 StringSaver &Saver, TokenizerCallback Tokenizer,
2107 SmallVectorImpl<const char *> &Argv, bool MarkEOLs = false,
2108 bool RelativeNames = false,
2109 llvm::Optional<llvm::StringRef> CurrentDir = llvm::None);
2110
2111/// A convenience helper which concatenates the options specified by the
2112/// environment variable EnvVar and command line options, then expands response
2113/// files recursively. The tokenizer is a predefined GNU or Windows one.
2114/// \return true if all @files were expanded successfully or there were none.
2115bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar,
2116 StringSaver &Saver,
2117 SmallVectorImpl<const char *> &NewArgv);
2118
2119/// Mark all options not part of this category as cl::ReallyHidden.
2120///
2121/// \param Category the category of options to keep displaying
2122///
2123/// Some tools (like clang-format) like to be able to hide all options that are
2124/// not specific to the tool. This function allows a tool to specify a single
2125/// option category to display in the -help output.
2126void HideUnrelatedOptions(cl::OptionCategory &Category,
2127 SubCommand &Sub = *TopLevelSubCommand);
2128
2129/// Mark all options not part of the categories as cl::ReallyHidden.
2130///
2131/// \param Categories the categories of options to keep displaying.
2132///
2133/// Some tools (like clang-format) like to be able to hide all options that are
2134/// not specific to the tool. This function allows a tool to specify a single
2135/// option category to display in the -help output.
2136void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2137 SubCommand &Sub = *TopLevelSubCommand);
2138
2139/// Reset all command line options to a state that looks as if they have
2140/// never appeared on the command line. This is useful for being able to parse
2141/// a command line multiple times (especially useful for writing tests).
2142void ResetAllOptionOccurrences();
2143
2144/// Reset the command line parser back to its initial state. This
2145/// removes
2146/// all options, categories, and subcommands and returns the parser to a state
2147/// where no options are supported.
2148void ResetCommandLineParser();
2149
2150/// Parses `Arg` into the option handler `Handler`.
2151bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i);
2152
2153} // end namespace cl
2154
2155} // end namespace llvm
2156
2157#endif // LLVM_SUPPORT_COMMANDLINE_H