blob: b1142d79cdb21bd780af5b2a11fc57d96def0359 [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"
Serge Pavlovf258ff12016-11-20 06:25:07 +000033#include "llvm/Support/FileSystem.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Host.h"
35#include "llvm/Support/ManagedStatic.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/Path.h"
David Majnemerafb38af2016-07-24 17:19:59 +000038#include "llvm/Support/Process.h"
Rafael Espindola454adf62015-06-13 12:49:52 +000039#include "llvm/Support/StringSaver.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Support/raw_ostream.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000041#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000042#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000043using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000044using namespace cl;
45
Chandler Carruthe96dd892014-04-21 22:55:11 +000046#define DEBUG_TYPE "commandline"
47
Mandeep Singh Grangf6b069c2016-12-14 00:15:57 +000048#if LLVM_ENABLE_ABI_BREAKING_CHECKS
49namespace llvm {
50// If LLVM_ENABLE_ABI_BREAKING_CHECKS is set the flag -mllvm -reverse-iterate
51// can be used to toggle forward/reverse iteration of unordered containers.
52// This will help uncover differences in codegen caused due to undefined
53// iteration order.
54static cl::opt<bool, true> ReverseIteration("reverse-iterate",
Mehdi Amini76a00b52016-12-14 02:35:32 +000055 cl::location(ReverseIterate<bool>::value));
Mandeep Singh Grangf6b069c2016-12-14 00:15:57 +000056}
57#endif
58
Chris Lattner3e5d60f2006-08-27 12:45:47 +000059//===----------------------------------------------------------------------===//
60// Template instantiations and anchors.
61//
Chris Bieneman5d232242015-01-13 19:14:20 +000062namespace llvm {
63namespace cl {
Benjamin Kramera667d1a2015-07-13 17:21:31 +000064template class basic_parser<bool>;
65template class basic_parser<boolOrDefault>;
66template class basic_parser<int>;
67template class basic_parser<unsigned>;
68template class basic_parser<unsigned long long>;
69template class basic_parser<double>;
70template class basic_parser<float>;
71template class basic_parser<std::string>;
72template class basic_parser<char>;
Chris Lattner3e5d60f2006-08-27 12:45:47 +000073
Benjamin Kramera667d1a2015-07-13 17:21:31 +000074template class opt<unsigned>;
75template class opt<int>;
76template class opt<std::string>;
77template class opt<char>;
78template class opt<bool>;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000079}
80} // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000081
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000082// Pin the vtables to this file.
83void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000084void OptionValue<boolOrDefault>::anchor() {}
85void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000086void Option::anchor() {}
87void basic_parser_impl::anchor() {}
88void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000089void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000090void parser<int>::anchor() {}
91void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000092void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000093void parser<double>::anchor() {}
94void parser<float>::anchor() {}
95void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000096void parser<char>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000097
98//===----------------------------------------------------------------------===//
99
Benjamin Kramer970eac42015-02-06 17:51:54 +0000100namespace {
101
Chris Bienemand1d94302015-01-28 19:00:25 +0000102class CommandLineParser {
103public:
104 // Globals for name and overview of program. Program name is not a string to
105 // avoid static ctor/dtor issues.
Chris Bienemanb6866422015-01-28 22:25:00 +0000106 std::string ProgramName;
Mehdi Aminie11b7452016-10-01 03:43:20 +0000107 StringRef ProgramOverview;
Reid Spencer9501b9b2004-09-01 04:41:28 +0000108
Chris Bienemand1d94302015-01-28 19:00:25 +0000109 // This collects additional help to be printed.
Mehdi Aminie11b7452016-10-01 03:43:20 +0000110 std::vector<StringRef> MoreHelp;
Chris Bienemand1d94302015-01-28 19:00:25 +0000111
Chris Bieneman67e426a2015-02-13 22:54:32 +0000112 // This collects the different option categories that have been registered.
113 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
114
Zachary Turner07670b32016-06-29 21:48:26 +0000115 // This collects the different subcommands that have been registered.
116 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
Chris Bienemand1d94302015-01-28 19:00:25 +0000117
Mehdi Aminie11b7452016-10-01 03:43:20 +0000118 CommandLineParser() : ActiveSubCommand(nullptr) {
Zachary Turner07670b32016-06-29 21:48:26 +0000119 registerSubCommand(&*TopLevelSubCommand);
120 registerSubCommand(&*AllSubCommands);
121 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000122
Zachary Turner07670b32016-06-29 21:48:26 +0000123 void ResetAllOptionOccurrences();
124
125 bool ParseCommandLineOptions(int argc, const char *const *argv,
Mehdi Aminie11b7452016-10-01 03:43:20 +0000126 StringRef Overview, bool IgnoreErrors);
Zachary Turner07670b32016-06-29 21:48:26 +0000127
Mehdi Aminie11b7452016-10-01 03:43:20 +0000128 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
Zachary Turner07670b32016-06-29 21:48:26 +0000129 if (Opt.hasArgStr())
130 return;
131 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
132 errs() << ProgramName << ": CommandLine Error: Option '" << Name
133 << "' registered more than once!\n";
134 report_fatal_error("inconsistency in registered CommandLine options");
135 }
136
137 // If we're adding this to all sub-commands, add it to the ones that have
138 // already been registered.
139 if (SC == &*AllSubCommands) {
140 for (const auto &Sub : RegisteredSubCommands) {
141 if (SC == Sub)
142 continue;
143 addLiteralOption(Opt, Sub, Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000144 }
145 }
146 }
147
Mehdi Aminie11b7452016-10-01 03:43:20 +0000148 void addLiteralOption(Option &Opt, StringRef Name) {
Zachary Turner07670b32016-06-29 21:48:26 +0000149 if (Opt.Subs.empty())
150 addLiteralOption(Opt, &*TopLevelSubCommand, Name);
151 else {
152 for (auto SC : Opt.Subs)
153 addLiteralOption(Opt, SC, Name);
154 }
155 }
156
157 void addOption(Option *O, SubCommand *SC) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000158 bool HadErrors = false;
David Blaikieff43d692015-11-17 19:00:52 +0000159 if (O->hasArgStr()) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000160 // Add argument to the argument map!
Zachary Turner07670b32016-06-29 21:48:26 +0000161 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000162 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
163 << "' registered more than once!\n";
164 HadErrors = true;
165 }
166 }
167
168 // Remember information about positional options.
169 if (O->getFormattingFlag() == cl::Positional)
Zachary Turner07670b32016-06-29 21:48:26 +0000170 SC->PositionalOpts.push_back(O);
Chris Bienemand1d94302015-01-28 19:00:25 +0000171 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Zachary Turner07670b32016-06-29 21:48:26 +0000172 SC->SinkOpts.push_back(O);
Chris Bienemand1d94302015-01-28 19:00:25 +0000173 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Zachary Turner07670b32016-06-29 21:48:26 +0000174 if (SC->ConsumeAfterOpt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000175 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
176 HadErrors = true;
177 }
Zachary Turner07670b32016-06-29 21:48:26 +0000178 SC->ConsumeAfterOpt = O;
Chris Bienemand1d94302015-01-28 19:00:25 +0000179 }
180
181 // Fail hard if there were errors. These are strictly unrecoverable and
182 // indicate serious issues such as conflicting option names or an
183 // incorrectly
184 // linked LLVM distribution.
185 if (HadErrors)
186 report_fatal_error("inconsistency in registered CommandLine options");
Zachary Turner07670b32016-06-29 21:48:26 +0000187
188 // If we're adding this to all sub-commands, add it to the ones that have
189 // already been registered.
190 if (SC == &*AllSubCommands) {
191 for (const auto &Sub : RegisteredSubCommands) {
192 if (SC == Sub)
193 continue;
194 addOption(O, Sub);
195 }
196 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000197 }
198
Zachary Turner07670b32016-06-29 21:48:26 +0000199 void addOption(Option *O) {
200 if (O->Subs.empty()) {
201 addOption(O, &*TopLevelSubCommand);
202 } else {
203 for (auto SC : O->Subs)
204 addOption(O, SC);
205 }
206 }
207
208 void removeOption(Option *O, SubCommand *SC) {
David Blaikieff43d692015-11-17 19:00:52 +0000209 SmallVector<StringRef, 16> OptionNames;
Chris Bienemand1d94302015-01-28 19:00:25 +0000210 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000211 if (O->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +0000212 OptionNames.push_back(O->ArgStr);
Zachary Turner07670b32016-06-29 21:48:26 +0000213
214 SubCommand &Sub = *SC;
Chris Bienemand1d94302015-01-28 19:00:25 +0000215 for (auto Name : OptionNames)
Zachary Turner07670b32016-06-29 21:48:26 +0000216 Sub.OptionsMap.erase(Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000217
218 if (O->getFormattingFlag() == cl::Positional)
Zachary Turner07670b32016-06-29 21:48:26 +0000219 for (auto Opt = Sub.PositionalOpts.begin();
220 Opt != Sub.PositionalOpts.end(); ++Opt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000221 if (*Opt == O) {
Zachary Turner07670b32016-06-29 21:48:26 +0000222 Sub.PositionalOpts.erase(Opt);
Chris Bienemand1d94302015-01-28 19:00:25 +0000223 break;
224 }
225 }
226 else if (O->getMiscFlags() & cl::Sink)
Zachary Turner07670b32016-06-29 21:48:26 +0000227 for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000228 if (*Opt == O) {
Zachary Turner07670b32016-06-29 21:48:26 +0000229 Sub.SinkOpts.erase(Opt);
Chris Bienemand1d94302015-01-28 19:00:25 +0000230 break;
231 }
232 }
Zachary Turner07670b32016-06-29 21:48:26 +0000233 else if (O == Sub.ConsumeAfterOpt)
234 Sub.ConsumeAfterOpt = nullptr;
Chris Bienemand1d94302015-01-28 19:00:25 +0000235 }
236
Zachary Turner07670b32016-06-29 21:48:26 +0000237 void removeOption(Option *O) {
238 if (O->Subs.empty())
239 removeOption(O, &*TopLevelSubCommand);
240 else {
241 if (O->isInAllSubCommands()) {
242 for (auto SC : RegisteredSubCommands)
243 removeOption(O, SC);
244 } else {
245 for (auto SC : O->Subs)
246 removeOption(O, SC);
247 }
248 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000249 }
250
Zachary Turner07670b32016-06-29 21:48:26 +0000251 bool hasOptions(const SubCommand &Sub) const {
252 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
253 nullptr != Sub.ConsumeAfterOpt);
254 }
255
256 bool hasOptions() const {
257 for (const auto &S : RegisteredSubCommands) {
258 if (hasOptions(*S))
259 return true;
260 }
261 return false;
262 }
263
264 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
265
266 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
267 SubCommand &Sub = *SC;
268 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000269 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
270 << "' registered more than once!\n";
271 report_fatal_error("inconsistency in registered CommandLine options");
272 }
Zachary Turner07670b32016-06-29 21:48:26 +0000273 Sub.OptionsMap.erase(O->ArgStr);
274 }
275
276 void updateArgStr(Option *O, StringRef NewName) {
277 if (O->Subs.empty())
278 updateArgStr(O, NewName, &*TopLevelSubCommand);
279 else {
280 for (auto SC : O->Subs)
281 updateArgStr(O, NewName, SC);
282 }
Chris Bienemand1d94302015-01-28 19:00:25 +0000283 }
Chris Bienemand77bbab2015-01-30 22:16:01 +0000284
285 void printOptionValues();
Chris Bieneman542f56a2015-02-13 22:54:27 +0000286
Chris Bieneman67e426a2015-02-13 22:54:32 +0000287 void registerCategory(OptionCategory *cat) {
Sanjoy Das39c226f2016-06-10 21:18:39 +0000288 assert(count_if(RegisteredOptionCategories,
289 [cat](const OptionCategory *Category) {
290 return cat->getName() == Category->getName();
291 }) == 0 &&
Chris Bieneman67e426a2015-02-13 22:54:32 +0000292 "Duplicate option categories");
293
294 RegisteredOptionCategories.insert(cat);
295 }
296
Zachary Turner07670b32016-06-29 21:48:26 +0000297 void registerSubCommand(SubCommand *sub) {
298 assert(count_if(RegisteredSubCommands,
299 [sub](const SubCommand *Sub) {
Mehdi Aminie11b7452016-10-01 03:43:20 +0000300 return (!sub->getName().empty()) &&
Zachary Turner07670b32016-06-29 21:48:26 +0000301 (Sub->getName() == sub->getName());
302 }) == 0 &&
303 "Duplicate subcommands");
304 RegisteredSubCommands.insert(sub);
305
306 // For all options that have been registered for all subcommands, add the
307 // option to this subcommand now.
308 if (sub != &*AllSubCommands) {
309 for (auto &E : AllSubCommands->OptionsMap) {
310 Option *O = E.second;
311 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
312 O->hasArgStr())
313 addOption(O, sub);
314 else
Mehdi Aminie11b7452016-10-01 03:43:20 +0000315 addLiteralOption(*O, sub, E.first());
Zachary Turner07670b32016-06-29 21:48:26 +0000316 }
317 }
318 }
319
320 void unregisterSubCommand(SubCommand *sub) {
321 RegisteredSubCommands.erase(sub);
322 }
323
Dean Michael Berris27358cf2016-10-05 05:20:08 +0000324 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
325 getRegisteredSubcommands() {
326 return make_range(RegisteredSubCommands.begin(),
327 RegisteredSubCommands.end());
328 }
329
Zachary Turner07670b32016-06-29 21:48:26 +0000330 void reset() {
331 ActiveSubCommand = nullptr;
332 ProgramName.clear();
Mehdi Aminie11b7452016-10-01 03:43:20 +0000333 ProgramOverview = StringRef();
Zachary Turner07670b32016-06-29 21:48:26 +0000334
335 MoreHelp.clear();
336 RegisteredOptionCategories.clear();
337
338 ResetAllOptionOccurrences();
339 RegisteredSubCommands.clear();
340
341 TopLevelSubCommand->reset();
342 AllSubCommands->reset();
343 registerSubCommand(&*TopLevelSubCommand);
344 registerSubCommand(&*AllSubCommands);
345 }
346
Chris Bieneman542f56a2015-02-13 22:54:27 +0000347private:
Zachary Turner07670b32016-06-29 21:48:26 +0000348 SubCommand *ActiveSubCommand;
349
350 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
Mehdi Aminie11b7452016-10-01 03:43:20 +0000351 SubCommand *LookupSubCommand(StringRef Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000352};
353
Benjamin Kramer970eac42015-02-06 17:51:54 +0000354} // namespace
355
Chris Bienemand1d94302015-01-28 19:00:25 +0000356static ManagedStatic<CommandLineParser> GlobalParser;
357
Mehdi Aminie11b7452016-10-01 03:43:20 +0000358void cl::AddLiteralOption(Option &O, StringRef Name) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000359 GlobalParser->addLiteralOption(O, Name);
360}
Chris Lattner37bcd992004-11-19 17:08:15 +0000361
Mehdi Aminie11b7452016-10-01 03:43:20 +0000362extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000363 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000364}
365
Chris Lattner5247f602007-04-06 21:06:55 +0000366void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000367 GlobalParser->addOption(this);
368 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000369}
370
Chris Bienemand1d94302015-01-28 19:00:25 +0000371void Option::removeArgument() { GlobalParser->removeOption(this); }
372
David Blaikieff43d692015-11-17 19:00:52 +0000373void Option::setArgStr(StringRef S) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000374 if (FullyInitialized)
375 GlobalParser->updateArgStr(this, S);
Mehdi Aminie4c7f122017-01-08 22:30:43 +0000376 assert((S.empty() || S[0] != '-') && "Option can't start with '-");
Chris Bienemand1d94302015-01-28 19:00:25 +0000377 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000378}
379
Andrew Trick0537a982013-05-06 21:56:23 +0000380// Initialise the general option category.
381OptionCategory llvm::cl::GeneralCategory("General options");
382
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000383void OptionCategory::registerCategory() {
Chris Bieneman67e426a2015-02-13 22:54:32 +0000384 GlobalParser->registerCategory(this);
Andrew Trick0537a982013-05-06 21:56:23 +0000385}
Chris Lattneraf039c52007-04-12 00:36:29 +0000386
Zachary Turner07670b32016-06-29 21:48:26 +0000387// A special subcommand representing no subcommand
388ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
389
390// A special subcommand that can be used to put an option into all subcommands.
391ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
392
393void SubCommand::registerSubCommand() {
394 GlobalParser->registerSubCommand(this);
395}
396
397void SubCommand::unregisterSubCommand() {
398 GlobalParser->unregisterSubCommand(this);
399}
400
401void SubCommand::reset() {
402 PositionalOpts.clear();
403 SinkOpts.clear();
404 OptionsMap.clear();
405
406 ConsumeAfterOpt = nullptr;
407}
408
409SubCommand::operator bool() const {
410 return (GlobalParser->getActiveSubCommand() == this);
411}
412
Chris Lattner5df56c42002-07-22 02:07:59 +0000413//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000414// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000415//
416
Chris Lattner2031b022007-04-05 21:58:17 +0000417/// LookupOption - Lookup the option specified by the specified option on the
418/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000419/// that as well. This assumes that leading dashes have already been stripped.
Zachary Turner07670b32016-06-29 21:48:26 +0000420Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
421 StringRef &Value) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000422 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000423 if (Arg.empty())
424 return nullptr;
Zachary Turner07670b32016-06-29 21:48:26 +0000425 assert(&Sub != &*AllSubCommands);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000426
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000427 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000428
Chris Lattner0a40a972009-09-20 01:53:12 +0000429 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000430 if (EqualPos == StringRef::npos) {
431 // Look up the option.
Zachary Turner07670b32016-06-29 21:48:26 +0000432 auto I = Sub.OptionsMap.find(Arg);
433 if (I == Sub.OptionsMap.end())
434 return nullptr;
435
436 return I != Sub.OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000437 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000438
Chris Lattnere7c1e212009-09-20 05:03:30 +0000439 // If the argument before the = is a valid option name, we match. If not,
440 // return Arg unmolested.
Zachary Turner07670b32016-06-29 21:48:26 +0000441 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
442 if (I == Sub.OptionsMap.end())
Chris Bieneman5d232242015-01-13 19:14:20 +0000443 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000444
Chris Bieneman5d232242015-01-13 19:14:20 +0000445 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000446 Arg = Arg.substr(0, EqualPos);
447 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000448}
449
Mehdi Aminie11b7452016-10-01 03:43:20 +0000450SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
451 if (Name.empty())
Zachary Turner07670b32016-06-29 21:48:26 +0000452 return &*TopLevelSubCommand;
453 for (auto S : RegisteredSubCommands) {
454 if (S == &*AllSubCommands)
455 continue;
Mehdi Aminie11b7452016-10-01 03:43:20 +0000456 if (S->getName().empty())
Zachary Turner07670b32016-06-29 21:48:26 +0000457 continue;
458
459 if (StringRef(S->getName()) == StringRef(Name))
460 return S;
461 }
462 return &*TopLevelSubCommand;
463}
464
Daniel Dunbarf4132132011-01-18 01:59:24 +0000465/// LookupNearestOption - Lookup the closest match to the option specified by
466/// the specified option on the command line. If there is a value specified
467/// (after an equal sign) return that as well. This assumes that leading dashes
468/// have already been stripped.
469static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000470 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000471 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000472 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000473 if (Arg.empty())
474 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000475
476 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000477 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000478 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000479 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000480
481 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000482 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000483 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000484 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
485 ie = OptionsMap.end();
486 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000487 Option *O = it->second;
David Blaikieff43d692015-11-17 19:00:52 +0000488 SmallVector<StringRef, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000489 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000490 if (O->hasArgStr())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000491 OptionNames.push_back(O->ArgStr);
492
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000493 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
494 StringRef Flag = PermitValue ? LHS : Arg;
David Blaikieff43d692015-11-17 19:00:52 +0000495 for (auto Name : OptionNames) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000496 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000497 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000498 if (!Best || Distance < BestDistance) {
499 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000500 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000501 if (RHS.empty() || !PermitValue)
David Blaikieff43d692015-11-17 19:00:52 +0000502 NearestString = Name;
Bill Wendling318f03f2012-07-19 00:15:11 +0000503 else
David Blaikieff43d692015-11-17 19:00:52 +0000504 NearestString = (Twine(Name) + "=" + RHS).str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000505 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000506 }
507 }
508
509 return Best;
510}
511
Alp Tokercb402912014-01-24 17:20:08 +0000512/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
513/// that does special handling of cl::CommaSeparated options.
514static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
515 StringRef ArgName, StringRef Value,
516 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000517 // Check to see if this option accepts a comma separated list of values. If
518 // it does, we have to split up the value into multiple values.
519 if (Handler->getMiscFlags() & CommaSeparated) {
520 StringRef Val(Value);
521 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000522
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000523 while (Pos != StringRef::npos) {
524 // Process the portion before the comma.
525 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
526 return true;
527 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000528 Val = Val.substr(Pos + 1);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000529 // Check for another comma.
530 Pos = Val.find(',');
531 }
532
533 Value = Val;
534 }
535
Alexander Kornienko66da20a2015-12-28 15:46:15 +0000536 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000537}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000538
Chris Lattner40fef802009-09-20 01:49:31 +0000539/// ProvideOption - For Value, this differentiates between an empty value ("")
540/// and a null value (StringRef()). The later is accepted for arguments that
541/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000542static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000543 StringRef Value, int argc,
544 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000545 // Is this a multi-argument option?
546 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
547
Chris Lattnere81c4092001-10-27 05:54:17 +0000548 // Enforce value requirements
549 switch (Handler->getValueExpectedFlag()) {
550 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000551 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000552 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000553 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000554 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000555 assert(argv && "null check");
Mehdi Aminie11b7452016-10-01 03:43:20 +0000556 Value = StringRef(argv[++i]);
Chris Lattnere81c4092001-10-27 05:54:17 +0000557 }
558 break;
559 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000560 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000561 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000562 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000563
Chris Lattner40fef802009-09-20 01:49:31 +0000564 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000565 return Handler->error("does not allow a value! '" + Twine(Value) +
566 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000567 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000568 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000569 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000570 }
571
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000572 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000573 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000574 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000575
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000576 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000577 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000578
Chris Lattner40fef802009-09-20 01:49:31 +0000579 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000580 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000581 return true;
582 --NumAdditionalVals;
583 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000584 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000585
586 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000587 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000588 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000589 assert(argv && "null check");
Mehdi Aminie11b7452016-10-01 03:43:20 +0000590 Value = StringRef(argv[++i]);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000591
Alp Tokercb402912014-01-24 17:20:08 +0000592 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000593 return true;
594 MultiArg = true;
595 --NumAdditionalVals;
596 }
597 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000598}
599
Chris Lattnerca2552d2009-09-20 00:07:40 +0000600static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000601 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000602 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000603}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000604
Chris Lattner5df56c42002-07-22 02:07:59 +0000605// Option predicates...
606static inline bool isGrouping(const Option *O) {
607 return O->getFormattingFlag() == cl::Grouping;
608}
609static inline bool isPrefixedOrGrouping(const Option *O) {
610 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
611}
612
613// getOptionPred - Check to see if there are any options that satisfy the
614// specified predicate with names that are the prefixes in Name. This is
615// checked by progressively stripping characters off of the name, checking to
616// see if there options that satisfy the predicate. If we find one, return it,
617// otherwise return null.
618//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000619static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000620 bool (*Pred)(const Option *),
621 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000622
Chris Bieneman5d232242015-01-13 19:14:20 +0000623 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000624
Chris Lattnere7c1e212009-09-20 05:03:30 +0000625 // Loop while we haven't found an option and Name still has at least two
626 // characters in it (so that the next iteration will not be the empty
627 // string.
628 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000629 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000630 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000631 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000632
Chris Lattner5247f602007-04-06 21:06:55 +0000633 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000634 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000635 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000636 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000637 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000638}
639
Chris Lattnere7c1e212009-09-20 05:03:30 +0000640/// HandlePrefixedOrGroupedOption - The specified argument string (which started
641/// with at least one '-') does not fully match an available option. Check to
642/// see if this is a prefix or grouped option. If so, split arg into output an
643/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000644static Option *
645HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
646 bool &ErrorParsing,
647 const StringMap<Option *> &OptionsMap) {
648 if (Arg.size() == 1)
649 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000650
651 // Do the lookup!
652 size_t Length = 0;
653 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000654 if (!PGOpt)
655 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000656
Chris Lattnere7c1e212009-09-20 05:03:30 +0000657 // If the option is a prefixed option, then the value is simply the
658 // rest of the name... so fall through to later processing, by
659 // setting up the argument name flags and value fields.
660 if (PGOpt->getFormattingFlag() == cl::Prefix) {
661 Value = Arg.substr(Length);
662 Arg = Arg.substr(0, Length);
663 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
664 return PGOpt;
665 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000666
Chris Lattnere7c1e212009-09-20 05:03:30 +0000667 // This must be a grouped option... handle them now. Grouping options can't
668 // have values.
669 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000670
Chris Lattnere7c1e212009-09-20 05:03:30 +0000671 do {
672 // Move current arg name out of Arg into OneArgName.
673 StringRef OneArgName = Arg.substr(0, Length);
674 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000675
Chris Lattnere7c1e212009-09-20 05:03:30 +0000676 // Because ValueRequired is an invalid flag for grouped arguments,
677 // we don't need to pass argc/argv in.
678 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
679 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000680 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000681 ErrorParsing |=
682 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000683
Chris Lattnere7c1e212009-09-20 05:03:30 +0000684 // Get the next grouping option.
685 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
686 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000687
Chris Lattnere7c1e212009-09-20 05:03:30 +0000688 // Return the last option with Arg cut down to just the last one.
689 return PGOpt;
690}
691
Chris Lattner5df56c42002-07-22 02:07:59 +0000692static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000693 return O->getNumOccurrencesFlag() == cl::Required ||
694 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000695}
696
697static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000698 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
699 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000700}
Chris Lattnere81c4092001-10-27 05:54:17 +0000701
Chris Bieneman5d232242015-01-13 19:14:20 +0000702static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000703
Chris Bieneman5d232242015-01-13 19:14:20 +0000704static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000705
Reid Klecknera73c7782013-07-18 16:52:05 +0000706void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000707 SmallVectorImpl<const char *> &NewArgv,
708 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000709 SmallString<128> Token;
710 for (size_t I = 0, E = Src.size(); I != E; ++I) {
711 // Consume runs of whitespace.
712 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000713 while (I != E && isWhitespace(Src[I])) {
714 // Mark the end of lines in response files
715 if (MarkEOLs && Src[I] == '\n')
716 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000717 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000718 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000719 if (I == E)
720 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000721 }
722
Nico Weberfa7f4892016-04-26 13:53:56 +0000723 // Backslash escapes the next character.
724 if (I + 1 < E && Src[I] == '\\') {
Chris Bieneman5d232242015-01-13 19:14:20 +0000725 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000726 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000727 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000728 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000729
Reid Klecknera73c7782013-07-18 16:52:05 +0000730 // Consume a quoted string.
731 if (isQuote(Src[I])) {
732 char Quote = Src[I++];
733 while (I != E && Src[I] != Quote) {
Nico Weberfa7f4892016-04-26 13:53:56 +0000734 // Backslash escapes the next character.
735 if (Src[I] == '\\' && I + 1 != E)
Reid Klecknera73c7782013-07-18 16:52:05 +0000736 ++I;
737 Token.push_back(Src[I]);
738 ++I;
739 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000740 if (I == E)
741 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000742 continue;
743 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000744
Reid Klecknera73c7782013-07-18 16:52:05 +0000745 // End the token if this is whitespace.
746 if (isWhitespace(Src[I])) {
747 if (!Token.empty())
Mehdi Aminiec4fb5b2016-10-05 01:32:41 +0000748 NewArgv.push_back(Saver.save(StringRef(Token)).data());
Reid Klecknera73c7782013-07-18 16:52:05 +0000749 Token.clear();
750 continue;
751 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000752
Reid Klecknera73c7782013-07-18 16:52:05 +0000753 // This is a normal character. Append it.
754 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000755 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000756
757 // Append the last token after hitting EOF with no whitespace.
758 if (!Token.empty())
Mehdi Aminiec4fb5b2016-10-05 01:32:41 +0000759 NewArgv.push_back(Saver.save(StringRef(Token)).data());
Reid Klecknere3f146d2014-08-22 19:29:17 +0000760 // Mark the end of response files
761 if (MarkEOLs)
762 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000763}
764
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000765/// Backslashes are interpreted in a rather complicated way in the Windows-style
766/// command line, because backslashes are used both to separate path and to
767/// escape double quote. This method consumes runs of backslashes as well as the
768/// following double quote if it's escaped.
769///
770/// * If an even number of backslashes is followed by a double quote, one
771/// backslash is output for every pair of backslashes, and the last double
772/// quote remains unconsumed. The double quote will later be interpreted as
773/// the start or end of a quoted string in the main loop outside of this
774/// function.
775///
776/// * If an odd number of backslashes is followed by a double quote, one
777/// backslash is output for every pair of backslashes, and a double quote is
778/// output for the last pair of backslash-double quote. The double quote is
779/// consumed in this case.
780///
781/// * Otherwise, backslashes are interpreted literally.
782static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
783 size_t E = Src.size();
784 int BackslashCount = 0;
785 // Skip the backslashes.
786 do {
787 ++I;
788 ++BackslashCount;
789 } while (I != E && Src[I] == '\\');
790
791 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
792 if (FollowedByDoubleQuote) {
793 Token.append(BackslashCount / 2, '\\');
794 if (BackslashCount % 2 == 0)
795 return I - 1;
796 Token.push_back('"');
797 return I;
798 }
799 Token.append(BackslashCount, '\\');
800 return I - 1;
801}
802
Reid Klecknera73c7782013-07-18 16:52:05 +0000803void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000804 SmallVectorImpl<const char *> &NewArgv,
805 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000806 SmallString<128> Token;
807
808 // This is a small state machine to consume characters until it reaches the
809 // end of the source string.
810 enum { INIT, UNQUOTED, QUOTED } State = INIT;
811 for (size_t I = 0, E = Src.size(); I != E; ++I) {
812 // INIT state indicates that the current input index is at the start of
813 // the string or between tokens.
814 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000815 if (isWhitespace(Src[I])) {
816 // Mark the end of lines in response files
817 if (MarkEOLs && Src[I] == '\n')
818 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000819 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000820 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000821 if (Src[I] == '"') {
822 State = QUOTED;
823 continue;
824 }
825 if (Src[I] == '\\') {
826 I = parseBackslash(Src, I, Token);
827 State = UNQUOTED;
828 continue;
829 }
830 Token.push_back(Src[I]);
831 State = UNQUOTED;
832 continue;
833 }
834
835 // UNQUOTED state means that it's reading a token not quoted by double
836 // quotes.
837 if (State == UNQUOTED) {
838 // Whitespace means the end of the token.
839 if (isWhitespace(Src[I])) {
Mehdi Aminiec4fb5b2016-10-05 01:32:41 +0000840 NewArgv.push_back(Saver.save(StringRef(Token)).data());
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000841 Token.clear();
842 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000843 // Mark the end of lines in response files
844 if (MarkEOLs && Src[I] == '\n')
845 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000846 continue;
847 }
848 if (Src[I] == '"') {
849 State = QUOTED;
850 continue;
851 }
852 if (Src[I] == '\\') {
853 I = parseBackslash(Src, I, Token);
854 continue;
855 }
856 Token.push_back(Src[I]);
857 continue;
858 }
859
860 // QUOTED state means that it's reading a token quoted by double quotes.
861 if (State == QUOTED) {
862 if (Src[I] == '"') {
863 State = UNQUOTED;
864 continue;
865 }
866 if (Src[I] == '\\') {
867 I = parseBackslash(Src, I, Token);
868 continue;
869 }
870 Token.push_back(Src[I]);
871 }
872 }
873 // Append the last token after hitting EOF with no whitespace.
874 if (!Token.empty())
Mehdi Aminiec4fb5b2016-10-05 01:32:41 +0000875 NewArgv.push_back(Saver.save(StringRef(Token)).data());
Reid Klecknere3f146d2014-08-22 19:29:17 +0000876 // Mark the end of response files
877 if (MarkEOLs)
878 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000879}
880
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000881// It is called byte order marker but the UTF-8 BOM is actually not affected
882// by the host system's endianness.
883static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
Chris Bienemanceaf5f62015-02-13 22:54:29 +0000884 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000885}
886
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000887static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
Reid Klecknera73c7782013-07-18 16:52:05 +0000888 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000889 SmallVectorImpl<const char *> &NewArgv,
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000890 bool MarkEOLs, bool RelativeNames) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000891 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
892 MemoryBuffer::getFile(FName);
893 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000894 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000895 MemoryBuffer &MemBuf = *MemBufOrErr.get();
896 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000897
898 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000899 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000900 std::string UTF8Buf;
901 if (hasUTF16ByteOrderMark(BufRef)) {
902 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
903 return false;
904 Str = StringRef(UTF8Buf);
905 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000906 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
907 // these bytes before parsing.
908 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
909 else if (hasUTF8ByteOrderMark(BufRef))
910 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000911
912 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000913 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000914
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000915 // If names of nested response files should be resolved relative to including
916 // file, replace the included response file names with their full paths
917 // obtained by required resolution.
918 if (RelativeNames)
919 for (unsigned I = 0; I < NewArgv.size(); ++I)
920 if (NewArgv[I]) {
921 StringRef Arg = NewArgv[I];
922 if (Arg.front() == '@') {
923 StringRef FileName = Arg.drop_front();
924 if (llvm::sys::path::is_relative(FileName)) {
925 SmallString<128> ResponseFile;
926 ResponseFile.append(1, '@');
Serge Pavlovf258ff12016-11-20 06:25:07 +0000927 if (llvm::sys::path::is_relative(FName)) {
928 SmallString<128> curr_dir;
929 llvm::sys::fs::current_path(curr_dir);
930 ResponseFile.append(curr_dir.str());
931 }
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000932 llvm::sys::path::append(
933 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
934 NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
935 }
936 }
937 }
938
Reid Klecknera73c7782013-07-18 16:52:05 +0000939 return true;
940}
941
942/// \brief Expand response files on a command line recursively using the given
943/// StringSaver and tokenization strategy.
944bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000945 SmallVectorImpl<const char *> &Argv,
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000946 bool MarkEOLs, bool RelativeNames) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000947 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000948 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000949
950 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000951 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000952 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000953 // Check if it is an EOL marker
954 if (Arg == nullptr) {
955 ++I;
956 continue;
957 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000958 if (Arg[0] != '@') {
959 ++I;
960 continue;
961 }
962
963 // If we have too many response files, leave some unexpanded. This avoids
964 // crashing on self-referential response files.
965 if (RspFiles++ > 20)
966 return false;
967
968 // Replace this response file argument with the tokenization of its
969 // contents. Nested response files are expanded in subsequent iterations.
Reid Klecknera73c7782013-07-18 16:52:05 +0000970 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000971 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
Serge Pavlov6ac8e032016-11-01 06:53:29 +0000972 MarkEOLs, RelativeNames)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000973 // We couldn't read this file, so we leave it in the argument stream and
974 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000975 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000976 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000977 continue;
978 }
979 Argv.erase(Argv.begin() + I);
980 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
981 }
982 return AllExpanded;
983}
984
Brian Gaekeca782d92003-08-14 22:00:59 +0000985/// ParseEnvironmentOptions - An alternative entry point to the
986/// CommandLine library, which allows you to read the program's name
987/// from the caller (as PROGNAME) and its command-line arguments from
988/// an environment variable (whose name is given in ENVVAR).
989///
Chris Lattnera60f3552004-05-06 22:04:31 +0000990void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000991 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000992 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000993 assert(progName && "Program name not specified");
994 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000995
Brian Gaeke497216d2003-08-15 21:05:57 +0000996 // Get the environment variable they want us to parse options out of.
Mehdi Aminie11b7452016-10-01 03:43:20 +0000997 llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
Brian Gaeke497216d2003-08-15 21:05:57 +0000998 if (!envValue)
999 return;
1000
Brian Gaekeca782d92003-08-14 22:00:59 +00001001 // Get program's "name", which we wouldn't know without the caller
1002 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +00001003 SmallVector<const char *, 20> newArgv;
Rafael Espindola454adf62015-06-13 12:49:52 +00001004 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +00001005 StringSaver Saver(A);
Mehdi Aminiec4fb5b2016-10-05 01:32:41 +00001006 newArgv.push_back(Saver.save(progName).data());
Brian Gaekeca782d92003-08-14 22:00:59 +00001007
1008 // Parse the value of the environment variable into a "command line"
1009 // and hand it off to ParseCommandLineOptions().
David Majnemerafb38af2016-07-24 17:19:59 +00001010 TokenizeGNUCommandLine(*envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +00001011 int newArgc = static_cast<int>(newArgv.size());
Mehdi Aminie11b7452016-10-01 03:43:20 +00001012 ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001013}
1014
Zachary Turner07670b32016-06-29 21:48:26 +00001015bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
Mehdi Aminie11b7452016-10-01 03:43:20 +00001016 StringRef Overview, bool IgnoreErrors) {
Zachary Turner07670b32016-06-29 21:48:26 +00001017 return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
1018 IgnoreErrors);
Chris Bienemand1d94302015-01-28 19:00:25 +00001019}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001020
Zachary Turner07670b32016-06-29 21:48:26 +00001021void CommandLineParser::ResetAllOptionOccurrences() {
1022 // So that we can parse different command lines multiple times in succession
1023 // we reset all option values to look like they have never been seen before.
1024 for (auto SC : RegisteredSubCommands) {
1025 for (auto &O : SC->OptionsMap)
1026 O.second->reset();
1027 }
1028}
1029
1030bool CommandLineParser::ParseCommandLineOptions(int argc,
Chris Bienemand1d94302015-01-28 19:00:25 +00001031 const char *const *argv,
Mehdi Aminie11b7452016-10-01 03:43:20 +00001032 StringRef Overview,
Zachary Turner07670b32016-06-29 21:48:26 +00001033 bool IgnoreErrors) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001034 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001035
1036 // Expand response files.
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001037 SmallVector<const char *, 20> newArgv(argv, argv + argc);
Rafael Espindola454adf62015-06-13 12:49:52 +00001038 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +00001039 StringSaver Saver(A);
Reid Klecknera73c7782013-07-18 16:52:05 +00001040 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +00001041 argv = &newArgv[0];
1042 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001043
Chris Lattner5af1cbc2006-10-13 00:06:24 +00001044 // Copy the program name into ProgName, making sure not to overflow it.
Mehdi Aminie11b7452016-10-01 03:43:20 +00001045 ProgramName = sys::path::filename(StringRef(argv[0]));
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001046
Chris Lattner36a57d32001-07-23 17:17:47 +00001047 ProgramOverview = Overview;
1048 bool ErrorParsing = false;
1049
Chris Lattner5df56c42002-07-22 02:07:59 +00001050 // Check out the positional arguments to collect information about them.
1051 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001052
Chris Lattnerd380d842005-08-08 17:25:38 +00001053 // Determine whether or not there are an unlimited number of positionals
1054 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001055
Zachary Turner07670b32016-06-29 21:48:26 +00001056 int FirstArg = 1;
1057 SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1058 if (argc >= 2 && argv[FirstArg][0] != '-') {
1059 // If the first argument specifies a valid subcommand, start processing
1060 // options from the second argument.
Mehdi Aminie11b7452016-10-01 03:43:20 +00001061 ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
Zachary Turner07670b32016-06-29 21:48:26 +00001062 if (ChosenSubCommand != &*TopLevelSubCommand)
1063 FirstArg = 2;
1064 }
1065 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1066
1067 assert(ChosenSubCommand);
1068 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1069 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1070 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1071 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1072
Chris Bienemand1d94302015-01-28 19:00:25 +00001073 if (ConsumeAfterOpt) {
1074 assert(PositionalOpts.size() > 0 &&
1075 "Cannot specify cl::ConsumeAfter without a positional argument!");
1076 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001077 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001078
1079 // Calculate how many positional values are _required_.
1080 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +00001081 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001082 Option *Opt = PositionalOpts[i];
1083 if (RequiresValue(Opt))
1084 ++NumPositionalRequired;
1085 else if (ConsumeAfterOpt) {
1086 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +00001087 // unless there is only one positional argument...
Zachary Turner07670b32016-06-29 21:48:26 +00001088 if (PositionalOpts.size() > 1) {
1089 if (!IgnoreErrors)
1090 Opt->error("error - this positional option will never be matched, "
1091 "because it does not Require a value, and a "
1092 "cl::ConsumeAfter option is active!");
1093 ErrorParsing = true;
1094 }
David Blaikieff43d692015-11-17 19:00:52 +00001095 } else if (UnboundedFound && !Opt->hasArgStr()) {
Chris Lattner2da046f2003-07-30 17:34:02 +00001096 // This option does not "require" a value... Make sure this option is
1097 // not specified after an option that eats all extra arguments, or this
1098 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +00001099 //
Zachary Turner07670b32016-06-29 21:48:26 +00001100 if (!IgnoreErrors) {
1101 Opt->error("error - option can never match, because "
1102 "another positional argument will match an "
1103 "unbounded number of values, and this option"
1104 " does not require a value!");
1105 errs() << ProgramName << ": CommandLine Error: Option '"
1106 << Opt->ArgStr << "' is all messed up!\n";
1107 errs() << PositionalOpts.size();
1108 }
1109 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001110 }
1111 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1112 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +00001113 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +00001114 }
1115
Reid Spencer2027a6f2004-08-13 19:47:30 +00001116 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +00001117 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +00001118 //
Chris Bieneman5d232242015-01-13 19:14:20 +00001119 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +00001120
Chris Lattner2da046f2003-07-30 17:34:02 +00001121 // If the program has named positional arguments, and the name has been run
1122 // across, keep track of which positional argument was named. Otherwise put
1123 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +00001124 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001125
Chris Lattner36a57d32001-07-23 17:17:47 +00001126 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +00001127 bool DashDashFound = false; // Have we read '--'?
Zachary Turner07670b32016-06-29 21:48:26 +00001128 for (int i = FirstArg; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +00001129 Option *Handler = nullptr;
1130 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +00001131 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +00001132 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +00001133 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +00001134
1135 // Check to see if this is a positional argument. This argument is
1136 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +00001137 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +00001138 //
1139 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1140 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +00001141 if (ActivePositionalArg) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001142 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
Chris Bieneman5d232242015-01-13 19:14:20 +00001143 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001144 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001145
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001146 if (!PositionalOpts.empty()) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001147 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
Chris Lattner5df56c42002-07-22 02:07:59 +00001148
1149 // All of the positional arguments have been fulfulled, give the rest to
1150 // the consume after option... if it's specified...
1151 //
Craig Topper8d399f82014-04-09 04:20:00 +00001152 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001153 for (++i; i < argc; ++i)
Mehdi Aminie11b7452016-10-01 03:43:20 +00001154 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
Chris Bieneman5d232242015-01-13 19:14:20 +00001155 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +00001156 }
1157
1158 // Delay processing positional arguments until the end...
1159 continue;
1160 }
Chris Lattnera60f3552004-05-06 22:04:31 +00001161 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1162 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001163 DashDashFound = true; // This is the mythical "--"?
1164 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +00001165 } else if (ActivePositionalArg &&
1166 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1167 // If there is a positional argument eating options, check to see if this
1168 // option is another positional argument. If so, treat it as an argument,
1169 // otherwise feed it to the eating positional.
Mehdi Aminie11b7452016-10-01 03:43:20 +00001170 ArgName = StringRef(argv[i] + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +00001171 // Eat leading dashes.
1172 while (!ArgName.empty() && ArgName[0] == '-')
1173 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001174
Zachary Turner07670b32016-06-29 21:48:26 +00001175 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
Chris Lattnera60f3552004-05-06 22:04:31 +00001176 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001177 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
Chris Bieneman5d232242015-01-13 19:14:20 +00001178 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +00001179 }
1180
Chris Bieneman5d232242015-01-13 19:14:20 +00001181 } else { // We start with a '-', must be an argument.
Mehdi Aminie11b7452016-10-01 03:43:20 +00001182 ArgName = StringRef(argv[i] + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +00001183 // Eat leading dashes.
1184 while (!ArgName.empty() && ArgName[0] == '-')
1185 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001186
Zachary Turner07670b32016-06-29 21:48:26 +00001187 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001188
Chris Lattnera60f3552004-05-06 22:04:31 +00001189 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +00001190 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +00001191 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1192 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +00001193
1194 // Otherwise, look for the closest available option to report to the user
1195 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +00001196 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001197 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +00001198 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +00001199 }
1200
Craig Topper8d399f82014-04-09 04:20:00 +00001201 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001202 if (SinkOpts.empty()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001203 if (!IgnoreErrors) {
1204 errs() << ProgramName << ": Unknown command line argument '"
1205 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +00001206
Zachary Turner07670b32016-06-29 21:48:26 +00001207 if (NearestHandler) {
1208 // If we know a near match, report it as well.
1209 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
1210 << "'?\n";
1211 }
Daniel Dunbar72d523b2011-01-24 17:27:17 +00001212 }
Daniel Dunbarf4132132011-01-18 01:59:24 +00001213
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001214 ErrorParsing = true;
1215 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +00001216 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1217 E = SinkOpts.end();
1218 I != E; ++I)
Mehdi Aminie11b7452016-10-01 03:43:20 +00001219 (*I)->addOccurrence(i, "", StringRef(argv[i]));
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001220 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001221 continue;
1222 }
1223
Chris Lattner2da046f2003-07-30 17:34:02 +00001224 // If this is a named positional argument, just remember that it is the
1225 // active one...
1226 if (Handler->getFormattingFlag() == cl::Positional)
1227 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001228 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001229 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001230 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001231
Chris Lattner5df56c42002-07-22 02:07:59 +00001232 // Check and handle positional arguments now...
1233 if (NumPositionalRequired > PositionalVals.size()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001234 if (!IgnoreErrors) {
1235 errs() << ProgramName
1236 << ": Not enough positional command line arguments specified!\n"
1237 << "Must specify at least " << NumPositionalRequired
Ying Yi60a3da32016-07-22 10:52:21 +00001238 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1239 << ": See: " << argv[0] << " - help\n";
Zachary Turner07670b32016-06-29 21:48:26 +00001240 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001241
Chris Lattner5df56c42002-07-22 02:07:59 +00001242 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001243 } else if (!HasUnlimitedPositionals &&
1244 PositionalVals.size() > PositionalOpts.size()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001245 if (!IgnoreErrors) {
1246 errs() << ProgramName << ": Too many positional arguments specified!\n"
1247 << "Can specify at most " << PositionalOpts.size()
1248 << " positional arguments: See: " << argv[0] << " -help\n";
1249 }
Chris Lattnerd380d842005-08-08 17:25:38 +00001250 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001251
Craig Topper8d399f82014-04-09 04:20:00 +00001252 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001253 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001254 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1255 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001256 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001257 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001258 PositionalVals[ValNo].second);
1259 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001260 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001261 }
1262
1263 // If we _can_ give this option more arguments, do so now, as long as we
1264 // do not give it values that others need. 'Done' controls whether the
1265 // option even _WANTS_ any more.
1266 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001267 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001268 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001269 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001270 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001271 Done = true; // Optional arguments want _at most_ one value
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001272 LLVM_FALLTHROUGH;
Chris Bieneman5d232242015-01-13 19:14:20 +00001273 case cl::ZeroOrMore: // Zero or more will take all they can get...
1274 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001275 ProvidePositionalOption(PositionalOpts[i],
1276 PositionalVals[ValNo].first,
1277 PositionalVals[ValNo].second);
1278 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001279 break;
1280 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001281 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001282 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001283 }
1284 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001285 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001286 } else {
1287 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1288 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001289 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001290 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001291 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001292 PositionalVals[ValNo].first,
1293 PositionalVals[ValNo].second);
1294 ValNo++;
1295 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001296
1297 // Handle the case where there is just one positional option, and it's
1298 // optional. In this case, we want to give JUST THE FIRST option to the
1299 // positional option and keep the rest for the consume after. The above
1300 // loop would have assigned no values to positional options in this case.
1301 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001302 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1303 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001304 PositionalVals[ValNo].first,
1305 PositionalVals[ValNo].second);
1306 ValNo++;
1307 }
Misha Brukman10468d82005-04-21 22:55:34 +00001308
Chris Lattner5df56c42002-07-22 02:07:59 +00001309 // Handle over all of the rest of the arguments to the
1310 // cl::ConsumeAfter command line option...
1311 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001312 ErrorParsing |=
1313 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1314 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001315 }
1316
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001317 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001318 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001319 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001320 case Required:
1321 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001322 if (Opt.second->getNumOccurrences() == 0) {
1323 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001324 ErrorParsing = true;
1325 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001326 LLVM_FALLTHROUGH;
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001327 default:
1328 break;
1329 }
1330 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001331
Rafael Espindolacf14a382010-11-19 21:14:29 +00001332 // Now that we know if -debug is specified, we can use it.
1333 // Note that if ReadResponseFiles == true, this must be done before the
1334 // memory allocated for the expanded command line is free()d below.
1335 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001336 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1337 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001338
Chris Lattner5df56c42002-07-22 02:07:59 +00001339 // Free all of the memory allocated to the map. Command line options may only
1340 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001341 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001342
1343 // If we had an error processing our arguments, don't let the program execute
Zachary Turner07670b32016-06-29 21:48:26 +00001344 if (ErrorParsing) {
1345 if (!IgnoreErrors)
1346 exit(1);
1347 return false;
1348 }
1349 return true;
Chris Lattner36a57d32001-07-23 17:17:47 +00001350}
1351
1352//===----------------------------------------------------------------------===//
1353// Option Base class implementation
1354//
Chris Lattner36a57d32001-07-23 17:17:47 +00001355
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001356bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001357 if (!ArgName.data())
1358 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001359 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001360 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001361 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001362 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001363
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001364 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001365 return true;
1366}
1367
Chris Bieneman5d232242015-01-13 19:14:20 +00001368bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1369 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001370 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001371 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001372
Misha Brukman069e6b52003-07-10 16:49:51 +00001373 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001374 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001375 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001376 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001377 break;
1378 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001379 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001380 return error("must occur exactly one time!", ArgName);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001381 LLVM_FALLTHROUGH;
Chris Lattner36a57d32001-07-23 17:17:47 +00001382 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001383 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001384 case ConsumeAfter:
1385 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001386 }
1387
Reid Spencer2027a6f2004-08-13 19:47:30 +00001388 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001389}
1390
Chris Lattner5df56c42002-07-22 02:07:59 +00001391// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1392// has been specified yet.
1393//
David Blaikieff43d692015-11-17 19:00:52 +00001394static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1395 if (O.ValueStr.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001396 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001397 return O.ValueStr;
1398}
1399
1400//===----------------------------------------------------------------------===//
1401// cl::alias class implementation
1402//
1403
Chris Lattner36a57d32001-07-23 17:17:47 +00001404// Return the width of the option tag for printing...
David Blaikieff43d692015-11-17 19:00:52 +00001405size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001406
Daniel Berlin25f1db12017-02-19 04:28:56 +00001407void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1408 size_t FirstLineIndentedBy) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001409 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1410 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1411 while (!Split.second.empty()) {
1412 Split = Split.second.split('\n');
1413 outs().indent(Indent) << Split.first << "\n";
1414 }
1415}
1416
Chris Lattner1b7a5152006-04-28 05:36:25 +00001417// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001418void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001419 outs() << " -" << ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001420 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001421}
1422
Chris Lattner36a57d32001-07-23 17:17:47 +00001423//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001424// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001425//
1426
Chris Lattnerb4101b12002-08-07 18:36:37 +00001427// basic_parser implementation
1428//
1429
1430// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001431size_t basic_parser_impl::getOptionWidth(const Option &O) const {
David Blaikieff43d692015-11-17 19:00:52 +00001432 size_t Len = O.ArgStr.size();
Mehdi Aminie11b7452016-10-01 03:43:20 +00001433 auto ValName = getValueName();
1434 if (!ValName.empty())
David Blaikieff43d692015-11-17 19:00:52 +00001435 Len += getValueStr(O, ValName).size() + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001436
1437 return Len + 6;
1438}
1439
Misha Brukman10468d82005-04-21 22:55:34 +00001440// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001441// to-be-maintained width is specified.
1442//
1443void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001444 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001445 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001446
Mehdi Aminie11b7452016-10-01 03:43:20 +00001447 auto ValName = getValueName();
1448 if (!ValName.empty())
Chris Lattner471ba482009-08-23 08:43:55 +00001449 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001450
Daniel Berlin25f1db12017-02-19 04:28:56 +00001451 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001452}
1453
Andrew Trick12004012011-04-05 18:54:36 +00001454void basic_parser_impl::printOptionName(const Option &O,
1455 size_t GlobalWidth) const {
1456 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001457 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001458}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001459
Chris Lattner5df56c42002-07-22 02:07:59 +00001460// parser<bool> implementation
1461//
Chris Bieneman5d232242015-01-13 19:14:20 +00001462bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1463 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001464 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001465 Arg == "1") {
1466 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001467 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001468 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001469
Chris Lattneraecd74d2009-09-19 18:55:05 +00001470 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1471 Value = false;
1472 return false;
1473 }
1474 return O.error("'" + Arg +
1475 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001476}
1477
Dale Johannesen82810c82007-05-22 17:14:46 +00001478// parser<boolOrDefault> implementation
1479//
Chris Bieneman5d232242015-01-13 19:14:20 +00001480bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1481 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001482 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1483 Arg == "1") {
1484 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001485 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001486 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001487 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1488 Value = BOU_FALSE;
1489 return false;
1490 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001491
Chris Lattneraecd74d2009-09-19 18:55:05 +00001492 return O.error("'" + Arg +
1493 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001494}
1495
Chris Lattner5df56c42002-07-22 02:07:59 +00001496// parser<int> implementation
1497//
Chris Bieneman5d232242015-01-13 19:14:20 +00001498bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1499 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001500 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001501 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001502 return false;
1503}
1504
Chris Lattner719c7152003-06-28 15:47:20 +00001505// parser<unsigned> implementation
1506//
Chris Bieneman5d232242015-01-13 19:14:20 +00001507bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1508 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001509
1510 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001511 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001512 return false;
1513}
1514
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001515// parser<unsigned long long> implementation
1516//
1517bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001518 StringRef Arg,
1519 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001520
1521 if (Arg.getAsInteger(0, Value))
1522 return O.error("'" + Arg + "' value invalid for uint argument!");
1523 return false;
1524}
1525
Chris Lattnerb4101b12002-08-07 18:36:37 +00001526// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001527//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001528static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001529 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1530 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001531 char *End;
1532 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001533 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001534 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001535 return false;
1536}
1537
Chris Bieneman5d232242015-01-13 19:14:20 +00001538bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1539 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001540 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001541}
1542
Chris Bieneman5d232242015-01-13 19:14:20 +00001543bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1544 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001545 double dVal;
1546 if (parseDouble(O, Arg, dVal))
1547 return true;
1548 Val = (float)dVal;
1549 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001550}
1551
Chris Lattner5df56c42002-07-22 02:07:59 +00001552// generic_parser_base implementation
1553//
1554
Chris Lattner494c0b02002-07-23 17:15:12 +00001555// findOption - Return the option number corresponding to the specified
1556// argument string. If the option is not found, getNumOptions() is returned.
1557//
Mehdi Aminie11b7452016-10-01 03:43:20 +00001558unsigned generic_parser_base::findOption(StringRef Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001559 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001560
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001561 for (unsigned i = 0; i != e; ++i) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001562 if (getOption(i) == Name)
Chris Lattner494c0b02002-07-23 17:15:12 +00001563 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001564 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001565 return e;
1566}
1567
Chris Lattner5df56c42002-07-22 02:07:59 +00001568// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001569size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001570 if (O.hasArgStr()) {
David Blaikieff43d692015-11-17 19:00:52 +00001571 size_t Size = O.ArgStr.size() + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001572 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Mehdi Aminie11b7452016-10-01 03:43:20 +00001573 Size = std::max(Size, getOption(i).size() + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001574 return Size;
1575 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001576 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001577 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Mehdi Aminie11b7452016-10-01 03:43:20 +00001578 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001579 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001580 }
1581}
1582
Misha Brukman10468d82005-04-21 22:55:34 +00001583// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001584// to-be-maintained width is specified.
1585//
1586void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001587 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001588 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001589 outs() << " -" << O.ArgStr;
Daniel Berlin25f1db12017-02-19 04:28:56 +00001590 Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001591
Chris Lattner5df56c42002-07-22 02:07:59 +00001592 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001593 size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001594 outs() << " =" << getOption(i);
1595 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001596 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001597 } else {
David Blaikieff43d692015-11-17 19:00:52 +00001598 if (!O.HelpStr.empty())
Chris Lattnere7c1e212009-09-20 05:03:30 +00001599 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001600 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001601 auto Option = getOption(i);
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001602 outs() << " -" << Option;
Daniel Berlin25f1db12017-02-19 04:28:56 +00001603 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001604 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001605 }
1606}
1607
Andrew Trick12004012011-04-05 18:54:36 +00001608static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1609
1610// printGenericOptionDiff - Print the value of this option and it's default.
1611//
1612// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001613void generic_parser_base::printGenericOptionDiff(
1614 const Option &O, const GenericOptionValue &Value,
1615 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001616 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001617 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001618
1619 unsigned NumOpts = getNumOptions();
1620 for (unsigned i = 0; i != NumOpts; ++i) {
1621 if (Value.compare(getOptionValue(i)))
1622 continue;
1623
1624 outs() << "= " << getOption(i);
Mehdi Aminie11b7452016-10-01 03:43:20 +00001625 size_t L = getOption(i).size();
Andrew Trick12004012011-04-05 18:54:36 +00001626 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1627 outs().indent(NumSpaces) << " (default: ";
1628 for (unsigned j = 0; j != NumOpts; ++j) {
1629 if (Default.compare(getOptionValue(j)))
1630 continue;
1631 outs() << getOption(j);
1632 break;
1633 }
1634 outs() << ")\n";
1635 return;
1636 }
1637 outs() << "= *unknown option value*\n";
1638}
1639
1640// printOptionDiff - Specializations for printing basic value types.
1641//
Chris Bieneman5d232242015-01-13 19:14:20 +00001642#define PRINT_OPT_DIFF(T) \
1643 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1644 size_t GlobalWidth) const { \
1645 printOptionName(O, GlobalWidth); \
1646 std::string Str; \
1647 { \
1648 raw_string_ostream SS(Str); \
1649 SS << V; \
1650 } \
1651 outs() << "= " << Str; \
1652 size_t NumSpaces = \
1653 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1654 outs().indent(NumSpaces) << " (default: "; \
1655 if (D.hasValue()) \
1656 outs() << D.getValue(); \
1657 else \
1658 outs() << "*no default*"; \
1659 outs() << ")\n"; \
1660 }
Andrew Trick12004012011-04-05 18:54:36 +00001661
Frits van Bommel87e33672011-04-06 12:29:56 +00001662PRINT_OPT_DIFF(bool)
1663PRINT_OPT_DIFF(boolOrDefault)
1664PRINT_OPT_DIFF(int)
1665PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001666PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001667PRINT_OPT_DIFF(double)
1668PRINT_OPT_DIFF(float)
1669PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001670
Chris Bieneman5d232242015-01-13 19:14:20 +00001671void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
Benjamin Kramerc321e532016-06-08 19:09:22 +00001672 const OptionValue<std::string> &D,
Chris Bieneman5d232242015-01-13 19:14:20 +00001673 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001674 printOptionName(O, GlobalWidth);
1675 outs() << "= " << V;
1676 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1677 outs().indent(NumSpaces) << " (default: ";
1678 if (D.hasValue())
1679 outs() << D.getValue();
1680 else
1681 outs() << "*no default*";
1682 outs() << ")\n";
1683}
1684
1685// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001686void basic_parser_impl::printOptionNoValue(const Option &O,
1687 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001688 printOptionName(O, GlobalWidth);
1689 outs() << "= *cannot print option value*\n";
1690}
Chris Lattner36a57d32001-07-23 17:17:47 +00001691
1692//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001693// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001694//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001695
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001696static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1697 const std::pair<const char *, Option *> *RHS) {
1698 return strcmp(LHS->first, RHS->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001699}
1700
Zachary Turner07670b32016-06-29 21:48:26 +00001701static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1702 const std::pair<const char *, SubCommand *> *RHS) {
1703 return strcmp(LHS->first, RHS->first);
1704}
1705
Andrew Trick12004012011-04-05 18:54:36 +00001706// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001707static void sortOpts(StringMap<Option *> &OptMap,
1708 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1709 bool ShowHidden) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001710 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001711
Chris Bieneman5d232242015-01-13 19:14:20 +00001712 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001713 I != E; ++I) {
1714 // Ignore really-hidden options.
1715 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1716 continue;
1717
1718 // Unless showhidden is set, ignore hidden flags.
1719 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1720 continue;
1721
1722 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001723 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001724 continue;
1725
Chris Bieneman5d232242015-01-13 19:14:20 +00001726 Opts.push_back(
1727 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001728 }
1729
1730 // Sort the options list alphabetically.
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001731 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
Andrew Trick12004012011-04-05 18:54:36 +00001732}
1733
Zachary Turner07670b32016-06-29 21:48:26 +00001734static void
1735sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1736 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1737 for (const auto &S : SubMap) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001738 if (S->getName().empty())
Zachary Turner07670b32016-06-29 21:48:26 +00001739 continue;
Mehdi Aminie11b7452016-10-01 03:43:20 +00001740 Subs.push_back(std::make_pair(S->getName().data(), S));
Zachary Turner07670b32016-06-29 21:48:26 +00001741 }
1742 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1743}
1744
Chris Lattner36a57d32001-07-23 17:17:47 +00001745namespace {
1746
Chris Lattner5df56c42002-07-22 02:07:59 +00001747class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001748protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001749 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001750 typedef SmallVector<std::pair<const char *, Option *>, 128>
1751 StrOptionPairVector;
Zachary Turner07670b32016-06-29 21:48:26 +00001752 typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1753 StrSubCommandPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001754 // Print the options. Opts is assumed to be alphabetically sorted.
1755 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1756 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1757 Opts[i].second->printOptionInfo(MaxArgLen);
1758 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001759
Zachary Turner07670b32016-06-29 21:48:26 +00001760 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1761 for (const auto &S : Subs) {
1762 outs() << " " << S.first;
Mehdi Aminie11b7452016-10-01 03:43:20 +00001763 if (!S.second->getDescription().empty()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001764 outs().indent(MaxSubLen - strlen(S.first));
1765 outs() << " - " << S.second->getDescription();
1766 }
1767 outs() << "\n";
1768 }
1769 }
1770
Chris Lattner5df56c42002-07-22 02:07:59 +00001771public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001772 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001773 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001774
Andrew Trick0537a982013-05-06 21:56:23 +00001775 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001776 void operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001777 if (!Value)
Chris Bieneman5d232242015-01-13 19:14:20 +00001778 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001779
Zachary Turner07670b32016-06-29 21:48:26 +00001780 SubCommand *Sub = GlobalParser->getActiveSubCommand();
1781 auto &OptionsMap = Sub->OptionsMap;
1782 auto &PositionalOpts = Sub->PositionalOpts;
1783 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1784
Andrew Trick0537a982013-05-06 21:56:23 +00001785 StrOptionPairVector Opts;
Zachary Turner07670b32016-06-29 21:48:26 +00001786 sortOpts(OptionsMap, Opts, ShowHidden);
1787
1788 StrSubCommandPairVector Subs;
1789 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
Chris Lattner36a57d32001-07-23 17:17:47 +00001790
Mehdi Aminie11b7452016-10-01 03:43:20 +00001791 if (!GlobalParser->ProgramOverview.empty())
Chris Bienemand1d94302015-01-28 19:00:25 +00001792 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001793
Zachary Turner79f33332016-10-11 15:58:48 +00001794 if (Sub == &*TopLevelSubCommand) {
1795 outs() << "USAGE: " << GlobalParser->ProgramName;
1796 if (Subs.size() > 2)
1797 outs() << " [subcommand]";
1798 outs() << " [options]";
1799 } else {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001800 if (!Sub->getDescription().empty()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001801 outs() << "SUBCOMMAND '" << Sub->getName()
1802 << "': " << Sub->getDescription() << "\n\n";
1803 }
1804 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1805 << " [options]";
1806 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001807
Zachary Turner07670b32016-06-29 21:48:26 +00001808 for (auto Opt : PositionalOpts) {
David Blaikieff43d692015-11-17 19:00:52 +00001809 if (Opt->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +00001810 outs() << " --" << Opt->ArgStr;
1811 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001812 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001813
1814 // Print the consume after option info if it exists...
Zachary Turner07670b32016-06-29 21:48:26 +00001815 if (ConsumeAfterOpt)
1816 outs() << " " << ConsumeAfterOpt->HelpStr;
1817
Alex Lorenzd6802872016-10-12 10:04:35 +00001818 if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
Zachary Turner07670b32016-06-29 21:48:26 +00001819 // Compute the maximum subcommand length...
1820 size_t MaxSubLen = 0;
1821 for (size_t i = 0, e = Subs.size(); i != e; ++i)
1822 MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1823
1824 outs() << "\n\n";
1825 outs() << "SUBCOMMANDS:\n\n";
1826 printSubCommands(Subs, MaxSubLen);
1827 outs() << "\n";
1828 outs() << " Type \"" << GlobalParser->ProgramName
1829 << " <subcommand> -help\" to get more help on a specific "
1830 "subcommand";
1831 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001832
Chris Lattner471ba482009-08-23 08:43:55 +00001833 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001834
1835 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001836 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001837 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001838 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001839
Chris Lattner471ba482009-08-23 08:43:55 +00001840 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001841 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001842
Chris Lattner37bcd992004-11-19 17:08:15 +00001843 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001844 for (auto I : GlobalParser->MoreHelp)
1845 outs() << I;
1846 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001847
Reid Spencer5e554702004-11-16 06:11:52 +00001848 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001849 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001850 }
1851};
Andrew Trick0537a982013-05-06 21:56:23 +00001852
1853class CategorizedHelpPrinter : public HelpPrinter {
1854public:
1855 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1856
1857 // Helper function for printOptions().
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001858 // It shall return a negative value if A's name should be lexicographically
1859 // ordered before B's name. It returns a value greater equal zero otherwise.
1860 static int OptionCategoryCompare(OptionCategory *const *A,
1861 OptionCategory *const *B) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00001862 return (*A)->getName() == (*B)->getName();
Andrew Trick0537a982013-05-06 21:56:23 +00001863 }
1864
1865 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001866 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001867
1868protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001869 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001870 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001871 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001872
Alp Tokercb402912014-01-24 17:20:08 +00001873 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001874 // sorting.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001875 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1876 E = GlobalParser->RegisteredOptionCategories.end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001877 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001878 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001879 }
Andrew Trick0537a982013-05-06 21:56:23 +00001880
1881 // Sort the different option categories alphabetically.
1882 assert(SortedCategories.size() > 0 && "No option categories registered!");
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001883 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1884 OptionCategoryCompare);
Andrew Trick0537a982013-05-06 21:56:23 +00001885
1886 // Create map to empty vectors.
1887 for (std::vector<OptionCategory *>::const_iterator
1888 I = SortedCategories.begin(),
1889 E = SortedCategories.end();
1890 I != E; ++I)
1891 CategorizedOptions[*I] = std::vector<Option *>();
1892
1893 // Walk through pre-sorted options and assign into categories.
1894 // Because the options are already alphabetically sorted the
1895 // options within categories will also be alphabetically sorted.
1896 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1897 Option *Opt = Opts[I].second;
1898 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1899 "Option has an unregistered category");
1900 CategorizedOptions[Opt->Category].push_back(Opt);
1901 }
1902
1903 // Now do printing.
1904 for (std::vector<OptionCategory *>::const_iterator
1905 Category = SortedCategories.begin(),
1906 E = SortedCategories.end();
1907 Category != E; ++Category) {
1908 // Hide empty categories for -help, but show for -help-hidden.
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001909 const auto &CategoryOptions = CategorizedOptions[*Category];
1910 bool IsEmptyCategory = CategoryOptions.empty();
Andrew Trick0537a982013-05-06 21:56:23 +00001911 if (!ShowHidden && IsEmptyCategory)
1912 continue;
1913
1914 // Print category information.
1915 outs() << "\n";
1916 outs() << (*Category)->getName() << ":\n";
1917
1918 // Check if description is set.
Mehdi Aminie11b7452016-10-01 03:43:20 +00001919 if (!(*Category)->getDescription().empty())
Andrew Trick0537a982013-05-06 21:56:23 +00001920 outs() << (*Category)->getDescription() << "\n\n";
1921 else
1922 outs() << "\n";
1923
1924 // When using -help-hidden explicitly state if the category has no
1925 // options associated with it.
1926 if (IsEmptyCategory) {
1927 outs() << " This option category has no options.\n";
1928 continue;
1929 }
1930 // Loop over the options in the category and print.
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001931 for (const Option *Opt : CategoryOptions)
1932 Opt->printOptionInfo(MaxArgLen);
Andrew Trick0537a982013-05-06 21:56:23 +00001933 }
1934 }
1935};
1936
1937// This wraps the Uncategorizing and Categorizing printers and decides
1938// at run time which should be invoked.
1939class HelpPrinterWrapper {
1940private:
1941 HelpPrinter &UncategorizedPrinter;
1942 CategorizedHelpPrinter &CategorizedPrinter;
1943
1944public:
1945 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001946 CategorizedHelpPrinter &CategorizedPrinter)
1947 : UncategorizedPrinter(UncategorizedPrinter),
1948 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001949
1950 // Invoke the printer.
1951 void operator=(bool Value);
1952};
1953
Chris Lattneradb19d62006-10-12 22:09:17 +00001954} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001955
Andrew Trick0537a982013-05-06 21:56:23 +00001956// Declare the four HelpPrinter instances that are used to print out help, or
1957// help-hidden as an uncategorized list or in categories.
1958static HelpPrinter UncategorizedNormalPrinter(false);
1959static HelpPrinter UncategorizedHiddenPrinter(true);
1960static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1961static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1962
Andrew Trick0537a982013-05-06 21:56:23 +00001963// Declare HelpPrinter wrappers that will decide whether or not to invoke
1964// a categorizing help printer
1965static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1966 CategorizedNormalPrinter);
1967static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1968 CategorizedHiddenPrinter);
1969
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001970// Define a category for generic options that all tools should have.
1971static cl::OptionCategory GenericCategory("Generic Options");
1972
Andrew Trick0537a982013-05-06 21:56:23 +00001973// Define uncategorized help printers.
1974// -help-list is hidden by default because if Option categories are being used
1975// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001976static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1977 "help-list",
1978 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001979 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001980 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Chris Lattner5df56c42002-07-22 02:07:59 +00001981
Chris Bieneman5d232242015-01-13 19:14:20 +00001982static cl::opt<HelpPrinter, true, parser<bool>>
1983 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1984 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Zachary Turner07670b32016-06-29 21:48:26 +00001985 cl::ValueDisallowed, cl::cat(GenericCategory),
1986 cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00001987
1988// Define uncategorized/categorized help printers. These printers change their
1989// behaviour at runtime depending on whether one or more Option categories have
1990// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001991static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1992 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001993 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001994 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Chris Lattner5df56c42002-07-22 02:07:59 +00001995
Chris Bieneman5d232242015-01-13 19:14:20 +00001996static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1997 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001998 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
Zachary Turner07670b32016-06-29 21:48:26 +00001999 cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00002000
Chris Bieneman5d232242015-01-13 19:14:20 +00002001static cl::opt<bool> PrintOptions(
2002 "print-options",
2003 cl::desc("Print non-default options after command line parsing"),
Zachary Turner07670b32016-06-29 21:48:26 +00002004 cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2005 cl::sub(*AllSubCommands));
Andrew Trick0537a982013-05-06 21:56:23 +00002006
Chris Bieneman5d232242015-01-13 19:14:20 +00002007static cl::opt<bool> PrintAllOptions(
2008 "print-all-options",
2009 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Zachary Turner07670b32016-06-29 21:48:26 +00002010 cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
Andrew Trick12004012011-04-05 18:54:36 +00002011
Andrew Trick0537a982013-05-06 21:56:23 +00002012void HelpPrinterWrapper::operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002013 if (!Value)
Andrew Trick0537a982013-05-06 21:56:23 +00002014 return;
2015
2016 // Decide which printer to invoke. If more than one option category is
2017 // registered then it is useful to show the categorized help instead of
2018 // uncategorized help.
Chris Bieneman67e426a2015-02-13 22:54:32 +00002019 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
Andrew Trick0537a982013-05-06 21:56:23 +00002020 // unhide -help-list option so user can have uncategorized output if they
2021 // want it.
2022 HLOp.setHiddenFlag(NotHidden);
2023
2024 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00002025 } else
Andrew Trick0537a982013-05-06 21:56:23 +00002026 UncategorizedPrinter = true; // Invoke uncategorized printer
2027}
2028
Andrew Trick12004012011-04-05 18:54:36 +00002029// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00002030void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2031
2032void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00002033 if (!PrintOptions && !PrintAllOptions)
2034 return;
Andrew Trick12004012011-04-05 18:54:36 +00002035
Chris Bieneman5d232242015-01-13 19:14:20 +00002036 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Zachary Turner07670b32016-06-29 21:48:26 +00002037 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00002038
2039 // Compute the maximum argument length...
2040 size_t MaxArgLen = 0;
2041 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2042 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2043
2044 for (size_t i = 0, e = Opts.size(); i != e; ++i)
2045 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2046}
2047
Craig Topperc10719f2014-04-07 04:17:22 +00002048static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00002049
Chris Bieneman5d232242015-01-13 19:14:20 +00002050static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00002051
Chris Lattneradb19d62006-10-12 22:09:17 +00002052namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00002053class VersionPrinter {
2054public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00002055 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00002056 raw_ostream &OS = outs();
Chris Bienemanef43d442016-03-15 18:07:46 +00002057#ifdef PACKAGE_VENDOR
2058 OS << PACKAGE_VENDOR << " ";
2059#else
2060 OS << "LLVM (http://llvm.org/):\n ";
2061#endif
2062 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00002063#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00002064 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00002065#endif
Chris Lattner131dca92009-09-20 06:18:38 +00002066 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002067#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00002068 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002069#else
Chris Lattner131dca92009-09-20 06:18:38 +00002070 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002071#endif
2072#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00002073 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00002074#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00002075 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00002076 if (CPU == "generic")
2077 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00002078 OS << ".\n"
Sebastian Pop94441fb2011-11-01 21:32:20 +00002079 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00002080 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00002081 }
2082 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00002083 if (!OptionWasSpecified)
2084 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00002085
Craig Topperc10719f2014-04-07 04:17:22 +00002086 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00002087 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00002088 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00002089 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00002090 print();
2091
2092 // Iterate over any registered extra printers and call them to add further
2093 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00002094 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00002095 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00002096 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
2097 E = ExtraVersionPrinters->end();
2098 I != E; ++I)
2099 (*I)();
2100 }
2101
Justin Bogner02b95842014-02-28 19:08:01 +00002102 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00002103 }
2104};
Chris Lattneradb19d62006-10-12 22:09:17 +00002105} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00002106
Reid Spencerff6cc122004-08-04 00:36:06 +00002107// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00002108static VersionPrinter VersionPrinterInstance;
2109
Chris Bieneman5d232242015-01-13 19:14:20 +00002110static cl::opt<VersionPrinter, true, parser<bool>>
2111 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00002112 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2113 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00002114
Reid Spencer5e554702004-11-16 06:11:52 +00002115// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00002116void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2117 // This looks weird, but it actually prints the help message. The Printers are
2118 // types of HelpPrinter and the help gets printed when its operator= is
2119 // invoked. That's because the "normal" usages of the help printer is to be
2120 // assigned true/false depending on whether -help or -help-hidden was given or
2121 // not. Since we're circumventing that we have to make it look like -help or
2122 // -help-hidden were given, so we assign true.
2123
2124 if (!Hidden && !Categorized)
2125 UncategorizedNormalPrinter = true;
2126 else if (!Hidden && Categorized)
2127 CategorizedNormalPrinter = true;
2128 else if (Hidden && !Categorized)
2129 UncategorizedHiddenPrinter = true;
2130 else
2131 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00002132}
Reid Spencerb3171672006-06-05 16:22:56 +00002133
Devang Patel9eb2caae2007-02-01 01:43:37 +00002134/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00002135void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00002136
Chris Bieneman5d232242015-01-13 19:14:20 +00002137void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00002138
2139void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00002140 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00002141 ExtraVersionPrinters = new std::vector<void (*)()>;
2142
2143 ExtraVersionPrinters->push_back(func);
2144}
Andrew Trick7cb710d2013-05-06 21:56:35 +00002145
Zachary Turner07670b32016-06-29 21:48:26 +00002146StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2147 auto &Subs = GlobalParser->RegisteredSubCommands;
2148 (void)Subs;
David Majnemer0d955d02016-08-11 22:21:41 +00002149 assert(is_contained(Subs, &Sub));
Zachary Turner07670b32016-06-29 21:48:26 +00002150 return Sub.OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00002151}
Peter Collingbournee1863192014-10-16 22:47:52 +00002152
Dean Michael Berris27358cf2016-10-05 05:20:08 +00002153iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2154cl::getRegisteredSubcommands() {
2155 return GlobalParser->getRegisteredSubcommands();
2156}
2157
Zachary Turner07670b32016-06-29 21:48:26 +00002158void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2159 for (auto &I : Sub.OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00002160 if (I.second->Category != &Category &&
2161 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00002162 I.second->setHiddenFlag(cl::ReallyHidden);
2163 }
2164}
2165
Zachary Turner07670b32016-06-29 21:48:26 +00002166void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2167 SubCommand &Sub) {
Chris Bieneman01043252015-01-26 21:57:29 +00002168 auto CategoriesBegin = Categories.begin();
2169 auto CategoriesEnd = Categories.end();
Zachary Turner07670b32016-06-29 21:48:26 +00002170 for (auto &I : Sub.OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00002171 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2172 CategoriesEnd &&
2173 I.second->Category != &GenericCategory)
2174 I.second->setHiddenFlag(cl::ReallyHidden);
2175 }
2176}
2177
Zachary Turner07670b32016-06-29 21:48:26 +00002178void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2179void cl::ResetAllOptionOccurrences() {
2180 GlobalParser->ResetAllOptionOccurrences();
2181}
2182
Peter Collingbournee1863192014-10-16 22:47:52 +00002183void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2184 const char *Overview) {
Mehdi Aminie11b7452016-10-01 03:43:20 +00002185 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview), true);
Peter Collingbournee1863192014-10-16 22:47:52 +00002186}