blob: 102bc909889d480c969495cfda92056ce2b2a3e9 [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Peter Collingbournee1863192014-10-16 22:47:52 +000020#include "llvm-c/Support.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000021#include "llvm/ADT/ArrayRef.h"
Zachary Turner07670b32016-06-29 21:48:26 +000022#include "llvm/ADT/DenseMap.h"
David Majnemerafb38af2016-07-24 17:19:59 +000023#include "llvm/ADT/Optional.h"
Benjamin Kramerbd5ee502015-03-14 00:20:13 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000025#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000027#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000028#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000029#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000030#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/Host.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/Path.h"
David Majnemerafb38af2016-07-24 17:19:59 +000037#include "llvm/Support/Process.h"
Rafael Espindola454adf62015-06-13 12:49:52 +000038#include "llvm/Support/StringSaver.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Support/raw_ostream.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000040#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000041#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000042using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000043using namespace cl;
44
Chandler Carruthe96dd892014-04-21 22:55:11 +000045#define DEBUG_TYPE "commandline"
46
Chris Lattner3e5d60f2006-08-27 12:45:47 +000047//===----------------------------------------------------------------------===//
48// Template instantiations and anchors.
49//
Chris Bieneman5d232242015-01-13 19:14:20 +000050namespace llvm {
51namespace cl {
Benjamin Kramera667d1a2015-07-13 17:21:31 +000052template class basic_parser<bool>;
53template class basic_parser<boolOrDefault>;
54template class basic_parser<int>;
55template class basic_parser<unsigned>;
56template class basic_parser<unsigned long long>;
57template class basic_parser<double>;
58template class basic_parser<float>;
59template class basic_parser<std::string>;
60template class basic_parser<char>;
Chris Lattner3e5d60f2006-08-27 12:45:47 +000061
Benjamin Kramera667d1a2015-07-13 17:21:31 +000062template class opt<unsigned>;
63template class opt<int>;
64template class opt<std::string>;
65template class opt<char>;
66template class opt<bool>;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000067}
68} // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000069
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000070// Pin the vtables to this file.
71void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000072void OptionValue<boolOrDefault>::anchor() {}
73void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000074void Option::anchor() {}
75void basic_parser_impl::anchor() {}
76void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000077void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000078void parser<int>::anchor() {}
79void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000080void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000081void parser<double>::anchor() {}
82void parser<float>::anchor() {}
83void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000084void parser<char>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000085
86//===----------------------------------------------------------------------===//
87
Benjamin Kramer970eac42015-02-06 17:51:54 +000088namespace {
89
Chris Bienemand1d94302015-01-28 19:00:25 +000090class CommandLineParser {
91public:
92 // Globals for name and overview of program. Program name is not a string to
93 // avoid static ctor/dtor issues.
Chris Bienemanb6866422015-01-28 22:25:00 +000094 std::string ProgramName;
NAKAMURA Takumi81828182015-01-29 11:06:59 +000095 const char *ProgramOverview;
Reid Spencer9501b9b2004-09-01 04:41:28 +000096
Chris Bienemand1d94302015-01-28 19:00:25 +000097 // This collects additional help to be printed.
98 std::vector<const char *> MoreHelp;
99
Chris Bieneman67e426a2015-02-13 22:54:32 +0000100 // This collects the different option categories that have been registered.
101 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
102
Zachary Turner07670b32016-06-29 21:48:26 +0000103 // This collects the different subcommands that have been registered.
104 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
Chris Bienemand1d94302015-01-28 19:00:25 +0000105
Zachary Turner07670b32016-06-29 21:48:26 +0000106 CommandLineParser() : ProgramOverview(nullptr), ActiveSubCommand(nullptr) {
107 registerSubCommand(&*TopLevelSubCommand);
108 registerSubCommand(&*AllSubCommands);
109 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000110
Zachary Turner07670b32016-06-29 21:48:26 +0000111 void ResetAllOptionOccurrences();
112
113 bool ParseCommandLineOptions(int argc, const char *const *argv,
114 const char *Overview, bool IgnoreErrors);
115
116 void addLiteralOption(Option &Opt, SubCommand *SC, const char *Name) {
117 if (Opt.hasArgStr())
118 return;
119 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
120 errs() << ProgramName << ": CommandLine Error: Option '" << Name
121 << "' registered more than once!\n";
122 report_fatal_error("inconsistency in registered CommandLine options");
123 }
124
125 // If we're adding this to all sub-commands, add it to the ones that have
126 // already been registered.
127 if (SC == &*AllSubCommands) {
128 for (const auto &Sub : RegisteredSubCommands) {
129 if (SC == Sub)
130 continue;
131 addLiteralOption(Opt, Sub, Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000132 }
133 }
134 }
135
Zachary Turner07670b32016-06-29 21:48:26 +0000136 void addLiteralOption(Option &Opt, const char *Name) {
137 if (Opt.Subs.empty())
138 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
139 else {
140 for (auto SC : Opt.Subs)
141 addLiteralOption(Opt, SC, Name);
142 }
143 }
144
145 void addOption(Option *O, SubCommand *SC) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000146 bool HadErrors = false;
David Blaikieff43d692015-11-17 19:00:52 +0000147 if (O->hasArgStr()) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000148 // Add argument to the argument map!
Zachary Turner07670b32016-06-29 21:48:26 +0000149 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000150 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
151 << "' registered more than once!\n";
152 HadErrors = true;
153 }
154 }
155
156 // Remember information about positional options.
157 if (O->getFormattingFlag() == cl::Positional)
Zachary Turner07670b32016-06-29 21:48:26 +0000158 SC->PositionalOpts.push_back(O);
Chris Bienemand1d94302015-01-28 19:00:25 +0000159 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Zachary Turner07670b32016-06-29 21:48:26 +0000160 SC->SinkOpts.push_back(O);
Chris Bienemand1d94302015-01-28 19:00:25 +0000161 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Zachary Turner07670b32016-06-29 21:48:26 +0000162 if (SC->ConsumeAfterOpt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000163 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
164 HadErrors = true;
165 }
Zachary Turner07670b32016-06-29 21:48:26 +0000166 SC->ConsumeAfterOpt = O;
Chris Bienemand1d94302015-01-28 19:00:25 +0000167 }
168
169 // Fail hard if there were errors. These are strictly unrecoverable and
170 // indicate serious issues such as conflicting option names or an
171 // incorrectly
172 // linked LLVM distribution.
173 if (HadErrors)
174 report_fatal_error("inconsistency in registered CommandLine options");
Zachary Turner07670b32016-06-29 21:48:26 +0000175
176 // If we're adding this to all sub-commands, add it to the ones that have
177 // already been registered.
178 if (SC == &*AllSubCommands) {
179 for (const auto &Sub : RegisteredSubCommands) {
180 if (SC == Sub)
181 continue;
182 addOption(O, Sub);
183 }
184 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000185 }
186
Zachary Turner07670b32016-06-29 21:48:26 +0000187 void addOption(Option *O) {
188 if (O->Subs.empty()) {
189 addOption(O, &*TopLevelSubCommand);
190 } else {
191 for (auto SC : O->Subs)
192 addOption(O, SC);
193 }
194 }
195
196 void removeOption(Option *O, SubCommand *SC) {
David Blaikieff43d692015-11-17 19:00:52 +0000197 SmallVector<StringRef, 16> OptionNames;
Chris Bienemand1d94302015-01-28 19:00:25 +0000198 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000199 if (O->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +0000200 OptionNames.push_back(O->ArgStr);
Zachary Turner07670b32016-06-29 21:48:26 +0000201
202 SubCommand &Sub = *SC;
Chris Bienemand1d94302015-01-28 19:00:25 +0000203 for (auto Name : OptionNames)
Zachary Turner07670b32016-06-29 21:48:26 +0000204 Sub.OptionsMap.erase(Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000205
206 if (O->getFormattingFlag() == cl::Positional)
Zachary Turner07670b32016-06-29 21:48:26 +0000207 for (auto Opt = Sub.PositionalOpts.begin();
208 Opt != Sub.PositionalOpts.end(); ++Opt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000209 if (*Opt == O) {
Zachary Turner07670b32016-06-29 21:48:26 +0000210 Sub.PositionalOpts.erase(Opt);
Chris Bienemand1d94302015-01-28 19:00:25 +0000211 break;
212 }
213 }
214 else if (O->getMiscFlags() & cl::Sink)
Zachary Turner07670b32016-06-29 21:48:26 +0000215 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000216 if (*Opt == O) {
Zachary Turner07670b32016-06-29 21:48:26 +0000217 Sub.SinkOpts.erase(Opt);
Chris Bienemand1d94302015-01-28 19:00:25 +0000218 break;
219 }
220 }
Zachary Turner07670b32016-06-29 21:48:26 +0000221 else if (O == Sub.ConsumeAfterOpt)
222 Sub.ConsumeAfterOpt = nullptr;
Chris Bienemand1d94302015-01-28 19:00:25 +0000223 }
224
Zachary Turner07670b32016-06-29 21:48:26 +0000225 void removeOption(Option *O) {
226 if (O->Subs.empty())
227 removeOption(O, &*TopLevelSubCommand);
228 else {
229 if (O->isInAllSubCommands()) {
230 for (auto SC : RegisteredSubCommands)
231 removeOption(O, SC);
232 } else {
233 for (auto SC : O->Subs)
234 removeOption(O, SC);
235 }
236 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000237 }
238
Zachary Turner07670b32016-06-29 21:48:26 +0000239 bool hasOptions(const SubCommand &Sub) const {
240 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
241 nullptr != Sub.ConsumeAfterOpt);
242 }
243
244 bool hasOptions() const {
245 for (const auto &S : RegisteredSubCommands) {
246 if (hasOptions(*S))
247 return true;
248 }
249 return false;
250 }
251
252 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
253
254 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
255 SubCommand &Sub = *SC;
256 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000257 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
258 << "' registered more than once!\n";
259 report_fatal_error("inconsistency in registered CommandLine options");
260 }
Zachary Turner07670b32016-06-29 21:48:26 +0000261 Sub.OptionsMap.erase(O->ArgStr);
262 }
263
264 void updateArgStr(Option *O, StringRef NewName) {
265 if (O->Subs.empty())
266 updateArgStr(O, NewName, &*TopLevelSubCommand);
267 else {
268 for (auto SC : O->Subs)
269 updateArgStr(O, NewName, SC);
270 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000271 }
Chris Bienemand77bbab2015-01-30 22:16:01 +0000272
273 void printOptionValues();
Chris Bieneman542f56a2015-02-13 22:54:27 +0000274
Chris Bieneman67e426a2015-02-13 22:54:32 +0000275 void registerCategory(OptionCategory *cat) {
Sanjoy Das39c226f2016-06-10 21:18:39 +0000276 assert(count_if(RegisteredOptionCategories,
277 [cat](const OptionCategory *Category) {
278 return cat->getName() == Category->getName();
279 }) == 0 &&
Chris Bieneman67e426a2015-02-13 22:54:32 +0000280 "Duplicate option categories");
281
282 RegisteredOptionCategories.insert(cat);
283 }
284
Zachary Turner07670b32016-06-29 21:48:26 +0000285 void registerSubCommand(SubCommand *sub) {
286 assert(count_if(RegisteredSubCommands,
287 [sub](const SubCommand *Sub) {
288 return (sub->getName() != nullptr) &&
289 (Sub->getName() == sub->getName());
290 }) == 0 &&
291 "Duplicate subcommands");
292 RegisteredSubCommands.insert(sub);
293
294 // For all options that have been registered for all subcommands, add the
295 // option to this subcommand now.
296 if (sub != &*AllSubCommands) {
297 for (auto &E : AllSubCommands->OptionsMap) {
298 Option *O = E.second;
299 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
300 O->hasArgStr())
301 addOption(O, sub);
302 else
303 addLiteralOption(*O, sub, E.first().str().c_str());
304 }
305 }
306 }
307
308 void unregisterSubCommand(SubCommand *sub) {
309 RegisteredSubCommands.erase(sub);
310 }
311
312 void reset() {
313 ActiveSubCommand = nullptr;
314 ProgramName.clear();
315 ProgramOverview = nullptr;
316
317 MoreHelp.clear();
318 RegisteredOptionCategories.clear();
319
320 ResetAllOptionOccurrences();
321 RegisteredSubCommands.clear();
322
323 TopLevelSubCommand->reset();
324 AllSubCommands->reset();
325 registerSubCommand(&*TopLevelSubCommand);
326 registerSubCommand(&*AllSubCommands);
327 }
328
Chris Bieneman542f56a2015-02-13 22:54:27 +0000329private:
Zachary Turner07670b32016-06-29 21:48:26 +0000330 SubCommand *ActiveSubCommand;
331
332 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
333 SubCommand *LookupSubCommand(const char *Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000334};
335
Benjamin Kramer970eac42015-02-06 17:51:54 +0000336} // namespace
337
Chris Bienemand1d94302015-01-28 19:00:25 +0000338static ManagedStatic<CommandLineParser> GlobalParser;
339
340void cl::AddLiteralOption(Option &O, const char *Name) {
341 GlobalParser->addLiteralOption(O, Name);
342}
Chris Lattner37bcd992004-11-19 17:08:15 +0000343
Chris Bieneman5d232242015-01-13 19:14:20 +0000344extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000345 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000346}
347
Chris Lattner5247f602007-04-06 21:06:55 +0000348void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000349 GlobalParser->addOption(this);
350 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000351}
352
Chris Bienemand1d94302015-01-28 19:00:25 +0000353void Option::removeArgument() { GlobalParser->removeOption(this); }
354
David Blaikieff43d692015-11-17 19:00:52 +0000355void Option::setArgStr(StringRef S) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000356 if (FullyInitialized)
357 GlobalParser->updateArgStr(this, S);
358 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000359}
360
Andrew Trick0537a982013-05-06 21:56:23 +0000361// Initialise the general option category.
362OptionCategory llvm::cl::GeneralCategory("General options");
363
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000364void OptionCategory::registerCategory() {
Chris Bieneman67e426a2015-02-13 22:54:32 +0000365 GlobalParser->registerCategory(this);
Andrew Trick0537a982013-05-06 21:56:23 +0000366}
Chris Lattneraf039c52007-04-12 00:36:29 +0000367
Zachary Turner07670b32016-06-29 21:48:26 +0000368// A special subcommand representing no subcommand
369ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
370
371// A special subcommand that can be used to put an option into all subcommands.
372ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
373
374void SubCommand::registerSubCommand() {
375 GlobalParser->registerSubCommand(this);
376}
377
378void SubCommand::unregisterSubCommand() {
379 GlobalParser->unregisterSubCommand(this);
380}
381
382void SubCommand::reset() {
383 PositionalOpts.clear();
384 SinkOpts.clear();
385 OptionsMap.clear();
386
387 ConsumeAfterOpt = nullptr;
388}
389
390SubCommand::operator bool() const {
391 return (GlobalParser->getActiveSubCommand() == this);
392}
393
Chris Lattner5df56c42002-07-22 02:07:59 +0000394//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000395// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000396//
397
Chris Lattner2031b022007-04-05 21:58:17 +0000398/// LookupOption - Lookup the option specified by the specified option on the
399/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000400/// that as well. This assumes that leading dashes have already been stripped.
Zachary Turner07670b32016-06-29 21:48:26 +0000401Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
402 StringRef &Value) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000403 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000404 if (Arg.empty())
405 return nullptr;
Zachary Turner07670b32016-06-29 21:48:26 +0000406 assert(&Sub != &*AllSubCommands);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000407
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000408 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000409
Chris Lattner0a40a972009-09-20 01:53:12 +0000410 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000411 if (EqualPos == StringRef::npos) {
412 // Look up the option.
Zachary Turner07670b32016-06-29 21:48:26 +0000413 auto I = Sub.OptionsMap.find(Arg);
414 if (I == Sub.OptionsMap.end())
415 return nullptr;
416
417 return I != Sub.OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000418 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000419
Chris Lattnere7c1e212009-09-20 05:03:30 +0000420 // If the argument before the = is a valid option name, we match. If not,
421 // return Arg unmolested.
Zachary Turner07670b32016-06-29 21:48:26 +0000422 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
423 if (I == Sub.OptionsMap.end())
Chris Bieneman5d232242015-01-13 19:14:20 +0000424 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000425
Chris Bieneman5d232242015-01-13 19:14:20 +0000426 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000427 Arg = Arg.substr(0, EqualPos);
428 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000429}
430
Zachary Turner07670b32016-06-29 21:48:26 +0000431SubCommand *CommandLineParser::LookupSubCommand(const char *Name) {
432 if (Name == nullptr)
433 return &*TopLevelSubCommand;
434 for (auto S : RegisteredSubCommands) {
435 if (S == &*AllSubCommands)
436 continue;
437 if (S->getName() == nullptr)
438 continue;
439
440 if (StringRef(S->getName()) == StringRef(Name))
441 return S;
442 }
443 return &*TopLevelSubCommand;
444}
445
Daniel Dunbarf4132132011-01-18 01:59:24 +0000446/// LookupNearestOption - Lookup the closest match to the option specified by
447/// the specified option on the command line. If there is a value specified
448/// (after an equal sign) return that as well. This assumes that leading dashes
449/// have already been stripped.
450static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000451 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000452 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000453 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000454 if (Arg.empty())
455 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000456
457 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000458 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000459 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000460 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000461
462 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000463 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000464 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000465 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
466 ie = OptionsMap.end();
467 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000468 Option *O = it->second;
David Blaikieff43d692015-11-17 19:00:52 +0000469 SmallVector<StringRef, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000470 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000471 if (O->hasArgStr())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000472 OptionNames.push_back(O->ArgStr);
473
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000474 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
475 StringRef Flag = PermitValue ? LHS : Arg;
David Blaikieff43d692015-11-17 19:00:52 +0000476 for (auto Name : OptionNames) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000477 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000478 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000479 if (!Best || Distance < BestDistance) {
480 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000481 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000482 if (RHS.empty() || !PermitValue)
David Blaikieff43d692015-11-17 19:00:52 +0000483 NearestString = Name;
Bill Wendling318f03f2012-07-19 00:15:11 +0000484 else
David Blaikieff43d692015-11-17 19:00:52 +0000485 NearestString = (Twine(Name) + "=" + RHS).str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000486 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000487 }
488 }
489
490 return Best;
491}
492
Alp Tokercb402912014-01-24 17:20:08 +0000493/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
494/// that does special handling of cl::CommaSeparated options.
495static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
496 StringRef ArgName, StringRef Value,
497 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000498 // Check to see if this option accepts a comma separated list of values. If
499 // it does, we have to split up the value into multiple values.
500 if (Handler->getMiscFlags() & CommaSeparated) {
501 StringRef Val(Value);
502 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000503
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000504 while (Pos != StringRef::npos) {
505 // Process the portion before the comma.
506 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
507 return true;
508 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000509 Val = Val.substr(Pos + 1);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000510 // Check for another comma.
511 Pos = Val.find(',');
512 }
513
514 Value = Val;
515 }
516
Alexander Kornienko66da20a2015-12-28 15:46:15 +0000517 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000518}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000519
Chris Lattner40fef802009-09-20 01:49:31 +0000520/// ProvideOption - For Value, this differentiates between an empty value ("")
521/// and a null value (StringRef()). The later is accepted for arguments that
522/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000523static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000524 StringRef Value, int argc,
525 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000526 // Is this a multi-argument option?
527 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
528
Chris Lattnere81c4092001-10-27 05:54:17 +0000529 // Enforce value requirements
530 switch (Handler->getValueExpectedFlag()) {
531 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000532 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000533 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000534 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000535 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000536 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000537 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000538 }
539 break;
540 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000541 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000542 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000543 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000544
Chris Lattner40fef802009-09-20 01:49:31 +0000545 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000546 return Handler->error("does not allow a value! '" + Twine(Value) +
547 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000548 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000549 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000550 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000551 }
552
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000553 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000554 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000555 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000556
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000557 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000558 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000559
Chris Lattner40fef802009-09-20 01:49:31 +0000560 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000561 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000562 return true;
563 --NumAdditionalVals;
564 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000565 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000566
567 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000568 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000569 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000570 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000571 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000572
Alp Tokercb402912014-01-24 17:20:08 +0000573 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000574 return true;
575 MultiArg = true;
576 --NumAdditionalVals;
577 }
578 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000579}
580
Chris Lattnerca2552d2009-09-20 00:07:40 +0000581static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000582 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000583 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000584}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000585
Chris Lattner5df56c42002-07-22 02:07:59 +0000586// Option predicates...
587static inline bool isGrouping(const Option *O) {
588 return O->getFormattingFlag() == cl::Grouping;
589}
590static inline bool isPrefixedOrGrouping(const Option *O) {
591 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
592}
593
594// getOptionPred - Check to see if there are any options that satisfy the
595// specified predicate with names that are the prefixes in Name. This is
596// checked by progressively stripping characters off of the name, checking to
597// see if there options that satisfy the predicate. If we find one, return it,
598// otherwise return null.
599//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000600static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000601 bool (*Pred)(const Option *),
602 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000603
Chris Bieneman5d232242015-01-13 19:14:20 +0000604 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000605
Chris Lattnere7c1e212009-09-20 05:03:30 +0000606 // Loop while we haven't found an option and Name still has at least two
607 // characters in it (so that the next iteration will not be the empty
608 // string.
609 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000610 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000611 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000612 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000613
Chris Lattner5247f602007-04-06 21:06:55 +0000614 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000615 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000616 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000617 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000618 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000619}
620
Chris Lattnere7c1e212009-09-20 05:03:30 +0000621/// HandlePrefixedOrGroupedOption - The specified argument string (which started
622/// with at least one '-') does not fully match an available option. Check to
623/// see if this is a prefix or grouped option. If so, split arg into output an
624/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000625static Option *
626HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
627 bool &ErrorParsing,
628 const StringMap<Option *> &OptionsMap) {
629 if (Arg.size() == 1)
630 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000631
632 // Do the lookup!
633 size_t Length = 0;
634 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000635 if (!PGOpt)
636 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000637
Chris Lattnere7c1e212009-09-20 05:03:30 +0000638 // If the option is a prefixed option, then the value is simply the
639 // rest of the name... so fall through to later processing, by
640 // setting up the argument name flags and value fields.
641 if (PGOpt->getFormattingFlag() == cl::Prefix) {
642 Value = Arg.substr(Length);
643 Arg = Arg.substr(0, Length);
644 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
645 return PGOpt;
646 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000647
Chris Lattnere7c1e212009-09-20 05:03:30 +0000648 // This must be a grouped option... handle them now. Grouping options can't
649 // have values.
650 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000651
Chris Lattnere7c1e212009-09-20 05:03:30 +0000652 do {
653 // Move current arg name out of Arg into OneArgName.
654 StringRef OneArgName = Arg.substr(0, Length);
655 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000656
Chris Lattnere7c1e212009-09-20 05:03:30 +0000657 // Because ValueRequired is an invalid flag for grouped arguments,
658 // we don't need to pass argc/argv in.
659 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
660 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000661 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000662 ErrorParsing |=
663 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000664
Chris Lattnere7c1e212009-09-20 05:03:30 +0000665 // Get the next grouping option.
666 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
667 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000668
Chris Lattnere7c1e212009-09-20 05:03:30 +0000669 // Return the last option with Arg cut down to just the last one.
670 return PGOpt;
671}
672
Chris Lattner5df56c42002-07-22 02:07:59 +0000673static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000674 return O->getNumOccurrencesFlag() == cl::Required ||
675 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000676}
677
678static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000679 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
680 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000681}
Chris Lattnere81c4092001-10-27 05:54:17 +0000682
Chris Bieneman5d232242015-01-13 19:14:20 +0000683static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000684
Chris Bieneman5d232242015-01-13 19:14:20 +0000685static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000686
Reid Klecknera73c7782013-07-18 16:52:05 +0000687void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000688 SmallVectorImpl<const char *> &NewArgv,
689 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000690 SmallString<128> Token;
691 for (size_t I = 0, E = Src.size(); I != E; ++I) {
692 // Consume runs of whitespace.
693 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000694 while (I != E && isWhitespace(Src[I])) {
695 // Mark the end of lines in response files
696 if (MarkEOLs && Src[I] == '\n')
697 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000698 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000699 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000700 if (I == E)
701 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000702 }
703
Nico Weberfa7f4892016-04-26 13:53:56 +0000704 // Backslash escapes the next character.
705 if (I + 1 < E && Src[I] == '\\') {
Chris Bieneman5d232242015-01-13 19:14:20 +0000706 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000707 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000708 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000709 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000710
Reid Klecknera73c7782013-07-18 16:52:05 +0000711 // Consume a quoted string.
712 if (isQuote(Src[I])) {
713 char Quote = Src[I++];
714 while (I != E && Src[I] != Quote) {
Nico Weberfa7f4892016-04-26 13:53:56 +0000715 // Backslash escapes the next character.
716 if (Src[I] == '\\' && I + 1 != E)
Reid Klecknera73c7782013-07-18 16:52:05 +0000717 ++I;
718 Token.push_back(Src[I]);
719 ++I;
720 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000721 if (I == E)
722 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000723 continue;
724 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000725
Reid Klecknera73c7782013-07-18 16:52:05 +0000726 // End the token if this is whitespace.
727 if (isWhitespace(Src[I])) {
728 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000729 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000730 Token.clear();
731 continue;
732 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000733
Reid Klecknera73c7782013-07-18 16:52:05 +0000734 // This is a normal character. Append it.
735 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000736 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000737
738 // Append the last token after hitting EOF with no whitespace.
739 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000740 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000741 // Mark the end of response files
742 if (MarkEOLs)
743 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000744}
745
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000746/// Backslashes are interpreted in a rather complicated way in the Windows-style
747/// command line, because backslashes are used both to separate path and to
748/// escape double quote. This method consumes runs of backslashes as well as the
749/// following double quote if it's escaped.
750///
751/// * If an even number of backslashes is followed by a double quote, one
752/// backslash is output for every pair of backslashes, and the last double
753/// quote remains unconsumed. The double quote will later be interpreted as
754/// the start or end of a quoted string in the main loop outside of this
755/// function.
756///
757/// * If an odd number of backslashes is followed by a double quote, one
758/// backslash is output for every pair of backslashes, and a double quote is
759/// output for the last pair of backslash-double quote. The double quote is
760/// consumed in this case.
761///
762/// * Otherwise, backslashes are interpreted literally.
763static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
764 size_t E = Src.size();
765 int BackslashCount = 0;
766 // Skip the backslashes.
767 do {
768 ++I;
769 ++BackslashCount;
770 } while (I != E && Src[I] == '\\');
771
772 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
773 if (FollowedByDoubleQuote) {
774 Token.append(BackslashCount / 2, '\\');
775 if (BackslashCount % 2 == 0)
776 return I - 1;
777 Token.push_back('"');
778 return I;
779 }
780 Token.append(BackslashCount, '\\');
781 return I - 1;
782}
783
Reid Klecknera73c7782013-07-18 16:52:05 +0000784void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000785 SmallVectorImpl<const char *> &NewArgv,
786 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000787 SmallString<128> Token;
788
789 // This is a small state machine to consume characters until it reaches the
790 // end of the source string.
791 enum { INIT, UNQUOTED, QUOTED } State = INIT;
792 for (size_t I = 0, E = Src.size(); I != E; ++I) {
793 // INIT state indicates that the current input index is at the start of
794 // the string or between tokens.
795 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000796 if (isWhitespace(Src[I])) {
797 // Mark the end of lines in response files
798 if (MarkEOLs && Src[I] == '\n')
799 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000800 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000801 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000802 if (Src[I] == '"') {
803 State = QUOTED;
804 continue;
805 }
806 if (Src[I] == '\\') {
807 I = parseBackslash(Src, I, Token);
808 State = UNQUOTED;
809 continue;
810 }
811 Token.push_back(Src[I]);
812 State = UNQUOTED;
813 continue;
814 }
815
816 // UNQUOTED state means that it's reading a token not quoted by double
817 // quotes.
818 if (State == UNQUOTED) {
819 // Whitespace means the end of the token.
820 if (isWhitespace(Src[I])) {
Rafael Espindola454adf62015-06-13 12:49:52 +0000821 NewArgv.push_back(Saver.save(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000822 Token.clear();
823 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000824 // Mark the end of lines in response files
825 if (MarkEOLs && Src[I] == '\n')
826 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000827 continue;
828 }
829 if (Src[I] == '"') {
830 State = QUOTED;
831 continue;
832 }
833 if (Src[I] == '\\') {
834 I = parseBackslash(Src, I, Token);
835 continue;
836 }
837 Token.push_back(Src[I]);
838 continue;
839 }
840
841 // QUOTED state means that it's reading a token quoted by double quotes.
842 if (State == QUOTED) {
843 if (Src[I] == '"') {
844 State = UNQUOTED;
845 continue;
846 }
847 if (Src[I] == '\\') {
848 I = parseBackslash(Src, I, Token);
849 continue;
850 }
851 Token.push_back(Src[I]);
852 }
853 }
854 // Append the last token after hitting EOF with no whitespace.
855 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000856 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000857 // Mark the end of response files
858 if (MarkEOLs)
859 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000860}
861
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000862// It is called byte order marker but the UTF-8 BOM is actually not affected
863// by the host system's endianness.
864static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
Chris Bienemanceaf5f62015-02-13 22:54:29 +0000865 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000866}
867
Reid Klecknera73c7782013-07-18 16:52:05 +0000868static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
869 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000870 SmallVectorImpl<const char *> &NewArgv,
871 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000872 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
873 MemoryBuffer::getFile(FName);
874 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000875 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000876 MemoryBuffer &MemBuf = *MemBufOrErr.get();
877 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000878
879 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000880 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000881 std::string UTF8Buf;
882 if (hasUTF16ByteOrderMark(BufRef)) {
883 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
884 return false;
885 Str = StringRef(UTF8Buf);
886 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000887 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
888 // these bytes before parsing.
889 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
890 else if (hasUTF8ByteOrderMark(BufRef))
891 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000892
893 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000894 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000895
896 return true;
897}
898
899/// \brief Expand response files on a command line recursively using the given
900/// StringSaver and tokenization strategy.
901bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000902 SmallVectorImpl<const char *> &Argv,
903 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000904 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000905 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000906
907 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000908 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000909 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000910 // Check if it is an EOL marker
911 if (Arg == nullptr) {
912 ++I;
913 continue;
914 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000915 if (Arg[0] != '@') {
916 ++I;
917 continue;
918 }
919
920 // If we have too many response files, leave some unexpanded. This avoids
921 // crashing on self-referential response files.
922 if (RspFiles++ > 20)
923 return false;
924
925 // Replace this response file argument with the tokenization of its
926 // contents. Nested response files are expanded in subsequent iterations.
927 // FIXME: If a nested response file uses a relative path, is it relative to
928 // the cwd of the process or the response file?
929 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000930 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
931 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000932 // We couldn't read this file, so we leave it in the argument stream and
933 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000934 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000935 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000936 continue;
937 }
938 Argv.erase(Argv.begin() + I);
939 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
940 }
941 return AllExpanded;
942}
943
Brian Gaekeca782d92003-08-14 22:00:59 +0000944/// ParseEnvironmentOptions - An alternative entry point to the
945/// CommandLine library, which allows you to read the program's name
946/// from the caller (as PROGNAME) and its command-line arguments from
947/// an environment variable (whose name is given in ENVVAR).
948///
Chris Lattnera60f3552004-05-06 22:04:31 +0000949void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000950 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000951 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000952 assert(progName && "Program name not specified");
953 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000954
Brian Gaeke497216d2003-08-15 21:05:57 +0000955 // Get the environment variable they want us to parse options out of.
David Majnemerafb38af2016-07-24 17:19:59 +0000956 llvm::Optional<std::string> envValue = sys::Process::GetEnv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000957 if (!envValue)
958 return;
959
Brian Gaekeca782d92003-08-14 22:00:59 +0000960 // Get program's "name", which we wouldn't know without the caller
961 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000962 SmallVector<const char *, 20> newArgv;
Rafael Espindola454adf62015-06-13 12:49:52 +0000963 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000964 StringSaver Saver(A);
Rafael Espindola454adf62015-06-13 12:49:52 +0000965 newArgv.push_back(Saver.save(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000966
967 // Parse the value of the environment variable into a "command line"
968 // and hand it off to ParseCommandLineOptions().
David Majnemerafb38af2016-07-24 17:19:59 +0000969 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000970 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000971 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000972}
973
Zachary Turner07670b32016-06-29 21:48:26 +0000974bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
975 const char *Overview, bool IgnoreErrors) {
976 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
977 IgnoreErrors);
Chris Bienemand1d94302015-01-28 19:00:25 +0000978}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000979
Zachary Turner07670b32016-06-29 21:48:26 +0000980void CommandLineParser::ResetAllOptionOccurrences() {
981 // So that we can parse different command lines multiple times in succession
982 // we reset all option values to look like they have never been seen before.
983 for (auto SC : RegisteredSubCommands) {
984 for (auto &O : SC->OptionsMap)
985 O.second->reset();
986 }
987}
988
989bool CommandLineParser::ParseCommandLineOptions(int argc,
Chris Bienemand1d94302015-01-28 19:00:25 +0000990 const char *const *argv,
Zachary Turner07670b32016-06-29 21:48:26 +0000991 const char *Overview,
992 bool IgnoreErrors) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000993 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000994
995 // Expand response files.
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000996 SmallVector<const char *, 20> newArgv(argv, argv + argc);
Rafael Espindola454adf62015-06-13 12:49:52 +0000997 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000998 StringSaver Saver(A);
Reid Klecknera73c7782013-07-18 16:52:05 +0000999 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +00001000 argv = &newArgv[0];
1001 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001002
Chris Lattner5af1cbc2006-10-13 00:06:24 +00001003 // Copy the program name into ProgName, making sure not to overflow it.
Chris Bienemanb6866422015-01-28 22:25:00 +00001004 ProgramName = sys::path::filename(argv[0]);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001005
Chris Lattner36a57d32001-07-23 17:17:47 +00001006 ProgramOverview = Overview;
1007 bool ErrorParsing = false;
1008
Chris Lattner5df56c42002-07-22 02:07:59 +00001009 // Check out the positional arguments to collect information about them.
1010 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001011
Chris Lattnerd380d842005-08-08 17:25:38 +00001012 // Determine whether or not there are an unlimited number of positionals
1013 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001014
Zachary Turner07670b32016-06-29 21:48:26 +00001015 int FirstArg = 1;
1016 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1017 if (argc >= 2 && argv[FirstArg][0] != '-') {
1018 // If the first argument specifies a valid subcommand, start processing
1019 // options from the second argument.
1020 ChosenSubCommand = LookupSubCommand(argv[FirstArg]);
1021 if (ChosenSubCommand != &*TopLevelSubCommand)
1022 FirstArg = 2;
1023 }
1024 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1025
1026 assert(ChosenSubCommand);
1027 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1028 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1029 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1030 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1031
Chris Bienemand1d94302015-01-28 19:00:25 +00001032 if (ConsumeAfterOpt) {
1033 assert(PositionalOpts.size() > 0 &&
1034 "Cannot specify cl::ConsumeAfter without a positional argument!");
1035 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001036 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001037
1038 // Calculate how many positional values are _required_.
1039 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +00001040 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001041 Option *Opt = PositionalOpts[i];
1042 if (RequiresValue(Opt))
1043 ++NumPositionalRequired;
1044 else if (ConsumeAfterOpt) {
1045 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +00001046 // unless there is only one positional argument...
Zachary Turner07670b32016-06-29 21:48:26 +00001047 if (PositionalOpts.size() > 1) {
1048 if (!IgnoreErrors)
1049 Opt->error("error - this positional option will never be matched, "
1050 "because it does not Require a value, and a "
1051 "cl::ConsumeAfter option is active!");
1052 ErrorParsing = true;
1053 }
David Blaikieff43d692015-11-17 19:00:52 +00001054 } else if (UnboundedFound && !Opt->hasArgStr()) {
Chris Lattner2da046f2003-07-30 17:34:02 +00001055 // This option does not "require" a value... Make sure this option is
1056 // not specified after an option that eats all extra arguments, or this
1057 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +00001058 //
Zachary Turner07670b32016-06-29 21:48:26 +00001059 if (!IgnoreErrors) {
1060 Opt->error("error - option can never match, because "
1061 "another positional argument will match an "
1062 "unbounded number of values, and this option"
1063 " does not require a value!");
1064 errs() << ProgramName << ": CommandLine Error: Option '"
1065 << Opt->ArgStr << "' is all messed up!\n";
1066 errs() << PositionalOpts.size();
1067 }
1068 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001069 }
1070 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1071 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +00001072 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +00001073 }
1074
Reid Spencer2027a6f2004-08-13 19:47:30 +00001075 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +00001076 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +00001077 //
Chris Bieneman5d232242015-01-13 19:14:20 +00001078 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +00001079
Chris Lattner2da046f2003-07-30 17:34:02 +00001080 // If the program has named positional arguments, and the name has been run
1081 // across, keep track of which positional argument was named. Otherwise put
1082 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +00001083 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001084
Chris Lattner36a57d32001-07-23 17:17:47 +00001085 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +00001086 bool DashDashFound = false; // Have we read '--'?
Zachary Turner07670b32016-06-29 21:48:26 +00001087 for (int i = FirstArg; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +00001088 Option *Handler = nullptr;
1089 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +00001090 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +00001091 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +00001092 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +00001093
1094 // Check to see if this is a positional argument. This argument is
1095 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +00001096 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +00001097 //
1098 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1099 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +00001100 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +00001101 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +00001102 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001103 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001104
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001105 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001106 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +00001107
1108 // All of the positional arguments have been fulfulled, give the rest to
1109 // the consume after option... if it's specified...
1110 //
Craig Topper8d399f82014-04-09 04:20:00 +00001111 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001112 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001113 PositionalVals.push_back(std::make_pair(argv[i], i));
1114 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +00001115 }
1116
1117 // Delay processing positional arguments until the end...
1118 continue;
1119 }
Chris Lattnera60f3552004-05-06 22:04:31 +00001120 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1121 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001122 DashDashFound = true; // This is the mythical "--"?
1123 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +00001124 } else if (ActivePositionalArg &&
1125 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1126 // If there is a positional argument eating options, check to see if this
1127 // option is another positional argument. If so, treat it as an argument,
1128 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +00001129 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001130 // Eat leading dashes.
1131 while (!ArgName.empty() && ArgName[0] == '-')
1132 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001133
Zachary Turner07670b32016-06-29 21:48:26 +00001134 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
Chris Lattnera60f3552004-05-06 22:04:31 +00001135 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +00001136 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +00001137 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +00001138 }
1139
Chris Bieneman5d232242015-01-13 19:14:20 +00001140 } else { // We start with a '-', must be an argument.
1141 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001142 // Eat leading dashes.
1143 while (!ArgName.empty() && ArgName[0] == '-')
1144 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001145
Zachary Turner07670b32016-06-29 21:48:26 +00001146 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001147
Chris Lattnera60f3552004-05-06 22:04:31 +00001148 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +00001149 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +00001150 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1151 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +00001152
1153 // Otherwise, look for the closest available option to report to the user
1154 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +00001155 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001156 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +00001157 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +00001158 }
1159
Craig Topper8d399f82014-04-09 04:20:00 +00001160 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001161 if (SinkOpts.empty()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001162 if (!IgnoreErrors) {
1163 errs() << ProgramName << ": Unknown command line argument '"
1164 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +00001165
Zachary Turner07670b32016-06-29 21:48:26 +00001166 if (NearestHandler) {
1167 // If we know a near match, report it as well.
1168 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
1169 << "'?\n";
1170 }
Daniel Dunbar72d523b2011-01-24 17:27:17 +00001171 }
Daniel Dunbarf4132132011-01-18 01:59:24 +00001172
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001173 ErrorParsing = true;
1174 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +00001175 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1176 E = SinkOpts.end();
1177 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001178 (*I)->addOccurrence(i, "", argv[i]);
1179 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001180 continue;
1181 }
1182
Chris Lattner2da046f2003-07-30 17:34:02 +00001183 // If this is a named positional argument, just remember that it is the
1184 // active one...
1185 if (Handler->getFormattingFlag() == cl::Positional)
1186 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001187 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001188 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001189 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001190
Chris Lattner5df56c42002-07-22 02:07:59 +00001191 // Check and handle positional arguments now...
1192 if (NumPositionalRequired > PositionalVals.size()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001193 if (!IgnoreErrors) {
1194 errs() << ProgramName
1195 << ": Not enough positional command line arguments specified!\n"
1196 << "Must specify at least " << NumPositionalRequired
Ying Yi60a3da32016-07-22 10:52:21 +00001197 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1198 << ": See: " << argv[0] << " - help\n";
Zachary Turner07670b32016-06-29 21:48:26 +00001199 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001200
Chris Lattner5df56c42002-07-22 02:07:59 +00001201 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001202 } else if (!HasUnlimitedPositionals &&
1203 PositionalVals.size() > PositionalOpts.size()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001204 if (!IgnoreErrors) {
1205 errs() << ProgramName << ": Too many positional arguments specified!\n"
1206 << "Can specify at most " << PositionalOpts.size()
1207 << " positional arguments: See: " << argv[0] << " -help\n";
1208 }
Chris Lattnerd380d842005-08-08 17:25:38 +00001209 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001210
Craig Topper8d399f82014-04-09 04:20:00 +00001211 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001212 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001213 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1214 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001215 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001216 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001217 PositionalVals[ValNo].second);
1218 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001219 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001220 }
1221
1222 // If we _can_ give this option more arguments, do so now, as long as we
1223 // do not give it values that others need. 'Done' controls whether the
1224 // option even _WANTS_ any more.
1225 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001226 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001227 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001228 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001229 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001230 Done = true; // Optional arguments want _at most_ one value
1231 // FALL THROUGH
1232 case cl::ZeroOrMore: // Zero or more will take all they can get...
1233 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001234 ProvidePositionalOption(PositionalOpts[i],
1235 PositionalVals[ValNo].first,
1236 PositionalVals[ValNo].second);
1237 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001238 break;
1239 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001240 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001241 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001242 }
1243 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001244 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001245 } else {
1246 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1247 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001248 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001249 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001250 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001251 PositionalVals[ValNo].first,
1252 PositionalVals[ValNo].second);
1253 ValNo++;
1254 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001255
1256 // Handle the case where there is just one positional option, and it's
1257 // optional. In this case, we want to give JUST THE FIRST option to the
1258 // positional option and keep the rest for the consume after. The above
1259 // loop would have assigned no values to positional options in this case.
1260 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001261 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1262 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001263 PositionalVals[ValNo].first,
1264 PositionalVals[ValNo].second);
1265 ValNo++;
1266 }
Misha Brukman10468d82005-04-21 22:55:34 +00001267
Chris Lattner5df56c42002-07-22 02:07:59 +00001268 // Handle over all of the rest of the arguments to the
1269 // cl::ConsumeAfter command line option...
1270 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001271 ErrorParsing |=
1272 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1273 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001274 }
1275
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001276 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001277 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001278 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001279 case Required:
1280 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001281 if (Opt.second->getNumOccurrences() == 0) {
1282 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001283 ErrorParsing = true;
1284 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001285 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001286 default:
1287 break;
1288 }
1289 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001290
Rafael Espindolacf14a382010-11-19 21:14:29 +00001291 // Now that we know if -debug is specified, we can use it.
1292 // Note that if ReadResponseFiles == true, this must be done before the
1293 // memory allocated for the expanded command line is free()d below.
1294 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001295 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1296 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001297
Chris Lattner5df56c42002-07-22 02:07:59 +00001298 // Free all of the memory allocated to the map. Command line options may only
1299 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001300 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001301
1302 // If we had an error processing our arguments, don't let the program execute
Zachary Turner07670b32016-06-29 21:48:26 +00001303 if (ErrorParsing) {
1304 if (!IgnoreErrors)
1305 exit(1);
1306 return false;
1307 }
1308 return true;
Chris Lattner36a57d32001-07-23 17:17:47 +00001309}
1310
1311//===----------------------------------------------------------------------===//
1312// Option Base class implementation
1313//
Chris Lattner36a57d32001-07-23 17:17:47 +00001314
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001315bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001316 if (!ArgName.data())
1317 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001318 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001319 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001320 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001321 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001322
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001323 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001324 return true;
1325}
1326
Chris Bieneman5d232242015-01-13 19:14:20 +00001327bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1328 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001329 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001330 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001331
Misha Brukman069e6b52003-07-10 16:49:51 +00001332 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001333 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001334 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001335 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001336 break;
1337 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001338 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001339 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001340 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001341 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001342 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001343 case ConsumeAfter:
1344 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001345 }
1346
Reid Spencer2027a6f2004-08-13 19:47:30 +00001347 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001348}
1349
Chris Lattner5df56c42002-07-22 02:07:59 +00001350// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1351// has been specified yet.
1352//
David Blaikieff43d692015-11-17 19:00:52 +00001353static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1354 if (O.ValueStr.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001355 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001356 return O.ValueStr;
1357}
1358
1359//===----------------------------------------------------------------------===//
1360// cl::alias class implementation
1361//
1362
Chris Lattner36a57d32001-07-23 17:17:47 +00001363// Return the width of the option tag for printing...
David Blaikieff43d692015-11-17 19:00:52 +00001364size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001365
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001366static void printHelpStr(StringRef HelpStr, size_t Indent,
1367 size_t FirstLineIndentedBy) {
1368 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1369 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1370 while (!Split.second.empty()) {
1371 Split = Split.second.split('\n');
1372 outs().indent(Indent) << Split.first << "\n";
1373 }
1374}
1375
Chris Lattner1b7a5152006-04-28 05:36:25 +00001376// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001377void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001378 outs() << " -" << ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001379 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001380}
1381
Chris Lattner36a57d32001-07-23 17:17:47 +00001382//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001383// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001384//
1385
Chris Lattnerb4101b12002-08-07 18:36:37 +00001386// basic_parser implementation
1387//
1388
1389// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001390size_t basic_parser_impl::getOptionWidth(const Option &O) const {
David Blaikieff43d692015-11-17 19:00:52 +00001391 size_t Len = O.ArgStr.size();
Chris Lattnerb4101b12002-08-07 18:36:37 +00001392 if (const char *ValName = getValueName())
David Blaikieff43d692015-11-17 19:00:52 +00001393 Len += getValueStr(O, ValName).size() + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001394
1395 return Len + 6;
1396}
1397
Misha Brukman10468d82005-04-21 22:55:34 +00001398// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001399// to-be-maintained width is specified.
1400//
1401void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001402 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001403 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001404
1405 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001406 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001407
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001408 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001409}
1410
Andrew Trick12004012011-04-05 18:54:36 +00001411void basic_parser_impl::printOptionName(const Option &O,
1412 size_t GlobalWidth) const {
1413 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001414 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001415}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001416
Chris Lattner5df56c42002-07-22 02:07:59 +00001417// parser<bool> implementation
1418//
Chris Bieneman5d232242015-01-13 19:14:20 +00001419bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1420 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001421 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001422 Arg == "1") {
1423 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001424 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001425 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001426
Chris Lattneraecd74d2009-09-19 18:55:05 +00001427 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1428 Value = false;
1429 return false;
1430 }
1431 return O.error("'" + Arg +
1432 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001433}
1434
Dale Johannesen82810c82007-05-22 17:14:46 +00001435// parser<boolOrDefault> implementation
1436//
Chris Bieneman5d232242015-01-13 19:14:20 +00001437bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1438 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001439 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1440 Arg == "1") {
1441 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001442 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001443 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001444 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1445 Value = BOU_FALSE;
1446 return false;
1447 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001448
Chris Lattneraecd74d2009-09-19 18:55:05 +00001449 return O.error("'" + Arg +
1450 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001451}
1452
Chris Lattner5df56c42002-07-22 02:07:59 +00001453// parser<int> implementation
1454//
Chris Bieneman5d232242015-01-13 19:14:20 +00001455bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1456 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001457 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001458 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001459 return false;
1460}
1461
Chris Lattner719c7152003-06-28 15:47:20 +00001462// parser<unsigned> implementation
1463//
Chris Bieneman5d232242015-01-13 19:14:20 +00001464bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1465 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001466
1467 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001468 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001469 return false;
1470}
1471
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001472// parser<unsigned long long> implementation
1473//
1474bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001475 StringRef Arg,
1476 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001477
1478 if (Arg.getAsInteger(0, Value))
1479 return O.error("'" + Arg + "' value invalid for uint argument!");
1480 return false;
1481}
1482
Chris Lattnerb4101b12002-08-07 18:36:37 +00001483// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001484//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001485static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001486 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1487 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001488 char *End;
1489 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001490 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001491 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001492 return false;
1493}
1494
Chris Bieneman5d232242015-01-13 19:14:20 +00001495bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1496 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001497 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001498}
1499
Chris Bieneman5d232242015-01-13 19:14:20 +00001500bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1501 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001502 double dVal;
1503 if (parseDouble(O, Arg, dVal))
1504 return true;
1505 Val = (float)dVal;
1506 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001507}
1508
Chris Lattner5df56c42002-07-22 02:07:59 +00001509// generic_parser_base implementation
1510//
1511
Chris Lattner494c0b02002-07-23 17:15:12 +00001512// findOption - Return the option number corresponding to the specified
1513// argument string. If the option is not found, getNumOptions() is returned.
1514//
1515unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001516 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001517
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001518 for (unsigned i = 0; i != e; ++i) {
1519 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001520 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001521 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001522 return e;
1523}
1524
Chris Lattner5df56c42002-07-22 02:07:59 +00001525// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001526size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001527 if (O.hasArgStr()) {
David Blaikieff43d692015-11-17 19:00:52 +00001528 size_t Size = O.ArgStr.size() + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001529 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001530 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001531 return Size;
1532 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001533 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001534 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001535 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001536 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001537 }
1538}
1539
Misha Brukman10468d82005-04-21 22:55:34 +00001540// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001541// to-be-maintained width is specified.
1542//
1543void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001544 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001545 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001546 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001547 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001548
Chris Lattner5df56c42002-07-22 02:07:59 +00001549 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001550 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001551 outs() << " =" << getOption(i);
1552 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001553 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001554 } else {
David Blaikieff43d692015-11-17 19:00:52 +00001555 if (!O.HelpStr.empty())
Chris Lattnere7c1e212009-09-20 05:03:30 +00001556 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001557 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001558 const char *Option = getOption(i);
1559 outs() << " -" << Option;
1560 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001561 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001562 }
1563}
1564
Andrew Trick12004012011-04-05 18:54:36 +00001565static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1566
1567// printGenericOptionDiff - Print the value of this option and it's default.
1568//
1569// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001570void generic_parser_base::printGenericOptionDiff(
1571 const Option &O, const GenericOptionValue &Value,
1572 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001573 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001574 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001575
1576 unsigned NumOpts = getNumOptions();
1577 for (unsigned i = 0; i != NumOpts; ++i) {
1578 if (Value.compare(getOptionValue(i)))
1579 continue;
1580
1581 outs() << "= " << getOption(i);
1582 size_t L = std::strlen(getOption(i));
1583 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1584 outs().indent(NumSpaces) << " (default: ";
1585 for (unsigned j = 0; j != NumOpts; ++j) {
1586 if (Default.compare(getOptionValue(j)))
1587 continue;
1588 outs() << getOption(j);
1589 break;
1590 }
1591 outs() << ")\n";
1592 return;
1593 }
1594 outs() << "= *unknown option value*\n";
1595}
1596
1597// printOptionDiff - Specializations for printing basic value types.
1598//
Chris Bieneman5d232242015-01-13 19:14:20 +00001599#define PRINT_OPT_DIFF(T) \
1600 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1601 size_t GlobalWidth) const { \
1602 printOptionName(O, GlobalWidth); \
1603 std::string Str; \
1604 { \
1605 raw_string_ostream SS(Str); \
1606 SS << V; \
1607 } \
1608 outs() << "= " << Str; \
1609 size_t NumSpaces = \
1610 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1611 outs().indent(NumSpaces) << " (default: "; \
1612 if (D.hasValue()) \
1613 outs() << D.getValue(); \
1614 else \
1615 outs() << "*no default*"; \
1616 outs() << ")\n"; \
1617 }
Andrew Trick12004012011-04-05 18:54:36 +00001618
Frits van Bommel87e33672011-04-06 12:29:56 +00001619PRINT_OPT_DIFF(bool)
1620PRINT_OPT_DIFF(boolOrDefault)
1621PRINT_OPT_DIFF(int)
1622PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001623PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001624PRINT_OPT_DIFF(double)
1625PRINT_OPT_DIFF(float)
1626PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001627
Chris Bieneman5d232242015-01-13 19:14:20 +00001628void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
Benjamin Kramerc321e532016-06-08 19:09:22 +00001629 const OptionValue<std::string> &D,
Chris Bieneman5d232242015-01-13 19:14:20 +00001630 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001631 printOptionName(O, GlobalWidth);
1632 outs() << "= " << V;
1633 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1634 outs().indent(NumSpaces) << " (default: ";
1635 if (D.hasValue())
1636 outs() << D.getValue();
1637 else
1638 outs() << "*no default*";
1639 outs() << ")\n";
1640}
1641
1642// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001643void basic_parser_impl::printOptionNoValue(const Option &O,
1644 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001645 printOptionName(O, GlobalWidth);
1646 outs() << "= *cannot print option value*\n";
1647}
Chris Lattner36a57d32001-07-23 17:17:47 +00001648
1649//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001650// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001651//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001652
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001653static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1654 const std::pair<const char *, Option *> *RHS) {
1655 return strcmp(LHS->first, RHS->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001656}
1657
Zachary Turner07670b32016-06-29 21:48:26 +00001658static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1659 const std::pair<const char *, SubCommand *> *RHS) {
1660 return strcmp(LHS->first, RHS->first);
1661}
1662
Andrew Trick12004012011-04-05 18:54:36 +00001663// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001664static void sortOpts(StringMap<Option *> &OptMap,
1665 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1666 bool ShowHidden) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001667 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001668
Chris Bieneman5d232242015-01-13 19:14:20 +00001669 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001670 I != E; ++I) {
1671 // Ignore really-hidden options.
1672 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1673 continue;
1674
1675 // Unless showhidden is set, ignore hidden flags.
1676 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1677 continue;
1678
1679 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001680 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001681 continue;
1682
Chris Bieneman5d232242015-01-13 19:14:20 +00001683 Opts.push_back(
1684 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001685 }
1686
1687 // Sort the options list alphabetically.
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001688 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
Andrew Trick12004012011-04-05 18:54:36 +00001689}
1690
Zachary Turner07670b32016-06-29 21:48:26 +00001691static void
1692sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1693 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1694 for (const auto &S : SubMap) {
1695 if (S->getName() == nullptr)
1696 continue;
1697 Subs.push_back(std::make_pair(S->getName(), S));
1698 }
1699 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1700}
1701
Chris Lattner36a57d32001-07-23 17:17:47 +00001702namespace {
1703
Chris Lattner5df56c42002-07-22 02:07:59 +00001704class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001705protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001706 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001707 typedef SmallVector<std::pair<const char *, Option *>, 128>
1708 StrOptionPairVector;
Zachary Turner07670b32016-06-29 21:48:26 +00001709 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1710 StrSubCommandPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001711 // Print the options. Opts is assumed to be alphabetically sorted.
1712 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1713 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1714 Opts[i].second->printOptionInfo(MaxArgLen);
1715 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001716
Zachary Turner07670b32016-06-29 21:48:26 +00001717 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1718 for (const auto &S : Subs) {
1719 outs() << " " << S.first;
1720 if (S.second->getDescription()) {
1721 outs().indent(MaxSubLen - strlen(S.first));
1722 outs() << " - " << S.second->getDescription();
1723 }
1724 outs() << "\n";
1725 }
1726 }
1727
Chris Lattner5df56c42002-07-22 02:07:59 +00001728public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001729 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001730 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001731
Andrew Trick0537a982013-05-06 21:56:23 +00001732 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001733 void operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001734 if (!Value)
Chris Bieneman5d232242015-01-13 19:14:20 +00001735 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001736
Zachary Turner07670b32016-06-29 21:48:26 +00001737 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1738 auto &OptionsMap = Sub->OptionsMap;
1739 auto &PositionalOpts = Sub->PositionalOpts;
1740 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1741
Andrew Trick0537a982013-05-06 21:56:23 +00001742 StrOptionPairVector Opts;
Zachary Turner07670b32016-06-29 21:48:26 +00001743 sortOpts(OptionsMap, Opts, ShowHidden);
1744
1745 StrSubCommandPairVector Subs;
1746 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
Chris Lattner36a57d32001-07-23 17:17:47 +00001747
Chris Bienemand1d94302015-01-28 19:00:25 +00001748 if (GlobalParser->ProgramOverview)
1749 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001750
Zachary Turner07670b32016-06-29 21:48:26 +00001751 if (Sub == &*TopLevelSubCommand)
1752 outs() << "USAGE: " << GlobalParser->ProgramName
1753 << " [subcommand] [options]";
1754 else {
1755 if (Sub->getDescription() != nullptr) {
1756 outs() << "SUBCOMMAND '" << Sub->getName()
1757 << "': " << Sub->getDescription() << "\n\n";
1758 }
1759 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1760 << " [options]";
1761 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001762
Zachary Turner07670b32016-06-29 21:48:26 +00001763 for (auto Opt : PositionalOpts) {
David Blaikieff43d692015-11-17 19:00:52 +00001764 if (Opt->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +00001765 outs() << " --" << Opt->ArgStr;
1766 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001767 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001768
1769 // Print the consume after option info if it exists...
Zachary Turner07670b32016-06-29 21:48:26 +00001770 if (ConsumeAfterOpt)
1771 outs() << " " << ConsumeAfterOpt->HelpStr;
1772
1773 if (Sub == &*TopLevelSubCommand && Subs.size() > 2) {
1774 // Compute the maximum subcommand length...
1775 size_t MaxSubLen = 0;
1776 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1777 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1778
1779 outs() << "\n\n";
1780 outs() << "SUBCOMMANDS:\n\n";
1781 printSubCommands(Subs, MaxSubLen);
1782 outs() << "\n";
1783 outs() << " Type \"" << GlobalParser->ProgramName
1784 << " <subcommand> -help\" to get more help on a specific "
1785 "subcommand";
1786 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001787
Chris Lattner471ba482009-08-23 08:43:55 +00001788 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001789
1790 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001791 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001792 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001793 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001794
Chris Lattner471ba482009-08-23 08:43:55 +00001795 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001796 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001797
Chris Lattner37bcd992004-11-19 17:08:15 +00001798 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001799 for (auto I : GlobalParser->MoreHelp)
1800 outs() << I;
1801 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001802
Reid Spencer5e554702004-11-16 06:11:52 +00001803 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001804 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001805 }
1806};
Andrew Trick0537a982013-05-06 21:56:23 +00001807
1808class CategorizedHelpPrinter : public HelpPrinter {
1809public:
1810 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1811
1812 // Helper function for printOptions().
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001813 // It shall return a negative value if A's name should be lexicographically
1814 // ordered before B's name. It returns a value greater equal zero otherwise.
1815 static int OptionCategoryCompare(OptionCategory *const *A,
1816 OptionCategory *const *B) {
1817 return strcmp((*A)->getName(), (*B)->getName());
Andrew Trick0537a982013-05-06 21:56:23 +00001818 }
1819
1820 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001821 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001822
1823protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001824 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001825 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001826 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001827
Alp Tokercb402912014-01-24 17:20:08 +00001828 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001829 // sorting.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001830 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1831 E = GlobalParser->RegisteredOptionCategories.end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001832 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001833 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001834 }
Andrew Trick0537a982013-05-06 21:56:23 +00001835
1836 // Sort the different option categories alphabetically.
1837 assert(SortedCategories.size() > 0 && "No option categories registered!");
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001838 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1839 OptionCategoryCompare);
Andrew Trick0537a982013-05-06 21:56:23 +00001840
1841 // Create map to empty vectors.
1842 for (std::vector<OptionCategory *>::const_iterator
1843 I = SortedCategories.begin(),
1844 E = SortedCategories.end();
1845 I != E; ++I)
1846 CategorizedOptions[*I] = std::vector<Option *>();
1847
1848 // Walk through pre-sorted options and assign into categories.
1849 // Because the options are already alphabetically sorted the
1850 // options within categories will also be alphabetically sorted.
1851 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1852 Option *Opt = Opts[I].second;
1853 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1854 "Option has an unregistered category");
1855 CategorizedOptions[Opt->Category].push_back(Opt);
1856 }
1857
1858 // Now do printing.
1859 for (std::vector<OptionCategory *>::const_iterator
1860 Category = SortedCategories.begin(),
1861 E = SortedCategories.end();
1862 Category != E; ++Category) {
1863 // Hide empty categories for -help, but show for -help-hidden.
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001864 const auto &CategoryOptions = CategorizedOptions[*Category];
1865 bool IsEmptyCategory = CategoryOptions.empty();
Andrew Trick0537a982013-05-06 21:56:23 +00001866 if (!ShowHidden && IsEmptyCategory)
1867 continue;
1868
1869 // Print category information.
1870 outs() << "\n";
1871 outs() << (*Category)->getName() << ":\n";
1872
1873 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001874 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001875 outs() << (*Category)->getDescription() << "\n\n";
1876 else
1877 outs() << "\n";
1878
1879 // When using -help-hidden explicitly state if the category has no
1880 // options associated with it.
1881 if (IsEmptyCategory) {
1882 outs() << " This option category has no options.\n";
1883 continue;
1884 }
1885 // Loop over the options in the category and print.
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001886 for (const Option *Opt : CategoryOptions)
1887 Opt->printOptionInfo(MaxArgLen);
Andrew Trick0537a982013-05-06 21:56:23 +00001888 }
1889 }
1890};
1891
1892// This wraps the Uncategorizing and Categorizing printers and decides
1893// at run time which should be invoked.
1894class HelpPrinterWrapper {
1895private:
1896 HelpPrinter &UncategorizedPrinter;
1897 CategorizedHelpPrinter &CategorizedPrinter;
1898
1899public:
1900 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001901 CategorizedHelpPrinter &CategorizedPrinter)
1902 : UncategorizedPrinter(UncategorizedPrinter),
1903 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001904
1905 // Invoke the printer.
1906 void operator=(bool Value);
1907};
1908
Chris Lattneradb19d62006-10-12 22:09:17 +00001909} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001910
Andrew Trick0537a982013-05-06 21:56:23 +00001911// Declare the four HelpPrinter instances that are used to print out help, or
1912// help-hidden as an uncategorized list or in categories.
1913static HelpPrinter UncategorizedNormalPrinter(false);
1914static HelpPrinter UncategorizedHiddenPrinter(true);
1915static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1916static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1917
Andrew Trick0537a982013-05-06 21:56:23 +00001918// Declare HelpPrinter wrappers that will decide whether or not to invoke
1919// a categorizing help printer
1920static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1921 CategorizedNormalPrinter);
1922static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1923 CategorizedHiddenPrinter);
1924
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001925// Define a category for generic options that all tools should have.
1926static cl::OptionCategory GenericCategory("Generic Options");
1927
Andrew Trick0537a982013-05-06 21:56:23 +00001928// Define uncategorized help printers.
1929// -help-list is hidden by default because if Option categories are being used
1930// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001931static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1932 "help-list",
1933 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001934 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001935 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Chris Lattner5df56c42002-07-22 02:07:59 +00001936
Chris Bieneman5d232242015-01-13 19:14:20 +00001937static cl::opt<HelpPrinter, true, parser<bool>>
1938 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1939 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Zachary Turner07670b32016-06-29 21:48:26 +00001940 cl::ValueDisallowed, cl::cat(GenericCategory),
1941 cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00001942
1943// Define uncategorized/categorized help printers. These printers change their
1944// behaviour at runtime depending on whether one or more Option categories have
1945// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001946static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1947 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001948 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001949 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Chris Lattner5df56c42002-07-22 02:07:59 +00001950
Chris Bieneman5d232242015-01-13 19:14:20 +00001951static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1952 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001953 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001954 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00001955
Chris Bieneman5d232242015-01-13 19:14:20 +00001956static cl::opt<bool> PrintOptions(
1957 "print-options",
1958 cl::desc("Print non-default options after command line parsing"),
Zachary Turner07670b32016-06-29 21:48:26 +00001959 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
1960 cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00001961
Chris Bieneman5d232242015-01-13 19:14:20 +00001962static cl::opt<bool> PrintAllOptions(
1963 "print-all-options",
1964 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Zachary Turner07670b32016-06-29 21:48:26 +00001965 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Andrew Trick12004012011-04-05 18:54:36 +00001966
Andrew Trick0537a982013-05-06 21:56:23 +00001967void HelpPrinterWrapper::operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001968 if (!Value)
Andrew Trick0537a982013-05-06 21:56:23 +00001969 return;
1970
1971 // Decide which printer to invoke. If more than one option category is
1972 // registered then it is useful to show the categorized help instead of
1973 // uncategorized help.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001974 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
Andrew Trick0537a982013-05-06 21:56:23 +00001975 // unhide -help-list option so user can have uncategorized output if they
1976 // want it.
1977 HLOp.setHiddenFlag(NotHidden);
1978
1979 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001980 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001981 UncategorizedPrinter = true; // Invoke uncategorized printer
1982}
1983
Andrew Trick12004012011-04-05 18:54:36 +00001984// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00001985void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1986
1987void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001988 if (!PrintOptions && !PrintAllOptions)
1989 return;
Andrew Trick12004012011-04-05 18:54:36 +00001990
Chris Bieneman5d232242015-01-13 19:14:20 +00001991 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Zachary Turner07670b32016-06-29 21:48:26 +00001992 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001993
1994 // Compute the maximum argument length...
1995 size_t MaxArgLen = 0;
1996 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1997 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1998
1999 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2000 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2001}
2002
Craig Topperc10719f2014-04-07 04:17:22 +00002003static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00002004
Chris Bieneman5d232242015-01-13 19:14:20 +00002005static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00002006
Chris Lattneradb19d62006-10-12 22:09:17 +00002007namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00002008class VersionPrinter {
2009public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00002010 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00002011 raw_ostream &OS = outs();
Chris Bienemanef43d442016-03-15 18:07:46 +00002012#ifdef PACKAGE_VENDOR
2013 OS << PACKAGE_VENDOR << " ";
2014#else
2015 OS << "LLVM (http://llvm.org/):\n ";
2016#endif
2017 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00002018#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00002019 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00002020#endif
Chris Lattner131dca92009-09-20 06:18:38 +00002021 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002022#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00002023 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002024#else
Chris Lattner131dca92009-09-20 06:18:38 +00002025 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002026#endif
2027#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00002028 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002029#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00002030 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00002031 if (CPU == "generic")
2032 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00002033 OS << ".\n"
Sebastian Pop94441fb2011-11-01 21:32:20 +00002034 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00002035 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00002036 }
2037 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00002038 if (!OptionWasSpecified)
2039 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00002040
Craig Topperc10719f2014-04-07 04:17:22 +00002041 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00002042 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00002043 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00002044 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00002045 print();
2046
2047 // Iterate over any registered extra printers and call them to add further
2048 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00002049 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00002050 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00002051 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
2052 E = ExtraVersionPrinters->end();
2053 I != E; ++I)
2054 (*I)();
2055 }
2056
Justin Bogner02b95842014-02-28 19:08:01 +00002057 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00002058 }
2059};
Chris Lattneradb19d62006-10-12 22:09:17 +00002060} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00002061
Reid Spencerff6cc122004-08-04 00:36:06 +00002062// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00002063static VersionPrinter VersionPrinterInstance;
2064
Chris Bieneman5d232242015-01-13 19:14:20 +00002065static cl::opt<VersionPrinter, true, parser<bool>>
2066 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00002067 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2068 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00002069
Reid Spencer5e554702004-11-16 06:11:52 +00002070// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00002071void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2072 // This looks weird, but it actually prints the help message. The Printers are
2073 // types of HelpPrinter and the help gets printed when its operator= is
2074 // invoked. That's because the "normal" usages of the help printer is to be
2075 // assigned true/false depending on whether -help or -help-hidden was given or
2076 // not. Since we're circumventing that we have to make it look like -help or
2077 // -help-hidden were given, so we assign true.
2078
2079 if (!Hidden && !Categorized)
2080 UncategorizedNormalPrinter = true;
2081 else if (!Hidden && Categorized)
2082 CategorizedNormalPrinter = true;
2083 else if (Hidden && !Categorized)
2084 UncategorizedHiddenPrinter = true;
2085 else
2086 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00002087}
Reid Spencerb3171672006-06-05 16:22:56 +00002088
Devang Patel9eb2caae2007-02-01 01:43:37 +00002089/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00002090void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00002091
Chris Bieneman5d232242015-01-13 19:14:20 +00002092void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00002093
2094void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00002095 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00002096 ExtraVersionPrinters = new std::vector<void (*)()>;
2097
2098 ExtraVersionPrinters->push_back(func);
2099}
Andrew Trick7cb710d2013-05-06 21:56:35 +00002100
Zachary Turner07670b32016-06-29 21:48:26 +00002101StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2102 auto &Subs = GlobalParser->RegisteredSubCommands;
2103 (void)Subs;
David Majnemer0d955d02016-08-11 22:21:41 +00002104 assert(is_contained(Subs, &Sub));
Zachary Turner07670b32016-06-29 21:48:26 +00002105 return Sub.OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00002106}
Peter Collingbournee1863192014-10-16 22:47:52 +00002107
Zachary Turner07670b32016-06-29 21:48:26 +00002108void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2109 for (auto &I : Sub.OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00002110 if (I.second->Category != &Category &&
2111 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00002112 I.second->setHiddenFlag(cl::ReallyHidden);
2113 }
2114}
2115
Zachary Turner07670b32016-06-29 21:48:26 +00002116void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2117 SubCommand &Sub) {
Chris Bieneman01043252015-01-26 21:57:29 +00002118 auto CategoriesBegin = Categories.begin();
2119 auto CategoriesEnd = Categories.end();
Zachary Turner07670b32016-06-29 21:48:26 +00002120 for (auto &I : Sub.OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00002121 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2122 CategoriesEnd &&
2123 I.second->Category != &GenericCategory)
2124 I.second->setHiddenFlag(cl::ReallyHidden);
2125 }
2126}
2127
Zachary Turner07670b32016-06-29 21:48:26 +00002128void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2129void cl::ResetAllOptionOccurrences() {
2130 GlobalParser->ResetAllOptionOccurrences();
2131}
2132
Peter Collingbournee1863192014-10-16 22:47:52 +00002133void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2134 const char *Overview) {
Zachary Turner07670b32016-06-29 21:48:26 +00002135 llvm::cl::ParseCommandLineOptions(argc, argv, Overview, true);
Peter Collingbournee1863192014-10-16 22:47:52 +00002136}