blob: 985c8777701509a26c8ad26f7ef8ff1c230ff4c8 [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"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/raw_ostream.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000037#include <map>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000038#include <system_error>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "commandline"
43
Chris Lattner3e5d60f2006-08-27 12:45:47 +000044//===----------------------------------------------------------------------===//
45// Template instantiations and anchors.
46//
Douglas Gregor7baad732009-11-25 06:04:18 +000047namespace llvm { namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000048TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000049TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000050TEMPLATE_INSTANTIATION(class basic_parser<int>);
51TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000052TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000053TEMPLATE_INSTANTIATION(class basic_parser<double>);
54TEMPLATE_INSTANTIATION(class basic_parser<float>);
55TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000056TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000057
58TEMPLATE_INSTANTIATION(class opt<unsigned>);
59TEMPLATE_INSTANTIATION(class opt<int>);
60TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000061TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000062TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor7baad732009-11-25 06:04:18 +000063} } // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000064
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000065// Pin the vtables to this file.
66void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000067void OptionValue<boolOrDefault>::anchor() {}
68void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000069void Option::anchor() {}
70void basic_parser_impl::anchor() {}
71void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000072void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000073void parser<int>::anchor() {}
74void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000075void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000076void parser<double>::anchor() {}
77void parser<float>::anchor() {}
78void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000079void parser<char>::anchor() {}
Sean Silvadb794842014-08-15 23:39:01 +000080void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000081
82//===----------------------------------------------------------------------===//
83
Chris Lattner5af1cbc2006-10-13 00:06:24 +000084// Globals for name and overview of program. Program name is not a string to
85// avoid static ctor/dtor issues.
86static char ProgramName[80] = "<premain>";
Craig Topperc10719f2014-04-07 04:17:22 +000087static const char *ProgramOverview = nullptr;
Reid Spencer9501b9b2004-09-01 04:41:28 +000088
Chris Lattner37bcd992004-11-19 17:08:15 +000089// This collects additional help to be printed.
Chris Lattner8111c592006-10-04 21:52:35 +000090static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000091
Chris Lattner8111c592006-10-04 21:52:35 +000092extrahelp::extrahelp(const char *Help)
Chris Lattner37bcd992004-11-19 17:08:15 +000093 : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000094 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000095}
96
Chris Lattneraf039c52007-04-12 00:36:29 +000097static bool OptionListChanged = false;
98
99// MarkOptionsChanged - Internal helper function.
100void cl::MarkOptionsChanged() {
101 OptionListChanged = true;
102}
103
Chris Lattner5247f602007-04-06 21:06:55 +0000104/// RegisteredOptionList - This is the list of the command line options that
105/// have statically constructed themselves.
Craig Topperc10719f2014-04-07 04:17:22 +0000106static Option *RegisteredOptionList = nullptr;
Chris Lattner5247f602007-04-06 21:06:55 +0000107
108void Option::addArgument() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000109 assert(!NextRegistered && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000110
Chris Lattner5247f602007-04-06 21:06:55 +0000111 NextRegistered = RegisteredOptionList;
112 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000113 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000114}
115
Jordan Rosec25b0c72014-01-29 18:54:17 +0000116void Option::removeArgument() {
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000117 if (RegisteredOptionList == this) {
118 RegisteredOptionList = NextRegistered;
119 MarkOptionsChanged();
120 return;
121 }
122 Option *O = RegisteredOptionList;
123 for (; O->NextRegistered != this; O = O->NextRegistered)
124 ;
125 O->NextRegistered = NextRegistered;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000126 MarkOptionsChanged();
127}
128
Andrew Trick0537a982013-05-06 21:56:23 +0000129// This collects the different option categories that have been registered.
130typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
131static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
132
133// Initialise the general option category.
134OptionCategory llvm::cl::GeneralCategory("General options");
135
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000136void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000137 assert(std::count_if(RegisteredOptionCategories->begin(),
138 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000139 [this](const OptionCategory *Category) {
140 return getName() == Category->getName();
141 }) == 0 && "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000142
Andrew Trick0537a982013-05-06 21:56:23 +0000143 RegisteredOptionCategories->insert(this);
144}
Chris Lattneraf039c52007-04-12 00:36:29 +0000145
Chris Lattner5df56c42002-07-22 02:07:59 +0000146//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000147// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000148//
149
Chris Lattner5247f602007-04-06 21:06:55 +0000150/// GetOptionInfo - Scan the list of registered options, turning them into data
151/// structures that are easier to handle.
Chris Lattner131dca92009-09-20 06:18:38 +0000152static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
153 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000154 StringMap<Option*> &OptionsMap) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000155 bool HadErrors = false;
Chris Lattner56efff07f2009-09-20 06:21:43 +0000156 SmallVector<const char*, 16> OptionNames;
Craig Topperc10719f2014-04-07 04:17:22 +0000157 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000158 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159 // If this option wants to handle multiple option names, get the full set.
160 // This handles enum options like "-O1 -O2" etc.
161 O->getExtraOptionNames(OptionNames);
162 if (O->ArgStr[0])
163 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000164
Chris Lattner5247f602007-04-06 21:06:55 +0000165 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000166 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000167 // Add argument to the argument map!
David Blaikie5106ce72014-11-19 05:49:42 +0000168 if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000169 errs() << ProgramName << ": CommandLine Error: Option '"
170 << OptionNames[i] << "' registered more than once!\n";
171 HadErrors = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000172 }
173 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000174
Chris Lattner5247f602007-04-06 21:06:55 +0000175 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000176
Chris Lattner5247f602007-04-06 21:06:55 +0000177 // Remember information about positional options.
178 if (O->getFormattingFlag() == cl::Positional)
179 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000180 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000181 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000182 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000183 if (CAOpt) {
Chris Lattner5247f602007-04-06 21:06:55 +0000184 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000185 HadErrors = true;
186 }
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000187 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000188 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000189 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000190
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000191 if (CAOpt)
192 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000193
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000194 // Make sure that they are in order of registration not backwards.
195 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000196
197 // Fail hard if there were errors. These are strictly unrecoverable and
198 // indicate serious issues such as conflicting option names or an incorrectly
199 // linked LLVM distribution.
200 if (HadErrors)
201 report_fatal_error("inconsistency in registered CommandLine options");
Chris Lattner1f790af2002-07-29 20:58:42 +0000202}
203
Chris Lattner5247f602007-04-06 21:06:55 +0000204
Chris Lattner2031b022007-04-05 21:58:17 +0000205/// LookupOption - Lookup the option specified by the specified option on the
206/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000207/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000208static Option *LookupOption(StringRef &Arg, StringRef &Value,
209 const StringMap<Option*> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000210 // Reject all dashes.
Craig Topperc10719f2014-04-07 04:17:22 +0000211 if (Arg.empty()) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000212
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000213 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000214
Chris Lattner0a40a972009-09-20 01:53:12 +0000215 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000216 if (EqualPos == StringRef::npos) {
217 // Look up the option.
218 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000219 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000220 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000221
Chris Lattnere7c1e212009-09-20 05:03:30 +0000222 // If the argument before the = is a valid option name, we match. If not,
223 // return Arg unmolested.
224 StringMap<Option*>::const_iterator I =
225 OptionsMap.find(Arg.substr(0, EqualPos));
Craig Topperc10719f2014-04-07 04:17:22 +0000226 if (I == OptionsMap.end()) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000227
Chris Lattnere7c1e212009-09-20 05:03:30 +0000228 Value = Arg.substr(EqualPos+1);
229 Arg = Arg.substr(0, EqualPos);
230 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000231}
232
Daniel Dunbarf4132132011-01-18 01:59:24 +0000233/// LookupNearestOption - Lookup the closest match to the option specified by
234/// the specified option on the command line. If there is a value specified
235/// (after an equal sign) return that as well. This assumes that leading dashes
236/// have already been stripped.
237static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000238 const StringMap<Option*> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000239 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000240 // Reject all dashes.
Craig Topperc10719f2014-04-07 04:17:22 +0000241 if (Arg.empty()) return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000242
243 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000244 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
245 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
246 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000247
248 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000249 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000250 unsigned BestDistance = 0;
251 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
252 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000253 Option *O = it->second;
254 SmallVector<const char*, 16> OptionNames;
255 O->getExtraOptionNames(OptionNames);
256 if (O->ArgStr[0])
257 OptionNames.push_back(O->ArgStr);
258
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000259 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
260 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000261 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
262 StringRef Name = OptionNames[i];
263 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000264 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000265 if (!Best || Distance < BestDistance) {
266 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000267 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000268 if (RHS.empty() || !PermitValue)
269 NearestString = OptionNames[i];
270 else
271 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000272 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000273 }
274 }
275
276 return Best;
277}
278
Alp Tokercb402912014-01-24 17:20:08 +0000279/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
280/// that does special handling of cl::CommaSeparated options.
281static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
282 StringRef ArgName, StringRef Value,
283 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000284 // Check to see if this option accepts a comma separated list of values. If
285 // it does, we have to split up the value into multiple values.
286 if (Handler->getMiscFlags() & CommaSeparated) {
287 StringRef Val(Value);
288 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000289
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000290 while (Pos != StringRef::npos) {
291 // Process the portion before the comma.
292 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
293 return true;
294 // Erase the portion before the comma, AND the comma.
295 Val = Val.substr(Pos+1);
296 Value.substr(Pos+1); // Increment the original value pointer as well.
297 // Check for another comma.
298 Pos = Val.find(',');
299 }
300
301 Value = Val;
302 }
303
304 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
305 return true;
306
307 return false;
308}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000309
Chris Lattner40fef802009-09-20 01:49:31 +0000310/// ProvideOption - For Value, this differentiates between an empty value ("")
311/// and a null value (StringRef()). The later is accepted for arguments that
312/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000313static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000314 StringRef Value, int argc,
315 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000316 // Is this a multi-argument option?
317 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
318
Chris Lattnere81c4092001-10-27 05:54:17 +0000319 // Enforce value requirements
320 switch (Handler->getValueExpectedFlag()) {
321 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000322 if (!Value.data()) { // No value specified?
Chris Lattnerca2552d2009-09-20 00:07:40 +0000323 if (i+1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000324 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000325 // Steal the next argument, like for '-o filename'
326 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000327 }
328 break;
329 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000330 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000331 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000332 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000333
Chris Lattner40fef802009-09-20 01:49:31 +0000334 if (Value.data())
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000335 return Handler->error("does not allow a value! '" +
Chris Lattneraecd74d2009-09-19 18:55:05 +0000336 Twine(Value) + "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000337 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000338 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000339 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000340 }
341
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000342 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000343 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000344 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000345
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000346 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000347 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000348
Chris Lattner40fef802009-09-20 01:49:31 +0000349 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000350 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000351 return true;
352 --NumAdditionalVals;
353 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000354 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000355
356 while (NumAdditionalVals > 0) {
Chris Lattneraecd74d2009-09-19 18:55:05 +0000357 if (i+1 >= argc)
358 return Handler->error("not enough values!");
359 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000360
Alp Tokercb402912014-01-24 17:20:08 +0000361 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000362 return true;
363 MultiArg = true;
364 --NumAdditionalVals;
365 }
366 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000367}
368
Chris Lattnerca2552d2009-09-20 00:07:40 +0000369static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000370 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000371 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000372}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000373
Chris Lattner5df56c42002-07-22 02:07:59 +0000374
375// Option predicates...
376static inline bool isGrouping(const Option *O) {
377 return O->getFormattingFlag() == cl::Grouping;
378}
379static inline bool isPrefixedOrGrouping(const Option *O) {
380 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
381}
382
383// getOptionPred - Check to see if there are any options that satisfy the
384// specified predicate with names that are the prefixes in Name. This is
385// checked by progressively stripping characters off of the name, checking to
386// see if there options that satisfy the predicate. If we find one, return it,
387// otherwise return null.
388//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000389static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner5247f602007-04-06 21:06:55 +0000390 bool (*Pred)(const Option*),
Chris Lattnere7c1e212009-09-20 05:03:30 +0000391 const StringMap<Option*> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000392
Chris Lattnere7c1e212009-09-20 05:03:30 +0000393 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000394
Chris Lattnere7c1e212009-09-20 05:03:30 +0000395 // Loop while we haven't found an option and Name still has at least two
396 // characters in it (so that the next iteration will not be the empty
397 // string.
398 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000399 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000400 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000401 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000402
Chris Lattner5247f602007-04-06 21:06:55 +0000403 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000404 Length = Name.size();
Chris Lattner5247f602007-04-06 21:06:55 +0000405 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000406 }
Craig Topperc10719f2014-04-07 04:17:22 +0000407 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000408}
409
Chris Lattnere7c1e212009-09-20 05:03:30 +0000410/// HandlePrefixedOrGroupedOption - The specified argument string (which started
411/// with at least one '-') does not fully match an available option. Check to
412/// see if this is a prefix or grouped option. If so, split arg into output an
413/// Arg/Value pair and return the Option to parse it with.
414static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
415 bool &ErrorParsing,
416 const StringMap<Option*> &OptionsMap) {
Craig Topperc10719f2014-04-07 04:17:22 +0000417 if (Arg.size() == 1) return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000418
419 // Do the lookup!
420 size_t Length = 0;
421 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Craig Topper8d399f82014-04-09 04:20:00 +0000422 if (!PGOpt) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000423
Chris Lattnere7c1e212009-09-20 05:03:30 +0000424 // If the option is a prefixed option, then the value is simply the
425 // rest of the name... so fall through to later processing, by
426 // setting up the argument name flags and value fields.
427 if (PGOpt->getFormattingFlag() == cl::Prefix) {
428 Value = Arg.substr(Length);
429 Arg = Arg.substr(0, Length);
430 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
431 return PGOpt;
432 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000433
Chris Lattnere7c1e212009-09-20 05:03:30 +0000434 // This must be a grouped option... handle them now. Grouping options can't
435 // have values.
436 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000437
Chris Lattnere7c1e212009-09-20 05:03:30 +0000438 do {
439 // Move current arg name out of Arg into OneArgName.
440 StringRef OneArgName = Arg.substr(0, Length);
441 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000442
Chris Lattnere7c1e212009-09-20 05:03:30 +0000443 // Because ValueRequired is an invalid flag for grouped arguments,
444 // we don't need to pass argc/argv in.
445 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
446 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000447 int Dummy = 0;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000448 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
Craig Topperc10719f2014-04-07 04:17:22 +0000449 StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000450
Chris Lattnere7c1e212009-09-20 05:03:30 +0000451 // Get the next grouping option.
452 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
453 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000454
Chris Lattnere7c1e212009-09-20 05:03:30 +0000455 // Return the last option with Arg cut down to just the last one.
456 return PGOpt;
457}
458
459
460
Chris Lattner5df56c42002-07-22 02:07:59 +0000461static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000462 return O->getNumOccurrencesFlag() == cl::Required ||
463 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000464}
465
466static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000467 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
468 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000469}
Chris Lattnere81c4092001-10-27 05:54:17 +0000470
Reid Klecknera73c7782013-07-18 16:52:05 +0000471static bool isWhitespace(char C) {
472 return strchr(" \t\n\r\f\v", C);
473}
Brian Gaeke497216d2003-08-15 21:05:57 +0000474
Reid Klecknera73c7782013-07-18 16:52:05 +0000475static bool isQuote(char C) {
476 return C == '\"' || C == '\'';
477}
478
479static bool isGNUSpecial(char C) {
480 return strchr("\\\"\' ", C);
481}
482
483void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000484 SmallVectorImpl<const char *> &NewArgv,
485 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000486 SmallString<128> Token;
487 for (size_t I = 0, E = Src.size(); I != E; ++I) {
488 // Consume runs of whitespace.
489 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000490 while (I != E && isWhitespace(Src[I])) {
491 // Mark the end of lines in response files
492 if (MarkEOLs && Src[I] == '\n')
493 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000494 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000495 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000496 if (I == E) break;
497 }
498
499 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
500 // they are literal. This makes it much easier to read Windows file paths.
501 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
502 ++I; // Skip the escape.
503 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000504 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000505 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000506
Reid Klecknera73c7782013-07-18 16:52:05 +0000507 // Consume a quoted string.
508 if (isQuote(Src[I])) {
509 char Quote = Src[I++];
510 while (I != E && Src[I] != Quote) {
511 // Backslashes are literal, unless they escape a special character.
512 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
513 ++I;
514 Token.push_back(Src[I]);
515 ++I;
516 }
517 if (I == E) break;
518 continue;
519 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000520
Reid Klecknera73c7782013-07-18 16:52:05 +0000521 // End the token if this is whitespace.
522 if (isWhitespace(Src[I])) {
523 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000524 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000525 Token.clear();
526 continue;
527 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000528
Reid Klecknera73c7782013-07-18 16:52:05 +0000529 // This is a normal character. Append it.
530 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000531 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000532
533 // Append the last token after hitting EOF with no whitespace.
534 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000535 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000536 // Mark the end of response files
537 if (MarkEOLs)
538 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000539}
540
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000541/// Backslashes are interpreted in a rather complicated way in the Windows-style
542/// command line, because backslashes are used both to separate path and to
543/// escape double quote. This method consumes runs of backslashes as well as the
544/// following double quote if it's escaped.
545///
546/// * If an even number of backslashes is followed by a double quote, one
547/// backslash is output for every pair of backslashes, and the last double
548/// quote remains unconsumed. The double quote will later be interpreted as
549/// the start or end of a quoted string in the main loop outside of this
550/// function.
551///
552/// * If an odd number of backslashes is followed by a double quote, one
553/// backslash is output for every pair of backslashes, and a double quote is
554/// output for the last pair of backslash-double quote. The double quote is
555/// consumed in this case.
556///
557/// * Otherwise, backslashes are interpreted literally.
558static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
559 size_t E = Src.size();
560 int BackslashCount = 0;
561 // Skip the backslashes.
562 do {
563 ++I;
564 ++BackslashCount;
565 } while (I != E && Src[I] == '\\');
566
567 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
568 if (FollowedByDoubleQuote) {
569 Token.append(BackslashCount / 2, '\\');
570 if (BackslashCount % 2 == 0)
571 return I - 1;
572 Token.push_back('"');
573 return I;
574 }
575 Token.append(BackslashCount, '\\');
576 return I - 1;
577}
578
Reid Klecknera73c7782013-07-18 16:52:05 +0000579void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000580 SmallVectorImpl<const char *> &NewArgv,
581 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000582 SmallString<128> Token;
583
584 // This is a small state machine to consume characters until it reaches the
585 // end of the source string.
586 enum { INIT, UNQUOTED, QUOTED } State = INIT;
587 for (size_t I = 0, E = Src.size(); I != E; ++I) {
588 // INIT state indicates that the current input index is at the start of
589 // the string or between tokens.
590 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000591 if (isWhitespace(Src[I])) {
592 // Mark the end of lines in response files
593 if (MarkEOLs && Src[I] == '\n')
594 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000595 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000596 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000597 if (Src[I] == '"') {
598 State = QUOTED;
599 continue;
600 }
601 if (Src[I] == '\\') {
602 I = parseBackslash(Src, I, Token);
603 State = UNQUOTED;
604 continue;
605 }
606 Token.push_back(Src[I]);
607 State = UNQUOTED;
608 continue;
609 }
610
611 // UNQUOTED state means that it's reading a token not quoted by double
612 // quotes.
613 if (State == UNQUOTED) {
614 // Whitespace means the end of the token.
615 if (isWhitespace(Src[I])) {
Sean Silvadb794842014-08-15 23:39:01 +0000616 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000617 Token.clear();
618 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000619 // Mark the end of lines in response files
620 if (MarkEOLs && Src[I] == '\n')
621 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000622 continue;
623 }
624 if (Src[I] == '"') {
625 State = QUOTED;
626 continue;
627 }
628 if (Src[I] == '\\') {
629 I = parseBackslash(Src, I, Token);
630 continue;
631 }
632 Token.push_back(Src[I]);
633 continue;
634 }
635
636 // QUOTED state means that it's reading a token quoted by double quotes.
637 if (State == QUOTED) {
638 if (Src[I] == '"') {
639 State = UNQUOTED;
640 continue;
641 }
642 if (Src[I] == '\\') {
643 I = parseBackslash(Src, I, Token);
644 continue;
645 }
646 Token.push_back(Src[I]);
647 }
648 }
649 // Append the last token after hitting EOF with no whitespace.
650 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000651 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000652 // Mark the end of response files
653 if (MarkEOLs)
654 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000655}
656
657static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
658 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000659 SmallVectorImpl<const char *> &NewArgv,
660 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000661 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
662 MemoryBuffer::getFile(FName);
663 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000664 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000665 MemoryBuffer &MemBuf = *MemBufOrErr.get();
666 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000667
668 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000669 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000670 std::string UTF8Buf;
671 if (hasUTF16ByteOrderMark(BufRef)) {
672 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
673 return false;
674 Str = StringRef(UTF8Buf);
675 }
676
677 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000678 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000679
680 return true;
681}
682
683/// \brief Expand response files on a command line recursively using the given
684/// StringSaver and tokenization strategy.
685bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000686 SmallVectorImpl<const char *> &Argv,
687 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000688 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000689 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000690
691 // Don't cache Argv.size() because it can change.
692 for (unsigned I = 0; I != Argv.size(); ) {
693 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000694 // Check if it is an EOL marker
695 if (Arg == nullptr) {
696 ++I;
697 continue;
698 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000699 if (Arg[0] != '@') {
700 ++I;
701 continue;
702 }
703
704 // If we have too many response files, leave some unexpanded. This avoids
705 // crashing on self-referential response files.
706 if (RspFiles++ > 20)
707 return false;
708
709 // Replace this response file argument with the tokenization of its
710 // contents. Nested response files are expanded in subsequent iterations.
711 // FIXME: If a nested response file uses a relative path, is it relative to
712 // the cwd of the process or the response file?
713 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000714 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
715 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000716 // We couldn't read this file, so we leave it in the argument stream and
717 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000718 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000719 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000720 continue;
721 }
722 Argv.erase(Argv.begin() + I);
723 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
724 }
725 return AllExpanded;
726}
727
Sean Silvadb794842014-08-15 23:39:01 +0000728namespace {
729 class StrDupSaver : public StringSaver {
730 std::vector<char*> Dups;
731 public:
732 ~StrDupSaver() {
733 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
734 I != E; ++I) {
735 char *Dup = *I;
736 free(Dup);
737 }
738 }
739 const char *SaveString(const char *Str) override {
740 char *Dup = strdup(Str);
741 Dups.push_back(Dup);
742 return Dup;
743 }
744 };
745}
746
Brian Gaekeca782d92003-08-14 22:00:59 +0000747/// ParseEnvironmentOptions - An alternative entry point to the
748/// CommandLine library, which allows you to read the program's name
749/// from the caller (as PROGNAME) and its command-line arguments from
750/// an environment variable (whose name is given in ENVVAR).
751///
Chris Lattnera60f3552004-05-06 22:04:31 +0000752void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000753 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000754 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000755 assert(progName && "Program name not specified");
756 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000757
Brian Gaeke497216d2003-08-15 21:05:57 +0000758 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000759 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000760 if (!envValue)
761 return;
762
Brian Gaekeca782d92003-08-14 22:00:59 +0000763 // Get program's "name", which we wouldn't know without the caller
764 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000765 SmallVector<const char *, 20> newArgv;
Sean Silvadb794842014-08-15 23:39:01 +0000766 StrDupSaver Saver;
767 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000768
769 // Parse the value of the environment variable into a "command line"
770 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000771 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000772 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000773 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000774}
775
David Blaikie0210e972012-02-07 19:36:01 +0000776void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000777 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000778 // Process all registered options.
Chris Lattner131dca92009-09-20 06:18:38 +0000779 SmallVector<Option*, 4> PositionalOpts;
780 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000781 StringMap<Option*> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000782 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000783
Chris Lattner5247f602007-04-06 21:06:55 +0000784 assert((!Opts.empty() || !PositionalOpts.empty()) &&
785 "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000786
787 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000788 SmallVector<const char *, 20> newArgv;
789 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000790 newArgv.push_back(argv[i]);
Sean Silvadb794842014-08-15 23:39:01 +0000791 StrDupSaver Saver;
Reid Klecknera73c7782013-07-18 16:52:05 +0000792 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000793 argv = &newArgv[0];
794 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000795
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000796 // Copy the program name into ProgName, making sure not to overflow it.
NAKAMURA Takumic2c66492014-04-23 14:51:23 +0000797 StringRef ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000798 size_t Len = std::min(ProgName.size(), size_t(79));
799 memcpy(ProgramName, ProgName.data(), Len);
800 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000801
Chris Lattner36a57d32001-07-23 17:17:47 +0000802 ProgramOverview = Overview;
803 bool ErrorParsing = false;
804
Chris Lattner5df56c42002-07-22 02:07:59 +0000805 // Check out the positional arguments to collect information about them.
806 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000807
Chris Lattnerd380d842005-08-08 17:25:38 +0000808 // Determine whether or not there are an unlimited number of positionals
809 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000810
Craig Topperc10719f2014-04-07 04:17:22 +0000811 Option *ConsumeAfterOpt = nullptr;
Chris Lattner5df56c42002-07-22 02:07:59 +0000812 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000813 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000814 assert(PositionalOpts.size() > 1 &&
815 "Cannot specify cl::ConsumeAfter without a positional argument!");
816 ConsumeAfterOpt = PositionalOpts[0];
817 }
818
819 // Calculate how many positional values are _required_.
820 bool UnboundedFound = false;
Craig Topper8d399f82014-04-09 04:20:00 +0000821 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000822 i != e; ++i) {
823 Option *Opt = PositionalOpts[i];
824 if (RequiresValue(Opt))
825 ++NumPositionalRequired;
826 else if (ConsumeAfterOpt) {
827 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000828 // unless there is only one positional argument...
829 if (PositionalOpts.size() > 2)
830 ErrorParsing |=
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000831 Opt->error("error - this positional option will never be matched, "
Chris Lattnerd49ea882002-07-22 02:21:57 +0000832 "because it does not Require a value, and a "
833 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000834 } else if (UnboundedFound && !Opt->ArgStr[0]) {
835 // This option does not "require" a value... Make sure this option is
836 // not specified after an option that eats all extra arguments, or this
837 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000838 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000839 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000840 "another positional argument will match an "
841 "unbounded number of values, and this option"
842 " does not require a value!");
843 }
844 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
845 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000846 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000847 }
848
Reid Spencer2027a6f2004-08-13 19:47:30 +0000849 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000850 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000851 //
Chris Lattnerca2552d2009-09-20 00:07:40 +0000852 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000853
Chris Lattner2da046f2003-07-30 17:34:02 +0000854 // If the program has named positional arguments, and the name has been run
855 // across, keep track of which positional argument was named. Otherwise put
856 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000857 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000858
Chris Lattner36a57d32001-07-23 17:17:47 +0000859 // Loop over all of the arguments... processing them.
Chris Lattner5df56c42002-07-22 02:07:59 +0000860 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000861 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000862 Option *Handler = nullptr;
863 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000864 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000865 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000866 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000867
Chris Lattneraf039c52007-04-12 00:36:29 +0000868 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000869 // option has just been registered or deregistered. This can occur in
870 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000871 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000872 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000873 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000874 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000875 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000876 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000877 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000878
Chris Lattner5df56c42002-07-22 02:07:59 +0000879 // Check to see if this is a positional argument. This argument is
880 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000881 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000882 //
883 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
884 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000885 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000886 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner2da046f2003-07-30 17:34:02 +0000887 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000888 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000889
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000890 if (!PositionalOpts.empty()) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000891 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000892
893 // All of the positional arguments have been fulfulled, give the rest to
894 // the consume after option... if it's specified...
895 //
Craig Topper8d399f82014-04-09 04:20:00 +0000896 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000897 for (++i; i < argc; ++i)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000898 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000899 break; // Handle outside of the argument processing loop...
900 }
901
902 // Delay processing positional arguments until the end...
903 continue;
904 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000905 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
906 !DashDashFound) {
907 DashDashFound = true; // This is the mythical "--"?
908 continue; // Don't try to process it as an argument itself.
909 } else if (ActivePositionalArg &&
910 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
911 // If there is a positional argument eating options, check to see if this
912 // option is another positional argument. If so, treat it as an argument,
913 // otherwise feed it to the eating positional.
Chris Lattner36a57d32001-07-23 17:17:47 +0000914 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000915 // Eat leading dashes.
916 while (!ArgName.empty() && ArgName[0] == '-')
917 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000918
Chris Lattner5247f602007-04-06 21:06:55 +0000919 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000920 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000921 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnera60f3552004-05-06 22:04:31 +0000922 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000923 }
924
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000925 } else { // We start with a '-', must be an argument.
Chris Lattnera60f3552004-05-06 22:04:31 +0000926 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000927 // Eat leading dashes.
928 while (!ArgName.empty() && ArgName[0] == '-')
929 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000930
Chris Lattner5247f602007-04-06 21:06:55 +0000931 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000932
Chris Lattnera60f3552004-05-06 22:04:31 +0000933 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000934 if (!Handler)
Chris Lattnere7c1e212009-09-20 05:03:30 +0000935 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
936 ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000937
938 // Otherwise, look for the closest available option to report to the user
939 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000940 if (!Handler && SinkOpts.empty())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000941 NearestHandler = LookupNearestOption(ArgName, Opts,
942 NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000943 }
944
Craig Topper8d399f82014-04-09 04:20:00 +0000945 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000946 if (SinkOpts.empty()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000947 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands142b9ed2010-02-18 14:08:13 +0000948 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000949
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000950 if (NearestHandler) {
951 // If we know a near match, report it as well.
952 errs() << ProgramName << ": Did you mean '-"
953 << NearestHandlerString << "'?\n";
954 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000955
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000956 ErrorParsing = true;
957 } else {
Chris Lattner131dca92009-09-20 06:18:38 +0000958 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000959 E = SinkOpts.end(); I != E ; ++I)
960 (*I)->addOccurrence(i, "", argv[i]);
961 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000962 continue;
963 }
964
Chris Lattner2da046f2003-07-30 17:34:02 +0000965 // If this is a named positional argument, just remember that it is the
966 // active one...
967 if (Handler->getFormattingFlag() == cl::Positional)
968 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000969 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000970 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000971 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000972
Chris Lattner5df56c42002-07-22 02:07:59 +0000973 // Check and handle positional arguments now...
974 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000975 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000976 << ": Not enough positional command line arguments specified!\n"
977 << "Must specify at least " << NumPositionalRequired
Duncan Sands142b9ed2010-02-18 14:08:13 +0000978 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000979
Chris Lattner5df56c42002-07-22 02:07:59 +0000980 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000981 } else if (!HasUnlimitedPositionals &&
982 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000983 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000984 << ": Too many positional arguments specified!\n"
985 << "Can specify at most " << PositionalOpts.size()
Duncan Sands142b9ed2010-02-18 14:08:13 +0000986 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +0000987 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +0000988
Craig Topper8d399f82014-04-09 04:20:00 +0000989 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +0000990 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +0000991 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
992 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000993 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +0000994 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000995 PositionalVals[ValNo].second);
996 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000997 --NumPositionalRequired; // We fulfilled our duty...
998 }
999
1000 // If we _can_ give this option more arguments, do so now, as long as we
1001 // do not give it values that others need. 'Done' controls whether the
1002 // option even _WANTS_ any more.
1003 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001004 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner5df56c42002-07-22 02:07:59 +00001005 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001006 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001007 case cl::Optional:
1008 Done = true; // Optional arguments want _at most_ one value
1009 // FALL THROUGH
1010 case cl::ZeroOrMore: // Zero or more will take all they can get...
1011 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001012 ProvidePositionalOption(PositionalOpts[i],
1013 PositionalVals[ValNo].first,
1014 PositionalVals[ValNo].second);
1015 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001016 break;
1017 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001018 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner5df56c42002-07-22 02:07:59 +00001019 "positional argument processing!");
1020 }
1021 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001022 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001023 } else {
1024 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1025 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001026 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001027 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001028 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001029 PositionalVals[ValNo].first,
1030 PositionalVals[ValNo].second);
1031 ValNo++;
1032 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001033
1034 // Handle the case where there is just one positional option, and it's
1035 // optional. In this case, we want to give JUST THE FIRST option to the
1036 // positional option and keep the rest for the consume after. The above
1037 // loop would have assigned no values to positional options in this case.
1038 //
Reid Spencer2027a6f2004-08-13 19:47:30 +00001039 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001040 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001041 PositionalVals[ValNo].first,
1042 PositionalVals[ValNo].second);
1043 ValNo++;
1044 }
Misha Brukman10468d82005-04-21 22:55:34 +00001045
Chris Lattner5df56c42002-07-22 02:07:59 +00001046 // Handle over all of the rest of the arguments to the
1047 // cl::ConsumeAfter command line option...
1048 for (; ValNo != PositionalVals.size(); ++ValNo)
1049 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001050 PositionalVals[ValNo].first,
1051 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001052 }
1053
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001054 // Loop over args and make sure all required args are specified!
Justin Bogner973b2ff2014-07-14 19:24:13 +00001055 for (const auto &Opt : Opts) {
1056 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001057 case Required:
1058 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001059 if (Opt.second->getNumOccurrences() == 0) {
1060 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001061 ErrorParsing = true;
1062 }
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001063 // Fall through
1064 default:
1065 break;
1066 }
1067 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001068
Rafael Espindolacf14a382010-11-19 21:14:29 +00001069 // Now that we know if -debug is specified, we can use it.
1070 // Note that if ReadResponseFiles == true, this must be done before the
1071 // memory allocated for the expanded command line is free()d below.
1072 DEBUG(dbgs() << "Args: ";
1073 for (int i = 0; i < argc; ++i)
1074 dbgs() << argv[i] << ' ';
1075 dbgs() << '\n';
1076 );
1077
Chris Lattner5df56c42002-07-22 02:07:59 +00001078 // Free all of the memory allocated to the map. Command line options may only
1079 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001080 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001081 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001082 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001083
1084 // If we had an error processing our arguments, don't let the program execute
1085 if (ErrorParsing) exit(1);
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// Option Base class implementation
1090//
Chris Lattner36a57d32001-07-23 17:17:47 +00001091
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001092bool Option::error(const Twine &Message, StringRef ArgName) {
Craig Topper8d399f82014-04-09 04:20:00 +00001093 if (!ArgName.data()) ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001094 if (ArgName.empty())
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001095 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001096 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001097 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001098
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001099 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001100 return true;
1101}
1102
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001103bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001104 StringRef Value, bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001105 if (!MultiArg)
1106 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001107
Misha Brukman069e6b52003-07-10 16:49:51 +00001108 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001109 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001110 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001111 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001112 break;
1113 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001114 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001115 return error("must occur exactly one time!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001116 // Fall through
1117 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001118 case ZeroOrMore:
1119 case ConsumeAfter: break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001120 }
1121
Reid Spencer2027a6f2004-08-13 19:47:30 +00001122 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001123}
1124
Chris Lattner5df56c42002-07-22 02:07:59 +00001125
1126// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1127// has been specified yet.
1128//
1129static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1130 if (O.ValueStr[0] == 0) return DefaultMsg;
1131 return O.ValueStr;
1132}
1133
1134//===----------------------------------------------------------------------===//
1135// cl::alias class implementation
1136//
1137
Chris Lattner36a57d32001-07-23 17:17:47 +00001138// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001139size_t alias::getOptionWidth() const {
Chris Lattner36a57d32001-07-23 17:17:47 +00001140 return std::strlen(ArgStr)+6;
1141}
1142
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001143static void printHelpStr(StringRef HelpStr, size_t Indent,
1144 size_t FirstLineIndentedBy) {
1145 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1146 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1147 while (!Split.second.empty()) {
1148 Split = Split.second.split('\n');
1149 outs().indent(Indent) << Split.first << "\n";
1150 }
1151}
1152
Chris Lattner1b7a5152006-04-28 05:36:25 +00001153// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001154void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001155 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001156 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001157}
1158
Chris Lattner36a57d32001-07-23 17:17:47 +00001159//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001160// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001161//
1162
Chris Lattnerb4101b12002-08-07 18:36:37 +00001163// basic_parser implementation
1164//
1165
1166// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001167size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1168 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001169 if (const char *ValName = getValueName())
1170 Len += std::strlen(getValueStr(O, ValName))+3;
1171
1172 return Len + 6;
1173}
1174
Misha Brukman10468d82005-04-21 22:55:34 +00001175// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001176// to-be-maintained width is specified.
1177//
1178void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001179 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001180 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001181
1182 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001183 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001184
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001185 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001186}
1187
Andrew Trick12004012011-04-05 18:54:36 +00001188void basic_parser_impl::printOptionName(const Option &O,
1189 size_t GlobalWidth) const {
1190 outs() << " -" << O.ArgStr;
1191 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1192}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001193
1194
Chris Lattner5df56c42002-07-22 02:07:59 +00001195// parser<bool> implementation
1196//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001197bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001198 StringRef Arg, bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001199 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001200 Arg == "1") {
1201 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001202 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001203 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001204
Chris Lattneraecd74d2009-09-19 18:55:05 +00001205 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1206 Value = false;
1207 return false;
1208 }
1209 return O.error("'" + Arg +
1210 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001211}
1212
Dale Johannesen82810c82007-05-22 17:14:46 +00001213// parser<boolOrDefault> implementation
1214//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001215bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001216 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001217 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1218 Arg == "1") {
1219 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001220 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001221 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001222 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1223 Value = BOU_FALSE;
1224 return false;
1225 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001226
Chris Lattneraecd74d2009-09-19 18:55:05 +00001227 return O.error("'" + Arg +
1228 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001229}
1230
Chris Lattner5df56c42002-07-22 02:07:59 +00001231// parser<int> implementation
1232//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001233bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001234 StringRef Arg, int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001235 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001236 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001237 return false;
1238}
1239
Chris Lattner719c7152003-06-28 15:47:20 +00001240// parser<unsigned> implementation
1241//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001242bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001243 StringRef Arg, unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001244
1245 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001246 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001247 return false;
1248}
1249
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001250// parser<unsigned long long> implementation
1251//
1252bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1253 StringRef Arg, unsigned long long &Value){
1254
1255 if (Arg.getAsInteger(0, Value))
1256 return O.error("'" + Arg + "' value invalid for uint argument!");
1257 return false;
1258}
1259
Chris Lattnerb4101b12002-08-07 18:36:37 +00001260// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001261//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001262static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001263 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1264 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001265 char *End;
1266 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001267 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001268 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001269 return false;
1270}
1271
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001272bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001273 StringRef Arg, double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001274 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001275}
1276
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001277bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001278 StringRef Arg, float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001279 double dVal;
1280 if (parseDouble(O, Arg, dVal))
1281 return true;
1282 Val = (float)dVal;
1283 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001284}
1285
1286
Chris Lattner5df56c42002-07-22 02:07:59 +00001287
1288// generic_parser_base implementation
1289//
1290
Chris Lattner494c0b02002-07-23 17:15:12 +00001291// findOption - Return the option number corresponding to the specified
1292// argument string. If the option is not found, getNumOptions() is returned.
1293//
1294unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001295 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001296
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001297 for (unsigned i = 0; i != e; ++i) {
1298 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001299 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001300 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001301 return e;
1302}
1303
1304
Chris Lattner5df56c42002-07-22 02:07:59 +00001305// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001306size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001307 if (O.hasArgStr()) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001308 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001309 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001310 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001311 return Size;
1312 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001313 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001314 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001315 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001316 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001317 }
1318}
1319
Misha Brukman10468d82005-04-21 22:55:34 +00001320// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001321// to-be-maintained width is specified.
1322//
1323void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001324 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001325 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001326 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001327 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001328
Chris Lattner5df56c42002-07-22 02:07:59 +00001329 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001330 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001331 outs() << " =" << getOption(i);
1332 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001333 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001334 } else {
1335 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001336 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001337 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001338 const char *Option = getOption(i);
1339 outs() << " -" << Option;
1340 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001341 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001342 }
1343}
1344
Andrew Trick12004012011-04-05 18:54:36 +00001345static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1346
1347// printGenericOptionDiff - Print the value of this option and it's default.
1348//
1349// "Generic" options have each value mapped to a name.
1350void generic_parser_base::
1351printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1352 const GenericOptionValue &Default,
1353 size_t GlobalWidth) const {
1354 outs() << " -" << O.ArgStr;
1355 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1356
1357 unsigned NumOpts = getNumOptions();
1358 for (unsigned i = 0; i != NumOpts; ++i) {
1359 if (Value.compare(getOptionValue(i)))
1360 continue;
1361
1362 outs() << "= " << getOption(i);
1363 size_t L = std::strlen(getOption(i));
1364 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1365 outs().indent(NumSpaces) << " (default: ";
1366 for (unsigned j = 0; j != NumOpts; ++j) {
1367 if (Default.compare(getOptionValue(j)))
1368 continue;
1369 outs() << getOption(j);
1370 break;
1371 }
1372 outs() << ")\n";
1373 return;
1374 }
1375 outs() << "= *unknown option value*\n";
1376}
1377
1378// printOptionDiff - Specializations for printing basic value types.
1379//
Alp Tokere69170a2014-06-26 22:52:05 +00001380#define PRINT_OPT_DIFF(T) \
1381 void parser<T>:: \
1382 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1383 size_t GlobalWidth) const { \
1384 printOptionName(O, GlobalWidth); \
1385 std::string Str; \
1386 { \
1387 raw_string_ostream SS(Str); \
1388 SS << V; \
1389 } \
1390 outs() << "= " << Str; \
1391 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1392 outs().indent(NumSpaces) << " (default: "; \
1393 if (D.hasValue()) \
1394 outs() << D.getValue(); \
1395 else \
1396 outs() << "*no default*"; \
1397 outs() << ")\n"; \
1398 } \
Andrew Trick12004012011-04-05 18:54:36 +00001399
Frits van Bommel87e33672011-04-06 12:29:56 +00001400PRINT_OPT_DIFF(bool)
1401PRINT_OPT_DIFF(boolOrDefault)
1402PRINT_OPT_DIFF(int)
1403PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001404PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001405PRINT_OPT_DIFF(double)
1406PRINT_OPT_DIFF(float)
1407PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001408
1409void parser<std::string>::
1410printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1411 size_t GlobalWidth) const {
1412 printOptionName(O, GlobalWidth);
1413 outs() << "= " << V;
1414 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1415 outs().indent(NumSpaces) << " (default: ";
1416 if (D.hasValue())
1417 outs() << D.getValue();
1418 else
1419 outs() << "*no default*";
1420 outs() << ")\n";
1421}
1422
1423// Print a placeholder for options that don't yet support printOptionDiff().
1424void basic_parser_impl::
1425printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1426 printOptionName(O, GlobalWidth);
1427 outs() << "= *cannot print option value*\n";
1428}
Chris Lattner36a57d32001-07-23 17:17:47 +00001429
1430//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001431// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001432//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001433
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001434static int OptNameCompare(const void *LHS, const void *RHS) {
1435 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001436
Duncan Sands79d793e2012-03-12 10:51:06 +00001437 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001438}
1439
Andrew Trick12004012011-04-05 18:54:36 +00001440// Copy Options into a vector so we can sort them as we like.
1441static void
1442sortOpts(StringMap<Option*> &OptMap,
1443 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1444 bool ShowHidden) {
1445 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1446
1447 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1448 I != E; ++I) {
1449 // Ignore really-hidden options.
1450 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1451 continue;
1452
1453 // Unless showhidden is set, ignore hidden flags.
1454 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1455 continue;
1456
1457 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001458 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001459 continue;
1460
1461 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1462 I->second));
1463 }
1464
1465 // Sort the options list alphabetically.
1466 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1467}
1468
Chris Lattner36a57d32001-07-23 17:17:47 +00001469namespace {
1470
Chris Lattner5df56c42002-07-22 02:07:59 +00001471class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001472protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001473 const bool ShowHidden;
Andrew Trick0537a982013-05-06 21:56:23 +00001474 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1475 // Print the options. Opts is assumed to be alphabetically sorted.
1476 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1477 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1478 Opts[i].second->printOptionInfo(MaxArgLen);
1479 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001480
Chris Lattner5df56c42002-07-22 02:07:59 +00001481public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001482 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001483 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001484
Andrew Trick0537a982013-05-06 21:56:23 +00001485 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001486 void operator=(bool Value) {
1487 if (Value == false) return;
1488
Chris Lattner5247f602007-04-06 21:06:55 +00001489 // Get all the options.
Chris Lattner131dca92009-09-20 06:18:38 +00001490 SmallVector<Option*, 4> PositionalOpts;
1491 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001492 StringMap<Option*> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001493 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001494
Andrew Trick0537a982013-05-06 21:56:23 +00001495 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001496 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001497
1498 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001499 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001500
Chris Lattner471ba482009-08-23 08:43:55 +00001501 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001502
Chris Lattner8111c592006-10-04 21:52:35 +00001503 // Print out the positional options.
Craig Topperc10719f2014-04-07 04:17:22 +00001504 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001505 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001506 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1507 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001508
Craig Topperc10719f2014-04-07 04:17:22 +00001509 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001510 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001511 outs() << " --" << PositionalOpts[i]->ArgStr;
1512 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001513 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001514
1515 // Print the consume after option info if it exists...
Chris Lattner471ba482009-08-23 08:43:55 +00001516 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001517
Chris Lattner471ba482009-08-23 08:43:55 +00001518 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001519
1520 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001521 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001522 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001523 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001524
Chris Lattner471ba482009-08-23 08:43:55 +00001525 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001526 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001527
Chris Lattner37bcd992004-11-19 17:08:15 +00001528 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001529 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001530 E = MoreHelp->end();
1531 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001532 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001533 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001534
Reid Spencer5e554702004-11-16 06:11:52 +00001535 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001536 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001537 }
1538};
Andrew Trick0537a982013-05-06 21:56:23 +00001539
1540class CategorizedHelpPrinter : public HelpPrinter {
1541public:
1542 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1543
1544 // Helper function for printOptions().
1545 // It shall return true if A's name should be lexographically
1546 // ordered before B's name. It returns false otherwise.
1547 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001548 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001549 }
1550
1551 // Make sure we inherit our base class's operator=()
1552 using HelpPrinter::operator= ;
1553
1554protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001555 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001556 std::vector<OptionCategory *> SortedCategories;
1557 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1558
Alp Tokercb402912014-01-24 17:20:08 +00001559 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001560 // sorting.
1561 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1562 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001563 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001564 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001565 }
Andrew Trick0537a982013-05-06 21:56:23 +00001566
1567 // Sort the different option categories alphabetically.
1568 assert(SortedCategories.size() > 0 && "No option categories registered!");
1569 std::sort(SortedCategories.begin(), SortedCategories.end(),
1570 OptionCategoryCompare);
1571
1572 // Create map to empty vectors.
1573 for (std::vector<OptionCategory *>::const_iterator
1574 I = SortedCategories.begin(),
1575 E = SortedCategories.end();
1576 I != E; ++I)
1577 CategorizedOptions[*I] = std::vector<Option *>();
1578
1579 // Walk through pre-sorted options and assign into categories.
1580 // Because the options are already alphabetically sorted the
1581 // options within categories will also be alphabetically sorted.
1582 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1583 Option *Opt = Opts[I].second;
1584 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1585 "Option has an unregistered category");
1586 CategorizedOptions[Opt->Category].push_back(Opt);
1587 }
1588
1589 // Now do printing.
1590 for (std::vector<OptionCategory *>::const_iterator
1591 Category = SortedCategories.begin(),
1592 E = SortedCategories.end();
1593 Category != E; ++Category) {
1594 // Hide empty categories for -help, but show for -help-hidden.
1595 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1596 if (!ShowHidden && IsEmptyCategory)
1597 continue;
1598
1599 // Print category information.
1600 outs() << "\n";
1601 outs() << (*Category)->getName() << ":\n";
1602
1603 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001604 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001605 outs() << (*Category)->getDescription() << "\n\n";
1606 else
1607 outs() << "\n";
1608
1609 // When using -help-hidden explicitly state if the category has no
1610 // options associated with it.
1611 if (IsEmptyCategory) {
1612 outs() << " This option category has no options.\n";
1613 continue;
1614 }
1615 // Loop over the options in the category and print.
1616 for (std::vector<Option *>::const_iterator
1617 Opt = CategorizedOptions[*Category].begin(),
1618 E = CategorizedOptions[*Category].end();
1619 Opt != E; ++Opt)
1620 (*Opt)->printOptionInfo(MaxArgLen);
1621 }
1622 }
1623};
1624
1625// This wraps the Uncategorizing and Categorizing printers and decides
1626// at run time which should be invoked.
1627class HelpPrinterWrapper {
1628private:
1629 HelpPrinter &UncategorizedPrinter;
1630 CategorizedHelpPrinter &CategorizedPrinter;
1631
1632public:
1633 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1634 CategorizedHelpPrinter &CategorizedPrinter) :
1635 UncategorizedPrinter(UncategorizedPrinter),
1636 CategorizedPrinter(CategorizedPrinter) { }
1637
1638 // Invoke the printer.
1639 void operator=(bool Value);
1640};
1641
Chris Lattneradb19d62006-10-12 22:09:17 +00001642} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001643
Andrew Trick0537a982013-05-06 21:56:23 +00001644// Declare the four HelpPrinter instances that are used to print out help, or
1645// help-hidden as an uncategorized list or in categories.
1646static HelpPrinter UncategorizedNormalPrinter(false);
1647static HelpPrinter UncategorizedHiddenPrinter(true);
1648static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1649static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1650
1651
1652// Declare HelpPrinter wrappers that will decide whether or not to invoke
1653// a categorizing help printer
1654static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1655 CategorizedNormalPrinter);
1656static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1657 CategorizedHiddenPrinter);
1658
1659// Define uncategorized help printers.
1660// -help-list is hidden by default because if Option categories are being used
1661// then -help behaves the same as -help-list.
1662static cl::opt<HelpPrinter, true, parser<bool> >
1663HLOp("help-list",
1664 cl::desc("Display list of available options (-help-list-hidden for more)"),
1665 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001666
Chris Lattneradb19d62006-10-12 22:09:17 +00001667static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trick0537a982013-05-06 21:56:23 +00001668HLHOp("help-list-hidden",
1669 cl::desc("Display list of all available options"),
1670 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1671
1672// Define uncategorized/categorized help printers. These printers change their
1673// behaviour at runtime depending on whether one or more Option categories have
1674// been declared.
1675static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands142b9ed2010-02-18 14:08:13 +00001676HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trick0537a982013-05-06 21:56:23 +00001677 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001678
Andrew Trick0537a982013-05-06 21:56:23 +00001679static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001680HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trick0537a982013-05-06 21:56:23 +00001681 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1682
1683
Chris Lattner36a57d32001-07-23 17:17:47 +00001684
Andrew Trick12004012011-04-05 18:54:36 +00001685static cl::opt<bool>
1686PrintOptions("print-options",
1687 cl::desc("Print non-default options after command line parsing"),
1688 cl::Hidden, cl::init(false));
1689
1690static cl::opt<bool>
1691PrintAllOptions("print-all-options",
1692 cl::desc("Print all option values after command line parsing"),
1693 cl::Hidden, cl::init(false));
1694
Andrew Trick0537a982013-05-06 21:56:23 +00001695void HelpPrinterWrapper::operator=(bool Value) {
1696 if (Value == false)
1697 return;
1698
1699 // Decide which printer to invoke. If more than one option category is
1700 // registered then it is useful to show the categorized help instead of
1701 // uncategorized help.
1702 if (RegisteredOptionCategories->size() > 1) {
1703 // unhide -help-list option so user can have uncategorized output if they
1704 // want it.
1705 HLOp.setHiddenFlag(NotHidden);
1706
1707 CategorizedPrinter = true; // Invoke categorized printer
1708 }
1709 else
1710 UncategorizedPrinter = true; // Invoke uncategorized printer
1711}
1712
Andrew Trick12004012011-04-05 18:54:36 +00001713// Print the value of each option.
1714void cl::PrintOptionValues() {
1715 if (!PrintOptions && !PrintAllOptions) return;
1716
1717 // Get all the options.
1718 SmallVector<Option*, 4> PositionalOpts;
1719 SmallVector<Option*, 4> SinkOpts;
1720 StringMap<Option*> OptMap;
1721 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1722
1723 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1724 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1725
1726 // Compute the maximum argument length...
1727 size_t MaxArgLen = 0;
1728 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1729 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1730
1731 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1732 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1733}
1734
Craig Topperc10719f2014-04-07 04:17:22 +00001735static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001736
Craig Topperc10719f2014-04-07 04:17:22 +00001737static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001738
Chris Lattneradb19d62006-10-12 22:09:17 +00001739namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001740class VersionPrinter {
1741public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001742 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001743 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001744 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001745 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001746#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001747 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001748#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001749 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001750#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001751 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001752#else
Chris Lattner131dca92009-09-20 06:18:38 +00001753 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001754#endif
1755#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001756 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001757#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001758 std::string CPU = sys::getHostCPUName();
Benjamin Kramer713fd352009-11-17 17:57:04 +00001759 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001760 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001761#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001762 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001763#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001764 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001765 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001766 }
1767 void operator=(bool OptionWasSpecified) {
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001768 if (!OptionWasSpecified) return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001769
Craig Topperc10719f2014-04-07 04:17:22 +00001770 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001771 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001772 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001773 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001774 print();
1775
1776 // Iterate over any registered extra printers and call them to add further
1777 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001778 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001779 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001780 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1781 E = ExtraVersionPrinters->end();
1782 I != E; ++I)
1783 (*I)();
1784 }
1785
Justin Bogner02b95842014-02-28 19:08:01 +00001786 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001787 }
1788};
Chris Lattneradb19d62006-10-12 22:09:17 +00001789} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001790
1791
Reid Spencerff6cc122004-08-04 00:36:06 +00001792// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001793static VersionPrinter VersionPrinterInstance;
1794
1795static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001796VersOp("version", cl::desc("Display the version of this program"),
Reid Spencerff6cc122004-08-04 00:36:06 +00001797 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1798
Reid Spencer5e554702004-11-16 06:11:52 +00001799// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001800void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1801 // This looks weird, but it actually prints the help message. The Printers are
1802 // types of HelpPrinter and the help gets printed when its operator= is
1803 // invoked. That's because the "normal" usages of the help printer is to be
1804 // assigned true/false depending on whether -help or -help-hidden was given or
1805 // not. Since we're circumventing that we have to make it look like -help or
1806 // -help-hidden were given, so we assign true.
1807
1808 if (!Hidden && !Categorized)
1809 UncategorizedNormalPrinter = true;
1810 else if (!Hidden && Categorized)
1811 CategorizedNormalPrinter = true;
1812 else if (Hidden && !Categorized)
1813 UncategorizedHiddenPrinter = true;
1814 else
1815 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001816}
Reid Spencerb3171672006-06-05 16:22:56 +00001817
Devang Patel9eb2caae2007-02-01 01:43:37 +00001818/// Utility function for printing version number.
1819void cl::PrintVersionMessage() {
1820 VersionPrinterInstance.print();
1821}
1822
Reid Spencerb3171672006-06-05 16:22:56 +00001823void cl::SetVersionPrinter(void (*func)()) {
1824 OverrideVersionPrinter = func;
1825}
Chandler Carruthea7e5522011-07-22 07:50:40 +00001826
1827void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001828 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001829 ExtraVersionPrinters = new std::vector<void (*)()>;
1830
1831 ExtraVersionPrinters->push_back(func);
1832}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001833
1834void cl::getRegisteredOptions(StringMap<Option*> &Map)
1835{
1836 // Get all the options.
1837 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1838 SmallVector<Option*, 4> SinkOpts; //NOT USED
1839 assert(Map.size() == 0 && "StringMap must be empty");
1840 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1841 return;
1842}
Peter Collingbournee1863192014-10-16 22:47:52 +00001843
1844void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1845 const char *Overview) {
1846 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1847}