xref: /src/contrib/llvm-project/llvm/lib/Support/CommandLine.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1009b1c42SEd Schouten //===-- CommandLine.cpp - Command line parser implementation --------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This class implements a command line argument processor that is useful when
10009b1c42SEd Schouten // creating a tool.  It provides a simple, minimalistic interface that is easily
11009b1c42SEd Schouten // extensible and supports nonlocal (library) command line options.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten // Note that rather than trying to figure out what this code does, you could try
14009b1c42SEd Schouten // reading the library documentation located in docs/CommandLine.html
15009b1c42SEd Schouten //
16009b1c42SEd Schouten //===----------------------------------------------------------------------===//
17009b1c42SEd Schouten 
18009b1c42SEd Schouten #include "llvm/Support/CommandLine.h"
19344a3780SDimitry Andric 
20344a3780SDimitry Andric #include "DebugOptions.h"
21344a3780SDimitry Andric 
2267c32a98SDimitry Andric #include "llvm-c/Support.h"
23f8af5cf6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
246f8fc217SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
2559850d08SRoman Divacky #include "llvm/ADT/SmallPtrSet.h"
2659850d08SRoman Divacky #include "llvm/ADT/SmallString.h"
2708bbd35aSDimitry Andric #include "llvm/ADT/StringExtras.h"
2859850d08SRoman Divacky #include "llvm/ADT/StringMap.h"
29706b4fc4SDimitry Andric #include "llvm/ADT/StringRef.h"
3059850d08SRoman Divacky #include "llvm/ADT/Twine.h"
3159850d08SRoman Divacky #include "llvm/Config/config.h"
32f8af5cf6SDimitry Andric #include "llvm/Support/ConvertUTF.h"
334a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
34706b4fc4SDimitry Andric #include "llvm/Support/Error.h"
354a16efa3SDimitry Andric #include "llvm/Support/ErrorHandling.h"
36b915e9e0SDimitry Andric #include "llvm/Support/FileSystem.h"
374a16efa3SDimitry Andric #include "llvm/Support/ManagedStatic.h"
384a16efa3SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
394a16efa3SDimitry Andric #include "llvm/Support/Path.h"
40b915e9e0SDimitry Andric #include "llvm/Support/Process.h"
413a0822f0SDimitry Andric #include "llvm/Support/StringSaver.h"
42706b4fc4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
434a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
4459850d08SRoman Divacky #include <cstdlib>
45e3b55780SDimitry Andric #include <optional>
46706b4fc4SDimitry Andric #include <string>
47009b1c42SEd Schouten using namespace llvm;
48009b1c42SEd Schouten using namespace cl;
49009b1c42SEd Schouten 
505ca98fd9SDimitry Andric #define DEBUG_TYPE "commandline"
515ca98fd9SDimitry Andric 
52009b1c42SEd Schouten //===----------------------------------------------------------------------===//
53009b1c42SEd Schouten // Template instantiations and anchors.
54009b1c42SEd Schouten //
5567c32a98SDimitry Andric namespace llvm {
5667c32a98SDimitry Andric namespace cl {
57ee8648bdSDimitry Andric template class basic_parser<bool>;
58ee8648bdSDimitry Andric template class basic_parser<boolOrDefault>;
59ee8648bdSDimitry Andric template class basic_parser<int>;
60706b4fc4SDimitry Andric template class basic_parser<long>;
61706b4fc4SDimitry Andric template class basic_parser<long long>;
62ee8648bdSDimitry Andric template class basic_parser<unsigned>;
63e6d15924SDimitry Andric template class basic_parser<unsigned long>;
64ee8648bdSDimitry Andric template class basic_parser<unsigned long long>;
65ee8648bdSDimitry Andric template class basic_parser<double>;
66ee8648bdSDimitry Andric template class basic_parser<float>;
67ee8648bdSDimitry Andric template class basic_parser<std::string>;
68ee8648bdSDimitry Andric template class basic_parser<char>;
69009b1c42SEd Schouten 
70ee8648bdSDimitry Andric template class opt<unsigned>;
71ee8648bdSDimitry Andric template class opt<int>;
72ee8648bdSDimitry Andric template class opt<std::string>;
73ee8648bdSDimitry Andric template class opt<char>;
74ee8648bdSDimitry Andric template class opt<bool>;
75344a3780SDimitry Andric } // namespace cl
76344a3780SDimitry Andric } // namespace llvm
77009b1c42SEd Schouten 
78f8af5cf6SDimitry Andric // Pin the vtables to this file.
anchor()7963faed5bSDimitry Andric void GenericOptionValue::anchor() {}
anchor()8063faed5bSDimitry Andric void OptionValue<boolOrDefault>::anchor() {}
anchor()8163faed5bSDimitry Andric void OptionValue<std::string>::anchor() {}
anchor()82009b1c42SEd Schouten void Option::anchor() {}
anchor()83009b1c42SEd Schouten void basic_parser_impl::anchor() {}
anchor()84009b1c42SEd Schouten void parser<bool>::anchor() {}
anchor()85009b1c42SEd Schouten void parser<boolOrDefault>::anchor() {}
anchor()86009b1c42SEd Schouten void parser<int>::anchor() {}
anchor()87706b4fc4SDimitry Andric void parser<long>::anchor() {}
anchor()88706b4fc4SDimitry Andric void parser<long long>::anchor() {}
anchor()89009b1c42SEd Schouten void parser<unsigned>::anchor() {}
anchor()90e6d15924SDimitry Andric void parser<unsigned long>::anchor() {}
anchor()9130815c53SDimitry Andric void parser<unsigned long long>::anchor() {}
anchor()92009b1c42SEd Schouten void parser<double>::anchor() {}
anchor()93009b1c42SEd Schouten void parser<float>::anchor() {}
anchor()94009b1c42SEd Schouten void parser<std::string>::anchor() {}
anchor()95009b1c42SEd Schouten void parser<char>::anchor() {}
96009b1c42SEd Schouten 
97009b1c42SEd Schouten //===----------------------------------------------------------------------===//
98009b1c42SEd Schouten 
99706b4fc4SDimitry Andric const static size_t DefaultPad = 2;
100706b4fc4SDimitry Andric 
101e6d15924SDimitry Andric static StringRef ArgPrefix = "-";
102e6d15924SDimitry Andric static StringRef ArgPrefixLong = "--";
103e6d15924SDimitry Andric static StringRef ArgHelpPrefix = " - ";
104e6d15924SDimitry Andric 
argPlusPrefixesSize(StringRef ArgName,size_t Pad=DefaultPad)105706b4fc4SDimitry Andric static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
106e6d15924SDimitry Andric   size_t Len = ArgName.size();
107e6d15924SDimitry Andric   if (Len == 1)
108706b4fc4SDimitry Andric     return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
109706b4fc4SDimitry Andric   return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
110e6d15924SDimitry Andric }
111e6d15924SDimitry Andric 
argPrefix(StringRef ArgName,size_t Pad=DefaultPad)112706b4fc4SDimitry Andric static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
113706b4fc4SDimitry Andric   SmallString<8> Prefix;
114706b4fc4SDimitry Andric   for (size_t I = 0; I < Pad; ++I) {
115706b4fc4SDimitry Andric     Prefix.push_back(' ');
116706b4fc4SDimitry Andric   }
117706b4fc4SDimitry Andric   Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
118706b4fc4SDimitry Andric   return Prefix;
119e6d15924SDimitry Andric }
120e6d15924SDimitry Andric 
121e6d15924SDimitry Andric // Option predicates...
isGrouping(const Option * O)122e6d15924SDimitry Andric static inline bool isGrouping(const Option *O) {
123e6d15924SDimitry Andric   return O->getMiscFlags() & cl::Grouping;
124e6d15924SDimitry Andric }
isPrefixedOrGrouping(const Option * O)125e6d15924SDimitry Andric static inline bool isPrefixedOrGrouping(const Option *O) {
126e6d15924SDimitry Andric   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
127e6d15924SDimitry Andric          O->getFormattingFlag() == cl::AlwaysPrefix;
128e6d15924SDimitry Andric }
129e6d15924SDimitry Andric 
130e6d15924SDimitry Andric 
1315a5ac124SDimitry Andric namespace {
1325a5ac124SDimitry Andric 
133e6d15924SDimitry Andric class PrintArg {
134e6d15924SDimitry Andric   StringRef ArgName;
135706b4fc4SDimitry Andric   size_t Pad;
136e6d15924SDimitry Andric public:
PrintArg(StringRef ArgName,size_t Pad=DefaultPad)137706b4fc4SDimitry Andric   PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
138e6d15924SDimitry Andric   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
139e6d15924SDimitry Andric };
140e6d15924SDimitry Andric 
operator <<(raw_ostream & OS,const PrintArg & Arg)141e6d15924SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
142706b4fc4SDimitry Andric   OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
143e6d15924SDimitry Andric   return OS;
144e6d15924SDimitry Andric }
145e6d15924SDimitry Andric 
1465a5ac124SDimitry Andric class CommandLineParser {
1475a5ac124SDimitry Andric public:
148009b1c42SEd Schouten   // Globals for name and overview of program.  Program name is not a string to
149009b1c42SEd Schouten   // avoid static ctor/dtor issues.
1505a5ac124SDimitry Andric   std::string ProgramName;
151b915e9e0SDimitry Andric   StringRef ProgramOverview;
152009b1c42SEd Schouten 
153009b1c42SEd Schouten   // This collects additional help to be printed.
154b915e9e0SDimitry Andric   std::vector<StringRef> MoreHelp;
155009b1c42SEd Schouten 
156e6d15924SDimitry Andric   // This collects Options added with the cl::DefaultOption flag. Since they can
157e6d15924SDimitry Andric   // be overridden, they are not added to the appropriate SubCommands until
158e6d15924SDimitry Andric   // ParseCommandLineOptions actually runs.
159e6d15924SDimitry Andric   SmallVector<Option*, 4> DefaultOptions;
160e6d15924SDimitry Andric 
16159d6cff9SDimitry Andric   // This collects the different option categories that have been registered.
1625a5ac124SDimitry Andric   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
16359d6cff9SDimitry Andric 
16401095a5dSDimitry Andric   // This collects the different subcommands that have been registered.
16501095a5dSDimitry Andric   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
16659d6cff9SDimitry Andric 
CommandLineParser()1674df029ccSDimitry Andric   CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
1685ca98fd9SDimitry Andric 
16901095a5dSDimitry Andric   void ResetAllOptionOccurrences();
17001095a5dSDimitry Andric 
17101095a5dSDimitry Andric   bool ParseCommandLineOptions(int argc, const char *const *argv,
172e6d15924SDimitry Andric                                StringRef Overview, raw_ostream *Errs = nullptr,
173e6d15924SDimitry Andric                                bool LongOptionsUseDoubleDash = false);
17401095a5dSDimitry Andric 
forEachSubCommand(Option & Opt,function_ref<void (SubCommand &)> Action)17599aabd70SDimitry Andric   void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) {
17699aabd70SDimitry Andric     if (Opt.Subs.empty()) {
17799aabd70SDimitry Andric       Action(SubCommand::getTopLevel());
17899aabd70SDimitry Andric       return;
17999aabd70SDimitry Andric     }
18099aabd70SDimitry Andric     if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) {
18199aabd70SDimitry Andric       for (auto *SC : RegisteredSubCommands)
18299aabd70SDimitry Andric         Action(*SC);
1834df029ccSDimitry Andric       Action(SubCommand::getAll());
18499aabd70SDimitry Andric       return;
18599aabd70SDimitry Andric     }
18699aabd70SDimitry Andric     for (auto *SC : Opt.Subs) {
18799aabd70SDimitry Andric       assert(SC != &SubCommand::getAll() &&
18899aabd70SDimitry Andric              "SubCommand::getAll() should not be used with other subcommands");
18999aabd70SDimitry Andric       Action(*SC);
19099aabd70SDimitry Andric     }
19199aabd70SDimitry Andric   }
19299aabd70SDimitry Andric 
addLiteralOption(Option & Opt,SubCommand * SC,StringRef Name)193b915e9e0SDimitry Andric   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
19401095a5dSDimitry Andric     if (Opt.hasArgStr())
19501095a5dSDimitry Andric       return;
19601095a5dSDimitry Andric     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
1975a5ac124SDimitry Andric       errs() << ProgramName << ": CommandLine Error: Option '" << Name
1985a5ac124SDimitry Andric              << "' registered more than once!\n";
1995a5ac124SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
2005a5ac124SDimitry Andric     }
20159d6cff9SDimitry Andric   }
202009b1c42SEd Schouten 
addLiteralOption(Option & Opt,StringRef Name)203b915e9e0SDimitry Andric   void addLiteralOption(Option &Opt, StringRef Name) {
20499aabd70SDimitry Andric     forEachSubCommand(
20599aabd70SDimitry Andric         Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
20601095a5dSDimitry Andric   }
20701095a5dSDimitry Andric 
addOption(Option * O,SubCommand * SC)20801095a5dSDimitry Andric   void addOption(Option *O, SubCommand *SC) {
2095ca98fd9SDimitry Andric     bool HadErrors = false;
210dd58ef01SDimitry Andric     if (O->hasArgStr()) {
211e6d15924SDimitry Andric       // If it's a DefaultOption, check to make sure it isn't already there.
2127fa27ce4SDimitry Andric       if (O->isDefaultOption() && SC->OptionsMap.contains(O->ArgStr))
213e6d15924SDimitry Andric         return;
214e6d15924SDimitry Andric 
215009b1c42SEd Schouten       // Add argument to the argument map!
21601095a5dSDimitry Andric       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
2175a5ac124SDimitry Andric         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
2185a5ac124SDimitry Andric                << "' registered more than once!\n";
2195ca98fd9SDimitry Andric         HadErrors = true;
220009b1c42SEd Schouten       }
221009b1c42SEd Schouten     }
222009b1c42SEd Schouten 
223009b1c42SEd Schouten     // Remember information about positional options.
224009b1c42SEd Schouten     if (O->getFormattingFlag() == cl::Positional)
22501095a5dSDimitry Andric       SC->PositionalOpts.push_back(O);
226009b1c42SEd Schouten     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
22701095a5dSDimitry Andric       SC->SinkOpts.push_back(O);
228009b1c42SEd Schouten     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
22901095a5dSDimitry Andric       if (SC->ConsumeAfterOpt) {
230009b1c42SEd Schouten         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
2315ca98fd9SDimitry Andric         HadErrors = true;
2325ca98fd9SDimitry Andric       }
23301095a5dSDimitry Andric       SC->ConsumeAfterOpt = O;
234009b1c42SEd Schouten     }
2355ca98fd9SDimitry Andric 
2365ca98fd9SDimitry Andric     // Fail hard if there were errors. These are strictly unrecoverable and
2375a5ac124SDimitry Andric     // indicate serious issues such as conflicting option names or an
2385a5ac124SDimitry Andric     // incorrectly
2395ca98fd9SDimitry Andric     // linked LLVM distribution.
2405ca98fd9SDimitry Andric     if (HadErrors)
2415ca98fd9SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
242009b1c42SEd Schouten   }
243009b1c42SEd Schouten 
addOption(Option * O,bool ProcessDefaultOption=false)244e6d15924SDimitry Andric   void addOption(Option *O, bool ProcessDefaultOption = false) {
245e6d15924SDimitry Andric     if (!ProcessDefaultOption && O->isDefaultOption()) {
246e6d15924SDimitry Andric       DefaultOptions.push_back(O);
247e6d15924SDimitry Andric       return;
248e6d15924SDimitry Andric     }
24999aabd70SDimitry Andric     forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &SC); });
25001095a5dSDimitry Andric   }
25101095a5dSDimitry Andric 
removeOption(Option * O,SubCommand * SC)25201095a5dSDimitry Andric   void removeOption(Option *O, SubCommand *SC) {
253dd58ef01SDimitry Andric     SmallVector<StringRef, 16> OptionNames;
2545a5ac124SDimitry Andric     O->getExtraOptionNames(OptionNames);
255dd58ef01SDimitry Andric     if (O->hasArgStr())
2565a5ac124SDimitry Andric       OptionNames.push_back(O->ArgStr);
25701095a5dSDimitry Andric 
25801095a5dSDimitry Andric     SubCommand &Sub = *SC;
259e6d15924SDimitry Andric     auto End = Sub.OptionsMap.end();
260e6d15924SDimitry Andric     for (auto Name : OptionNames) {
261e6d15924SDimitry Andric       auto I = Sub.OptionsMap.find(Name);
262e6d15924SDimitry Andric       if (I != End && I->getValue() == O)
263e6d15924SDimitry Andric         Sub.OptionsMap.erase(I);
264e6d15924SDimitry Andric     }
2655a5ac124SDimitry Andric 
2665a5ac124SDimitry Andric     if (O->getFormattingFlag() == cl::Positional)
267344a3780SDimitry Andric       for (auto *Opt = Sub.PositionalOpts.begin();
26801095a5dSDimitry Andric            Opt != Sub.PositionalOpts.end(); ++Opt) {
2695a5ac124SDimitry Andric         if (*Opt == O) {
27001095a5dSDimitry Andric           Sub.PositionalOpts.erase(Opt);
2715a5ac124SDimitry Andric           break;
2725a5ac124SDimitry Andric         }
2735a5ac124SDimitry Andric       }
2745a5ac124SDimitry Andric     else if (O->getMiscFlags() & cl::Sink)
275344a3780SDimitry Andric       for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
2765a5ac124SDimitry Andric         if (*Opt == O) {
27701095a5dSDimitry Andric           Sub.SinkOpts.erase(Opt);
2785a5ac124SDimitry Andric           break;
2795a5ac124SDimitry Andric         }
2805a5ac124SDimitry Andric       }
28101095a5dSDimitry Andric     else if (O == Sub.ConsumeAfterOpt)
28201095a5dSDimitry Andric       Sub.ConsumeAfterOpt = nullptr;
2835a5ac124SDimitry Andric   }
2845a5ac124SDimitry Andric 
removeOption(Option * O)28501095a5dSDimitry Andric   void removeOption(Option *O) {
28699aabd70SDimitry Andric     forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &SC); });
2875a5ac124SDimitry Andric   }
2885a5ac124SDimitry Andric 
hasOptions(const SubCommand & Sub) const28901095a5dSDimitry Andric   bool hasOptions(const SubCommand &Sub) const {
29001095a5dSDimitry Andric     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
29101095a5dSDimitry Andric             nullptr != Sub.ConsumeAfterOpt);
29201095a5dSDimitry Andric   }
29301095a5dSDimitry Andric 
hasOptions() const29401095a5dSDimitry Andric   bool hasOptions() const {
295706b4fc4SDimitry Andric     for (const auto *S : RegisteredSubCommands) {
29601095a5dSDimitry Andric       if (hasOptions(*S))
29701095a5dSDimitry Andric         return true;
29801095a5dSDimitry Andric     }
29901095a5dSDimitry Andric     return false;
30001095a5dSDimitry Andric   }
30101095a5dSDimitry Andric 
hasNamedSubCommands() const302312c0ed1SDimitry Andric   bool hasNamedSubCommands() const {
303312c0ed1SDimitry Andric     for (const auto *S : RegisteredSubCommands)
304312c0ed1SDimitry Andric       if (!S->getName().empty())
305312c0ed1SDimitry Andric         return true;
306312c0ed1SDimitry Andric     return false;
307312c0ed1SDimitry Andric   }
308312c0ed1SDimitry Andric 
getActiveSubCommand()30901095a5dSDimitry Andric   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
31001095a5dSDimitry Andric 
updateArgStr(Option * O,StringRef NewName,SubCommand * SC)31101095a5dSDimitry Andric   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
31201095a5dSDimitry Andric     SubCommand &Sub = *SC;
31301095a5dSDimitry Andric     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
3145a5ac124SDimitry Andric       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
3155a5ac124SDimitry Andric              << "' registered more than once!\n";
3165a5ac124SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
3175a5ac124SDimitry Andric     }
31801095a5dSDimitry Andric     Sub.OptionsMap.erase(O->ArgStr);
31901095a5dSDimitry Andric   }
32001095a5dSDimitry Andric 
updateArgStr(Option * O,StringRef NewName)32101095a5dSDimitry Andric   void updateArgStr(Option *O, StringRef NewName) {
32299aabd70SDimitry Andric     forEachSubCommand(*O,
32399aabd70SDimitry Andric                       [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
324e6d15924SDimitry Andric   }
3255a5ac124SDimitry Andric 
3265a5ac124SDimitry Andric   void printOptionValues();
3275a5ac124SDimitry Andric 
registerCategory(OptionCategory * cat)3285a5ac124SDimitry Andric   void registerCategory(OptionCategory *cat) {
32901095a5dSDimitry Andric     assert(count_if(RegisteredOptionCategories,
3305a5ac124SDimitry Andric                     [cat](const OptionCategory *Category) {
3315a5ac124SDimitry Andric              return cat->getName() == Category->getName();
3325a5ac124SDimitry Andric            }) == 0 &&
3335a5ac124SDimitry Andric            "Duplicate option categories");
3345a5ac124SDimitry Andric 
3355a5ac124SDimitry Andric     RegisteredOptionCategories.insert(cat);
3365a5ac124SDimitry Andric   }
3375a5ac124SDimitry Andric 
registerSubCommand(SubCommand * sub)33801095a5dSDimitry Andric   void registerSubCommand(SubCommand *sub) {
33901095a5dSDimitry Andric     assert(count_if(RegisteredSubCommands,
34001095a5dSDimitry Andric                     [sub](const SubCommand *Sub) {
341b915e9e0SDimitry Andric                       return (!sub->getName().empty()) &&
34201095a5dSDimitry Andric                              (Sub->getName() == sub->getName());
34301095a5dSDimitry Andric                     }) == 0 &&
34401095a5dSDimitry Andric            "Duplicate subcommands");
34501095a5dSDimitry Andric     RegisteredSubCommands.insert(sub);
34601095a5dSDimitry Andric 
34701095a5dSDimitry Andric     // For all options that have been registered for all subcommands, add the
34801095a5dSDimitry Andric     // option to this subcommand now.
3494df029ccSDimitry Andric     assert(sub != &SubCommand::getAll() &&
3504df029ccSDimitry Andric            "SubCommand::getAll() should not be registered");
351e3b55780SDimitry Andric     for (auto &E : SubCommand::getAll().OptionsMap) {
35201095a5dSDimitry Andric       Option *O = E.second;
35301095a5dSDimitry Andric       if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
35401095a5dSDimitry Andric           O->hasArgStr())
35501095a5dSDimitry Andric         addOption(O, sub);
35601095a5dSDimitry Andric       else
357b915e9e0SDimitry Andric         addLiteralOption(*O, sub, E.first());
35801095a5dSDimitry Andric     }
35901095a5dSDimitry Andric   }
36001095a5dSDimitry Andric 
unregisterSubCommand(SubCommand * sub)36101095a5dSDimitry Andric   void unregisterSubCommand(SubCommand *sub) {
36201095a5dSDimitry Andric     RegisteredSubCommands.erase(sub);
36301095a5dSDimitry Andric   }
36401095a5dSDimitry Andric 
365b915e9e0SDimitry Andric   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()366b915e9e0SDimitry Andric   getRegisteredSubcommands() {
367b915e9e0SDimitry Andric     return make_range(RegisteredSubCommands.begin(),
368b915e9e0SDimitry Andric                       RegisteredSubCommands.end());
369b915e9e0SDimitry Andric   }
370b915e9e0SDimitry Andric 
reset()37101095a5dSDimitry Andric   void reset() {
37201095a5dSDimitry Andric     ActiveSubCommand = nullptr;
37301095a5dSDimitry Andric     ProgramName.clear();
374b915e9e0SDimitry Andric     ProgramOverview = StringRef();
37501095a5dSDimitry Andric 
37601095a5dSDimitry Andric     MoreHelp.clear();
37701095a5dSDimitry Andric     RegisteredOptionCategories.clear();
37801095a5dSDimitry Andric 
37901095a5dSDimitry Andric     ResetAllOptionOccurrences();
38001095a5dSDimitry Andric     RegisteredSubCommands.clear();
38101095a5dSDimitry Andric 
382e3b55780SDimitry Andric     SubCommand::getTopLevel().reset();
383e3b55780SDimitry Andric     SubCommand::getAll().reset();
384e3b55780SDimitry Andric     registerSubCommand(&SubCommand::getTopLevel());
385e6d15924SDimitry Andric 
386e6d15924SDimitry Andric     DefaultOptions.clear();
38701095a5dSDimitry Andric   }
38801095a5dSDimitry Andric 
3895a5ac124SDimitry Andric private:
390145449b1SDimitry Andric   SubCommand *ActiveSubCommand = nullptr;
39101095a5dSDimitry Andric 
39201095a5dSDimitry Andric   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
LookupLongOption(SubCommand & Sub,StringRef & Arg,StringRef & Value,bool LongOptionsUseDoubleDash,bool HaveDoubleDash)393e6d15924SDimitry Andric   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
394e6d15924SDimitry Andric                            bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
395e6d15924SDimitry Andric     Option *Opt = LookupOption(Sub, Arg, Value);
396e6d15924SDimitry Andric     if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
397e6d15924SDimitry Andric       return nullptr;
398e6d15924SDimitry Andric     return Opt;
399e6d15924SDimitry Andric   }
400312c0ed1SDimitry Andric   SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
4015a5ac124SDimitry Andric };
4025a5ac124SDimitry Andric 
4035a5ac124SDimitry Andric } // namespace
4045a5ac124SDimitry Andric 
4055a5ac124SDimitry Andric static ManagedStatic<CommandLineParser> GlobalParser;
4065a5ac124SDimitry Andric 
AddLiteralOption(Option & O,StringRef Name)407b915e9e0SDimitry Andric void cl::AddLiteralOption(Option &O, StringRef Name) {
4085a5ac124SDimitry Andric   GlobalParser->addLiteralOption(O, Name);
4095a5ac124SDimitry Andric }
4105a5ac124SDimitry Andric 
extrahelp(StringRef Help)411b915e9e0SDimitry Andric extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
4125a5ac124SDimitry Andric   GlobalParser->MoreHelp.push_back(Help);
4135a5ac124SDimitry Andric }
4145a5ac124SDimitry Andric 
addArgument()4155a5ac124SDimitry Andric void Option::addArgument() {
4165a5ac124SDimitry Andric   GlobalParser->addOption(this);
4175a5ac124SDimitry Andric   FullyInitialized = true;
4185a5ac124SDimitry Andric }
4195a5ac124SDimitry Andric 
removeArgument()4205a5ac124SDimitry Andric void Option::removeArgument() { GlobalParser->removeOption(this); }
4215a5ac124SDimitry Andric 
setArgStr(StringRef S)422dd58ef01SDimitry Andric void Option::setArgStr(StringRef S) {
4235a5ac124SDimitry Andric   if (FullyInitialized)
4245a5ac124SDimitry Andric     GlobalParser->updateArgStr(this, S);
425ac9a064cSDimitry Andric   assert(!S.starts_with("-") && "Option can't start with '-");
4265a5ac124SDimitry Andric   ArgStr = S;
427e6d15924SDimitry Andric   if (ArgStr.size() == 1)
428e6d15924SDimitry Andric     setMiscFlag(Grouping);
429e6d15924SDimitry Andric }
430e6d15924SDimitry Andric 
addCategory(OptionCategory & C)431e6d15924SDimitry Andric void Option::addCategory(OptionCategory &C) {
432e6d15924SDimitry Andric   assert(!Categories.empty() && "Categories cannot be empty.");
433e6d15924SDimitry Andric   // Maintain backward compatibility by replacing the default GeneralCategory
434e6d15924SDimitry Andric   // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
435e6d15924SDimitry Andric   // must be explicitly added if you want multiple categories that include it.
436344a3780SDimitry Andric   if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
437e6d15924SDimitry Andric     Categories[0] = &C;
438b60736ecSDimitry Andric   else if (!is_contained(Categories, &C))
439e6d15924SDimitry Andric     Categories.push_back(&C);
440e6d15924SDimitry Andric }
441e6d15924SDimitry Andric 
reset()442e6d15924SDimitry Andric void Option::reset() {
443e6d15924SDimitry Andric   NumOccurrences = 0;
444e6d15924SDimitry Andric   setDefault();
445e6d15924SDimitry Andric   if (isDefaultOption())
446e6d15924SDimitry Andric     removeArgument();
4475a5ac124SDimitry Andric }
4485a5ac124SDimitry Andric 
registerCategory()4495a5ac124SDimitry Andric void OptionCategory::registerCategory() {
4505a5ac124SDimitry Andric   GlobalParser->registerCategory(this);
4515a5ac124SDimitry Andric }
4525a5ac124SDimitry Andric 
453e6d15924SDimitry Andric // A special subcommand representing no subcommand. It is particularly important
454e6d15924SDimitry Andric // that this ManagedStatic uses constant initailization and not dynamic
455e6d15924SDimitry Andric // initialization because it is referenced from cl::opt constructors, which run
456e6d15924SDimitry Andric // dynamically in an arbitrary order.
457e6d15924SDimitry Andric LLVM_REQUIRE_CONSTANT_INITIALIZATION
458ac9a064cSDimitry Andric static ManagedStatic<SubCommand> TopLevelSubCommand;
45901095a5dSDimitry Andric 
46001095a5dSDimitry Andric // A special subcommand that can be used to put an option into all subcommands.
461ac9a064cSDimitry Andric static ManagedStatic<SubCommand> AllSubCommands;
46201095a5dSDimitry Andric 
getTopLevel()463e3b55780SDimitry Andric SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; }
464e3b55780SDimitry Andric 
getAll()465e3b55780SDimitry Andric SubCommand &SubCommand::getAll() { return *AllSubCommands; }
466e3b55780SDimitry Andric 
registerSubCommand()46701095a5dSDimitry Andric void SubCommand::registerSubCommand() {
46801095a5dSDimitry Andric   GlobalParser->registerSubCommand(this);
46901095a5dSDimitry Andric }
47001095a5dSDimitry Andric 
unregisterSubCommand()47101095a5dSDimitry Andric void SubCommand::unregisterSubCommand() {
47201095a5dSDimitry Andric   GlobalParser->unregisterSubCommand(this);
47301095a5dSDimitry Andric }
47401095a5dSDimitry Andric 
reset()47501095a5dSDimitry Andric void SubCommand::reset() {
47601095a5dSDimitry Andric   PositionalOpts.clear();
47701095a5dSDimitry Andric   SinkOpts.clear();
47801095a5dSDimitry Andric   OptionsMap.clear();
47901095a5dSDimitry Andric 
48001095a5dSDimitry Andric   ConsumeAfterOpt = nullptr;
48101095a5dSDimitry Andric }
48201095a5dSDimitry Andric 
operator bool() const48301095a5dSDimitry Andric SubCommand::operator bool() const {
48401095a5dSDimitry Andric   return (GlobalParser->getActiveSubCommand() == this);
48501095a5dSDimitry Andric }
48601095a5dSDimitry Andric 
4875a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
4885a5ac124SDimitry Andric // Basic, shared command line option processing machinery.
4895a5ac124SDimitry Andric //
4905a5ac124SDimitry Andric 
491009b1c42SEd Schouten /// LookupOption - Lookup the option specified by the specified option on the
492009b1c42SEd Schouten /// command line.  If there is a value specified (after an equal sign) return
49359850d08SRoman Divacky /// that as well.  This assumes that leading dashes have already been stripped.
LookupOption(SubCommand & Sub,StringRef & Arg,StringRef & Value)49401095a5dSDimitry Andric Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
49501095a5dSDimitry Andric                                         StringRef &Value) {
49659850d08SRoman Divacky   // Reject all dashes.
49767c32a98SDimitry Andric   if (Arg.empty())
49867c32a98SDimitry Andric     return nullptr;
499e3b55780SDimitry Andric   assert(&Sub != &SubCommand::getAll());
500009b1c42SEd Schouten 
50159850d08SRoman Divacky   size_t EqualPos = Arg.find('=');
502009b1c42SEd Schouten 
50359850d08SRoman Divacky   // If we have an equals sign, remember the value.
50459850d08SRoman Divacky   if (EqualPos == StringRef::npos) {
505009b1c42SEd Schouten     // Look up the option.
506b60736ecSDimitry Andric     return Sub.OptionsMap.lookup(Arg);
507009b1c42SEd Schouten   }
508009b1c42SEd Schouten 
509d8e91e46SDimitry Andric   // If the argument before the = is a valid option name and the option allows
510d8e91e46SDimitry Andric   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
511d8e91e46SDimitry Andric   // failure by returning nullptr.
51201095a5dSDimitry Andric   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
51301095a5dSDimitry Andric   if (I == Sub.OptionsMap.end())
51467c32a98SDimitry Andric     return nullptr;
51559850d08SRoman Divacky 
516344a3780SDimitry Andric   auto *O = I->second;
517d8e91e46SDimitry Andric   if (O->getFormattingFlag() == cl::AlwaysPrefix)
518d8e91e46SDimitry Andric     return nullptr;
519d8e91e46SDimitry Andric 
52059850d08SRoman Divacky   Value = Arg.substr(EqualPos + 1);
52159850d08SRoman Divacky   Arg = Arg.substr(0, EqualPos);
52259850d08SRoman Divacky   return I->second;
52359850d08SRoman Divacky }
52459850d08SRoman Divacky 
LookupSubCommand(StringRef Name,std::string & NearestString)525312c0ed1SDimitry Andric SubCommand *CommandLineParser::LookupSubCommand(StringRef Name,
526312c0ed1SDimitry Andric                                                 std::string &NearestString) {
527b915e9e0SDimitry Andric   if (Name.empty())
528e3b55780SDimitry Andric     return &SubCommand::getTopLevel();
529312c0ed1SDimitry Andric   // Find a subcommand with the edit distance == 1.
530312c0ed1SDimitry Andric   SubCommand *NearestMatch = nullptr;
531344a3780SDimitry Andric   for (auto *S : RegisteredSubCommands) {
5324df029ccSDimitry Andric     assert(S != &SubCommand::getAll() &&
5334df029ccSDimitry Andric            "SubCommand::getAll() is not expected in RegisteredSubCommands");
534b915e9e0SDimitry Andric     if (S->getName().empty())
53501095a5dSDimitry Andric       continue;
53601095a5dSDimitry Andric 
537ac9a064cSDimitry Andric     if (S->getName() == Name)
53801095a5dSDimitry Andric       return S;
539312c0ed1SDimitry Andric 
540312c0ed1SDimitry Andric     if (!NearestMatch && S->getName().edit_distance(Name) < 2)
541312c0ed1SDimitry Andric       NearestMatch = S;
54201095a5dSDimitry Andric   }
543312c0ed1SDimitry Andric 
544312c0ed1SDimitry Andric   if (NearestMatch)
545312c0ed1SDimitry Andric     NearestString = NearestMatch->getName();
546312c0ed1SDimitry Andric 
547e3b55780SDimitry Andric   return &SubCommand::getTopLevel();
54801095a5dSDimitry Andric }
54901095a5dSDimitry Andric 
550cf099d11SDimitry Andric /// LookupNearestOption - Lookup the closest match to the option specified by
551cf099d11SDimitry Andric /// the specified option on the command line.  If there is a value specified
552cf099d11SDimitry Andric /// (after an equal sign) return that as well.  This assumes that leading dashes
553cf099d11SDimitry Andric /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)554cf099d11SDimitry Andric static Option *LookupNearestOption(StringRef Arg,
555cf099d11SDimitry Andric                                    const StringMap<Option *> &OptionsMap,
5566b943ff3SDimitry Andric                                    std::string &NearestString) {
557cf099d11SDimitry Andric   // Reject all dashes.
55867c32a98SDimitry Andric   if (Arg.empty())
55967c32a98SDimitry Andric     return nullptr;
560cf099d11SDimitry Andric 
561cf099d11SDimitry Andric   // Split on any equal sign.
5626b943ff3SDimitry Andric   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
5636b943ff3SDimitry Andric   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
5646b943ff3SDimitry Andric   StringRef &RHS = SplitArg.second;
565cf099d11SDimitry Andric 
566cf099d11SDimitry Andric   // Find the closest match.
5675ca98fd9SDimitry Andric   Option *Best = nullptr;
568cf099d11SDimitry Andric   unsigned BestDistance = 0;
569cf099d11SDimitry Andric   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
57067c32a98SDimitry Andric                                            ie = OptionsMap.end();
57167c32a98SDimitry Andric        it != ie; ++it) {
572cf099d11SDimitry Andric     Option *O = it->second;
573cfca06d7SDimitry Andric     // Do not suggest really hidden options (not shown in any help).
574cfca06d7SDimitry Andric     if (O->getOptionHiddenFlag() == ReallyHidden)
575cfca06d7SDimitry Andric       continue;
576cfca06d7SDimitry Andric 
577dd58ef01SDimitry Andric     SmallVector<StringRef, 16> OptionNames;
578cf099d11SDimitry Andric     O->getExtraOptionNames(OptionNames);
579dd58ef01SDimitry Andric     if (O->hasArgStr())
580cf099d11SDimitry Andric       OptionNames.push_back(O->ArgStr);
581cf099d11SDimitry Andric 
5826b943ff3SDimitry Andric     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
5836b943ff3SDimitry Andric     StringRef Flag = PermitValue ? LHS : Arg;
584344a3780SDimitry Andric     for (const auto &Name : OptionNames) {
585cf099d11SDimitry Andric       unsigned Distance = StringRef(Name).edit_distance(
5866b943ff3SDimitry Andric           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
587cf099d11SDimitry Andric       if (!Best || Distance < BestDistance) {
588cf099d11SDimitry Andric         Best = O;
589cf099d11SDimitry Andric         BestDistance = Distance;
5906b943ff3SDimitry Andric         if (RHS.empty() || !PermitValue)
591cfca06d7SDimitry Andric           NearestString = std::string(Name);
5926b943ff3SDimitry Andric         else
593dd58ef01SDimitry Andric           NearestString = (Twine(Name) + "=" + RHS).str();
594cf099d11SDimitry Andric       }
595cf099d11SDimitry Andric     }
596cf099d11SDimitry Andric   }
597cf099d11SDimitry Andric 
598cf099d11SDimitry Andric   return Best;
599cf099d11SDimitry Andric }
600cf099d11SDimitry Andric 
6015ca98fd9SDimitry Andric /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
6025ca98fd9SDimitry Andric /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)6035ca98fd9SDimitry Andric static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
6045ca98fd9SDimitry Andric                                           StringRef ArgName, StringRef Value,
6055ca98fd9SDimitry Andric                                           bool MultiArg = false) {
60606f9d401SRoman Divacky   // Check to see if this option accepts a comma separated list of values.  If
60706f9d401SRoman Divacky   // it does, we have to split up the value into multiple values.
60806f9d401SRoman Divacky   if (Handler->getMiscFlags() & CommaSeparated) {
60906f9d401SRoman Divacky     StringRef Val(Value);
61006f9d401SRoman Divacky     StringRef::size_type Pos = Val.find(',');
61159850d08SRoman Divacky 
61206f9d401SRoman Divacky     while (Pos != StringRef::npos) {
61306f9d401SRoman Divacky       // Process the portion before the comma.
61406f9d401SRoman Divacky       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
61506f9d401SRoman Divacky         return true;
61606f9d401SRoman Divacky       // Erase the portion before the comma, AND the comma.
61706f9d401SRoman Divacky       Val = Val.substr(Pos + 1);
61806f9d401SRoman Divacky       // Check for another comma.
61906f9d401SRoman Divacky       Pos = Val.find(',');
62006f9d401SRoman Divacky     }
62106f9d401SRoman Divacky 
62206f9d401SRoman Divacky     Value = Val;
62306f9d401SRoman Divacky   }
62406f9d401SRoman Divacky 
625dd58ef01SDimitry Andric   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
62606f9d401SRoman Divacky }
62759850d08SRoman Divacky 
62859850d08SRoman Divacky /// ProvideOption - For Value, this differentiates between an empty value ("")
62959850d08SRoman Divacky /// and a null value (StringRef()).  The later is accepted for arguments that
63059850d08SRoman Divacky /// don't allow a value (-foo) the former is rejected (-foo=).
ProvideOption(Option * Handler,StringRef ArgName,StringRef Value,int argc,const char * const * argv,int & i)63159850d08SRoman Divacky static inline bool ProvideOption(Option *Handler, StringRef ArgName,
63263faed5bSDimitry Andric                                  StringRef Value, int argc,
63363faed5bSDimitry Andric                                  const char *const *argv, int &i) {
634009b1c42SEd Schouten   // Is this a multi-argument option?
635009b1c42SEd Schouten   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
636009b1c42SEd Schouten 
637009b1c42SEd Schouten   // Enforce value requirements
638009b1c42SEd Schouten   switch (Handler->getValueExpectedFlag()) {
639009b1c42SEd Schouten   case ValueRequired:
6405ca98fd9SDimitry Andric     if (!Value.data()) { // No value specified?
641d8e91e46SDimitry Andric       // If no other argument or the option only supports prefix form, we
642d8e91e46SDimitry Andric       // cannot look at the next argument.
643d8e91e46SDimitry Andric       if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
644009b1c42SEd Schouten         return Handler->error("requires a value!");
64559850d08SRoman Divacky       // Steal the next argument, like for '-o filename'
64667c32a98SDimitry Andric       assert(argv && "null check");
647b915e9e0SDimitry Andric       Value = StringRef(argv[++i]);
648009b1c42SEd Schouten     }
649009b1c42SEd Schouten     break;
650009b1c42SEd Schouten   case ValueDisallowed:
651009b1c42SEd Schouten     if (NumAdditionalVals > 0)
65259850d08SRoman Divacky       return Handler->error("multi-valued option specified"
653009b1c42SEd Schouten                             " with ValueDisallowed modifier!");
654009b1c42SEd Schouten 
65559850d08SRoman Divacky     if (Value.data())
65667c32a98SDimitry Andric       return Handler->error("does not allow a value! '" + Twine(Value) +
65767c32a98SDimitry Andric                             "' specified.");
658009b1c42SEd Schouten     break;
659009b1c42SEd Schouten   case ValueOptional:
660009b1c42SEd Schouten     break;
661009b1c42SEd Schouten   }
662009b1c42SEd Schouten 
663009b1c42SEd Schouten   // If this isn't a multi-arg option, just run the handler.
66459850d08SRoman Divacky   if (NumAdditionalVals == 0)
6655ca98fd9SDimitry Andric     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
66659850d08SRoman Divacky 
667009b1c42SEd Schouten   // If it is, run the handle several times.
668009b1c42SEd Schouten   bool MultiArg = false;
669009b1c42SEd Schouten 
67059850d08SRoman Divacky   if (Value.data()) {
6715ca98fd9SDimitry Andric     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
672009b1c42SEd Schouten       return true;
673009b1c42SEd Schouten     --NumAdditionalVals;
674009b1c42SEd Schouten     MultiArg = true;
675009b1c42SEd Schouten   }
676009b1c42SEd Schouten 
677009b1c42SEd Schouten   while (NumAdditionalVals > 0) {
67859850d08SRoman Divacky     if (i + 1 >= argc)
67959850d08SRoman Divacky       return Handler->error("not enough values!");
68067c32a98SDimitry Andric     assert(argv && "null check");
681b915e9e0SDimitry Andric     Value = StringRef(argv[++i]);
68259850d08SRoman Divacky 
6835ca98fd9SDimitry Andric     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
684009b1c42SEd Schouten       return true;
685009b1c42SEd Schouten     MultiArg = true;
686009b1c42SEd Schouten     --NumAdditionalVals;
687009b1c42SEd Schouten   }
688009b1c42SEd Schouten   return false;
689009b1c42SEd Schouten }
690009b1c42SEd Schouten 
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)6911d5ae102SDimitry Andric bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
692009b1c42SEd Schouten   int Dummy = i;
6935ca98fd9SDimitry Andric   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
694009b1c42SEd Schouten }
695009b1c42SEd Schouten 
696009b1c42SEd Schouten // getOptionPred - Check to see if there are any options that satisfy the
697009b1c42SEd Schouten // specified predicate with names that are the prefixes in Name.  This is
698009b1c42SEd Schouten // checked by progressively stripping characters off of the name, checking to
699009b1c42SEd Schouten // see if there options that satisfy the predicate.  If we find one, return it,
700009b1c42SEd Schouten // otherwise return null.
701009b1c42SEd Schouten //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)70259850d08SRoman Divacky static Option *getOptionPred(StringRef Name, size_t &Length,
703009b1c42SEd Schouten                              bool (*Pred)(const Option *),
70459850d08SRoman Divacky                              const StringMap<Option *> &OptionsMap) {
70559850d08SRoman Divacky   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
706e6d15924SDimitry Andric   if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
707e6d15924SDimitry Andric     OMI = OptionsMap.end();
708009b1c42SEd Schouten 
709009b1c42SEd Schouten   // Loop while we haven't found an option and Name still has at least two
710009b1c42SEd Schouten   // characters in it (so that the next iteration will not be the empty
71159850d08SRoman Divacky   // string.
71259850d08SRoman Divacky   while (OMI == OptionsMap.end() && Name.size() > 1) {
71359850d08SRoman Divacky     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
71459850d08SRoman Divacky     OMI = OptionsMap.find(Name);
715e6d15924SDimitry Andric     if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
716e6d15924SDimitry Andric       OMI = OptionsMap.end();
71759850d08SRoman Divacky   }
718009b1c42SEd Schouten 
719009b1c42SEd Schouten   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
72059850d08SRoman Divacky     Length = Name.size();
721009b1c42SEd Schouten     return OMI->second; // Found one!
722009b1c42SEd Schouten   }
7235ca98fd9SDimitry Andric   return nullptr; // No option found!
724009b1c42SEd Schouten }
725009b1c42SEd Schouten 
72659850d08SRoman Divacky /// HandlePrefixedOrGroupedOption - The specified argument string (which started
72759850d08SRoman Divacky /// with at least one '-') does not fully match an available option.  Check to
72859850d08SRoman Divacky /// see if this is a prefix or grouped option.  If so, split arg into output an
72959850d08SRoman Divacky /// Arg/Value pair and return the Option to parse it with.
73067c32a98SDimitry Andric static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)73167c32a98SDimitry Andric HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
73259850d08SRoman Divacky                               bool &ErrorParsing,
73359850d08SRoman Divacky                               const StringMap<Option *> &OptionsMap) {
73467c32a98SDimitry Andric   if (Arg.size() == 1)
73567c32a98SDimitry Andric     return nullptr;
73659850d08SRoman Divacky 
73759850d08SRoman Divacky   // Do the lookup!
73859850d08SRoman Divacky   size_t Length = 0;
73959850d08SRoman Divacky   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
74067c32a98SDimitry Andric   if (!PGOpt)
74167c32a98SDimitry Andric     return nullptr;
74259850d08SRoman Divacky 
743e6d15924SDimitry Andric   do {
744e6d15924SDimitry Andric     StringRef MaybeValue =
745e6d15924SDimitry Andric         (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
74659850d08SRoman Divacky     Arg = Arg.substr(0, Length);
74759850d08SRoman Divacky     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
748e6d15924SDimitry Andric 
749e6d15924SDimitry Andric     // cl::Prefix options do not preserve '=' when used separately.
750e6d15924SDimitry Andric     // The behavior for them with grouped options should be the same.
751e6d15924SDimitry Andric     if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
752e6d15924SDimitry Andric         (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
753e6d15924SDimitry Andric       Value = MaybeValue;
75459850d08SRoman Divacky       return PGOpt;
75559850d08SRoman Divacky     }
75659850d08SRoman Divacky 
757e6d15924SDimitry Andric     if (MaybeValue[0] == '=') {
758e6d15924SDimitry Andric       Value = MaybeValue.substr(1);
759e6d15924SDimitry Andric       return PGOpt;
760e6d15924SDimitry Andric     }
761e6d15924SDimitry Andric 
762e6d15924SDimitry Andric     // This must be a grouped option.
76359850d08SRoman Divacky     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
76459850d08SRoman Divacky 
765e6d15924SDimitry Andric     // Grouping options inside a group can't have values.
766e6d15924SDimitry Andric     if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
767e6d15924SDimitry Andric       ErrorParsing |= PGOpt->error("may not occur within a group!");
768e6d15924SDimitry Andric       return nullptr;
769e6d15924SDimitry Andric     }
77059850d08SRoman Divacky 
771e6d15924SDimitry Andric     // Because the value for the option is not required, we don't need to pass
772e6d15924SDimitry Andric     // argc/argv in.
773829000e0SRoman Divacky     int Dummy = 0;
774e6d15924SDimitry Andric     ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
77559850d08SRoman Divacky 
77659850d08SRoman Divacky     // Get the next grouping option.
777e6d15924SDimitry Andric     Arg = MaybeValue;
77859850d08SRoman Divacky     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
779e6d15924SDimitry Andric   } while (PGOpt);
78059850d08SRoman Divacky 
781e6d15924SDimitry Andric   // We could not find a grouping option in the remainder of Arg.
782e6d15924SDimitry Andric   return nullptr;
78359850d08SRoman Divacky }
78459850d08SRoman Divacky 
RequiresValue(const Option * O)785009b1c42SEd Schouten static bool RequiresValue(const Option *O) {
786009b1c42SEd Schouten   return O->getNumOccurrencesFlag() == cl::Required ||
787009b1c42SEd Schouten          O->getNumOccurrencesFlag() == cl::OneOrMore;
788009b1c42SEd Schouten }
789009b1c42SEd Schouten 
EatsUnboundedNumberOfValues(const Option * O)790009b1c42SEd Schouten static bool EatsUnboundedNumberOfValues(const Option *O) {
791009b1c42SEd Schouten   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
792009b1c42SEd Schouten          O->getNumOccurrencesFlag() == cl::OneOrMore;
793009b1c42SEd Schouten }
794009b1c42SEd Schouten 
isWhitespace(char C)795b2b7c066SDimitry Andric static bool isWhitespace(char C) {
796b2b7c066SDimitry Andric   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
797b2b7c066SDimitry Andric }
798009b1c42SEd Schouten 
isWhitespaceOrNull(char C)799d8e91e46SDimitry Andric static bool isWhitespaceOrNull(char C) {
800d8e91e46SDimitry Andric   return isWhitespace(C) || C == '\0';
801d8e91e46SDimitry Andric }
802d8e91e46SDimitry Andric 
isQuote(char C)80367c32a98SDimitry Andric static bool isQuote(char C) { return C == '\"' || C == '\''; }
804f8af5cf6SDimitry Andric 
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)805f8af5cf6SDimitry Andric void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
80667c32a98SDimitry Andric                                 SmallVectorImpl<const char *> &NewArgv,
80767c32a98SDimitry Andric                                 bool MarkEOLs) {
808f8af5cf6SDimitry Andric   SmallString<128> Token;
809f8af5cf6SDimitry Andric   for (size_t I = 0, E = Src.size(); I != E; ++I) {
810f8af5cf6SDimitry Andric     // Consume runs of whitespace.
811f8af5cf6SDimitry Andric     if (Token.empty()) {
81267c32a98SDimitry Andric       while (I != E && isWhitespace(Src[I])) {
813b60736ecSDimitry Andric         // Mark the end of lines in response files.
81467c32a98SDimitry Andric         if (MarkEOLs && Src[I] == '\n')
81567c32a98SDimitry Andric           NewArgv.push_back(nullptr);
816f8af5cf6SDimitry Andric         ++I;
81767c32a98SDimitry Andric       }
81867c32a98SDimitry Andric       if (I == E)
81967c32a98SDimitry Andric         break;
820f8af5cf6SDimitry Andric     }
821f8af5cf6SDimitry Andric 
822b2b7c066SDimitry Andric     char C = Src[I];
823b2b7c066SDimitry Andric 
82401095a5dSDimitry Andric     // Backslash escapes the next character.
825b2b7c066SDimitry Andric     if (I + 1 < E && C == '\\') {
826f8af5cf6SDimitry Andric       ++I; // Skip the escape.
827f8af5cf6SDimitry Andric       Token.push_back(Src[I]);
82859850d08SRoman Divacky       continue;
82959850d08SRoman Divacky     }
83059850d08SRoman Divacky 
831f8af5cf6SDimitry Andric     // Consume a quoted string.
832b2b7c066SDimitry Andric     if (isQuote(C)) {
833b2b7c066SDimitry Andric       ++I;
834b2b7c066SDimitry Andric       while (I != E && Src[I] != C) {
83501095a5dSDimitry Andric         // Backslash escapes the next character.
83601095a5dSDimitry Andric         if (Src[I] == '\\' && I + 1 != E)
837f8af5cf6SDimitry Andric           ++I;
838f8af5cf6SDimitry Andric         Token.push_back(Src[I]);
839f8af5cf6SDimitry Andric         ++I;
840009b1c42SEd Schouten       }
84167c32a98SDimitry Andric       if (I == E)
84267c32a98SDimitry Andric         break;
843f8af5cf6SDimitry Andric       continue;
844f8af5cf6SDimitry Andric     }
845f8af5cf6SDimitry Andric 
846f8af5cf6SDimitry Andric     // End the token if this is whitespace.
847b2b7c066SDimitry Andric     if (isWhitespace(C)) {
848f8af5cf6SDimitry Andric       if (!Token.empty())
849344a3780SDimitry Andric         NewArgv.push_back(Saver.save(Token.str()).data());
850b60736ecSDimitry Andric       // Mark the end of lines in response files.
851b60736ecSDimitry Andric       if (MarkEOLs && C == '\n')
852b60736ecSDimitry Andric         NewArgv.push_back(nullptr);
853f8af5cf6SDimitry Andric       Token.clear();
854f8af5cf6SDimitry Andric       continue;
855f8af5cf6SDimitry Andric     }
856f8af5cf6SDimitry Andric 
857f8af5cf6SDimitry Andric     // This is a normal character.  Append it.
858b2b7c066SDimitry Andric     Token.push_back(C);
859f8af5cf6SDimitry Andric   }
860f8af5cf6SDimitry Andric 
861f8af5cf6SDimitry Andric   // Append the last token after hitting EOF with no whitespace.
862f8af5cf6SDimitry Andric   if (!Token.empty())
863344a3780SDimitry Andric     NewArgv.push_back(Saver.save(Token.str()).data());
864f8af5cf6SDimitry Andric }
865f8af5cf6SDimitry Andric 
866f8af5cf6SDimitry Andric /// Backslashes are interpreted in a rather complicated way in the Windows-style
867f8af5cf6SDimitry Andric /// command line, because backslashes are used both to separate path and to
868f8af5cf6SDimitry Andric /// escape double quote. This method consumes runs of backslashes as well as the
869f8af5cf6SDimitry Andric /// following double quote if it's escaped.
870f8af5cf6SDimitry Andric ///
871f8af5cf6SDimitry Andric ///  * If an even number of backslashes is followed by a double quote, one
872f8af5cf6SDimitry Andric ///    backslash is output for every pair of backslashes, and the last double
873f8af5cf6SDimitry Andric ///    quote remains unconsumed. The double quote will later be interpreted as
874f8af5cf6SDimitry Andric ///    the start or end of a quoted string in the main loop outside of this
875f8af5cf6SDimitry Andric ///    function.
876f8af5cf6SDimitry Andric ///
877f8af5cf6SDimitry Andric ///  * If an odd number of backslashes is followed by a double quote, one
878f8af5cf6SDimitry Andric ///    backslash is output for every pair of backslashes, and a double quote is
879f8af5cf6SDimitry Andric ///    output for the last pair of backslash-double quote. The double quote is
880f8af5cf6SDimitry Andric ///    consumed in this case.
881f8af5cf6SDimitry Andric ///
882f8af5cf6SDimitry Andric ///  * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)883f8af5cf6SDimitry Andric static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
884f8af5cf6SDimitry Andric   size_t E = Src.size();
885f8af5cf6SDimitry Andric   int BackslashCount = 0;
886f8af5cf6SDimitry Andric   // Skip the backslashes.
887f8af5cf6SDimitry Andric   do {
888f8af5cf6SDimitry Andric     ++I;
889f8af5cf6SDimitry Andric     ++BackslashCount;
890f8af5cf6SDimitry Andric   } while (I != E && Src[I] == '\\');
891f8af5cf6SDimitry Andric 
892f8af5cf6SDimitry Andric   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
893f8af5cf6SDimitry Andric   if (FollowedByDoubleQuote) {
894f8af5cf6SDimitry Andric     Token.append(BackslashCount / 2, '\\');
895f8af5cf6SDimitry Andric     if (BackslashCount % 2 == 0)
896f8af5cf6SDimitry Andric       return I - 1;
897f8af5cf6SDimitry Andric     Token.push_back('"');
898f8af5cf6SDimitry Andric     return I;
899f8af5cf6SDimitry Andric   }
900f8af5cf6SDimitry Andric   Token.append(BackslashCount, '\\');
901f8af5cf6SDimitry Andric   return I - 1;
902f8af5cf6SDimitry Andric }
903f8af5cf6SDimitry Andric 
904145449b1SDimitry Andric // Windows treats whitespace, double quotes, and backslashes specially, except
905145449b1SDimitry Andric // when parsing the first token of a full command line, in which case
906145449b1SDimitry Andric // backslashes are not special.
isWindowsSpecialChar(char C)907cfca06d7SDimitry Andric static bool isWindowsSpecialChar(char C) {
908cfca06d7SDimitry Andric   return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
909cfca06d7SDimitry Andric }
isWindowsSpecialCharInCommandName(char C)910145449b1SDimitry Andric static bool isWindowsSpecialCharInCommandName(char C) {
911145449b1SDimitry Andric   return isWhitespaceOrNull(C) || C == '\"';
912145449b1SDimitry Andric }
913cfca06d7SDimitry Andric 
914cfca06d7SDimitry Andric // Windows tokenization implementation. The implementation is designed to be
915cfca06d7SDimitry Andric // inlined and specialized for the two user entry points.
tokenizeWindowsCommandLineImpl(StringRef Src,StringSaver & Saver,function_ref<void (StringRef)> AddToken,bool AlwaysCopy,function_ref<void ()> MarkEOL,bool InitialCommandName)916145449b1SDimitry Andric static inline void tokenizeWindowsCommandLineImpl(
917145449b1SDimitry Andric     StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
918145449b1SDimitry Andric     bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
919f8af5cf6SDimitry Andric   SmallString<128> Token;
920f8af5cf6SDimitry Andric 
921145449b1SDimitry Andric   // Sometimes, this function will be handling a full command line including an
922145449b1SDimitry Andric   // executable pathname at the start. In that situation, the initial pathname
923145449b1SDimitry Andric   // needs different handling from the following arguments, because when
924145449b1SDimitry Andric   // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
925145449b1SDimitry Andric   // escaping the quote character, whereas when libc scans the rest of the
926145449b1SDimitry Andric   // command line, it does.
927145449b1SDimitry Andric   bool CommandName = InitialCommandName;
928145449b1SDimitry Andric 
929cfca06d7SDimitry Andric   // Try to do as much work inside the state machine as possible.
930f8af5cf6SDimitry Andric   enum { INIT, UNQUOTED, QUOTED } State = INIT;
931145449b1SDimitry Andric 
932cfca06d7SDimitry Andric   for (size_t I = 0, E = Src.size(); I < E; ++I) {
933cfca06d7SDimitry Andric     switch (State) {
934cfca06d7SDimitry Andric     case INIT: {
935cfca06d7SDimitry Andric       assert(Token.empty() && "token should be empty in initial state");
936cfca06d7SDimitry Andric       // Eat whitespace before a token.
937cfca06d7SDimitry Andric       while (I < E && isWhitespaceOrNull(Src[I])) {
938cfca06d7SDimitry Andric         if (Src[I] == '\n')
939cfca06d7SDimitry Andric           MarkEOL();
940cfca06d7SDimitry Andric         ++I;
94167c32a98SDimitry Andric       }
942cfca06d7SDimitry Andric       // Stop if this was trailing whitespace.
943cfca06d7SDimitry Andric       if (I >= E)
944cfca06d7SDimitry Andric         break;
945cfca06d7SDimitry Andric       size_t Start = I;
946145449b1SDimitry Andric       if (CommandName) {
947145449b1SDimitry Andric         while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
948145449b1SDimitry Andric           ++I;
949145449b1SDimitry Andric       } else {
950cfca06d7SDimitry Andric         while (I < E && !isWindowsSpecialChar(Src[I]))
951cfca06d7SDimitry Andric           ++I;
952145449b1SDimitry Andric       }
953cfca06d7SDimitry Andric       StringRef NormalChars = Src.slice(Start, I);
954cfca06d7SDimitry Andric       if (I >= E || isWhitespaceOrNull(Src[I])) {
955cfca06d7SDimitry Andric         // No special characters: slice out the substring and start the next
956cfca06d7SDimitry Andric         // token. Copy the string if the caller asks us to.
957cfca06d7SDimitry Andric         AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
958145449b1SDimitry Andric         if (I < E && Src[I] == '\n') {
959b60736ecSDimitry Andric           MarkEOL();
960145449b1SDimitry Andric           CommandName = InitialCommandName;
961145449b1SDimitry Andric         } else {
962145449b1SDimitry Andric           CommandName = false;
963145449b1SDimitry Andric         }
964cfca06d7SDimitry Andric       } else if (Src[I] == '\"') {
965cfca06d7SDimitry Andric         Token += NormalChars;
966f8af5cf6SDimitry Andric         State = QUOTED;
967cfca06d7SDimitry Andric       } else if (Src[I] == '\\') {
968145449b1SDimitry Andric         assert(!CommandName && "or else we'd have treated it as a normal char");
969cfca06d7SDimitry Andric         Token += NormalChars;
970f8af5cf6SDimitry Andric         I = parseBackslash(Src, I, Token);
971f8af5cf6SDimitry Andric         State = UNQUOTED;
972cfca06d7SDimitry Andric       } else {
973cfca06d7SDimitry Andric         llvm_unreachable("unexpected special character");
974f8af5cf6SDimitry Andric       }
975cfca06d7SDimitry Andric       break;
976f8af5cf6SDimitry Andric     }
977f8af5cf6SDimitry Andric 
978cfca06d7SDimitry Andric     case UNQUOTED:
979cfca06d7SDimitry Andric       if (isWhitespaceOrNull(Src[I])) {
980cfca06d7SDimitry Andric         // Whitespace means the end of the token. If we are in this state, the
981cfca06d7SDimitry Andric         // token must have contained a special character, so we must copy the
982cfca06d7SDimitry Andric         // token.
983cfca06d7SDimitry Andric         AddToken(Saver.save(Token.str()));
984f8af5cf6SDimitry Andric         Token.clear();
985145449b1SDimitry Andric         if (Src[I] == '\n') {
986145449b1SDimitry Andric           CommandName = InitialCommandName;
987cfca06d7SDimitry Andric           MarkEOL();
988145449b1SDimitry Andric         } else {
989145449b1SDimitry Andric           CommandName = false;
990145449b1SDimitry Andric         }
991f8af5cf6SDimitry Andric         State = INIT;
992cfca06d7SDimitry Andric       } else if (Src[I] == '\"') {
993f8af5cf6SDimitry Andric         State = QUOTED;
994145449b1SDimitry Andric       } else if (Src[I] == '\\' && !CommandName) {
995f8af5cf6SDimitry Andric         I = parseBackslash(Src, I, Token);
996cfca06d7SDimitry Andric       } else {
997cfca06d7SDimitry Andric         Token.push_back(Src[I]);
998f8af5cf6SDimitry Andric       }
999cfca06d7SDimitry Andric       break;
1000f8af5cf6SDimitry Andric 
1001cfca06d7SDimitry Andric     case QUOTED:
1002cfca06d7SDimitry Andric       if (Src[I] == '\"') {
1003e6d15924SDimitry Andric         if (I < (E - 1) && Src[I + 1] == '"') {
1004e6d15924SDimitry Andric           // Consecutive double-quotes inside a quoted string implies one
1005e6d15924SDimitry Andric           // double-quote.
1006e6d15924SDimitry Andric           Token.push_back('"');
1007cfca06d7SDimitry Andric           ++I;
1008cfca06d7SDimitry Andric         } else {
1009cfca06d7SDimitry Andric           // Otherwise, end the quoted portion and return to the unquoted state.
1010f8af5cf6SDimitry Andric           State = UNQUOTED;
1011f8af5cf6SDimitry Andric         }
1012145449b1SDimitry Andric       } else if (Src[I] == '\\' && !CommandName) {
1013f8af5cf6SDimitry Andric         I = parseBackslash(Src, I, Token);
1014cfca06d7SDimitry Andric       } else {
1015cfca06d7SDimitry Andric         Token.push_back(Src[I]);
1016f8af5cf6SDimitry Andric       }
1017cfca06d7SDimitry Andric       break;
1018f8af5cf6SDimitry Andric     }
1019f8af5cf6SDimitry Andric   }
1020cfca06d7SDimitry Andric 
1021145449b1SDimitry Andric   if (State != INIT)
1022cfca06d7SDimitry Andric     AddToken(Saver.save(Token.str()));
1023cfca06d7SDimitry Andric }
1024cfca06d7SDimitry Andric 
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)1025cfca06d7SDimitry Andric void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
1026cfca06d7SDimitry Andric                                     SmallVectorImpl<const char *> &NewArgv,
1027cfca06d7SDimitry Andric                                     bool MarkEOLs) {
1028cfca06d7SDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1029cfca06d7SDimitry Andric   auto OnEOL = [&]() {
103067c32a98SDimitry Andric     if (MarkEOLs)
103167c32a98SDimitry Andric       NewArgv.push_back(nullptr);
1032cfca06d7SDimitry Andric   };
1033cfca06d7SDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1034145449b1SDimitry Andric                                  /*AlwaysCopy=*/true, OnEOL, false);
1035cfca06d7SDimitry Andric }
1036cfca06d7SDimitry Andric 
TokenizeWindowsCommandLineNoCopy(StringRef Src,StringSaver & Saver,SmallVectorImpl<StringRef> & NewArgv)1037cfca06d7SDimitry Andric void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
1038cfca06d7SDimitry Andric                                           SmallVectorImpl<StringRef> &NewArgv) {
1039cfca06d7SDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1040cfca06d7SDimitry Andric   auto OnEOL = []() {};
1041cfca06d7SDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1042145449b1SDimitry Andric                                  OnEOL, false);
1043145449b1SDimitry Andric }
1044145449b1SDimitry Andric 
TokenizeWindowsCommandLineFull(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)1045145449b1SDimitry Andric void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
1046145449b1SDimitry Andric                                         SmallVectorImpl<const char *> &NewArgv,
1047145449b1SDimitry Andric                                         bool MarkEOLs) {
1048145449b1SDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1049145449b1SDimitry Andric   auto OnEOL = [&]() {
1050145449b1SDimitry Andric     if (MarkEOLs)
1051145449b1SDimitry Andric       NewArgv.push_back(nullptr);
1052145449b1SDimitry Andric   };
1053145449b1SDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1054145449b1SDimitry Andric                                  /*AlwaysCopy=*/true, OnEOL, true);
1055f8af5cf6SDimitry Andric }
1056f8af5cf6SDimitry Andric 
tokenizeConfigFile(StringRef Source,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)1057eb11fae6SDimitry Andric void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1058eb11fae6SDimitry Andric                             SmallVectorImpl<const char *> &NewArgv,
1059eb11fae6SDimitry Andric                             bool MarkEOLs) {
1060eb11fae6SDimitry Andric   for (const char *Cur = Source.begin(); Cur != Source.end();) {
1061eb11fae6SDimitry Andric     SmallString<128> Line;
1062eb11fae6SDimitry Andric     // Check for comment line.
1063eb11fae6SDimitry Andric     if (isWhitespace(*Cur)) {
1064eb11fae6SDimitry Andric       while (Cur != Source.end() && isWhitespace(*Cur))
1065eb11fae6SDimitry Andric         ++Cur;
1066eb11fae6SDimitry Andric       continue;
1067eb11fae6SDimitry Andric     }
1068eb11fae6SDimitry Andric     if (*Cur == '#') {
1069eb11fae6SDimitry Andric       while (Cur != Source.end() && *Cur != '\n')
1070eb11fae6SDimitry Andric         ++Cur;
1071eb11fae6SDimitry Andric       continue;
1072eb11fae6SDimitry Andric     }
1073eb11fae6SDimitry Andric     // Find end of the current line.
1074eb11fae6SDimitry Andric     const char *Start = Cur;
1075eb11fae6SDimitry Andric     for (const char *End = Source.end(); Cur != End; ++Cur) {
1076eb11fae6SDimitry Andric       if (*Cur == '\\') {
1077eb11fae6SDimitry Andric         if (Cur + 1 != End) {
1078eb11fae6SDimitry Andric           ++Cur;
1079eb11fae6SDimitry Andric           if (*Cur == '\n' ||
1080eb11fae6SDimitry Andric               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1081eb11fae6SDimitry Andric             Line.append(Start, Cur - 1);
1082eb11fae6SDimitry Andric             if (*Cur == '\r')
1083eb11fae6SDimitry Andric               ++Cur;
1084eb11fae6SDimitry Andric             Start = Cur + 1;
1085eb11fae6SDimitry Andric           }
1086eb11fae6SDimitry Andric         }
1087eb11fae6SDimitry Andric       } else if (*Cur == '\n')
1088eb11fae6SDimitry Andric         break;
1089eb11fae6SDimitry Andric     }
1090eb11fae6SDimitry Andric     // Tokenize line.
1091eb11fae6SDimitry Andric     Line.append(Start, Cur);
1092eb11fae6SDimitry Andric     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1093eb11fae6SDimitry Andric   }
1094eb11fae6SDimitry Andric }
1095eb11fae6SDimitry Andric 
10965a5ac124SDimitry Andric // It is called byte order marker but the UTF-8 BOM is actually not affected
10975a5ac124SDimitry Andric // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)10985a5ac124SDimitry Andric static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
10995a5ac124SDimitry Andric   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
11005a5ac124SDimitry Andric }
11015a5ac124SDimitry Andric 
11026f8fc217SDimitry Andric // Substitute <CFGDIR> with the file's base path.
ExpandBasePaths(StringRef BasePath,StringSaver & Saver,const char * & Arg)11036f8fc217SDimitry Andric static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
11046f8fc217SDimitry Andric                             const char *&Arg) {
11056f8fc217SDimitry Andric   assert(sys::path::is_absolute(BasePath));
11066f8fc217SDimitry Andric   constexpr StringLiteral Token("<CFGDIR>");
11076f8fc217SDimitry Andric   const StringRef ArgString(Arg);
11086f8fc217SDimitry Andric 
11096f8fc217SDimitry Andric   SmallString<128> ResponseFile;
11106f8fc217SDimitry Andric   StringRef::size_type StartPos = 0;
11116f8fc217SDimitry Andric   for (StringRef::size_type TokenPos = ArgString.find(Token);
11126f8fc217SDimitry Andric        TokenPos != StringRef::npos;
11136f8fc217SDimitry Andric        TokenPos = ArgString.find(Token, StartPos)) {
11146f8fc217SDimitry Andric     // Token may appear more than once per arg (e.g. comma-separated linker
11156f8fc217SDimitry Andric     // args). Support by using path-append on any subsequent appearances.
11166f8fc217SDimitry Andric     const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
11176f8fc217SDimitry Andric     if (ResponseFile.empty())
11186f8fc217SDimitry Andric       ResponseFile = LHS;
11196f8fc217SDimitry Andric     else
11206f8fc217SDimitry Andric       llvm::sys::path::append(ResponseFile, LHS);
11216f8fc217SDimitry Andric     ResponseFile.append(BasePath);
11226f8fc217SDimitry Andric     StartPos = TokenPos + Token.size();
11236f8fc217SDimitry Andric   }
11246f8fc217SDimitry Andric 
11256f8fc217SDimitry Andric   if (!ResponseFile.empty()) {
11266f8fc217SDimitry Andric     // Path-append the remaining arg substring if at least one token appeared.
11276f8fc217SDimitry Andric     const StringRef Remaining = ArgString.substr(StartPos);
11286f8fc217SDimitry Andric     if (!Remaining.empty())
11296f8fc217SDimitry Andric       llvm::sys::path::append(ResponseFile, Remaining);
11306f8fc217SDimitry Andric     Arg = Saver.save(ResponseFile.str()).data();
11316f8fc217SDimitry Andric   }
11326f8fc217SDimitry Andric }
11336f8fc217SDimitry Andric 
1134706b4fc4SDimitry Andric // FName must be an absolute path.
expandResponseFile(StringRef FName,SmallVectorImpl<const char * > & NewArgv)1135e3b55780SDimitry Andric Error ExpansionContext::expandResponseFile(
1136e3b55780SDimitry Andric     StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1137706b4fc4SDimitry Andric   assert(sys::path::is_absolute(FName));
1138706b4fc4SDimitry Andric   llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1139e3b55780SDimitry Andric       FS->getBufferForFile(FName);
1140e3b55780SDimitry Andric   if (!MemBufOrErr) {
1141e3b55780SDimitry Andric     std::error_code EC = MemBufOrErr.getError();
1142e3b55780SDimitry Andric     return llvm::createStringError(EC, Twine("cannot not open file '") + FName +
1143e3b55780SDimitry Andric                                            "': " + EC.message());
1144e3b55780SDimitry Andric   }
114567c32a98SDimitry Andric   MemoryBuffer &MemBuf = *MemBufOrErr.get();
114667c32a98SDimitry Andric   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1147f8af5cf6SDimitry Andric 
1148f8af5cf6SDimitry Andric   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
114967c32a98SDimitry Andric   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1150f8af5cf6SDimitry Andric   std::string UTF8Buf;
1151f8af5cf6SDimitry Andric   if (hasUTF16ByteOrderMark(BufRef)) {
1152f8af5cf6SDimitry Andric     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1153706b4fc4SDimitry Andric       return llvm::createStringError(std::errc::illegal_byte_sequence,
1154706b4fc4SDimitry Andric                                      "Could not convert UTF16 to UTF8");
1155f8af5cf6SDimitry Andric     Str = StringRef(UTF8Buf);
1156f8af5cf6SDimitry Andric   }
11575a5ac124SDimitry Andric   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
11585a5ac124SDimitry Andric   // these bytes before parsing.
11595a5ac124SDimitry Andric   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
11605a5ac124SDimitry Andric   else if (hasUTF8ByteOrderMark(BufRef))
11615a5ac124SDimitry Andric     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1162f8af5cf6SDimitry Andric 
1163f8af5cf6SDimitry Andric   // Tokenize the contents into NewArgv.
116467c32a98SDimitry Andric   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1165f8af5cf6SDimitry Andric 
1166e3b55780SDimitry Andric   // Expanded file content may require additional transformations, like using
1167e3b55780SDimitry Andric   // absolute paths instead of relative in '@file' constructs or expanding
1168e3b55780SDimitry Andric   // macros.
1169e3b55780SDimitry Andric   if (!RelativeNames && !InConfigFile)
1170706b4fc4SDimitry Andric     return Error::success();
1171e3b55780SDimitry Andric 
1172e3b55780SDimitry Andric   StringRef BasePath = llvm::sys::path::parent_path(FName);
1173e3b55780SDimitry Andric   for (const char *&Arg : NewArgv) {
11746f8fc217SDimitry Andric     if (!Arg)
11756f8fc217SDimitry Andric       continue;
11766f8fc217SDimitry Andric 
11776f8fc217SDimitry Andric     // Substitute <CFGDIR> with the file's base path.
1178e3b55780SDimitry Andric     if (InConfigFile)
11796f8fc217SDimitry Andric       ExpandBasePaths(BasePath, Saver, Arg);
11806f8fc217SDimitry Andric 
1181e3b55780SDimitry Andric     // Discover the case, when argument should be transformed into '@file' and
1182e3b55780SDimitry Andric     // evaluate 'file' for it.
1183e3b55780SDimitry Andric     StringRef ArgStr(Arg);
1184e3b55780SDimitry Andric     StringRef FileName;
1185e3b55780SDimitry Andric     bool ConfigInclusion = false;
1186e3b55780SDimitry Andric     if (ArgStr.consume_front("@")) {
1187e3b55780SDimitry Andric       FileName = ArgStr;
1188706b4fc4SDimitry Andric       if (!llvm::sys::path::is_relative(FileName))
1189706b4fc4SDimitry Andric         continue;
1190e3b55780SDimitry Andric     } else if (ArgStr.consume_front("--config=")) {
1191e3b55780SDimitry Andric       FileName = ArgStr;
1192e3b55780SDimitry Andric       ConfigInclusion = true;
1193e3b55780SDimitry Andric     } else {
1194e3b55780SDimitry Andric       continue;
1195e3b55780SDimitry Andric     }
1196706b4fc4SDimitry Andric 
1197e3b55780SDimitry Andric     // Update expansion construct.
1198706b4fc4SDimitry Andric     SmallString<128> ResponseFile;
1199706b4fc4SDimitry Andric     ResponseFile.push_back('@');
1200e3b55780SDimitry Andric     if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
1201e3b55780SDimitry Andric       SmallString<128> FilePath;
1202e3b55780SDimitry Andric       if (!findConfigFile(FileName, FilePath))
1203e3b55780SDimitry Andric         return createStringError(
1204e3b55780SDimitry Andric             std::make_error_code(std::errc::no_such_file_or_directory),
1205e3b55780SDimitry Andric             "cannot not find configuration file: " + FileName);
1206e3b55780SDimitry Andric       ResponseFile.append(FilePath);
1207e3b55780SDimitry Andric     } else {
1208706b4fc4SDimitry Andric       ResponseFile.append(BasePath);
1209706b4fc4SDimitry Andric       llvm::sys::path::append(ResponseFile, FileName);
1210e3b55780SDimitry Andric     }
12116f8fc217SDimitry Andric     Arg = Saver.save(ResponseFile.str()).data();
1212706b4fc4SDimitry Andric   }
1213706b4fc4SDimitry Andric   return Error::success();
1214f8af5cf6SDimitry Andric }
1215f8af5cf6SDimitry Andric 
1216eb11fae6SDimitry Andric /// Expand response files on a command line recursively using the given
1217f8af5cf6SDimitry Andric /// StringSaver and tokenization strategy.
expandResponseFiles(SmallVectorImpl<const char * > & Argv)1218e3b55780SDimitry Andric Error ExpansionContext::expandResponseFiles(
1219e3b55780SDimitry Andric     SmallVectorImpl<const char *> &Argv) {
1220e6d15924SDimitry Andric   struct ResponseFileRecord {
1221706b4fc4SDimitry Andric     std::string File;
1222e6d15924SDimitry Andric     size_t End;
1223e6d15924SDimitry Andric   };
1224e6d15924SDimitry Andric 
1225e6d15924SDimitry Andric   // To detect recursive response files, we maintain a stack of files and the
1226e6d15924SDimitry Andric   // position of the last argument in the file. This position is updated
1227e6d15924SDimitry Andric   // dynamically as we recursively expand files.
1228e6d15924SDimitry Andric   SmallVector<ResponseFileRecord, 3> FileStack;
1229e6d15924SDimitry Andric 
1230e6d15924SDimitry Andric   // Push a dummy entry that represents the initial command line, removing
1231e6d15924SDimitry Andric   // the need to check for an empty list.
1232e6d15924SDimitry Andric   FileStack.push_back({"", Argv.size()});
1233f8af5cf6SDimitry Andric 
1234f8af5cf6SDimitry Andric   // Don't cache Argv.size() because it can change.
1235f8af5cf6SDimitry Andric   for (unsigned I = 0; I != Argv.size();) {
1236e6d15924SDimitry Andric     while (I == FileStack.back().End) {
1237e6d15924SDimitry Andric       // Passing the end of a file's argument list, so we can remove it from the
1238e6d15924SDimitry Andric       // stack.
1239e6d15924SDimitry Andric       FileStack.pop_back();
1240e6d15924SDimitry Andric     }
1241e6d15924SDimitry Andric 
1242f8af5cf6SDimitry Andric     const char *Arg = Argv[I];
124367c32a98SDimitry Andric     // Check if it is an EOL marker
124467c32a98SDimitry Andric     if (Arg == nullptr) {
124567c32a98SDimitry Andric       ++I;
124667c32a98SDimitry Andric       continue;
124767c32a98SDimitry Andric     }
1248e6d15924SDimitry Andric 
1249f8af5cf6SDimitry Andric     if (Arg[0] != '@') {
1250f8af5cf6SDimitry Andric       ++I;
1251f8af5cf6SDimitry Andric       continue;
1252f8af5cf6SDimitry Andric     }
1253f8af5cf6SDimitry Andric 
1254e6d15924SDimitry Andric     const char *FName = Arg + 1;
1255706b4fc4SDimitry Andric     // Note that CurrentDir is only used for top-level rsp files, the rest will
1256706b4fc4SDimitry Andric     // always have an absolute path deduced from the containing file.
1257706b4fc4SDimitry Andric     SmallString<128> CurrDir;
1258706b4fc4SDimitry Andric     if (llvm::sys::path::is_relative(FName)) {
1259e3b55780SDimitry Andric       if (CurrentDir.empty()) {
1260e3b55780SDimitry Andric         if (auto CWD = FS->getCurrentWorkingDirectory()) {
1261e3b55780SDimitry Andric           CurrDir = *CWD;
1262e3b55780SDimitry Andric         } else {
1263e3b55780SDimitry Andric           return createStringError(
1264e3b55780SDimitry Andric               CWD.getError(), Twine("cannot get absolute path for: ") + FName);
1265e3b55780SDimitry Andric         }
1266e3b55780SDimitry Andric       } else {
1267e3b55780SDimitry Andric         CurrDir = CurrentDir;
1268e3b55780SDimitry Andric       }
1269706b4fc4SDimitry Andric       llvm::sys::path::append(CurrDir, FName);
1270706b4fc4SDimitry Andric       FName = CurrDir.c_str();
1271706b4fc4SDimitry Andric     }
1272e3b55780SDimitry Andric 
1273e3b55780SDimitry Andric     ErrorOr<llvm::vfs::Status> Res = FS->status(FName);
1274e3b55780SDimitry Andric     if (!Res || !Res->exists()) {
1275e3b55780SDimitry Andric       std::error_code EC = Res.getError();
1276e3b55780SDimitry Andric       if (!InConfigFile) {
1277e3b55780SDimitry Andric         // If the specified file does not exist, leave '@file' unexpanded, as
1278e3b55780SDimitry Andric         // libiberty does.
1279e3b55780SDimitry Andric         if (!EC || EC == llvm::errc::no_such_file_or_directory) {
1280e3b55780SDimitry Andric           ++I;
1281e3b55780SDimitry Andric           continue;
1282706b4fc4SDimitry Andric         }
1283706b4fc4SDimitry Andric       }
1284e3b55780SDimitry Andric       if (!EC)
1285e3b55780SDimitry Andric         EC = llvm::errc::no_such_file_or_directory;
1286e3b55780SDimitry Andric       return createStringError(EC, Twine("cannot not open file '") + FName +
1287e3b55780SDimitry Andric                                        "': " + EC.message());
1288e3b55780SDimitry Andric     }
1289e3b55780SDimitry Andric     const llvm::vfs::Status &FileStatus = Res.get();
1290e3b55780SDimitry Andric 
1291e3b55780SDimitry Andric     auto IsEquivalent =
1292e3b55780SDimitry Andric         [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
1293e3b55780SDimitry Andric       ErrorOr<llvm::vfs::Status> RHS = FS->status(RFile.File);
1294e3b55780SDimitry Andric       if (!RHS)
1295e3b55780SDimitry Andric         return RHS.getError();
1296e3b55780SDimitry Andric       return FileStatus.equivalent(*RHS);
1297e6d15924SDimitry Andric     };
1298e6d15924SDimitry Andric 
1299e6d15924SDimitry Andric     // Check for recursive response files.
1300e3b55780SDimitry Andric     for (const auto &F : drop_begin(FileStack)) {
1301e3b55780SDimitry Andric       if (ErrorOr<bool> R = IsEquivalent(F)) {
1302e3b55780SDimitry Andric         if (R.get())
1303e3b55780SDimitry Andric           return createStringError(
1304e3b55780SDimitry Andric               R.getError(), Twine("recursive expansion of: '") + F.File + "'");
1305e3b55780SDimitry Andric       } else {
1306e3b55780SDimitry Andric         return createStringError(R.getError(),
1307e3b55780SDimitry Andric                                  Twine("cannot open file: ") + F.File);
1308e3b55780SDimitry Andric       }
1309e6d15924SDimitry Andric     }
1310f8af5cf6SDimitry Andric 
1311f8af5cf6SDimitry Andric     // Replace this response file argument with the tokenization of its
1312f8af5cf6SDimitry Andric     // contents.  Nested response files are expanded in subsequent iterations.
1313f8af5cf6SDimitry Andric     SmallVector<const char *, 0> ExpandedArgv;
1314e3b55780SDimitry Andric     if (Error Err = expandResponseFile(FName, ExpandedArgv))
1315e3b55780SDimitry Andric       return Err;
1316e6d15924SDimitry Andric 
1317e6d15924SDimitry Andric     for (ResponseFileRecord &Record : FileStack) {
1318e6d15924SDimitry Andric       // Increase the end of all active records by the number of newly expanded
1319e6d15924SDimitry Andric       // arguments, minus the response file itself.
1320e6d15924SDimitry Andric       Record.End += ExpandedArgv.size() - 1;
1321e6d15924SDimitry Andric     }
1322e6d15924SDimitry Andric 
1323e6d15924SDimitry Andric     FileStack.push_back({FName, I + ExpandedArgv.size()});
1324f8af5cf6SDimitry Andric     Argv.erase(Argv.begin() + I);
1325f8af5cf6SDimitry Andric     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1326f8af5cf6SDimitry Andric   }
1327e6d15924SDimitry Andric 
1328e6d15924SDimitry Andric   // If successful, the top of the file stack will mark the end of the Argv
1329e6d15924SDimitry Andric   // stream. A failure here indicates a bug in the stack popping logic above.
1330e6d15924SDimitry Andric   // Note that FileStack may have more than one element at this point because we
1331e6d15924SDimitry Andric   // don't have a chance to pop the stack when encountering recursive files at
1332e6d15924SDimitry Andric   // the end of the stream, so seeing that doesn't indicate a bug.
1333e6d15924SDimitry Andric   assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1334e3b55780SDimitry Andric   return Error::success();
1335344a3780SDimitry Andric }
1336344a3780SDimitry Andric 
expandResponseFiles(int Argc,const char * const * Argv,const char * EnvVar,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv)1337b60736ecSDimitry Andric bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1338b60736ecSDimitry Andric                              const char *EnvVar, StringSaver &Saver,
1339b60736ecSDimitry Andric                              SmallVectorImpl<const char *> &NewArgv) {
1340e3b55780SDimitry Andric #ifdef _WIN32
1341e3b55780SDimitry Andric   auto Tokenize = cl::TokenizeWindowsCommandLine;
1342e3b55780SDimitry Andric #else
1343e3b55780SDimitry Andric   auto Tokenize = cl::TokenizeGNUCommandLine;
1344e3b55780SDimitry Andric #endif
1345b60736ecSDimitry Andric   // The environment variable specifies initial options.
1346b60736ecSDimitry Andric   if (EnvVar)
1347e3b55780SDimitry Andric     if (std::optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1348b60736ecSDimitry Andric       Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1349b60736ecSDimitry Andric 
1350b60736ecSDimitry Andric   // Command line options can override the environment variable.
1351b60736ecSDimitry Andric   NewArgv.append(Argv + 1, Argv + Argc);
1352e3b55780SDimitry Andric   ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1353e3b55780SDimitry Andric   if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
1354e3b55780SDimitry Andric     errs() << toString(std::move(Err)) << '\n';
1355e3b55780SDimitry Andric     return false;
1356e3b55780SDimitry Andric   }
1357e3b55780SDimitry Andric   return true;
1358b60736ecSDimitry Andric }
1359b60736ecSDimitry Andric 
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv)1360e3b55780SDimitry Andric bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1361e3b55780SDimitry Andric                              SmallVectorImpl<const char *> &Argv) {
1362e3b55780SDimitry Andric   ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1363e3b55780SDimitry Andric   if (Error Err = ECtx.expandResponseFiles(Argv)) {
1364e3b55780SDimitry Andric     errs() << toString(std::move(Err)) << '\n';
1365e3b55780SDimitry Andric     return false;
1366e3b55780SDimitry Andric   }
1367e3b55780SDimitry Andric   return true;
1368e3b55780SDimitry Andric }
1369e3b55780SDimitry Andric 
ExpansionContext(BumpPtrAllocator & A,TokenizerCallback T)1370e3b55780SDimitry Andric ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
1371e3b55780SDimitry Andric     : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {}
1372e3b55780SDimitry Andric 
findConfigFile(StringRef FileName,SmallVectorImpl<char> & FilePath)1373e3b55780SDimitry Andric bool ExpansionContext::findConfigFile(StringRef FileName,
1374e3b55780SDimitry Andric                                       SmallVectorImpl<char> &FilePath) {
1375e3b55780SDimitry Andric   SmallString<128> CfgFilePath;
1376e3b55780SDimitry Andric   const auto FileExists = [this](SmallString<128> Path) -> bool {
1377e3b55780SDimitry Andric     auto Status = FS->status(Path);
1378e3b55780SDimitry Andric     return Status &&
1379e3b55780SDimitry Andric            Status->getType() == llvm::sys::fs::file_type::regular_file;
1380e3b55780SDimitry Andric   };
1381e3b55780SDimitry Andric 
1382e3b55780SDimitry Andric   // If file name contains directory separator, treat it as a path to
1383e3b55780SDimitry Andric   // configuration file.
1384e3b55780SDimitry Andric   if (llvm::sys::path::has_parent_path(FileName)) {
1385e3b55780SDimitry Andric     CfgFilePath = FileName;
1386e3b55780SDimitry Andric     if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
1387e3b55780SDimitry Andric       return false;
1388e3b55780SDimitry Andric     if (!FileExists(CfgFilePath))
1389e3b55780SDimitry Andric       return false;
1390e3b55780SDimitry Andric     FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1391e3b55780SDimitry Andric     return true;
1392e3b55780SDimitry Andric   }
1393e3b55780SDimitry Andric 
1394e3b55780SDimitry Andric   // Look for the file in search directories.
1395e3b55780SDimitry Andric   for (const StringRef &Dir : SearchDirs) {
1396e3b55780SDimitry Andric     if (Dir.empty())
1397e3b55780SDimitry Andric       continue;
1398e3b55780SDimitry Andric     CfgFilePath.assign(Dir);
1399e3b55780SDimitry Andric     llvm::sys::path::append(CfgFilePath, FileName);
1400e3b55780SDimitry Andric     llvm::sys::path::native(CfgFilePath);
1401e3b55780SDimitry Andric     if (FileExists(CfgFilePath)) {
1402e3b55780SDimitry Andric       FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1403e3b55780SDimitry Andric       return true;
1404e3b55780SDimitry Andric     }
1405e3b55780SDimitry Andric   }
1406e3b55780SDimitry Andric 
1407e3b55780SDimitry Andric   return false;
1408e3b55780SDimitry Andric }
1409e3b55780SDimitry Andric 
readConfigFile(StringRef CfgFile,SmallVectorImpl<const char * > & Argv)1410e3b55780SDimitry Andric Error ExpansionContext::readConfigFile(StringRef CfgFile,
1411eb11fae6SDimitry Andric                                        SmallVectorImpl<const char *> &Argv) {
1412706b4fc4SDimitry Andric   SmallString<128> AbsPath;
1413706b4fc4SDimitry Andric   if (sys::path::is_relative(CfgFile)) {
1414e3b55780SDimitry Andric     AbsPath.assign(CfgFile);
1415e3b55780SDimitry Andric     if (std::error_code EC = FS->makeAbsolute(AbsPath))
1416e3b55780SDimitry Andric       return make_error<StringError>(
1417e3b55780SDimitry Andric           EC, Twine("cannot get absolute path for " + CfgFile));
1418706b4fc4SDimitry Andric     CfgFile = AbsPath.str();
1419706b4fc4SDimitry Andric   }
1420e3b55780SDimitry Andric   InConfigFile = true;
1421e3b55780SDimitry Andric   RelativeNames = true;
1422e3b55780SDimitry Andric   if (Error Err = expandResponseFile(CfgFile, Argv))
1423e3b55780SDimitry Andric     return Err;
1424e3b55780SDimitry Andric   return expandResponseFiles(Argv);
1425eb11fae6SDimitry Andric }
1426eb11fae6SDimitry Andric 
1427344a3780SDimitry Andric static void initCommonOptions();
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,const char * EnvVar,bool LongOptionsUseDoubleDash)142801095a5dSDimitry Andric bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1429d8e91e46SDimitry Andric                                  StringRef Overview, raw_ostream *Errs,
1430e6d15924SDimitry Andric                                  const char *EnvVar,
1431e6d15924SDimitry Andric                                  bool LongOptionsUseDoubleDash) {
1432344a3780SDimitry Andric   initCommonOptions();
1433d8e91e46SDimitry Andric   SmallVector<const char *, 20> NewArgv;
1434d8e91e46SDimitry Andric   BumpPtrAllocator A;
1435d8e91e46SDimitry Andric   StringSaver Saver(A);
1436d8e91e46SDimitry Andric   NewArgv.push_back(argv[0]);
1437d8e91e46SDimitry Andric 
1438d8e91e46SDimitry Andric   // Parse options from environment variable.
1439d8e91e46SDimitry Andric   if (EnvVar) {
1440e3b55780SDimitry Andric     if (std::optional<std::string> EnvValue =
1441d8e91e46SDimitry Andric             sys::Process::GetEnv(StringRef(EnvVar)))
1442d8e91e46SDimitry Andric       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1443d8e91e46SDimitry Andric   }
1444d8e91e46SDimitry Andric 
1445d8e91e46SDimitry Andric   // Append options from command line.
1446d8e91e46SDimitry Andric   for (int I = 1; I < argc; ++I)
1447d8e91e46SDimitry Andric     NewArgv.push_back(argv[I]);
1448d8e91e46SDimitry Andric   int NewArgc = static_cast<int>(NewArgv.size());
1449d8e91e46SDimitry Andric 
1450d8e91e46SDimitry Andric   // Parse all options.
1451d8e91e46SDimitry Andric   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1452e6d15924SDimitry Andric                                                Errs, LongOptionsUseDoubleDash);
14535a5ac124SDimitry Andric }
1454009b1c42SEd Schouten 
1455c0981da4SDimitry Andric /// Reset all options at least once, so that we can parse different options.
ResetAllOptionOccurrences()145601095a5dSDimitry Andric void CommandLineParser::ResetAllOptionOccurrences() {
1457c0981da4SDimitry Andric   // Reset all option values to look like they have never been seen before.
1458c0981da4SDimitry Andric   // Options might be reset twice (they can be reference in both OptionsMap
1459c0981da4SDimitry Andric   // and one of the other members), but that does not harm.
1460344a3780SDimitry Andric   for (auto *SC : RegisteredSubCommands) {
146101095a5dSDimitry Andric     for (auto &O : SC->OptionsMap)
146201095a5dSDimitry Andric       O.second->reset();
1463c0981da4SDimitry Andric     for (Option *O : SC->PositionalOpts)
1464c0981da4SDimitry Andric       O->reset();
1465c0981da4SDimitry Andric     for (Option *O : SC->SinkOpts)
1466c0981da4SDimitry Andric       O->reset();
1467c0981da4SDimitry Andric     if (SC->ConsumeAfterOpt)
1468c0981da4SDimitry Andric       SC->ConsumeAfterOpt->reset();
146901095a5dSDimitry Andric   }
147001095a5dSDimitry Andric }
147101095a5dSDimitry Andric 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,bool LongOptionsUseDoubleDash)147201095a5dSDimitry Andric bool CommandLineParser::ParseCommandLineOptions(int argc,
14735a5ac124SDimitry Andric                                                 const char *const *argv,
1474b915e9e0SDimitry Andric                                                 StringRef Overview,
1475e6d15924SDimitry Andric                                                 raw_ostream *Errs,
1476e6d15924SDimitry Andric                                                 bool LongOptionsUseDoubleDash) {
14775a5ac124SDimitry Andric   assert(hasOptions() && "No options specified!");
1478009b1c42SEd Schouten 
1479009b1c42SEd Schouten   ProgramOverview = Overview;
148071d5a254SDimitry Andric   bool IgnoreErrors = Errs;
148171d5a254SDimitry Andric   if (!Errs)
148271d5a254SDimitry Andric     Errs = &errs();
1483009b1c42SEd Schouten   bool ErrorParsing = false;
1484009b1c42SEd Schouten 
1485e3b55780SDimitry Andric   // Expand response files.
1486e3b55780SDimitry Andric   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1487e3b55780SDimitry Andric   BumpPtrAllocator A;
1488e3b55780SDimitry Andric #ifdef _WIN32
1489e3b55780SDimitry Andric   auto Tokenize = cl::TokenizeWindowsCommandLine;
1490e3b55780SDimitry Andric #else
1491e3b55780SDimitry Andric   auto Tokenize = cl::TokenizeGNUCommandLine;
1492e3b55780SDimitry Andric #endif
1493e3b55780SDimitry Andric   ExpansionContext ECtx(A, Tokenize);
1494e3b55780SDimitry Andric   if (Error Err = ECtx.expandResponseFiles(newArgv)) {
1495e3b55780SDimitry Andric     *Errs << toString(std::move(Err)) << '\n';
1496e3b55780SDimitry Andric     return false;
1497e3b55780SDimitry Andric   }
1498e3b55780SDimitry Andric   argv = &newArgv[0];
1499e3b55780SDimitry Andric   argc = static_cast<int>(newArgv.size());
1500e3b55780SDimitry Andric 
1501e3b55780SDimitry Andric   // Copy the program name into ProgName, making sure not to overflow it.
1502e3b55780SDimitry Andric   ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1503e3b55780SDimitry Andric 
1504009b1c42SEd Schouten   // Check out the positional arguments to collect information about them.
1505009b1c42SEd Schouten   unsigned NumPositionalRequired = 0;
1506009b1c42SEd Schouten 
1507009b1c42SEd Schouten   // Determine whether or not there are an unlimited number of positionals
1508009b1c42SEd Schouten   bool HasUnlimitedPositionals = false;
1509009b1c42SEd Schouten 
151001095a5dSDimitry Andric   int FirstArg = 1;
1511e3b55780SDimitry Andric   SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1512312c0ed1SDimitry Andric   std::string NearestSubCommandString;
1513312c0ed1SDimitry Andric   bool MaybeNamedSubCommand =
1514312c0ed1SDimitry Andric       argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands();
1515312c0ed1SDimitry Andric   if (MaybeNamedSubCommand) {
151601095a5dSDimitry Andric     // If the first argument specifies a valid subcommand, start processing
151701095a5dSDimitry Andric     // options from the second argument.
1518312c0ed1SDimitry Andric     ChosenSubCommand =
1519312c0ed1SDimitry Andric         LookupSubCommand(StringRef(argv[FirstArg]), NearestSubCommandString);
1520e3b55780SDimitry Andric     if (ChosenSubCommand != &SubCommand::getTopLevel())
152101095a5dSDimitry Andric       FirstArg = 2;
152201095a5dSDimitry Andric   }
152301095a5dSDimitry Andric   GlobalParser->ActiveSubCommand = ChosenSubCommand;
152401095a5dSDimitry Andric 
152501095a5dSDimitry Andric   assert(ChosenSubCommand);
152601095a5dSDimitry Andric   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
152701095a5dSDimitry Andric   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
152801095a5dSDimitry Andric   auto &SinkOpts = ChosenSubCommand->SinkOpts;
152901095a5dSDimitry Andric   auto &OptionsMap = ChosenSubCommand->OptionsMap;
153001095a5dSDimitry Andric 
1531344a3780SDimitry Andric   for (auto *O: DefaultOptions) {
1532e6d15924SDimitry Andric     addOption(O, true);
1533e6d15924SDimitry Andric   }
1534e6d15924SDimitry Andric 
15355a5ac124SDimitry Andric   if (ConsumeAfterOpt) {
15365a5ac124SDimitry Andric     assert(PositionalOpts.size() > 0 &&
1537009b1c42SEd Schouten            "Cannot specify cl::ConsumeAfter without a positional argument!");
1538009b1c42SEd Schouten   }
15395a5ac124SDimitry Andric   if (!PositionalOpts.empty()) {
1540009b1c42SEd Schouten 
1541009b1c42SEd Schouten     // Calculate how many positional values are _required_.
1542009b1c42SEd Schouten     bool UnboundedFound = false;
15435a5ac124SDimitry Andric     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1544009b1c42SEd Schouten       Option *Opt = PositionalOpts[i];
1545009b1c42SEd Schouten       if (RequiresValue(Opt))
1546009b1c42SEd Schouten         ++NumPositionalRequired;
1547009b1c42SEd Schouten       else if (ConsumeAfterOpt) {
1548009b1c42SEd Schouten         // ConsumeAfter cannot be combined with "optional" positional options
1549009b1c42SEd Schouten         // unless there is only one positional argument...
155001095a5dSDimitry Andric         if (PositionalOpts.size() > 1) {
155101095a5dSDimitry Andric           if (!IgnoreErrors)
155201095a5dSDimitry Andric             Opt->error("error - this positional option will never be matched, "
1553009b1c42SEd Schouten                        "because it does not Require a value, and a "
1554009b1c42SEd Schouten                        "cl::ConsumeAfter option is active!");
155501095a5dSDimitry Andric           ErrorParsing = true;
155601095a5dSDimitry Andric         }
1557dd58ef01SDimitry Andric       } else if (UnboundedFound && !Opt->hasArgStr()) {
1558009b1c42SEd Schouten         // This option does not "require" a value...  Make sure this option is
1559009b1c42SEd Schouten         // not specified after an option that eats all extra arguments, or this
1560009b1c42SEd Schouten         // one will never get any!
1561009b1c42SEd Schouten         //
156271d5a254SDimitry Andric         if (!IgnoreErrors)
156301095a5dSDimitry Andric           Opt->error("error - option can never match, because "
1564009b1c42SEd Schouten                      "another positional argument will match an "
1565009b1c42SEd Schouten                      "unbounded number of values, and this option"
1566009b1c42SEd Schouten                      " does not require a value!");
156771d5a254SDimitry Andric         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
156871d5a254SDimitry Andric               << "' is all messed up!\n";
156971d5a254SDimitry Andric         *Errs << PositionalOpts.size();
157001095a5dSDimitry Andric         ErrorParsing = true;
157101095a5dSDimitry Andric       }
1572009b1c42SEd Schouten       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1573009b1c42SEd Schouten     }
1574009b1c42SEd Schouten     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1575009b1c42SEd Schouten   }
1576009b1c42SEd Schouten 
1577009b1c42SEd Schouten   // PositionalVals - A vector of "positional" arguments we accumulate into
157859850d08SRoman Divacky   // the process at the end.
1579009b1c42SEd Schouten   //
158059850d08SRoman Divacky   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1581009b1c42SEd Schouten 
1582009b1c42SEd Schouten   // If the program has named positional arguments, and the name has been run
1583009b1c42SEd Schouten   // across, keep track of which positional argument was named.  Otherwise put
1584009b1c42SEd Schouten   // the positional args into the PositionalVals list...
15855ca98fd9SDimitry Andric   Option *ActivePositionalArg = nullptr;
1586009b1c42SEd Schouten 
1587009b1c42SEd Schouten   // Loop over all of the arguments... processing them.
1588009b1c42SEd Schouten   bool DashDashFound = false; // Have we read '--'?
158901095a5dSDimitry Andric   for (int i = FirstArg; i < argc; ++i) {
15905ca98fd9SDimitry Andric     Option *Handler = nullptr;
15916b943ff3SDimitry Andric     std::string NearestHandlerString;
159259850d08SRoman Divacky     StringRef Value;
159359850d08SRoman Divacky     StringRef ArgName = "";
1594e6d15924SDimitry Andric     bool HaveDoubleDash = false;
1595009b1c42SEd Schouten 
1596009b1c42SEd Schouten     // Check to see if this is a positional argument.  This argument is
1597009b1c42SEd Schouten     // considered to be positional if it doesn't start with '-', if it is "-"
1598009b1c42SEd Schouten     // itself, or if we have seen "--" already.
1599009b1c42SEd Schouten     //
1600009b1c42SEd Schouten     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1601009b1c42SEd Schouten       // Positional argument!
1602009b1c42SEd Schouten       if (ActivePositionalArg) {
1603b915e9e0SDimitry Andric         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1604009b1c42SEd Schouten         continue; // We are done!
160559850d08SRoman Divacky       }
160659850d08SRoman Divacky 
160759850d08SRoman Divacky       if (!PositionalOpts.empty()) {
1608b915e9e0SDimitry Andric         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1609009b1c42SEd Schouten 
1610009b1c42SEd Schouten         // All of the positional arguments have been fulfulled, give the rest to
1611009b1c42SEd Schouten         // the consume after option... if it's specified...
1612009b1c42SEd Schouten         //
16135ca98fd9SDimitry Andric         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1614009b1c42SEd Schouten           for (++i; i < argc; ++i)
1615b915e9e0SDimitry Andric             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1616009b1c42SEd Schouten           break; // Handle outside of the argument processing loop...
1617009b1c42SEd Schouten         }
1618009b1c42SEd Schouten 
1619009b1c42SEd Schouten         // Delay processing positional arguments until the end...
1620009b1c42SEd Schouten         continue;
1621009b1c42SEd Schouten       }
1622009b1c42SEd Schouten     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1623009b1c42SEd Schouten                !DashDashFound) {
1624009b1c42SEd Schouten       DashDashFound = true; // This is the mythical "--"?
1625009b1c42SEd Schouten       continue;             // Don't try to process it as an argument itself.
1626009b1c42SEd Schouten     } else if (ActivePositionalArg &&
1627009b1c42SEd Schouten                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1628009b1c42SEd Schouten       // If there is a positional argument eating options, check to see if this
1629009b1c42SEd Schouten       // option is another positional argument.  If so, treat it as an argument,
1630009b1c42SEd Schouten       // otherwise feed it to the eating positional.
1631b915e9e0SDimitry Andric       ArgName = StringRef(argv[i] + 1);
1632e6d15924SDimitry Andric       // Eat second dash.
16334df029ccSDimitry Andric       if (ArgName.consume_front("-"))
1634e6d15924SDimitry Andric         HaveDoubleDash = true;
163559850d08SRoman Divacky 
1636e6d15924SDimitry Andric       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1637e6d15924SDimitry Andric                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1638009b1c42SEd Schouten       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1639b915e9e0SDimitry Andric         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1640009b1c42SEd Schouten         continue; // We are done!
1641009b1c42SEd Schouten       }
164259850d08SRoman Divacky     } else { // We start with a '-', must be an argument.
1643b915e9e0SDimitry Andric       ArgName = StringRef(argv[i] + 1);
1644e6d15924SDimitry Andric       // Eat second dash.
16454df029ccSDimitry Andric       if (ArgName.consume_front("-"))
1646e6d15924SDimitry Andric         HaveDoubleDash = true;
164759850d08SRoman Divacky 
1648e6d15924SDimitry Andric       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1649e6d15924SDimitry Andric                                  LongOptionsUseDoubleDash, HaveDoubleDash);
1650009b1c42SEd Schouten 
1651b1c73532SDimitry Andric       // If Handler is not found in a specialized subcommand, look up handler
1652b1c73532SDimitry Andric       // in the top-level subcommand.
1653b1c73532SDimitry Andric       // cl::opt without cl::sub belongs to top-level subcommand.
1654b1c73532SDimitry Andric       if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel())
1655b1c73532SDimitry Andric         Handler = LookupLongOption(SubCommand::getTopLevel(), ArgName, Value,
1656b1c73532SDimitry Andric                                    LongOptionsUseDoubleDash, HaveDoubleDash);
1657b1c73532SDimitry Andric 
1658009b1c42SEd Schouten       // Check to see if this "option" is really a prefixed or grouped argument.
1659e6d15924SDimitry Andric       if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
16605a5ac124SDimitry Andric         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
16615a5ac124SDimitry Andric                                                 OptionsMap);
1662cf099d11SDimitry Andric 
1663cf099d11SDimitry Andric       // Otherwise, look for the closest available option to report to the user
1664cf099d11SDimitry Andric       // in the upcoming error.
16655ca98fd9SDimitry Andric       if (!Handler && SinkOpts.empty())
16665a5ac124SDimitry Andric         LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1667009b1c42SEd Schouten     }
1668009b1c42SEd Schouten 
16695ca98fd9SDimitry Andric     if (!Handler) {
1670312c0ed1SDimitry Andric       if (!SinkOpts.empty()) {
167177fc4c14SDimitry Andric         for (Option *SinkOpt : SinkOpts)
167277fc4c14SDimitry Andric           SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1673312c0ed1SDimitry Andric         continue;
1674009b1c42SEd Schouten       }
1675312c0ed1SDimitry Andric 
1676312c0ed1SDimitry Andric       auto ReportUnknownArgument = [&](bool IsArg,
1677312c0ed1SDimitry Andric                                        StringRef NearestArgumentName) {
1678312c0ed1SDimitry Andric         *Errs << ProgramName << ": Unknown "
1679312c0ed1SDimitry Andric               << (IsArg ? "command line argument" : "subcommand") << " '"
1680312c0ed1SDimitry Andric               << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
1681312c0ed1SDimitry Andric 
1682312c0ed1SDimitry Andric         if (NearestArgumentName.empty())
1683312c0ed1SDimitry Andric           return;
1684312c0ed1SDimitry Andric 
1685312c0ed1SDimitry Andric         *Errs << ProgramName << ": Did you mean '";
1686312c0ed1SDimitry Andric         if (IsArg)
1687312c0ed1SDimitry Andric           *Errs << PrintArg(NearestArgumentName, 0);
1688312c0ed1SDimitry Andric         else
1689312c0ed1SDimitry Andric           *Errs << NearestArgumentName;
1690312c0ed1SDimitry Andric         *Errs << "'?\n";
1691312c0ed1SDimitry Andric       };
1692312c0ed1SDimitry Andric 
1693312c0ed1SDimitry Andric       if (i > 1 || !MaybeNamedSubCommand)
1694312c0ed1SDimitry Andric         ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString);
1695312c0ed1SDimitry Andric       else
1696312c0ed1SDimitry Andric         ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString);
1697312c0ed1SDimitry Andric 
1698312c0ed1SDimitry Andric       ErrorParsing = true;
1699009b1c42SEd Schouten       continue;
1700009b1c42SEd Schouten     }
1701009b1c42SEd Schouten 
1702009b1c42SEd Schouten     // If this is a named positional argument, just remember that it is the
1703009b1c42SEd Schouten     // active one...
1704eb11fae6SDimitry Andric     if (Handler->getFormattingFlag() == cl::Positional) {
1705eb11fae6SDimitry Andric       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1706eb11fae6SDimitry Andric         Handler->error("This argument does not take a value.\n"
1707eb11fae6SDimitry Andric                        "\tInstead, it consumes any positional arguments until "
1708eb11fae6SDimitry Andric                        "the next recognized option.", *Errs);
1709eb11fae6SDimitry Andric         ErrorParsing = true;
1710eb11fae6SDimitry Andric       }
1711009b1c42SEd Schouten       ActivePositionalArg = Handler;
1712eb11fae6SDimitry Andric     }
1713009b1c42SEd Schouten     else
1714009b1c42SEd Schouten       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1715009b1c42SEd Schouten   }
1716009b1c42SEd Schouten 
1717009b1c42SEd Schouten   // Check and handle positional arguments now...
1718009b1c42SEd Schouten   if (NumPositionalRequired > PositionalVals.size()) {
171971d5a254SDimitry Andric       *Errs << ProgramName
1720009b1c42SEd Schouten              << ": Not enough positional command line arguments specified!\n"
1721009b1c42SEd Schouten              << "Must specify at least " << NumPositionalRequired
1722b915e9e0SDimitry Andric              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1723e6d15924SDimitry Andric              << ": See: " << argv[0] << " --help\n";
1724009b1c42SEd Schouten 
1725009b1c42SEd Schouten     ErrorParsing = true;
1726104bd817SRoman Divacky   } else if (!HasUnlimitedPositionals &&
1727104bd817SRoman Divacky              PositionalVals.size() > PositionalOpts.size()) {
172871d5a254SDimitry Andric     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1729009b1c42SEd Schouten           << "Can specify at most " << PositionalOpts.size()
1730e6d15924SDimitry Andric           << " positional arguments: See: " << argv[0] << " --help\n";
1731009b1c42SEd Schouten     ErrorParsing = true;
1732009b1c42SEd Schouten 
17335ca98fd9SDimitry Andric   } else if (!ConsumeAfterOpt) {
173459850d08SRoman Divacky     // Positional args have already been handled if ConsumeAfter is specified.
1735009b1c42SEd Schouten     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1736ac9a064cSDimitry Andric     for (Option *Opt : PositionalOpts) {
1737ac9a064cSDimitry Andric       if (RequiresValue(Opt)) {
1738ac9a064cSDimitry Andric         ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1739009b1c42SEd Schouten                                 PositionalVals[ValNo].second);
1740009b1c42SEd Schouten         ValNo++;
1741009b1c42SEd Schouten         --NumPositionalRequired; // We fulfilled our duty...
1742009b1c42SEd Schouten       }
1743009b1c42SEd Schouten 
1744009b1c42SEd Schouten       // If we _can_ give this option more arguments, do so now, as long as we
1745009b1c42SEd Schouten       // do not give it values that others need.  'Done' controls whether the
1746009b1c42SEd Schouten       // option even _WANTS_ any more.
1747009b1c42SEd Schouten       //
1748ac9a064cSDimitry Andric       bool Done = Opt->getNumOccurrencesFlag() == cl::Required;
1749009b1c42SEd Schouten       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1750ac9a064cSDimitry Andric         switch (Opt->getNumOccurrencesFlag()) {
1751009b1c42SEd Schouten         case cl::Optional:
1752009b1c42SEd Schouten           Done = true; // Optional arguments want _at most_ one value
1753e3b55780SDimitry Andric           [[fallthrough]];
1754009b1c42SEd Schouten         case cl::ZeroOrMore: // Zero or more will take all they can get...
1755009b1c42SEd Schouten         case cl::OneOrMore:  // One or more will take all they can get...
1756ac9a064cSDimitry Andric           ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1757009b1c42SEd Schouten                                   PositionalVals[ValNo].second);
1758009b1c42SEd Schouten           ValNo++;
1759009b1c42SEd Schouten           break;
1760009b1c42SEd Schouten         default:
176159850d08SRoman Divacky           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1762009b1c42SEd Schouten                            "positional argument processing!");
1763009b1c42SEd Schouten         }
1764009b1c42SEd Schouten       }
1765009b1c42SEd Schouten     }
1766009b1c42SEd Schouten   } else {
1767009b1c42SEd Schouten     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1768009b1c42SEd Schouten     unsigned ValNo = 0;
1769ac9a064cSDimitry Andric     for (Option *Opt : PositionalOpts)
1770ac9a064cSDimitry Andric       if (RequiresValue(Opt)) {
1771ac9a064cSDimitry Andric         ErrorParsing |= ProvidePositionalOption(
1772ac9a064cSDimitry Andric             Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1773009b1c42SEd Schouten         ValNo++;
1774009b1c42SEd Schouten       }
1775009b1c42SEd Schouten 
1776009b1c42SEd Schouten     // Handle the case where there is just one positional option, and it's
1777009b1c42SEd Schouten     // optional.  In this case, we want to give JUST THE FIRST option to the
1778009b1c42SEd Schouten     // positional option and keep the rest for the consume after.  The above
1779009b1c42SEd Schouten     // loop would have assigned no values to positional options in this case.
1780009b1c42SEd Schouten     //
17815a5ac124SDimitry Andric     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
17825a5ac124SDimitry Andric       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1783009b1c42SEd Schouten                                               PositionalVals[ValNo].first,
1784009b1c42SEd Schouten                                               PositionalVals[ValNo].second);
1785009b1c42SEd Schouten       ValNo++;
1786009b1c42SEd Schouten     }
1787009b1c42SEd Schouten 
1788009b1c42SEd Schouten     // Handle over all of the rest of the arguments to the
1789009b1c42SEd Schouten     // cl::ConsumeAfter command line option...
1790009b1c42SEd Schouten     for (; ValNo != PositionalVals.size(); ++ValNo)
179167c32a98SDimitry Andric       ErrorParsing |=
179267c32a98SDimitry Andric           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1793009b1c42SEd Schouten                                   PositionalVals[ValNo].second);
1794009b1c42SEd Schouten   }
1795009b1c42SEd Schouten 
1796009b1c42SEd Schouten   // Loop over args and make sure all required args are specified!
17975a5ac124SDimitry Andric   for (const auto &Opt : OptionsMap) {
17985ca98fd9SDimitry Andric     switch (Opt.second->getNumOccurrencesFlag()) {
1799009b1c42SEd Schouten     case Required:
1800009b1c42SEd Schouten     case OneOrMore:
18015ca98fd9SDimitry Andric       if (Opt.second->getNumOccurrences() == 0) {
18025ca98fd9SDimitry Andric         Opt.second->error("must be specified at least once!");
1803009b1c42SEd Schouten         ErrorParsing = true;
1804009b1c42SEd Schouten       }
1805e3b55780SDimitry Andric       [[fallthrough]];
1806009b1c42SEd Schouten     default:
1807009b1c42SEd Schouten       break;
1808009b1c42SEd Schouten     }
1809009b1c42SEd Schouten   }
1810009b1c42SEd Schouten 
1811cf099d11SDimitry Andric   // Now that we know if -debug is specified, we can use it.
1812cf099d11SDimitry Andric   // Note that if ReadResponseFiles == true, this must be done before the
1813cf099d11SDimitry Andric   // memory allocated for the expanded command line is free()d below.
1814eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Args: ";
181567c32a98SDimitry Andric              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
181667c32a98SDimitry Andric              dbgs() << '\n';);
1817cf099d11SDimitry Andric 
1818009b1c42SEd Schouten   // Free all of the memory allocated to the map.  Command line options may only
1819009b1c42SEd Schouten   // be processed once!
18205a5ac124SDimitry Andric   MoreHelp.clear();
1821009b1c42SEd Schouten 
1822009b1c42SEd Schouten   // If we had an error processing our arguments, don't let the program execute
182301095a5dSDimitry Andric   if (ErrorParsing) {
182401095a5dSDimitry Andric     if (!IgnoreErrors)
182567c32a98SDimitry Andric       exit(1);
182601095a5dSDimitry Andric     return false;
182701095a5dSDimitry Andric   }
182801095a5dSDimitry Andric   return true;
1829009b1c42SEd Schouten }
1830009b1c42SEd Schouten 
1831009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1832009b1c42SEd Schouten // Option Base class implementation
1833009b1c42SEd Schouten //
1834009b1c42SEd Schouten 
error(const Twine & Message,StringRef ArgName,raw_ostream & Errs)1835eb11fae6SDimitry Andric bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
183667c32a98SDimitry Andric   if (!ArgName.data())
183767c32a98SDimitry Andric     ArgName = ArgStr;
183859850d08SRoman Divacky   if (ArgName.empty())
1839eb11fae6SDimitry Andric     Errs << HelpStr; // Be nice for positional arguments
1840009b1c42SEd Schouten   else
1841706b4fc4SDimitry Andric     Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1842009b1c42SEd Schouten 
1843eb11fae6SDimitry Andric   Errs << " option: " << Message << "\n";
1844009b1c42SEd Schouten   return true;
1845009b1c42SEd Schouten }
1846009b1c42SEd Schouten 
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)184767c32a98SDimitry Andric bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
184867c32a98SDimitry Andric                            bool MultiArg) {
1849009b1c42SEd Schouten   if (!MultiArg)
1850009b1c42SEd Schouten     NumOccurrences++; // Increment the number of times we have been seen
1851009b1c42SEd Schouten 
1852009b1c42SEd Schouten   return handleOccurrence(pos, ArgName, Value);
1853009b1c42SEd Schouten }
1854009b1c42SEd Schouten 
1855009b1c42SEd Schouten // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1856009b1c42SEd Schouten // has been specified yet.
1857009b1c42SEd Schouten //
getValueStr(const Option & O,StringRef DefaultMsg)1858dd58ef01SDimitry Andric static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1859dd58ef01SDimitry Andric   if (O.ValueStr.empty())
186067c32a98SDimitry Andric     return DefaultMsg;
1861009b1c42SEd Schouten   return O.ValueStr;
1862009b1c42SEd Schouten }
1863009b1c42SEd Schouten 
1864009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1865009b1c42SEd Schouten // cl::alias class implementation
1866009b1c42SEd Schouten //
1867009b1c42SEd Schouten 
1868009b1c42SEd Schouten // Return the width of the option tag for printing...
getOptionWidth() const1869e6d15924SDimitry Andric size_t alias::getOptionWidth() const {
1870e6d15924SDimitry Andric   return argPlusPrefixesSize(ArgStr);
1871e6d15924SDimitry Andric }
1872009b1c42SEd Schouten 
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)187371d5a254SDimitry Andric void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1874f8af5cf6SDimitry Andric                           size_t FirstLineIndentedBy) {
1875e6d15924SDimitry Andric   assert(Indent >= FirstLineIndentedBy);
1876f8af5cf6SDimitry Andric   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1877e6d15924SDimitry Andric   outs().indent(Indent - FirstLineIndentedBy)
1878e6d15924SDimitry Andric       << ArgHelpPrefix << Split.first << "\n";
1879f8af5cf6SDimitry Andric   while (!Split.second.empty()) {
1880f8af5cf6SDimitry Andric     Split = Split.second.split('\n');
1881f8af5cf6SDimitry Andric     outs().indent(Indent) << Split.first << "\n";
1882f8af5cf6SDimitry Andric   }
1883f8af5cf6SDimitry Andric }
1884f8af5cf6SDimitry Andric 
printEnumValHelpStr(StringRef HelpStr,size_t BaseIndent,size_t FirstLineIndentedBy)1885344a3780SDimitry Andric void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1886344a3780SDimitry Andric                                  size_t FirstLineIndentedBy) {
1887344a3780SDimitry Andric   const StringRef ValHelpPrefix = "  ";
1888344a3780SDimitry Andric   assert(BaseIndent >= FirstLineIndentedBy);
1889344a3780SDimitry Andric   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1890344a3780SDimitry Andric   outs().indent(BaseIndent - FirstLineIndentedBy)
1891344a3780SDimitry Andric       << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1892344a3780SDimitry Andric   while (!Split.second.empty()) {
1893344a3780SDimitry Andric     Split = Split.second.split('\n');
1894344a3780SDimitry Andric     outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1895344a3780SDimitry Andric   }
1896344a3780SDimitry Andric }
1897344a3780SDimitry Andric 
1898009b1c42SEd Schouten // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1899009b1c42SEd Schouten void alias::printOptionInfo(size_t GlobalWidth) const {
1900e6d15924SDimitry Andric   outs() << PrintArg(ArgStr);
1901e6d15924SDimitry Andric   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
1902009b1c42SEd Schouten }
1903009b1c42SEd Schouten 
1904009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1905009b1c42SEd Schouten // Parser Implementation code...
1906009b1c42SEd Schouten //
1907009b1c42SEd Schouten 
1908009b1c42SEd Schouten // basic_parser implementation
1909009b1c42SEd Schouten //
1910009b1c42SEd Schouten 
1911009b1c42SEd Schouten // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1912009b1c42SEd Schouten size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1913e6d15924SDimitry Andric   size_t Len = argPlusPrefixesSize(O.ArgStr);
1914b915e9e0SDimitry Andric   auto ValName = getValueName();
1915eb11fae6SDimitry Andric   if (!ValName.empty()) {
1916eb11fae6SDimitry Andric     size_t FormattingLen = 3;
1917eb11fae6SDimitry Andric     if (O.getMiscFlags() & PositionalEatsArgs)
1918eb11fae6SDimitry Andric       FormattingLen = 6;
1919eb11fae6SDimitry Andric     Len += getValueStr(O, ValName).size() + FormattingLen;
1920eb11fae6SDimitry Andric   }
1921009b1c42SEd Schouten 
1922e6d15924SDimitry Andric   return Len;
1923009b1c42SEd Schouten }
1924009b1c42SEd Schouten 
1925009b1c42SEd Schouten // printOptionInfo - Print out information about this option.  The
1926009b1c42SEd Schouten // to-be-maintained width is specified.
1927009b1c42SEd Schouten //
printOptionInfo(const Option & O,size_t GlobalWidth) const1928009b1c42SEd Schouten void basic_parser_impl::printOptionInfo(const Option &O,
1929009b1c42SEd Schouten                                         size_t GlobalWidth) const {
1930e6d15924SDimitry Andric   outs() << PrintArg(O.ArgStr);
1931009b1c42SEd Schouten 
1932b915e9e0SDimitry Andric   auto ValName = getValueName();
1933eb11fae6SDimitry Andric   if (!ValName.empty()) {
1934eb11fae6SDimitry Andric     if (O.getMiscFlags() & PositionalEatsArgs) {
1935eb11fae6SDimitry Andric       outs() << " <" << getValueStr(O, ValName) << ">...";
1936cfca06d7SDimitry Andric     } else if (O.getValueExpectedFlag() == ValueOptional)
1937cfca06d7SDimitry Andric       outs() << "[=<" << getValueStr(O, ValName) << ">]";
19381f917f69SDimitry Andric     else {
19391f917f69SDimitry Andric       outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
19401f917f69SDimitry Andric              << '>';
19411f917f69SDimitry Andric     }
1942eb11fae6SDimitry Andric   }
1943009b1c42SEd Schouten 
194471d5a254SDimitry Andric   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1945009b1c42SEd Schouten }
1946009b1c42SEd Schouten 
printOptionName(const Option & O,size_t GlobalWidth) const19476b943ff3SDimitry Andric void basic_parser_impl::printOptionName(const Option &O,
19486b943ff3SDimitry Andric                                         size_t GlobalWidth) const {
1949e6d15924SDimitry Andric   outs() << PrintArg(O.ArgStr);
1950dd58ef01SDimitry Andric   outs().indent(GlobalWidth - O.ArgStr.size());
19516b943ff3SDimitry Andric }
1952009b1c42SEd Schouten 
1953009b1c42SEd Schouten // parser<bool> implementation
1954009b1c42SEd Schouten //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)195567c32a98SDimitry Andric bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
195667c32a98SDimitry Andric                          bool &Value) {
1957009b1c42SEd Schouten   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1958009b1c42SEd Schouten       Arg == "1") {
1959009b1c42SEd Schouten     Value = true;
1960009b1c42SEd Schouten     return false;
1961009b1c42SEd Schouten   }
1962009b1c42SEd Schouten 
196359850d08SRoman Divacky   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
196459850d08SRoman Divacky     Value = false;
196559850d08SRoman Divacky     return false;
196659850d08SRoman Divacky   }
196759850d08SRoman Divacky   return O.error("'" + Arg +
196859850d08SRoman Divacky                  "' is invalid value for boolean argument! Try 0 or 1");
196959850d08SRoman Divacky }
197059850d08SRoman Divacky 
1971009b1c42SEd Schouten // parser<boolOrDefault> implementation
1972009b1c42SEd Schouten //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)197367c32a98SDimitry Andric bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
197467c32a98SDimitry Andric                                   boolOrDefault &Value) {
1975009b1c42SEd Schouten   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1976009b1c42SEd Schouten       Arg == "1") {
1977009b1c42SEd Schouten     Value = BOU_TRUE;
1978009b1c42SEd Schouten     return false;
1979009b1c42SEd Schouten   }
198059850d08SRoman Divacky   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
198159850d08SRoman Divacky     Value = BOU_FALSE;
198259850d08SRoman Divacky     return false;
198359850d08SRoman Divacky   }
198459850d08SRoman Divacky 
198559850d08SRoman Divacky   return O.error("'" + Arg +
198659850d08SRoman Divacky                  "' is invalid value for boolean argument! Try 0 or 1");
198759850d08SRoman Divacky }
1988009b1c42SEd Schouten 
1989009b1c42SEd Schouten // parser<int> implementation
1990009b1c42SEd Schouten //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)199167c32a98SDimitry Andric bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
199267c32a98SDimitry Andric                         int &Value) {
199359850d08SRoman Divacky   if (Arg.getAsInteger(0, Value))
199459850d08SRoman Divacky     return O.error("'" + Arg + "' value invalid for integer argument!");
1995009b1c42SEd Schouten   return false;
1996009b1c42SEd Schouten }
1997009b1c42SEd Schouten 
1998706b4fc4SDimitry Andric // parser<long> implementation
1999706b4fc4SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,long & Value)2000706b4fc4SDimitry Andric bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2001706b4fc4SDimitry Andric                          long &Value) {
2002706b4fc4SDimitry Andric   if (Arg.getAsInteger(0, Value))
2003706b4fc4SDimitry Andric     return O.error("'" + Arg + "' value invalid for long argument!");
2004706b4fc4SDimitry Andric   return false;
2005706b4fc4SDimitry Andric }
2006706b4fc4SDimitry Andric 
2007706b4fc4SDimitry Andric // parser<long long> implementation
2008706b4fc4SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,long long & Value)2009706b4fc4SDimitry Andric bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2010706b4fc4SDimitry Andric                               long long &Value) {
2011706b4fc4SDimitry Andric   if (Arg.getAsInteger(0, Value))
2012706b4fc4SDimitry Andric     return O.error("'" + Arg + "' value invalid for llong argument!");
2013706b4fc4SDimitry Andric   return false;
2014706b4fc4SDimitry Andric }
2015706b4fc4SDimitry Andric 
2016009b1c42SEd Schouten // parser<unsigned> implementation
2017009b1c42SEd Schouten //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)201867c32a98SDimitry Andric bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
201967c32a98SDimitry Andric                              unsigned &Value) {
202059850d08SRoman Divacky 
202159850d08SRoman Divacky   if (Arg.getAsInteger(0, Value))
202259850d08SRoman Divacky     return O.error("'" + Arg + "' value invalid for uint argument!");
2023009b1c42SEd Schouten   return false;
2024009b1c42SEd Schouten }
2025009b1c42SEd Schouten 
2026e6d15924SDimitry Andric // parser<unsigned long> implementation
2027e6d15924SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long & Value)2028e6d15924SDimitry Andric bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2029e6d15924SDimitry Andric                                   unsigned long &Value) {
2030e6d15924SDimitry Andric 
2031e6d15924SDimitry Andric   if (Arg.getAsInteger(0, Value))
2032e6d15924SDimitry Andric     return O.error("'" + Arg + "' value invalid for ulong argument!");
2033e6d15924SDimitry Andric   return false;
2034e6d15924SDimitry Andric }
2035e6d15924SDimitry Andric 
203630815c53SDimitry Andric // parser<unsigned long long> implementation
203730815c53SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)203830815c53SDimitry Andric bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
203967c32a98SDimitry Andric                                        StringRef Arg,
204067c32a98SDimitry Andric                                        unsigned long long &Value) {
204130815c53SDimitry Andric 
204230815c53SDimitry Andric   if (Arg.getAsInteger(0, Value))
2043e6d15924SDimitry Andric     return O.error("'" + Arg + "' value invalid for ullong argument!");
204430815c53SDimitry Andric   return false;
204530815c53SDimitry Andric }
204630815c53SDimitry Andric 
2047009b1c42SEd Schouten // parser<double>/parser<float> implementation
2048009b1c42SEd Schouten //
parseDouble(Option & O,StringRef Arg,double & Value)204959850d08SRoman Divacky static bool parseDouble(Option &O, StringRef Arg, double &Value) {
205008bbd35aSDimitry Andric   if (to_float(Arg, Value))
2051009b1c42SEd Schouten     return false;
205208bbd35aSDimitry Andric   return O.error("'" + Arg + "' value invalid for floating point argument!");
2053009b1c42SEd Schouten }
2054009b1c42SEd Schouten 
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)205567c32a98SDimitry Andric bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
205667c32a98SDimitry Andric                            double &Val) {
2057009b1c42SEd Schouten   return parseDouble(O, Arg, Val);
2058009b1c42SEd Schouten }
2059009b1c42SEd Schouten 
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)206067c32a98SDimitry Andric bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
206167c32a98SDimitry Andric                           float &Val) {
2062009b1c42SEd Schouten   double dVal;
2063009b1c42SEd Schouten   if (parseDouble(O, Arg, dVal))
2064009b1c42SEd Schouten     return true;
2065009b1c42SEd Schouten   Val = (float)dVal;
2066009b1c42SEd Schouten   return false;
2067009b1c42SEd Schouten }
2068009b1c42SEd Schouten 
2069009b1c42SEd Schouten // generic_parser_base implementation
2070009b1c42SEd Schouten //
2071009b1c42SEd Schouten 
2072009b1c42SEd Schouten // findOption - Return the option number corresponding to the specified
2073009b1c42SEd Schouten // argument string.  If the option is not found, getNumOptions() is returned.
2074009b1c42SEd Schouten //
findOption(StringRef Name)2075b915e9e0SDimitry Andric unsigned generic_parser_base::findOption(StringRef Name) {
207659850d08SRoman Divacky   unsigned e = getNumOptions();
2077009b1c42SEd Schouten 
207859850d08SRoman Divacky   for (unsigned i = 0; i != e; ++i) {
2079b915e9e0SDimitry Andric     if (getOption(i) == Name)
2080009b1c42SEd Schouten       return i;
208159850d08SRoman Divacky   }
2082009b1c42SEd Schouten   return e;
2083009b1c42SEd Schouten }
2084009b1c42SEd Schouten 
2085e6d15924SDimitry Andric static StringRef EqValue = "=<value>";
2086e6d15924SDimitry Andric static StringRef EmptyOption = "<empty>";
2087e6d15924SDimitry Andric static StringRef OptionPrefix = "    =";
getOptionPrefixesSize()2088344a3780SDimitry Andric static size_t getOptionPrefixesSize() {
2089344a3780SDimitry Andric   return OptionPrefix.size() + ArgHelpPrefix.size();
2090344a3780SDimitry Andric }
2091e6d15924SDimitry Andric 
shouldPrintOption(StringRef Name,StringRef Description,const Option & O)2092e6d15924SDimitry Andric static bool shouldPrintOption(StringRef Name, StringRef Description,
2093e6d15924SDimitry Andric                               const Option &O) {
2094e6d15924SDimitry Andric   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2095e6d15924SDimitry Andric          !Description.empty();
2096e6d15924SDimitry Andric }
2097e6d15924SDimitry Andric 
2098009b1c42SEd Schouten // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const2099009b1c42SEd Schouten size_t generic_parser_base::getOptionWidth(const Option &O) const {
2100009b1c42SEd Schouten   if (O.hasArgStr()) {
2101e6d15924SDimitry Andric     size_t Size =
2102e6d15924SDimitry Andric         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2103e6d15924SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2104e6d15924SDimitry Andric       StringRef Name = getOption(i);
2105e6d15924SDimitry Andric       if (!shouldPrintOption(Name, getDescription(i), O))
2106e6d15924SDimitry Andric         continue;
2107e6d15924SDimitry Andric       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2108344a3780SDimitry Andric       Size = std::max(Size, NameSize + getOptionPrefixesSize());
2109e6d15924SDimitry Andric     }
2110009b1c42SEd Schouten     return Size;
2111009b1c42SEd Schouten   } else {
2112009b1c42SEd Schouten     size_t BaseSize = 0;
2113009b1c42SEd Schouten     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2114b915e9e0SDimitry Andric       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2115009b1c42SEd Schouten     return BaseSize;
2116009b1c42SEd Schouten   }
2117009b1c42SEd Schouten }
2118009b1c42SEd Schouten 
2119009b1c42SEd Schouten // printOptionInfo - Print out information about this option.  The
2120009b1c42SEd Schouten // to-be-maintained width is specified.
2121009b1c42SEd Schouten //
printOptionInfo(const Option & O,size_t GlobalWidth) const2122009b1c42SEd Schouten void generic_parser_base::printOptionInfo(const Option &O,
2123009b1c42SEd Schouten                                           size_t GlobalWidth) const {
2124009b1c42SEd Schouten   if (O.hasArgStr()) {
2125e6d15924SDimitry Andric     // When the value is optional, first print a line just describing the
2126e6d15924SDimitry Andric     // option without values.
2127e6d15924SDimitry Andric     if (O.getValueExpectedFlag() == ValueOptional) {
2128009b1c42SEd Schouten       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2129e6d15924SDimitry Andric         if (getOption(i).empty()) {
2130e6d15924SDimitry Andric           outs() << PrintArg(O.ArgStr);
2131e6d15924SDimitry Andric           Option::printHelpStr(O.HelpStr, GlobalWidth,
2132e6d15924SDimitry Andric                                argPlusPrefixesSize(O.ArgStr));
2133e6d15924SDimitry Andric           break;
2134e6d15924SDimitry Andric         }
2135e6d15924SDimitry Andric       }
2136e6d15924SDimitry Andric     }
2137e6d15924SDimitry Andric 
2138e6d15924SDimitry Andric     outs() << PrintArg(O.ArgStr) << EqValue;
2139e6d15924SDimitry Andric     Option::printHelpStr(O.HelpStr, GlobalWidth,
2140e6d15924SDimitry Andric                          EqValue.size() +
2141e6d15924SDimitry Andric                              argPlusPrefixesSize(O.ArgStr));
2142e6d15924SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2143e6d15924SDimitry Andric       StringRef OptionName = getOption(i);
2144e6d15924SDimitry Andric       StringRef Description = getDescription(i);
2145e6d15924SDimitry Andric       if (!shouldPrintOption(OptionName, Description, O))
2146e6d15924SDimitry Andric         continue;
2147344a3780SDimitry Andric       size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2148e6d15924SDimitry Andric       outs() << OptionPrefix << OptionName;
2149e6d15924SDimitry Andric       if (OptionName.empty()) {
2150e6d15924SDimitry Andric         outs() << EmptyOption;
2151344a3780SDimitry Andric         assert(FirstLineIndent >= EmptyOption.size());
2152344a3780SDimitry Andric         FirstLineIndent += EmptyOption.size();
2153e6d15924SDimitry Andric       }
2154e6d15924SDimitry Andric       if (!Description.empty())
2155344a3780SDimitry Andric         Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2156344a3780SDimitry Andric       else
2157e6d15924SDimitry Andric         outs() << '\n';
2158009b1c42SEd Schouten     }
2159009b1c42SEd Schouten   } else {
2160dd58ef01SDimitry Andric     if (!O.HelpStr.empty())
216159850d08SRoman Divacky       outs() << "  " << O.HelpStr << '\n';
2162009b1c42SEd Schouten     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2163e6d15924SDimitry Andric       StringRef Option = getOption(i);
2164e6d15924SDimitry Andric       outs() << "    " << PrintArg(Option);
216571d5a254SDimitry Andric       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2166009b1c42SEd Schouten     }
2167009b1c42SEd Schouten   }
2168009b1c42SEd Schouten }
2169009b1c42SEd Schouten 
21706b943ff3SDimitry Andric static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
21716b943ff3SDimitry Andric 
21726b943ff3SDimitry Andric // printGenericOptionDiff - Print the value of this option and it's default.
21736b943ff3SDimitry Andric //
21746b943ff3SDimitry Andric // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const217567c32a98SDimitry Andric void generic_parser_base::printGenericOptionDiff(
217667c32a98SDimitry Andric     const Option &O, const GenericOptionValue &Value,
217767c32a98SDimitry Andric     const GenericOptionValue &Default, size_t GlobalWidth) const {
2178e6d15924SDimitry Andric   outs() << "  " << PrintArg(O.ArgStr);
2179dd58ef01SDimitry Andric   outs().indent(GlobalWidth - O.ArgStr.size());
21806b943ff3SDimitry Andric 
21816b943ff3SDimitry Andric   unsigned NumOpts = getNumOptions();
21826b943ff3SDimitry Andric   for (unsigned i = 0; i != NumOpts; ++i) {
2183b1c73532SDimitry Andric     if (!Value.compare(getOptionValue(i)))
21846b943ff3SDimitry Andric       continue;
21856b943ff3SDimitry Andric 
21866b943ff3SDimitry Andric     outs() << "= " << getOption(i);
2187b915e9e0SDimitry Andric     size_t L = getOption(i).size();
21886b943ff3SDimitry Andric     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
21896b943ff3SDimitry Andric     outs().indent(NumSpaces) << " (default: ";
21906b943ff3SDimitry Andric     for (unsigned j = 0; j != NumOpts; ++j) {
2191b1c73532SDimitry Andric       if (!Default.compare(getOptionValue(j)))
21926b943ff3SDimitry Andric         continue;
21936b943ff3SDimitry Andric       outs() << getOption(j);
21946b943ff3SDimitry Andric       break;
21956b943ff3SDimitry Andric     }
21966b943ff3SDimitry Andric     outs() << ")\n";
21976b943ff3SDimitry Andric     return;
21986b943ff3SDimitry Andric   }
21996b943ff3SDimitry Andric   outs() << "= *unknown option value*\n";
22006b943ff3SDimitry Andric }
22016b943ff3SDimitry Andric 
22026b943ff3SDimitry Andric // printOptionDiff - Specializations for printing basic value types.
22036b943ff3SDimitry Andric //
22046b943ff3SDimitry Andric #define PRINT_OPT_DIFF(T)                                                      \
220567c32a98SDimitry Andric   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
22066b943ff3SDimitry Andric                                   size_t GlobalWidth) const {                  \
22076b943ff3SDimitry Andric     printOptionName(O, GlobalWidth);                                           \
22086b943ff3SDimitry Andric     std::string Str;                                                           \
22096b943ff3SDimitry Andric     {                                                                          \
22106b943ff3SDimitry Andric       raw_string_ostream SS(Str);                                              \
22116b943ff3SDimitry Andric       SS << V;                                                                 \
22126b943ff3SDimitry Andric     }                                                                          \
22136b943ff3SDimitry Andric     outs() << "= " << Str;                                                     \
221467c32a98SDimitry Andric     size_t NumSpaces =                                                         \
221567c32a98SDimitry Andric         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
22166b943ff3SDimitry Andric     outs().indent(NumSpaces) << " (default: ";                                 \
22176b943ff3SDimitry Andric     if (D.hasValue())                                                          \
22186b943ff3SDimitry Andric       outs() << D.getValue();                                                  \
22196b943ff3SDimitry Andric     else                                                                       \
22206b943ff3SDimitry Andric       outs() << "*no default*";                                                \
22216b943ff3SDimitry Andric     outs() << ")\n";                                                           \
222267c32a98SDimitry Andric   }
22236b943ff3SDimitry Andric 
22246b943ff3SDimitry Andric PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)22256b943ff3SDimitry Andric PRINT_OPT_DIFF(boolOrDefault)
22266b943ff3SDimitry Andric PRINT_OPT_DIFF(int)
2227706b4fc4SDimitry Andric PRINT_OPT_DIFF(long)
2228706b4fc4SDimitry Andric PRINT_OPT_DIFF(long long)
22296b943ff3SDimitry Andric PRINT_OPT_DIFF(unsigned)
2230e6d15924SDimitry Andric PRINT_OPT_DIFF(unsigned long)
223130815c53SDimitry Andric PRINT_OPT_DIFF(unsigned long long)
22326b943ff3SDimitry Andric PRINT_OPT_DIFF(double)
22336b943ff3SDimitry Andric PRINT_OPT_DIFF(float)
22346b943ff3SDimitry Andric PRINT_OPT_DIFF(char)
22356b943ff3SDimitry Andric 
223667c32a98SDimitry Andric void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
223701095a5dSDimitry Andric                                           const OptionValue<std::string> &D,
22386b943ff3SDimitry Andric                                           size_t GlobalWidth) const {
22396b943ff3SDimitry Andric   printOptionName(O, GlobalWidth);
22406b943ff3SDimitry Andric   outs() << "= " << V;
22416b943ff3SDimitry Andric   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
22426b943ff3SDimitry Andric   outs().indent(NumSpaces) << " (default: ";
22436b943ff3SDimitry Andric   if (D.hasValue())
22446b943ff3SDimitry Andric     outs() << D.getValue();
22456b943ff3SDimitry Andric   else
22466b943ff3SDimitry Andric     outs() << "*no default*";
22476b943ff3SDimitry Andric   outs() << ")\n";
22486b943ff3SDimitry Andric }
22496b943ff3SDimitry Andric 
22506b943ff3SDimitry Andric // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const225167c32a98SDimitry Andric void basic_parser_impl::printOptionNoValue(const Option &O,
225267c32a98SDimitry Andric                                            size_t GlobalWidth) const {
22536b943ff3SDimitry Andric   printOptionName(O, GlobalWidth);
22546b943ff3SDimitry Andric   outs() << "= *cannot print option value*\n";
22556b943ff3SDimitry Andric }
2256009b1c42SEd Schouten 
2257009b1c42SEd Schouten //===----------------------------------------------------------------------===//
225867a71b31SRoman Divacky // -help and -help-hidden option implementation
2259009b1c42SEd Schouten //
2260009b1c42SEd Schouten 
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)22615a5ac124SDimitry Andric static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
22625a5ac124SDimitry Andric                           const std::pair<const char *, Option *> *RHS) {
22635a5ac124SDimitry Andric   return strcmp(LHS->first, RHS->first);
226459850d08SRoman Divacky }
226559850d08SRoman Divacky 
SubNameCompare(const std::pair<const char *,SubCommand * > * LHS,const std::pair<const char *,SubCommand * > * RHS)226601095a5dSDimitry Andric static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
226701095a5dSDimitry Andric                           const std::pair<const char *, SubCommand *> *RHS) {
226801095a5dSDimitry Andric   return strcmp(LHS->first, RHS->first);
226901095a5dSDimitry Andric }
227001095a5dSDimitry Andric 
22716b943ff3SDimitry Andric // Copy Options into a vector so we can sort them as we like.
sortOpts(StringMap<Option * > & OptMap,SmallVectorImpl<std::pair<const char *,Option * >> & Opts,bool ShowHidden)227267c32a98SDimitry Andric static void sortOpts(StringMap<Option *> &OptMap,
22736b943ff3SDimitry Andric                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
22746b943ff3SDimitry Andric                      bool ShowHidden) {
227501095a5dSDimitry Andric   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
22766b943ff3SDimitry Andric 
22776b943ff3SDimitry Andric   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
22786b943ff3SDimitry Andric        I != E; ++I) {
22796b943ff3SDimitry Andric     // Ignore really-hidden options.
22806b943ff3SDimitry Andric     if (I->second->getOptionHiddenFlag() == ReallyHidden)
22816b943ff3SDimitry Andric       continue;
22826b943ff3SDimitry Andric 
22836b943ff3SDimitry Andric     // Unless showhidden is set, ignore hidden flags.
22846b943ff3SDimitry Andric     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
22856b943ff3SDimitry Andric       continue;
22866b943ff3SDimitry Andric 
22876b943ff3SDimitry Andric     // If we've already seen this option, don't add it to the list again.
228867c32a98SDimitry Andric     if (!OptionSet.insert(I->second).second)
22896b943ff3SDimitry Andric       continue;
22906b943ff3SDimitry Andric 
229167c32a98SDimitry Andric     Opts.push_back(
229267c32a98SDimitry Andric         std::pair<const char *, Option *>(I->getKey().data(), I->second));
22936b943ff3SDimitry Andric   }
22946b943ff3SDimitry Andric 
22956b943ff3SDimitry Andric   // Sort the options list alphabetically.
22965a5ac124SDimitry Andric   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
22976b943ff3SDimitry Andric }
22986b943ff3SDimitry Andric 
229901095a5dSDimitry Andric static void
sortSubCommands(const SmallPtrSetImpl<SubCommand * > & SubMap,SmallVectorImpl<std::pair<const char *,SubCommand * >> & Subs)230001095a5dSDimitry Andric sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
230101095a5dSDimitry Andric                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2302706b4fc4SDimitry Andric   for (auto *S : SubMap) {
2303b915e9e0SDimitry Andric     if (S->getName().empty())
230401095a5dSDimitry Andric       continue;
2305b915e9e0SDimitry Andric     Subs.push_back(std::make_pair(S->getName().data(), S));
230601095a5dSDimitry Andric   }
230701095a5dSDimitry Andric   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
230801095a5dSDimitry Andric }
230901095a5dSDimitry Andric 
2310009b1c42SEd Schouten namespace {
2311009b1c42SEd Schouten 
2312009b1c42SEd Schouten class HelpPrinter {
231359d6cff9SDimitry Andric protected:
2314009b1c42SEd Schouten   const bool ShowHidden;
231567c32a98SDimitry Andric   typedef SmallVector<std::pair<const char *, Option *>, 128>
231667c32a98SDimitry Andric       StrOptionPairVector;
231701095a5dSDimitry Andric   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
231801095a5dSDimitry Andric       StrSubCommandPairVector;
231959d6cff9SDimitry Andric   // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)232059d6cff9SDimitry Andric   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
232159d6cff9SDimitry Andric     for (size_t i = 0, e = Opts.size(); i != e; ++i)
232259d6cff9SDimitry Andric       Opts[i].second->printOptionInfo(MaxArgLen);
232359d6cff9SDimitry Andric   }
2324009b1c42SEd Schouten 
printSubCommands(StrSubCommandPairVector & Subs,size_t MaxSubLen)232501095a5dSDimitry Andric   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
232601095a5dSDimitry Andric     for (const auto &S : Subs) {
232701095a5dSDimitry Andric       outs() << "  " << S.first;
2328b915e9e0SDimitry Andric       if (!S.second->getDescription().empty()) {
232901095a5dSDimitry Andric         outs().indent(MaxSubLen - strlen(S.first));
233001095a5dSDimitry Andric         outs() << " - " << S.second->getDescription();
233101095a5dSDimitry Andric       }
233201095a5dSDimitry Andric       outs() << "\n";
233301095a5dSDimitry Andric     }
233401095a5dSDimitry Andric   }
233501095a5dSDimitry Andric 
2336009b1c42SEd Schouten public:
HelpPrinter(bool showHidden)23374a16efa3SDimitry Andric   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2338145449b1SDimitry Andric   virtual ~HelpPrinter() = default;
2339009b1c42SEd Schouten 
234059d6cff9SDimitry Andric   // Invoke the printer.
operator =(bool Value)2341009b1c42SEd Schouten   void operator=(bool Value) {
23425a5ac124SDimitry Andric     if (!Value)
234367c32a98SDimitry Andric       return;
2344044eb2f6SDimitry Andric     printHelp();
2345009b1c42SEd Schouten 
2346044eb2f6SDimitry Andric     // Halt the program since help information was printed
2347044eb2f6SDimitry Andric     exit(0);
2348044eb2f6SDimitry Andric   }
2349044eb2f6SDimitry Andric 
printHelp()2350044eb2f6SDimitry Andric   void printHelp() {
235101095a5dSDimitry Andric     SubCommand *Sub = GlobalParser->getActiveSubCommand();
235201095a5dSDimitry Andric     auto &OptionsMap = Sub->OptionsMap;
235301095a5dSDimitry Andric     auto &PositionalOpts = Sub->PositionalOpts;
235401095a5dSDimitry Andric     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
235501095a5dSDimitry Andric 
235659d6cff9SDimitry Andric     StrOptionPairVector Opts;
235701095a5dSDimitry Andric     sortOpts(OptionsMap, Opts, ShowHidden);
235801095a5dSDimitry Andric 
235901095a5dSDimitry Andric     StrSubCommandPairVector Subs;
236001095a5dSDimitry Andric     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2361009b1c42SEd Schouten 
2362b915e9e0SDimitry Andric     if (!GlobalParser->ProgramOverview.empty())
23635a5ac124SDimitry Andric       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
236459850d08SRoman Divacky 
2365e3b55780SDimitry Andric     if (Sub == &SubCommand::getTopLevel()) {
2366b915e9e0SDimitry Andric       outs() << "USAGE: " << GlobalParser->ProgramName;
2367b1c73532SDimitry Andric       if (!Subs.empty())
2368b915e9e0SDimitry Andric         outs() << " [subcommand]";
2369b915e9e0SDimitry Andric       outs() << " [options]";
2370b915e9e0SDimitry Andric     } else {
2371b915e9e0SDimitry Andric       if (!Sub->getDescription().empty()) {
237201095a5dSDimitry Andric         outs() << "SUBCOMMAND '" << Sub->getName()
237301095a5dSDimitry Andric                << "': " << Sub->getDescription() << "\n\n";
237401095a5dSDimitry Andric       }
237501095a5dSDimitry Andric       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
237601095a5dSDimitry Andric              << " [options]";
237701095a5dSDimitry Andric     }
2378009b1c42SEd Schouten 
2379344a3780SDimitry Andric     for (auto *Opt : PositionalOpts) {
2380dd58ef01SDimitry Andric       if (Opt->hasArgStr())
23815a5ac124SDimitry Andric         outs() << " --" << Opt->ArgStr;
23825a5ac124SDimitry Andric       outs() << " " << Opt->HelpStr;
2383009b1c42SEd Schouten     }
2384009b1c42SEd Schouten 
2385009b1c42SEd Schouten     // Print the consume after option info if it exists...
238601095a5dSDimitry Andric     if (ConsumeAfterOpt)
238701095a5dSDimitry Andric       outs() << " " << ConsumeAfterOpt->HelpStr;
238801095a5dSDimitry Andric 
2389e3b55780SDimitry Andric     if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
239001095a5dSDimitry Andric       // Compute the maximum subcommand length...
239101095a5dSDimitry Andric       size_t MaxSubLen = 0;
239201095a5dSDimitry Andric       for (size_t i = 0, e = Subs.size(); i != e; ++i)
239301095a5dSDimitry Andric         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
239401095a5dSDimitry Andric 
239501095a5dSDimitry Andric       outs() << "\n\n";
239601095a5dSDimitry Andric       outs() << "SUBCOMMANDS:\n\n";
239701095a5dSDimitry Andric       printSubCommands(Subs, MaxSubLen);
239801095a5dSDimitry Andric       outs() << "\n";
239901095a5dSDimitry Andric       outs() << "  Type \"" << GlobalParser->ProgramName
2400e6d15924SDimitry Andric              << " <subcommand> --help\" to get more help on a specific "
240101095a5dSDimitry Andric                 "subcommand";
240201095a5dSDimitry Andric     }
2403009b1c42SEd Schouten 
240459850d08SRoman Divacky     outs() << "\n\n";
2405009b1c42SEd Schouten 
2406009b1c42SEd Schouten     // Compute the maximum argument length...
24074a16efa3SDimitry Andric     size_t MaxArgLen = 0;
2408009b1c42SEd Schouten     for (size_t i = 0, e = Opts.size(); i != e; ++i)
2409009b1c42SEd Schouten       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2410009b1c42SEd Schouten 
241159850d08SRoman Divacky     outs() << "OPTIONS:\n";
241259d6cff9SDimitry Andric     printOptions(Opts, MaxArgLen);
2413009b1c42SEd Schouten 
2414009b1c42SEd Schouten     // Print any extra help the user has declared.
2415344a3780SDimitry Andric     for (const auto &I : GlobalParser->MoreHelp)
24165a5ac124SDimitry Andric       outs() << I;
24175a5ac124SDimitry Andric     GlobalParser->MoreHelp.clear();
2418009b1c42SEd Schouten   }
2419009b1c42SEd Schouten };
242059d6cff9SDimitry Andric 
242159d6cff9SDimitry Andric class CategorizedHelpPrinter : public HelpPrinter {
242259d6cff9SDimitry Andric public:
CategorizedHelpPrinter(bool showHidden)242359d6cff9SDimitry Andric   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
242459d6cff9SDimitry Andric 
242559d6cff9SDimitry Andric   // Helper function for printOptions().
24265a5ac124SDimitry Andric   // It shall return a negative value if A's name should be lexicographically
242771d5a254SDimitry Andric   // ordered before B's name. It returns a value greater than zero if B's name
242871d5a254SDimitry Andric   // should be ordered before A's name, and it returns 0 otherwise.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)24295a5ac124SDimitry Andric   static int OptionCategoryCompare(OptionCategory *const *A,
24305a5ac124SDimitry Andric                                    OptionCategory *const *B) {
243171d5a254SDimitry Andric     return (*A)->getName().compare((*B)->getName());
243259d6cff9SDimitry Andric   }
243359d6cff9SDimitry Andric 
243459d6cff9SDimitry Andric   // Make sure we inherit our base class's operator=()
243559d6cff9SDimitry Andric   using HelpPrinter::operator=;
243659d6cff9SDimitry Andric 
243759d6cff9SDimitry Andric protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)24385ca98fd9SDimitry Andric   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
243959d6cff9SDimitry Andric     std::vector<OptionCategory *> SortedCategories;
24406f8fc217SDimitry Andric     DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
244159d6cff9SDimitry Andric 
24425ca98fd9SDimitry Andric     // Collect registered option categories into vector in preparation for
244359d6cff9SDimitry Andric     // sorting.
244477fc4c14SDimitry Andric     for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
244577fc4c14SDimitry Andric       SortedCategories.push_back(Category);
244659d6cff9SDimitry Andric 
244759d6cff9SDimitry Andric     // Sort the different option categories alphabetically.
244859d6cff9SDimitry Andric     assert(SortedCategories.size() > 0 && "No option categories registered!");
24495a5ac124SDimitry Andric     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
245059d6cff9SDimitry Andric                    OptionCategoryCompare);
245159d6cff9SDimitry Andric 
245259d6cff9SDimitry Andric     // Walk through pre-sorted options and assign into categories.
245359d6cff9SDimitry Andric     // Because the options are already alphabetically sorted the
245459d6cff9SDimitry Andric     // options within categories will also be alphabetically sorted.
245559d6cff9SDimitry Andric     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
245659d6cff9SDimitry Andric       Option *Opt = Opts[I].second;
2457e6d15924SDimitry Andric       for (auto &Cat : Opt->Categories) {
24584b4fe385SDimitry Andric         assert(llvm::is_contained(SortedCategories, Cat) &&
245959d6cff9SDimitry Andric                "Option has an unregistered category");
2460e6d15924SDimitry Andric         CategorizedOptions[Cat].push_back(Opt);
2461e6d15924SDimitry Andric       }
246259d6cff9SDimitry Andric     }
246359d6cff9SDimitry Andric 
246459d6cff9SDimitry Andric     // Now do printing.
246577fc4c14SDimitry Andric     for (OptionCategory *Category : SortedCategories) {
2466e6d15924SDimitry Andric       // Hide empty categories for --help, but show for --help-hidden.
246777fc4c14SDimitry Andric       const auto &CategoryOptions = CategorizedOptions[Category];
2468aca2e42cSDimitry Andric       if (CategoryOptions.empty())
246959d6cff9SDimitry Andric         continue;
247059d6cff9SDimitry Andric 
247159d6cff9SDimitry Andric       // Print category information.
247259d6cff9SDimitry Andric       outs() << "\n";
247377fc4c14SDimitry Andric       outs() << Category->getName() << ":\n";
247459d6cff9SDimitry Andric 
247559d6cff9SDimitry Andric       // Check if description is set.
247677fc4c14SDimitry Andric       if (!Category->getDescription().empty())
247777fc4c14SDimitry Andric         outs() << Category->getDescription() << "\n\n";
247859d6cff9SDimitry Andric       else
247959d6cff9SDimitry Andric         outs() << "\n";
248059d6cff9SDimitry Andric 
248159d6cff9SDimitry Andric       // Loop over the options in the category and print.
248201095a5dSDimitry Andric       for (const Option *Opt : CategoryOptions)
248301095a5dSDimitry Andric         Opt->printOptionInfo(MaxArgLen);
248459d6cff9SDimitry Andric     }
248559d6cff9SDimitry Andric   }
248659d6cff9SDimitry Andric };
248759d6cff9SDimitry Andric 
248859d6cff9SDimitry Andric // This wraps the Uncategorizing and Categorizing printers and decides
248959d6cff9SDimitry Andric // at run time which should be invoked.
249059d6cff9SDimitry Andric class HelpPrinterWrapper {
249159d6cff9SDimitry Andric private:
249259d6cff9SDimitry Andric   HelpPrinter &UncategorizedPrinter;
249359d6cff9SDimitry Andric   CategorizedHelpPrinter &CategorizedPrinter;
249459d6cff9SDimitry Andric 
249559d6cff9SDimitry Andric public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)249659d6cff9SDimitry Andric   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
249767c32a98SDimitry Andric                               CategorizedHelpPrinter &CategorizedPrinter)
249867c32a98SDimitry Andric       : UncategorizedPrinter(UncategorizedPrinter),
249959d6cff9SDimitry Andric         CategorizedPrinter(CategorizedPrinter) {}
250059d6cff9SDimitry Andric 
250159d6cff9SDimitry Andric   // Invoke the printer.
250259d6cff9SDimitry Andric   void operator=(bool Value);
250359d6cff9SDimitry Andric };
250459d6cff9SDimitry Andric 
2505009b1c42SEd Schouten } // End anonymous namespace
2506009b1c42SEd Schouten 
2507706b4fc4SDimitry Andric #if defined(__GNUC__)
2508706b4fc4SDimitry Andric // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2509706b4fc4SDimitry Andric // enabled.
2510706b4fc4SDimitry Andric # if defined(__OPTIMIZE__)
2511706b4fc4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 0
2512706b4fc4SDimitry Andric # else
2513706b4fc4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 1
2514706b4fc4SDimitry Andric # endif
2515706b4fc4SDimitry Andric #elif defined(_MSC_VER)
2516706b4fc4SDimitry Andric // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2517706b4fc4SDimitry Andric // Use _DEBUG instead. This macro actually corresponds to the choice between
2518706b4fc4SDimitry Andric // debug and release CRTs, but it is a reasonable proxy.
2519706b4fc4SDimitry Andric # if defined(_DEBUG)
2520706b4fc4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 1
2521706b4fc4SDimitry Andric # else
2522706b4fc4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 0
2523706b4fc4SDimitry Andric # endif
2524706b4fc4SDimitry Andric #else
2525706b4fc4SDimitry Andric // Otherwise, for an unknown compiler, assume this is an optimized build.
2526706b4fc4SDimitry Andric # define LLVM_IS_DEBUG_BUILD 0
2527706b4fc4SDimitry Andric #endif
2528706b4fc4SDimitry Andric 
2529009b1c42SEd Schouten namespace {
2530009b1c42SEd Schouten class VersionPrinter {
2531009b1c42SEd Schouten public:
print(std::vector<VersionPrinterTy> ExtraPrinters={})2532e3b55780SDimitry Andric   void print(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
253359850d08SRoman Divacky     raw_ostream &OS = outs();
253401095a5dSDimitry Andric #ifdef PACKAGE_VENDOR
253501095a5dSDimitry Andric     OS << PACKAGE_VENDOR << " ";
253601095a5dSDimitry Andric #else
253701095a5dSDimitry Andric     OS << "LLVM (http://llvm.org/):\n  ";
253801095a5dSDimitry Andric #endif
2539145449b1SDimitry Andric     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n  ";
2540706b4fc4SDimitry Andric #if LLVM_IS_DEBUG_BUILD
254159850d08SRoman Divacky     OS << "DEBUG build";
2542009b1c42SEd Schouten #else
254359850d08SRoman Divacky     OS << "Optimized build";
2544009b1c42SEd Schouten #endif
2545009b1c42SEd Schouten #ifndef NDEBUG
254659850d08SRoman Divacky     OS << " with assertions";
2547009b1c42SEd Schouten #endif
2548e3b55780SDimitry Andric     OS << ".\n";
2549e3b55780SDimitry Andric 
2550e3b55780SDimitry Andric     // Iterate over any registered extra printers and call them to add further
2551e3b55780SDimitry Andric     // information.
2552e3b55780SDimitry Andric     if (!ExtraPrinters.empty()) {
2553e3b55780SDimitry Andric       for (const auto &I : ExtraPrinters)
2554e3b55780SDimitry Andric         I(outs());
2555e3b55780SDimitry Andric     }
2556009b1c42SEd Schouten   }
2557344a3780SDimitry Andric   void operator=(bool OptionWasSpecified);
2558344a3780SDimitry Andric };
2559344a3780SDimitry Andric 
2560344a3780SDimitry Andric struct CommandLineCommonOptions {
2561344a3780SDimitry Andric   // Declare the four HelpPrinter instances that are used to print out help, or
2562344a3780SDimitry Andric   // help-hidden as an uncategorized list or in categories.
2563344a3780SDimitry Andric   HelpPrinter UncategorizedNormalPrinter{false};
2564344a3780SDimitry Andric   HelpPrinter UncategorizedHiddenPrinter{true};
2565344a3780SDimitry Andric   CategorizedHelpPrinter CategorizedNormalPrinter{false};
2566344a3780SDimitry Andric   CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2567344a3780SDimitry Andric   // Declare HelpPrinter wrappers that will decide whether or not to invoke
2568344a3780SDimitry Andric   // a categorizing help printer
2569344a3780SDimitry Andric   HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2570344a3780SDimitry Andric                                           CategorizedNormalPrinter};
2571344a3780SDimitry Andric   HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2572344a3780SDimitry Andric                                           CategorizedHiddenPrinter};
2573344a3780SDimitry Andric   // Define a category for generic options that all tools should have.
2574344a3780SDimitry Andric   cl::OptionCategory GenericCategory{"Generic Options"};
2575344a3780SDimitry Andric 
2576344a3780SDimitry Andric   // Define uncategorized help printers.
2577344a3780SDimitry Andric   // --help-list is hidden by default because if Option categories are being
2578344a3780SDimitry Andric   // used then --help behaves the same as --help-list.
2579344a3780SDimitry Andric   cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2580344a3780SDimitry Andric       "help-list",
2581344a3780SDimitry Andric       cl::desc(
2582344a3780SDimitry Andric           "Display list of available options (--help-list-hidden for more)"),
2583344a3780SDimitry Andric       cl::location(UncategorizedNormalPrinter),
2584344a3780SDimitry Andric       cl::Hidden,
2585344a3780SDimitry Andric       cl::ValueDisallowed,
2586344a3780SDimitry Andric       cl::cat(GenericCategory),
2587e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2588344a3780SDimitry Andric 
2589344a3780SDimitry Andric   cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2590344a3780SDimitry Andric       "help-list-hidden",
2591344a3780SDimitry Andric       cl::desc("Display list of all available options"),
2592344a3780SDimitry Andric       cl::location(UncategorizedHiddenPrinter),
2593344a3780SDimitry Andric       cl::Hidden,
2594344a3780SDimitry Andric       cl::ValueDisallowed,
2595344a3780SDimitry Andric       cl::cat(GenericCategory),
2596e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2597344a3780SDimitry Andric 
2598344a3780SDimitry Andric   // Define uncategorized/categorized help printers. These printers change their
2599344a3780SDimitry Andric   // behaviour at runtime depending on whether one or more Option categories
2600344a3780SDimitry Andric   // have been declared.
2601344a3780SDimitry Andric   cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2602344a3780SDimitry Andric       "help",
2603344a3780SDimitry Andric       cl::desc("Display available options (--help-hidden for more)"),
2604344a3780SDimitry Andric       cl::location(WrappedNormalPrinter),
2605344a3780SDimitry Andric       cl::ValueDisallowed,
2606344a3780SDimitry Andric       cl::cat(GenericCategory),
2607e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2608344a3780SDimitry Andric 
2609344a3780SDimitry Andric   cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2610344a3780SDimitry Andric                  cl::DefaultOption};
2611344a3780SDimitry Andric 
2612344a3780SDimitry Andric   cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2613344a3780SDimitry Andric       "help-hidden",
2614344a3780SDimitry Andric       cl::desc("Display all available options"),
2615344a3780SDimitry Andric       cl::location(WrappedHiddenPrinter),
2616344a3780SDimitry Andric       cl::Hidden,
2617344a3780SDimitry Andric       cl::ValueDisallowed,
2618344a3780SDimitry Andric       cl::cat(GenericCategory),
2619e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2620344a3780SDimitry Andric 
2621344a3780SDimitry Andric   cl::opt<bool> PrintOptions{
2622344a3780SDimitry Andric       "print-options",
2623344a3780SDimitry Andric       cl::desc("Print non-default options after command line parsing"),
2624344a3780SDimitry Andric       cl::Hidden,
2625344a3780SDimitry Andric       cl::init(false),
2626344a3780SDimitry Andric       cl::cat(GenericCategory),
2627e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2628344a3780SDimitry Andric 
2629344a3780SDimitry Andric   cl::opt<bool> PrintAllOptions{
2630344a3780SDimitry Andric       "print-all-options",
2631344a3780SDimitry Andric       cl::desc("Print all option values after command line parsing"),
2632344a3780SDimitry Andric       cl::Hidden,
2633344a3780SDimitry Andric       cl::init(false),
2634344a3780SDimitry Andric       cl::cat(GenericCategory),
2635e3b55780SDimitry Andric       cl::sub(SubCommand::getAll())};
2636344a3780SDimitry Andric 
2637344a3780SDimitry Andric   VersionPrinterTy OverrideVersionPrinter = nullptr;
2638344a3780SDimitry Andric 
2639344a3780SDimitry Andric   std::vector<VersionPrinterTy> ExtraVersionPrinters;
2640344a3780SDimitry Andric 
2641344a3780SDimitry Andric   // Define the --version option that prints out the LLVM version for the tool
2642344a3780SDimitry Andric   VersionPrinter VersionPrinterInstance;
2643344a3780SDimitry Andric 
2644344a3780SDimitry Andric   cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2645344a3780SDimitry Andric       "version", cl::desc("Display the version of this program"),
2646344a3780SDimitry Andric       cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2647344a3780SDimitry Andric       cl::cat(GenericCategory)};
2648344a3780SDimitry Andric };
2649344a3780SDimitry Andric } // End anonymous namespace
2650344a3780SDimitry Andric 
2651344a3780SDimitry Andric // Lazy-initialized global instance of options controlling the command-line
2652344a3780SDimitry Andric // parser and general handling.
2653344a3780SDimitry Andric static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2654344a3780SDimitry Andric 
initCommonOptions()2655344a3780SDimitry Andric static void initCommonOptions() {
2656344a3780SDimitry Andric   *CommonOptions;
2657344a3780SDimitry Andric   initDebugCounterOptions();
2658344a3780SDimitry Andric   initGraphWriterOptions();
2659344a3780SDimitry Andric   initSignalsOptions();
2660344a3780SDimitry Andric   initStatisticOptions();
2661344a3780SDimitry Andric   initTimerOptions();
2662344a3780SDimitry Andric   initTypeSizeOptions();
2663344a3780SDimitry Andric   initWithColorOptions();
2664344a3780SDimitry Andric   initDebugOptions();
2665344a3780SDimitry Andric   initRandomSeedOptions();
2666344a3780SDimitry Andric }
2667344a3780SDimitry Andric 
getGeneralCategory()2668344a3780SDimitry Andric OptionCategory &cl::getGeneralCategory() {
2669344a3780SDimitry Andric   // Initialise the general option category.
2670344a3780SDimitry Andric   static OptionCategory GeneralCategory{"General options"};
2671344a3780SDimitry Andric   return GeneralCategory;
2672344a3780SDimitry Andric }
2673344a3780SDimitry Andric 
operator =(bool OptionWasSpecified)2674344a3780SDimitry Andric void VersionPrinter::operator=(bool OptionWasSpecified) {
267567c32a98SDimitry Andric   if (!OptionWasSpecified)
267667c32a98SDimitry Andric     return;
267759850d08SRoman Divacky 
2678344a3780SDimitry Andric   if (CommonOptions->OverrideVersionPrinter != nullptr) {
2679344a3780SDimitry Andric     CommonOptions->OverrideVersionPrinter(outs());
26805ca98fd9SDimitry Andric     exit(0);
268159850d08SRoman Divacky   }
2682e3b55780SDimitry Andric   print(CommonOptions->ExtraVersionPrinters);
268330815c53SDimitry Andric 
26845ca98fd9SDimitry Andric   exit(0);
2685009b1c42SEd Schouten }
2686009b1c42SEd Schouten 
operator =(bool Value)2687344a3780SDimitry Andric void HelpPrinterWrapper::operator=(bool Value) {
2688344a3780SDimitry Andric   if (!Value)
2689344a3780SDimitry Andric     return;
2690009b1c42SEd Schouten 
2691344a3780SDimitry Andric   // Decide which printer to invoke. If more than one option category is
2692344a3780SDimitry Andric   // registered then it is useful to show the categorized help instead of
2693344a3780SDimitry Andric   // uncategorized help.
2694344a3780SDimitry Andric   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2695344a3780SDimitry Andric     // unhide --help-list option so user can have uncategorized output if they
2696344a3780SDimitry Andric     // want it.
2697344a3780SDimitry Andric     CommonOptions->HLOp.setHiddenFlag(NotHidden);
2698344a3780SDimitry Andric 
2699344a3780SDimitry Andric     CategorizedPrinter = true; // Invoke categorized printer
2700344a3780SDimitry Andric   } else
2701344a3780SDimitry Andric     UncategorizedPrinter = true; // Invoke uncategorized printer
2702344a3780SDimitry Andric }
2703344a3780SDimitry Andric 
2704344a3780SDimitry Andric // Print the value of each option.
PrintOptionValues()2705344a3780SDimitry Andric void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2706344a3780SDimitry Andric 
printOptionValues()2707344a3780SDimitry Andric void CommandLineParser::printOptionValues() {
2708344a3780SDimitry Andric   if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2709344a3780SDimitry Andric     return;
2710344a3780SDimitry Andric 
2711344a3780SDimitry Andric   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2712344a3780SDimitry Andric   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2713344a3780SDimitry Andric 
2714344a3780SDimitry Andric   // Compute the maximum argument length...
2715344a3780SDimitry Andric   size_t MaxArgLen = 0;
2716344a3780SDimitry Andric   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2717344a3780SDimitry Andric     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2718344a3780SDimitry Andric 
2719344a3780SDimitry Andric   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2720344a3780SDimitry Andric     Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2721344a3780SDimitry Andric }
2722009b1c42SEd Schouten 
2723009b1c42SEd Schouten // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)272459d6cff9SDimitry Andric void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
272559d6cff9SDimitry Andric   if (!Hidden && !Categorized)
2726344a3780SDimitry Andric     CommonOptions->UncategorizedNormalPrinter.printHelp();
272759d6cff9SDimitry Andric   else if (!Hidden && Categorized)
2728344a3780SDimitry Andric     CommonOptions->CategorizedNormalPrinter.printHelp();
272959d6cff9SDimitry Andric   else if (Hidden && !Categorized)
2730344a3780SDimitry Andric     CommonOptions->UncategorizedHiddenPrinter.printHelp();
273159d6cff9SDimitry Andric   else
2732344a3780SDimitry Andric     CommonOptions->CategorizedHiddenPrinter.printHelp();
2733009b1c42SEd Schouten }
2734009b1c42SEd Schouten 
getCompilerBuildConfig()2735ac9a064cSDimitry Andric ArrayRef<StringRef> cl::getCompilerBuildConfig() {
2736ac9a064cSDimitry Andric   static const StringRef Config[] = {
2737ac9a064cSDimitry Andric       // Placeholder to ensure the array always has elements, since it's an
2738ac9a064cSDimitry Andric       // error to have a zero-sized array. Slice this off before returning.
2739ac9a064cSDimitry Andric       "",
2740ac9a064cSDimitry Andric   // Actual compiler build config feature list:
2741ac9a064cSDimitry Andric #if LLVM_IS_DEBUG_BUILD
2742ac9a064cSDimitry Andric       "+unoptimized",
2743ac9a064cSDimitry Andric #endif
2744ac9a064cSDimitry Andric #ifndef NDEBUG
2745ac9a064cSDimitry Andric       "+assertions",
2746ac9a064cSDimitry Andric #endif
2747ac9a064cSDimitry Andric #ifdef EXPENSIVE_CHECKS
2748ac9a064cSDimitry Andric       "+expensive-checks",
2749ac9a064cSDimitry Andric #endif
2750ac9a064cSDimitry Andric #if __has_feature(address_sanitizer)
2751ac9a064cSDimitry Andric       "+asan",
2752ac9a064cSDimitry Andric #endif
2753ac9a064cSDimitry Andric #if __has_feature(dataflow_sanitizer)
2754ac9a064cSDimitry Andric       "+dfsan",
2755ac9a064cSDimitry Andric #endif
2756ac9a064cSDimitry Andric #if __has_feature(hwaddress_sanitizer)
2757ac9a064cSDimitry Andric       "+hwasan",
2758ac9a064cSDimitry Andric #endif
2759ac9a064cSDimitry Andric #if __has_feature(memory_sanitizer)
2760ac9a064cSDimitry Andric       "+msan",
2761ac9a064cSDimitry Andric #endif
2762ac9a064cSDimitry Andric #if __has_feature(thread_sanitizer)
2763ac9a064cSDimitry Andric       "+tsan",
2764ac9a064cSDimitry Andric #endif
2765ac9a064cSDimitry Andric #if __has_feature(undefined_behavior_sanitizer)
2766ac9a064cSDimitry Andric       "+ubsan",
2767ac9a064cSDimitry Andric #endif
2768ac9a064cSDimitry Andric   };
2769ac9a064cSDimitry Andric   return ArrayRef(Config).drop_front(1);
2770ac9a064cSDimitry Andric }
2771ac9a064cSDimitry Andric 
2772ac9a064cSDimitry Andric // Utility function for printing the build config.
printBuildConfig(raw_ostream & OS)2773ac9a064cSDimitry Andric void cl::printBuildConfig(raw_ostream &OS) {
2774ac9a064cSDimitry Andric #if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2775ac9a064cSDimitry Andric   OS << "Build config: ";
2776ac9a064cSDimitry Andric   llvm::interleaveComma(cl::getCompilerBuildConfig(), OS);
2777ac9a064cSDimitry Andric   OS << '\n';
2778ac9a064cSDimitry Andric #endif
2779ac9a064cSDimitry Andric }
2780ac9a064cSDimitry Andric 
2781009b1c42SEd Schouten /// Utility function for printing version number.
PrintVersionMessage()2782344a3780SDimitry Andric void cl::PrintVersionMessage() {
2783e3b55780SDimitry Andric   CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2784344a3780SDimitry Andric }
2785009b1c42SEd Schouten 
SetVersionPrinter(VersionPrinterTy func)2786344a3780SDimitry Andric void cl::SetVersionPrinter(VersionPrinterTy func) {
2787344a3780SDimitry Andric   CommonOptions->OverrideVersionPrinter = func;
2788344a3780SDimitry Andric }
278930815c53SDimitry Andric 
AddExtraVersionPrinter(VersionPrinterTy func)2790044eb2f6SDimitry Andric void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2791344a3780SDimitry Andric   CommonOptions->ExtraVersionPrinters.push_back(func);
279230815c53SDimitry Andric }
279359d6cff9SDimitry Andric 
getRegisteredOptions(SubCommand & Sub)279401095a5dSDimitry Andric StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2795c0981da4SDimitry Andric   initCommonOptions();
279601095a5dSDimitry Andric   auto &Subs = GlobalParser->RegisteredSubCommands;
279701095a5dSDimitry Andric   (void)Subs;
27987fa27ce4SDimitry Andric   assert(Subs.contains(&Sub));
279901095a5dSDimitry Andric   return Sub.OptionsMap;
28005a5ac124SDimitry Andric }
28015a5ac124SDimitry Andric 
2802b915e9e0SDimitry Andric iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()2803b915e9e0SDimitry Andric cl::getRegisteredSubcommands() {
2804b915e9e0SDimitry Andric   return GlobalParser->getRegisteredSubcommands();
2805b915e9e0SDimitry Andric }
2806b915e9e0SDimitry Andric 
HideUnrelatedOptions(cl::OptionCategory & Category,SubCommand & Sub)280701095a5dSDimitry Andric void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2808344a3780SDimitry Andric   initCommonOptions();
280901095a5dSDimitry Andric   for (auto &I : Sub.OptionsMap) {
2810f65dcba8SDimitry Andric     bool Unrelated = true;
2811e6d15924SDimitry Andric     for (auto &Cat : I.second->Categories) {
2812f65dcba8SDimitry Andric       if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2813f65dcba8SDimitry Andric         Unrelated = false;
28145a5ac124SDimitry Andric     }
2815f65dcba8SDimitry Andric     if (Unrelated)
2816f65dcba8SDimitry Andric       I.second->setHiddenFlag(cl::ReallyHidden);
28175a5ac124SDimitry Andric   }
2818e6d15924SDimitry Andric }
28195a5ac124SDimitry Andric 
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories,SubCommand & Sub)282001095a5dSDimitry Andric void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
282101095a5dSDimitry Andric                               SubCommand &Sub) {
2822344a3780SDimitry Andric   initCommonOptions();
282301095a5dSDimitry Andric   for (auto &I : Sub.OptionsMap) {
2824f65dcba8SDimitry Andric     bool Unrelated = true;
2825e6d15924SDimitry Andric     for (auto &Cat : I.second->Categories) {
2826f65dcba8SDimitry Andric       if (is_contained(Categories, Cat) ||
2827f65dcba8SDimitry Andric           Cat == &CommonOptions->GenericCategory)
2828f65dcba8SDimitry Andric         Unrelated = false;
28295a5ac124SDimitry Andric     }
2830f65dcba8SDimitry Andric     if (Unrelated)
2831f65dcba8SDimitry Andric       I.second->setHiddenFlag(cl::ReallyHidden);
283259d6cff9SDimitry Andric   }
2833e6d15924SDimitry Andric }
283467c32a98SDimitry Andric 
ResetCommandLineParser()283501095a5dSDimitry Andric void cl::ResetCommandLineParser() { GlobalParser->reset(); }
ResetAllOptionOccurrences()283601095a5dSDimitry Andric void cl::ResetAllOptionOccurrences() {
283701095a5dSDimitry Andric   GlobalParser->ResetAllOptionOccurrences();
283801095a5dSDimitry Andric }
283901095a5dSDimitry Andric 
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)284067c32a98SDimitry Andric void LLVMParseCommandLineOptions(int argc, const char *const *argv,
284167c32a98SDimitry Andric                                  const char *Overview) {
284271d5a254SDimitry Andric   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
284371d5a254SDimitry Andric                                     &llvm::nulls());
284467c32a98SDimitry Andric }
2845