blob: 8e937794be6d89b0c1a8d7474e321f9b352f626b [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-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 Lattner03fe1bd2001-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 Lattnerdbab15a2001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Chris Lattnerca179342009-08-23 18:09:02 +000020#include "llvm/ADT/OwningPtr.h"
Chris Lattner67aead62009-09-20 05:12:14 +000021#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner970e7df2009-09-19 23:59:02 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner67aead62009-09-20 05:12:14 +000023#include "llvm/ADT/StringMap.h"
Chris Lattnera460beb2009-09-19 18:55:05 +000024#include "llvm/ADT/Twine.h"
Chris Lattnerca179342009-08-23 18:09:02 +000025#include "llvm/Config/config.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/Host.h"
29#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/Path.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/system_error.h"
Brian Gaeke2d6a2362003-10-10 17:01:36 +000034#include <cerrno>
Chris Lattnerca179342009-08-23 18:09:02 +000035#include <cstdlib>
Andrew Trickb7ad33b2013-05-06 21:56:23 +000036#include <map>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000037using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000038using namespace cl;
39
Chris Lattner7422a762006-08-27 12:45:47 +000040//===----------------------------------------------------------------------===//
41// Template instantiations and anchors.
42//
Douglas Gregorb3587cf2009-11-25 06:04:18 +000043namespace llvm { namespace cl {
Chris Lattner7422a762006-08-27 12:45:47 +000044TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000045TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000046TEMPLATE_INSTANTIATION(class basic_parser<int>);
47TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramerb3514562011-09-15 21:17:37 +000048TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner7422a762006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<double>);
50TEMPLATE_INSTANTIATION(class basic_parser<float>);
51TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000052TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000053
54TEMPLATE_INSTANTIATION(class opt<unsigned>);
55TEMPLATE_INSTANTIATION(class opt<int>);
56TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000057TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000058TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregorb3587cf2009-11-25 06:04:18 +000059} } // end namespace llvm::cl
Chris Lattner7422a762006-08-27 12:45:47 +000060
David Blaikie0becc962011-12-01 08:00:17 +000061void GenericOptionValue::anchor() {}
62void OptionValue<boolOrDefault>::anchor() {}
63void OptionValue<std::string>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000064void Option::anchor() {}
65void basic_parser_impl::anchor() {}
66void parser<bool>::anchor() {}
Dale Johannesen81da02b2007-05-22 17:14:46 +000067void parser<boolOrDefault>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000068void parser<int>::anchor() {}
69void parser<unsigned>::anchor() {}
Benjamin Kramerb3514562011-09-15 21:17:37 +000070void parser<unsigned long long>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000071void parser<double>::anchor() {}
72void parser<float>::anchor() {}
73void parser<std::string>::anchor() {}
Bill Wendlingb587f962009-04-29 23:26:16 +000074void parser<char>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000075
76//===----------------------------------------------------------------------===//
77
Chris Lattnerefa3da52006-10-13 00:06:24 +000078// Globals for name and overview of program. Program name is not a string to
79// avoid static ctor/dtor issues.
80static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000081static const char *ProgramOverview = 0;
82
Chris Lattnerc540ebb2004-11-19 17:08:15 +000083// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000084static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000085
Chris Lattner90aa8392006-10-04 21:52:35 +000086extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000087 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000088 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000089}
90
Chris Lattner69d6f132007-04-12 00:36:29 +000091static bool OptionListChanged = false;
92
93// MarkOptionsChanged - Internal helper function.
94void cl::MarkOptionsChanged() {
95 OptionListChanged = true;
96}
97
Chris Lattner9878d6a2007-04-06 21:06:55 +000098/// RegisteredOptionList - This is the list of the command line options that
99/// have statically constructed themselves.
100static Option *RegisteredOptionList = 0;
101
102void Option::addArgument() {
103 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000104
Chris Lattner9878d6a2007-04-06 21:06:55 +0000105 NextRegistered = RegisteredOptionList;
106 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +0000107 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000108}
109
Andrew Trickb7ad33b2013-05-06 21:56:23 +0000110// This collects the different option categories that have been registered.
111typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
112static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
113
114// Initialise the general option category.
115OptionCategory llvm::cl::GeneralCategory("General options");
116
117void OptionCategory::registerCategory()
118{
119 RegisteredOptionCategories->insert(this);
120}
Chris Lattner69d6f132007-04-12 00:36:29 +0000121
Chris Lattner331de232002-07-22 02:07:59 +0000122//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +0000123// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +0000124//
125
Chris Lattner9878d6a2007-04-06 21:06:55 +0000126/// GetOptionInfo - Scan the list of registered options, turning them into data
127/// structures that are easier to handle.
Chris Lattner49b301c2009-09-20 06:18:38 +0000128static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
129 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer461c8762009-09-19 10:01:45 +0000130 StringMap<Option*> &OptionsMap) {
Chris Lattner1908aea2009-09-20 06:21:43 +0000131 SmallVector<const char*, 16> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000132 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000133 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
134 // If this option wants to handle multiple option names, get the full set.
135 // This handles enum options like "-O1 -O2" etc.
136 O->getExtraOptionNames(OptionNames);
137 if (O->ArgStr[0])
138 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000139
Chris Lattner9878d6a2007-04-06 21:06:55 +0000140 // Handle named options.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000141 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000142 // Add argument to the argument map!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000143 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000144 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijman33540ad2008-05-30 13:26:11 +0000145 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner9878d6a2007-04-06 21:06:55 +0000146 }
147 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000148
Chris Lattner9878d6a2007-04-06 21:06:55 +0000149 OptionNames.clear();
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000150
Chris Lattner9878d6a2007-04-06 21:06:55 +0000151 // Remember information about positional options.
152 if (O->getFormattingFlag() == cl::Positional)
153 PositionalOpts.push_back(O);
Dan Gohman61e015f2008-02-23 01:55:25 +0000154 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000155 SinkOpts.push_back(O);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000156 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000157 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000158 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000159 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000160 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000161 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000162
Chris Lattneree2b3202007-04-07 05:38:53 +0000163 if (CAOpt)
164 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000165
Chris Lattneree2b3202007-04-07 05:38:53 +0000166 // Make sure that they are in order of registration not backwards.
167 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000168}
169
Chris Lattner9878d6a2007-04-06 21:06:55 +0000170
Chris Lattneraf035f32007-04-05 21:58:17 +0000171/// LookupOption - Lookup the option specified by the specified option on the
172/// command line. If there is a value specified (after an equal sign) return
Chris Lattnerb1687372009-09-20 05:03:30 +0000173/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner8a7a0582009-09-20 02:02:24 +0000174static Option *LookupOption(StringRef &Arg, StringRef &Value,
175 const StringMap<Option*> &OptionsMap) {
Chris Lattner8a7a0582009-09-20 02:02:24 +0000176 // Reject all dashes.
177 if (Arg.empty()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000178
Chris Lattner8a7a0582009-09-20 02:02:24 +0000179 size_t EqualPos = Arg.find('=');
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000180
Chris Lattner4e247ec2009-09-20 01:53:12 +0000181 // If we have an equals sign, remember the value.
Chris Lattnerb1687372009-09-20 05:03:30 +0000182 if (EqualPos == StringRef::npos) {
183 // Look up the option.
184 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
185 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000186 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000187
Chris Lattnerb1687372009-09-20 05:03:30 +0000188 // If the argument before the = is a valid option name, we match. If not,
189 // return Arg unmolested.
190 StringMap<Option*>::const_iterator I =
191 OptionsMap.find(Arg.substr(0, EqualPos));
192 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000193
Chris Lattnerb1687372009-09-20 05:03:30 +0000194 Value = Arg.substr(EqualPos+1);
195 Arg = Arg.substr(0, EqualPos);
196 return I->second;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000197}
198
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000199/// LookupNearestOption - Lookup the closest match to the option specified by
200/// the specified option on the command line. If there is a value specified
201/// (after an equal sign) return that as well. This assumes that leading dashes
202/// have already been stripped.
203static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000204 const StringMap<Option*> &OptionsMap,
Nick Lewycky95d206a2011-05-02 05:24:47 +0000205 std::string &NearestString) {
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000206 // Reject all dashes.
207 if (Arg.empty()) return 0;
208
209 // Split on any equal sign.
Nick Lewycky95d206a2011-05-02 05:24:47 +0000210 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
211 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
212 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000213
214 // Find the closest match.
215 Option *Best = 0;
216 unsigned BestDistance = 0;
217 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
218 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000219 Option *O = it->second;
220 SmallVector<const char*, 16> OptionNames;
221 O->getExtraOptionNames(OptionNames);
222 if (O->ArgStr[0])
223 OptionNames.push_back(O->ArgStr);
224
Nick Lewycky95d206a2011-05-02 05:24:47 +0000225 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
226 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000227 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
228 StringRef Name = OptionNames[i];
229 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewycky95d206a2011-05-02 05:24:47 +0000230 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000231 if (!Best || Distance < BestDistance) {
232 Best = O;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000233 BestDistance = Distance;
Bill Wendling2127c9b2012-07-19 00:15:11 +0000234 if (RHS.empty() || !PermitValue)
235 NearestString = OptionNames[i];
236 else
237 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000238 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000239 }
240 }
241
242 return Best;
243}
244
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000245/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
246/// does special handling of cl::CommaSeparated options.
247static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
248 StringRef ArgName,
249 StringRef Value, bool MultiArg = false)
250{
251 // Check to see if this option accepts a comma separated list of values. If
252 // it does, we have to split up the value into multiple values.
253 if (Handler->getMiscFlags() & CommaSeparated) {
254 StringRef Val(Value);
255 StringRef::size_type Pos = Val.find(',');
Chris Lattnerb1687372009-09-20 05:03:30 +0000256
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000257 while (Pos != StringRef::npos) {
258 // Process the portion before the comma.
259 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
260 return true;
261 // Erase the portion before the comma, AND the comma.
262 Val = Val.substr(Pos+1);
263 Value.substr(Pos+1); // Increment the original value pointer as well.
264 // Check for another comma.
265 Pos = Val.find(',');
266 }
267
268 Value = Val;
269 }
270
271 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
272 return true;
273
274 return false;
275}
Chris Lattnerb1687372009-09-20 05:03:30 +0000276
Chris Lattner341620b2009-09-20 01:49:31 +0000277/// ProvideOption - For Value, this differentiates between an empty value ("")
278/// and a null value (StringRef()). The later is accepted for arguments that
279/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000280static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikieebba0552012-02-07 19:36:01 +0000281 StringRef Value, int argc,
282 const char *const *argv, int &i) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000283 // Is this a multi-argument option?
284 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
285
Chris Lattnercaccd762001-10-27 05:54:17 +0000286 // Enforce value requirements
287 switch (Handler->getValueExpectedFlag()) {
288 case ValueRequired:
Chris Lattner341620b2009-09-20 01:49:31 +0000289 if (Value.data() == 0) { // No value specified?
Chris Lattnerba112292009-09-20 00:07:40 +0000290 if (i+1 >= argc)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000291 return Handler->error("requires a value!");
Chris Lattnerba112292009-09-20 00:07:40 +0000292 // Steal the next argument, like for '-o filename'
293 Value = argv[++i];
Chris Lattnercaccd762001-10-27 05:54:17 +0000294 }
295 break;
296 case ValueDisallowed:
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000297 if (NumAdditionalVals > 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000298 return Handler->error("multi-valued option specified"
Chris Lattnerba112292009-09-20 00:07:40 +0000299 " with ValueDisallowed modifier!");
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000300
Chris Lattner341620b2009-09-20 01:49:31 +0000301 if (Value.data())
Benjamin Kramere6864c12009-08-02 12:13:02 +0000302 return Handler->error("does not allow a value! '" +
Chris Lattnera460beb2009-09-19 18:55:05 +0000303 Twine(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000304 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000305 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000306 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000307 }
308
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000309 // If this isn't a multi-arg option, just run the handler.
Chris Lattnera460beb2009-09-19 18:55:05 +0000310 if (NumAdditionalVals == 0)
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000311 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
Chris Lattnera460beb2009-09-19 18:55:05 +0000312
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000313 // If it is, run the handle several times.
Chris Lattnera460beb2009-09-19 18:55:05 +0000314 bool MultiArg = false;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000315
Chris Lattner341620b2009-09-20 01:49:31 +0000316 if (Value.data()) {
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000317 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000318 return true;
319 --NumAdditionalVals;
320 MultiArg = true;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000321 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000322
323 while (NumAdditionalVals > 0) {
Chris Lattnera460beb2009-09-19 18:55:05 +0000324 if (i+1 >= argc)
325 return Handler->error("not enough values!");
326 Value = argv[++i];
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000327
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000328 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000329 return true;
330 MultiArg = true;
331 --NumAdditionalVals;
332 }
333 return false;
Chris Lattnercaccd762001-10-27 05:54:17 +0000334}
335
Chris Lattnerba112292009-09-20 00:07:40 +0000336static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000337 int Dummy = i;
Chris Lattner341620b2009-09-20 01:49:31 +0000338 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000339}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000340
Chris Lattner331de232002-07-22 02:07:59 +0000341
342// Option predicates...
343static inline bool isGrouping(const Option *O) {
344 return O->getFormattingFlag() == cl::Grouping;
345}
346static inline bool isPrefixedOrGrouping(const Option *O) {
347 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
348}
349
350// getOptionPred - Check to see if there are any options that satisfy the
351// specified predicate with names that are the prefixes in Name. This is
352// checked by progressively stripping characters off of the name, checking to
353// see if there options that satisfy the predicate. If we find one, return it,
354// otherwise return null.
355//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000356static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000357 bool (*Pred)(const Option*),
Chris Lattnerb1687372009-09-20 05:03:30 +0000358 const StringMap<Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000359
Chris Lattnerb1687372009-09-20 05:03:30 +0000360 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000361
Chris Lattnerb1687372009-09-20 05:03:30 +0000362 // Loop while we haven't found an option and Name still has at least two
363 // characters in it (so that the next iteration will not be the empty
364 // string.
365 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000366 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000367 OMI = OptionsMap.find(Name);
Chris Lattnerb1687372009-09-20 05:03:30 +0000368 }
Chris Lattner331de232002-07-22 02:07:59 +0000369
Chris Lattner9878d6a2007-04-06 21:06:55 +0000370 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000371 Length = Name.size();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000372 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000373 }
374 return 0; // No option found!
375}
376
Chris Lattnerb1687372009-09-20 05:03:30 +0000377/// HandlePrefixedOrGroupedOption - The specified argument string (which started
378/// with at least one '-') does not fully match an available option. Check to
379/// see if this is a prefix or grouped option. If so, split arg into output an
380/// Arg/Value pair and return the Option to parse it with.
381static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
382 bool &ErrorParsing,
383 const StringMap<Option*> &OptionsMap) {
384 if (Arg.size() == 1) return 0;
385
386 // Do the lookup!
387 size_t Length = 0;
388 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
389 if (PGOpt == 0) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000390
Chris Lattnerb1687372009-09-20 05:03:30 +0000391 // If the option is a prefixed option, then the value is simply the
392 // rest of the name... so fall through to later processing, by
393 // setting up the argument name flags and value fields.
394 if (PGOpt->getFormattingFlag() == cl::Prefix) {
395 Value = Arg.substr(Length);
396 Arg = Arg.substr(0, Length);
397 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
398 return PGOpt;
399 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000400
Chris Lattnerb1687372009-09-20 05:03:30 +0000401 // This must be a grouped option... handle them now. Grouping options can't
402 // have values.
403 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000404
Chris Lattnerb1687372009-09-20 05:03:30 +0000405 do {
406 // Move current arg name out of Arg into OneArgName.
407 StringRef OneArgName = Arg.substr(0, Length);
408 Arg = Arg.substr(Length);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000409
Chris Lattnerb1687372009-09-20 05:03:30 +0000410 // Because ValueRequired is an invalid flag for grouped arguments,
411 // we don't need to pass argc/argv in.
412 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
413 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sands1fa8b002010-01-09 08:30:33 +0000414 int Dummy = 0;
Chris Lattnerb1687372009-09-20 05:03:30 +0000415 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
416 StringRef(), 0, 0, Dummy);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000417
Chris Lattnerb1687372009-09-20 05:03:30 +0000418 // Get the next grouping option.
419 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
420 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000421
Chris Lattnerb1687372009-09-20 05:03:30 +0000422 // Return the last option with Arg cut down to just the last one.
423 return PGOpt;
424}
425
426
427
Chris Lattner331de232002-07-22 02:07:59 +0000428static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000429 return O->getNumOccurrencesFlag() == cl::Required ||
430 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000431}
432
433static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000434 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
435 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000436}
Chris Lattnercaccd762001-10-27 05:54:17 +0000437
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000438/// ParseCStringVector - Break INPUT up wherever one or more
439/// whitespace characters are found, and store the resulting tokens in
440/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000441/// using strdup(), so it is the caller's responsibility to free()
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000442/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000443///
Chris Lattner63e944b2009-09-24 05:38:36 +0000444static void ParseCStringVector(std::vector<char *> &OutputVector,
445 const char *Input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000446 // Characters which will be treated as token separators:
Chris Lattner63e944b2009-09-24 05:38:36 +0000447 StringRef Delims = " \v\f\t\r\n";
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000448
Chris Lattner63e944b2009-09-24 05:38:36 +0000449 StringRef WorkStr(Input);
450 while (!WorkStr.empty()) {
451 // If the first character is a delimiter, strip them off.
452 if (Delims.find(WorkStr[0]) != StringRef::npos) {
453 size_t Pos = WorkStr.find_first_not_of(Delims);
454 if (Pos == StringRef::npos) Pos = WorkStr.size();
455 WorkStr = WorkStr.substr(Pos);
456 continue;
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000457 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000458
Chris Lattner63e944b2009-09-24 05:38:36 +0000459 // Find position of first delimiter.
460 size_t Pos = WorkStr.find_first_of(Delims);
461 if (Pos == StringRef::npos) Pos = WorkStr.size();
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000462
Chris Lattner63e944b2009-09-24 05:38:36 +0000463 // Everything from 0 to Pos is the next word to copy.
464 char *NewStr = (char*)malloc(Pos+1);
465 memcpy(NewStr, WorkStr.data(), Pos);
466 NewStr[Pos] = 0;
467 OutputVector.push_back(NewStr);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000468
Chris Lattner63e944b2009-09-24 05:38:36 +0000469 WorkStr = WorkStr.substr(Pos);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000470 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000471}
472
473/// ParseEnvironmentOptions - An alternative entry point to the
474/// CommandLine library, which allows you to read the program's name
475/// from the caller (as PROGNAME) and its command-line arguments from
476/// an environment variable (whose name is given in ENVVAR).
477///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000478void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000479 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000480 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000481 assert(progName && "Program name not specified");
482 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000483
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000484 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000485 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000486 if (!envValue)
487 return;
488
Brian Gaeke06b06c52003-08-14 22:00:59 +0000489 // Get program's "name", which we wouldn't know without the caller
490 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000491 std::vector<char*> newArgv;
492 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000493
494 // Parse the value of the environment variable into a "command line"
495 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000496 ParseCStringVector(newArgv, envValue);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000497 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000498 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000499
500 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000501 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
502 i != e; ++i)
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000503 free(*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000504}
505
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000506
507/// ExpandResponseFiles - Copy the contents of argv into newArgv,
508/// substituting the contents of the response files for the arguments
509/// of type @file.
David Blaikieebba0552012-02-07 19:36:01 +0000510static void ExpandResponseFiles(unsigned argc, const char*const* argv,
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000511 std::vector<char*>& newArgv) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000512 for (unsigned i = 1; i != argc; ++i) {
David Blaikieebba0552012-02-07 19:36:01 +0000513 const char *arg = argv[i];
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000514
515 if (arg[0] == '@') {
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000516 sys::PathWithStatus respFile(++arg);
517
518 // Check that the response file is not empty (mmap'ing empty
519 // files can be problematic).
520 const sys::FileStatus *FileStat = respFile.getFileStatus();
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000521 if (FileStat && FileStat->getSize() != 0) {
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000522
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000523 // If we could open the file, parse its contents, otherwise
524 // pass the @file option verbatim.
Mikhail Glushenkov6c55b1c2009-01-28 03:46:22 +0000525
526 // TODO: we should also support recursive loading of response files,
527 // since this is how gcc behaves. (From their man page: "The file may
528 // itself contain additional @file options; any such options will be
529 // processed recursively.")
530
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000531 // Mmap the response file into memory.
532 OwningPtr<MemoryBuffer> respFilePtr;
533 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000534 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
535 continue;
536 }
537 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000538 }
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000539 newArgv.push_back(strdup(arg));
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000540 }
541}
542
David Blaikieebba0552012-02-07 19:36:01 +0000543void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000544 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000545 // Process all registered options.
Chris Lattner49b301c2009-09-20 06:18:38 +0000546 SmallVector<Option*, 4> PositionalOpts;
547 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +0000548 StringMap<Option*> Opts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000549 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000550
Chris Lattner9878d6a2007-04-06 21:06:55 +0000551 assert((!Opts.empty() || !PositionalOpts.empty()) &&
552 "No options specified!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000553
554 // Expand response files.
555 std::vector<char*> newArgv;
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000556 newArgv.push_back(strdup(argv[0]));
557 ExpandResponseFiles(argc, argv, newArgv);
558 argv = &newArgv[0];
559 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000560
Chris Lattnerefa3da52006-10-13 00:06:24 +0000561 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencerb3127bb2010-12-18 00:19:10 +0000562 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000563 size_t Len = std::min(ProgName.size(), size_t(79));
564 memcpy(ProgramName, ProgName.data(), Len);
565 ProgramName[Len] = '\0';
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000566
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000567 ProgramOverview = Overview;
568 bool ErrorParsing = false;
569
Chris Lattner331de232002-07-22 02:07:59 +0000570 // Check out the positional arguments to collect information about them.
571 unsigned NumPositionalRequired = 0;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000572
Chris Lattnerde013242005-08-08 17:25:38 +0000573 // Determine whether or not there are an unlimited number of positionals
574 bool HasUnlimitedPositionals = false;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000575
Chris Lattner331de232002-07-22 02:07:59 +0000576 Option *ConsumeAfterOpt = 0;
577 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000578 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000579 assert(PositionalOpts.size() > 1 &&
580 "Cannot specify cl::ConsumeAfter without a positional argument!");
581 ConsumeAfterOpt = PositionalOpts[0];
582 }
583
584 // Calculate how many positional values are _required_.
585 bool UnboundedFound = false;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000586 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner331de232002-07-22 02:07:59 +0000587 i != e; ++i) {
588 Option *Opt = PositionalOpts[i];
589 if (RequiresValue(Opt))
590 ++NumPositionalRequired;
591 else if (ConsumeAfterOpt) {
592 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000593 // unless there is only one positional argument...
594 if (PositionalOpts.size() > 2)
595 ErrorParsing |=
Benjamin Kramere6864c12009-08-02 12:13:02 +0000596 Opt->error("error - this positional option will never be matched, "
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000597 "because it does not Require a value, and a "
598 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000599 } else if (UnboundedFound && !Opt->ArgStr[0]) {
600 // This option does not "require" a value... Make sure this option is
601 // not specified after an option that eats all extra arguments, or this
602 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000603 //
Benjamin Kramere6864c12009-08-02 12:13:02 +0000604 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner331de232002-07-22 02:07:59 +0000605 "another positional argument will match an "
606 "unbounded number of values, and this option"
607 " does not require a value!");
608 }
609 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
610 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000611 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000612 }
613
Reid Spencer1e13fd22004-08-13 19:47:30 +0000614 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerba112292009-09-20 00:07:40 +0000615 // the process at the end.
Chris Lattner331de232002-07-22 02:07:59 +0000616 //
Chris Lattnerba112292009-09-20 00:07:40 +0000617 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000618
Chris Lattner9cf3d472003-07-30 17:34:02 +0000619 // If the program has named positional arguments, and the name has been run
620 // across, keep track of which positional argument was named. Otherwise put
621 // the positional args into the PositionalVals list...
622 Option *ActivePositionalArg = 0;
623
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000624 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000625 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000626 for (int i = 1; i < argc; ++i) {
627 Option *Handler = 0;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000628 Option *NearestHandler = 0;
Nick Lewycky95d206a2011-05-02 05:24:47 +0000629 std::string NearestHandlerString;
Chris Lattner4e247ec2009-09-20 01:53:12 +0000630 StringRef Value;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000631 StringRef ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000632
Chris Lattner69d6f132007-04-12 00:36:29 +0000633 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000634 // option has just been registered or deregistered. This can occur in
635 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000636 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000637 PositionalOpts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000638 SinkOpts.clear();
Chris Lattner159b0a432007-04-11 15:35:18 +0000639 Opts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000640 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000641 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000642 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000643
Chris Lattner331de232002-07-22 02:07:59 +0000644 // Check to see if this is a positional argument. This argument is
645 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000646 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000647 //
648 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
649 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000650 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000651 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000652 continue; // We are done!
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000653 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000654
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000655 if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000656 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000657
658 // All of the positional arguments have been fulfulled, give the rest to
659 // the consume after option... if it's specified...
660 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000661 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000662 ConsumeAfterOpt != 0) {
663 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000664 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000665 break; // Handle outside of the argument processing loop...
666 }
667
668 // Delay processing positional arguments until the end...
669 continue;
670 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000671 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
672 !DashDashFound) {
673 DashDashFound = true; // This is the mythical "--"?
674 continue; // Don't try to process it as an argument itself.
675 } else if (ActivePositionalArg &&
676 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
677 // If there is a positional argument eating options, check to see if this
678 // option is another positional argument. If so, treat it as an argument,
679 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000680 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000681 // Eat leading dashes.
682 while (!ArgName.empty() && ArgName[0] == '-')
683 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000684
Chris Lattner9878d6a2007-04-06 21:06:55 +0000685 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000686 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000687 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000688 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000689 }
690
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000691 } else { // We start with a '-', must be an argument.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000692 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000693 // Eat leading dashes.
694 while (!ArgName.empty() && ArgName[0] == '-')
695 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000696
Chris Lattner9878d6a2007-04-06 21:06:55 +0000697 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000698
Chris Lattnerbf455c22004-05-06 22:04:31 +0000699 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnerb1687372009-09-20 05:03:30 +0000700 if (Handler == 0)
701 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
702 ErrorParsing, Opts);
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000703
704 // Otherwise, look for the closest available option to report to the user
705 // in the upcoming error.
706 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000707 NearestHandler = LookupNearestOption(ArgName, Opts,
708 NearestHandlerString);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000709 }
710
711 if (Handler == 0) {
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000712 if (SinkOpts.empty()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000713 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000714 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000715
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000716 if (NearestHandler) {
717 // If we know a near match, report it as well.
718 errs() << ProgramName << ": Did you mean '-"
719 << NearestHandlerString << "'?\n";
720 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000721
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000722 ErrorParsing = true;
723 } else {
Chris Lattner49b301c2009-09-20 06:18:38 +0000724 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000725 E = SinkOpts.end(); I != E ; ++I)
726 (*I)->addOccurrence(i, "", argv[i]);
727 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000728 continue;
729 }
730
Chris Lattner9cf3d472003-07-30 17:34:02 +0000731 // If this is a named positional argument, just remember that it is the
732 // active one...
733 if (Handler->getFormattingFlag() == cl::Positional)
734 ActivePositionalArg = Handler;
Chris Lattner341620b2009-09-20 01:49:31 +0000735 else
Chris Lattner4e247ec2009-09-20 01:53:12 +0000736 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000737 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000738
Chris Lattner331de232002-07-22 02:07:59 +0000739 // Check and handle positional arguments now...
740 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000741 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000742 << ": Not enough positional command line arguments specified!\n"
743 << "Must specify at least " << NumPositionalRequired
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000744 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000745
Chris Lattner331de232002-07-22 02:07:59 +0000746 ErrorParsing = true;
Dan Gohman16e02092010-03-24 19:38:02 +0000747 } else if (!HasUnlimitedPositionals &&
748 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000749 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000750 << ": Too many positional arguments specified!\n"
751 << "Can specify at most " << PositionalOpts.size()
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000752 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000753 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000754
755 } else if (ConsumeAfterOpt == 0) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000756 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000757 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
758 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner331de232002-07-22 02:07:59 +0000759 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000760 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000761 PositionalVals[ValNo].second);
762 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000763 --NumPositionalRequired; // We fulfilled our duty...
764 }
765
766 // If we _can_ give this option more arguments, do so now, as long as we
767 // do not give it values that others need. 'Done' controls whether the
768 // option even _WANTS_ any more.
769 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000770 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000771 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000772 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000773 case cl::Optional:
774 Done = true; // Optional arguments want _at most_ one value
775 // FALL THROUGH
776 case cl::ZeroOrMore: // Zero or more will take all they can get...
777 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000778 ProvidePositionalOption(PositionalOpts[i],
779 PositionalVals[ValNo].first,
780 PositionalVals[ValNo].second);
781 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000782 break;
783 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000784 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000785 "positional argument processing!");
786 }
787 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000788 }
Chris Lattner331de232002-07-22 02:07:59 +0000789 } else {
790 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
791 unsigned ValNo = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000792 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000793 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000794 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000795 PositionalVals[ValNo].first,
796 PositionalVals[ValNo].second);
797 ValNo++;
798 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000799
800 // Handle the case where there is just one positional option, and it's
801 // optional. In this case, we want to give JUST THE FIRST option to the
802 // positional option and keep the rest for the consume after. The above
803 // loop would have assigned no values to positional options in this case.
804 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000805 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000806 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000807 PositionalVals[ValNo].first,
808 PositionalVals[ValNo].second);
809 ValNo++;
810 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000811
Chris Lattner331de232002-07-22 02:07:59 +0000812 // Handle over all of the rest of the arguments to the
813 // cl::ConsumeAfter command line option...
814 for (; ValNo != PositionalVals.size(); ++ValNo)
815 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000816 PositionalVals[ValNo].first,
817 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000818 }
819
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000820 // Loop over args and make sure all required args are specified!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000821 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000822 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000823 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000824 case Required:
825 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000826 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramere6864c12009-08-02 12:13:02 +0000827 I->second->error("must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000828 ErrorParsing = true;
829 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000830 // Fall through
831 default:
832 break;
833 }
834 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000835
Rafael Espindolaa962b402010-11-19 21:14:29 +0000836 // Now that we know if -debug is specified, we can use it.
837 // Note that if ReadResponseFiles == true, this must be done before the
838 // memory allocated for the expanded command line is free()d below.
839 DEBUG(dbgs() << "Args: ";
840 for (int i = 0; i < argc; ++i)
841 dbgs() << argv[i] << ' ';
842 dbgs() << '\n';
843 );
844
Chris Lattner331de232002-07-22 02:07:59 +0000845 // Free all of the memory allocated to the map. Command line options may only
846 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000847 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000848 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000849 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000850
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000851 // Free the memory allocated by ExpandResponseFiles.
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000852 // Free all the strdup()ed strings.
853 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
854 i != e; ++i)
855 free(*i);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000856
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000857 // If we had an error processing our arguments, don't let the program execute
858 if (ErrorParsing) exit(1);
859}
860
861//===----------------------------------------------------------------------===//
862// Option Base class implementation
863//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000864
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000865bool Option::error(const Twine &Message, StringRef ArgName) {
866 if (ArgName.data() == 0) ArgName = ArgStr;
867 if (ArgName.empty())
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000868 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000869 else
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000870 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000871
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000872 errs() << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000873 return true;
874}
875
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000876bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000877 StringRef Value, bool MultiArg) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000878 if (!MultiArg)
879 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000880
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000881 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000882 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000883 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000884 return error("may only occur zero or one times!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000885 break;
886 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000887 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000888 return error("must occur exactly one time!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000889 // Fall through
890 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000891 case ZeroOrMore:
892 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000893 }
894
Reid Spencer1e13fd22004-08-13 19:47:30 +0000895 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000896}
897
Chris Lattner331de232002-07-22 02:07:59 +0000898
899// getValueStr - Get the value description string, using "DefaultMsg" if nothing
900// has been specified yet.
901//
902static const char *getValueStr(const Option &O, const char *DefaultMsg) {
903 if (O.ValueStr[0] == 0) return DefaultMsg;
904 return O.ValueStr;
905}
906
907//===----------------------------------------------------------------------===//
908// cl::alias class implementation
909//
910
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000911// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000912size_t alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000913 return std::strlen(ArgStr)+6;
914}
915
Chris Lattnera0de8432006-04-28 05:36:25 +0000916// Print out the option for the alias.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000917void alias::printOptionInfo(size_t GlobalWidth) const {
918 size_t L = std::strlen(ArgStr);
Evan Chengff276b42011-06-13 20:45:54 +0000919 outs() << " -" << ArgStr;
920 outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000921}
922
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000923//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000924// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000925//
926
Chris Lattner9b14eb52002-08-07 18:36:37 +0000927// basic_parser implementation
928//
929
930// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000931size_t basic_parser_impl::getOptionWidth(const Option &O) const {
932 size_t Len = std::strlen(O.ArgStr);
Chris Lattner9b14eb52002-08-07 18:36:37 +0000933 if (const char *ValName = getValueName())
934 Len += std::strlen(getValueStr(O, ValName))+3;
935
936 return Len + 6;
937}
938
Misha Brukmanf976c852005-04-21 22:55:34 +0000939// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000940// to-be-maintained width is specified.
941//
942void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +0000943 size_t GlobalWidth) const {
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000944 outs() << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000945
946 if (const char *ValName = getValueName())
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000947 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattner9b14eb52002-08-07 18:36:37 +0000948
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000949 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
Chris Lattner9b14eb52002-08-07 18:36:37 +0000950}
951
Andrew Trickce969022011-04-05 18:54:36 +0000952void basic_parser_impl::printOptionName(const Option &O,
953 size_t GlobalWidth) const {
954 outs() << " -" << O.ArgStr;
955 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
956}
Chris Lattner9b14eb52002-08-07 18:36:37 +0000957
958
Chris Lattner331de232002-07-22 02:07:59 +0000959// parser<bool> implementation
960//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000961bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000962 StringRef Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000963 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000964 Arg == "1") {
965 Value = true;
Chris Lattnera460beb2009-09-19 18:55:05 +0000966 return false;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000967 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000968
Chris Lattnera460beb2009-09-19 18:55:05 +0000969 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
970 Value = false;
971 return false;
972 }
973 return O.error("'" + Arg +
974 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000975}
976
Dale Johannesen81da02b2007-05-22 17:14:46 +0000977// parser<boolOrDefault> implementation
978//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000979bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000980 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen81da02b2007-05-22 17:14:46 +0000981 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
982 Arg == "1") {
983 Value = BOU_TRUE;
Chris Lattnera460beb2009-09-19 18:55:05 +0000984 return false;
Dale Johannesen81da02b2007-05-22 17:14:46 +0000985 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000986 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
987 Value = BOU_FALSE;
988 return false;
989 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000990
Chris Lattnera460beb2009-09-19 18:55:05 +0000991 return O.error("'" + Arg +
992 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen81da02b2007-05-22 17:14:46 +0000993}
994
Chris Lattner331de232002-07-22 02:07:59 +0000995// parser<int> implementation
996//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000997bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000998 StringRef Arg, int &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +0000999 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001000 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001001 return false;
1002}
1003
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001004// parser<unsigned> implementation
1005//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001006bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001007 StringRef Arg, unsigned &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001008
1009 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001010 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001011 return false;
1012}
1013
Benjamin Kramerb3514562011-09-15 21:17:37 +00001014// parser<unsigned long long> implementation
1015//
1016bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1017 StringRef Arg, unsigned long long &Value){
1018
1019 if (Arg.getAsInteger(0, Value))
1020 return O.error("'" + Arg + "' value invalid for uint argument!");
1021 return false;
1022}
1023
Chris Lattner9b14eb52002-08-07 18:36:37 +00001024// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +00001025//
Chris Lattnera460beb2009-09-19 18:55:05 +00001026static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001027 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1028 const char *ArgStart = TmpStr.c_str();
Chris Lattner331de232002-07-22 02:07:59 +00001029 char *End;
1030 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +00001031 if (*End != 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001032 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +00001033 return false;
1034}
1035
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001036bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001037 StringRef Arg, double &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001038 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +00001039}
1040
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001041bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001042 StringRef Arg, float &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001043 double dVal;
1044 if (parseDouble(O, Arg, dVal))
1045 return true;
1046 Val = (float)dVal;
1047 return false;
Chris Lattner331de232002-07-22 02:07:59 +00001048}
1049
1050
Chris Lattner331de232002-07-22 02:07:59 +00001051
1052// generic_parser_base implementation
1053//
1054
Chris Lattneraa852bb2002-07-23 17:15:12 +00001055// findOption - Return the option number corresponding to the specified
1056// argument string. If the option is not found, getNumOptions() is returned.
1057//
1058unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer461c8762009-09-19 10:01:45 +00001059 unsigned e = getNumOptions();
Chris Lattneraa852bb2002-07-23 17:15:12 +00001060
Benjamin Kramer461c8762009-09-19 10:01:45 +00001061 for (unsigned i = 0; i != e; ++i) {
1062 if (strcmp(getOption(i), Name) == 0)
Chris Lattneraa852bb2002-07-23 17:15:12 +00001063 return i;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001064 }
Chris Lattneraa852bb2002-07-23 17:15:12 +00001065 return e;
1066}
1067
1068
Chris Lattner331de232002-07-22 02:07:59 +00001069// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001070size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner331de232002-07-22 02:07:59 +00001071 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001072 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner331de232002-07-22 02:07:59 +00001073 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001074 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001075 return Size;
1076 } else {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001077 size_t BaseSize = 0;
Chris Lattner331de232002-07-22 02:07:59 +00001078 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001079 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001080 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001081 }
1082}
1083
Misha Brukmanf976c852005-04-21 22:55:34 +00001084// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +00001085// to-be-maintained width is specified.
1086//
1087void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001088 size_t GlobalWidth) const {
Chris Lattner331de232002-07-22 02:07:59 +00001089 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001090 size_t L = std::strlen(O.ArgStr);
Chris Lattnerb1687372009-09-20 05:03:30 +00001091 outs() << " -" << O.ArgStr;
1092 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001093
Chris Lattner331de232002-07-22 02:07:59 +00001094 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001095 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerb1687372009-09-20 05:03:30 +00001096 outs() << " =" << getOption(i);
1097 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattner9c9be482002-01-31 00:42:56 +00001098 }
Chris Lattner331de232002-07-22 02:07:59 +00001099 } else {
1100 if (O.HelpStr[0])
Chris Lattnerb1687372009-09-20 05:03:30 +00001101 outs() << " " << O.HelpStr << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001102 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001103 size_t L = std::strlen(getOption(i));
Chris Lattnerb1687372009-09-20 05:03:30 +00001104 outs() << " -" << getOption(i);
1105 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001106 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001107 }
1108}
1109
Andrew Trickce969022011-04-05 18:54:36 +00001110static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1111
1112// printGenericOptionDiff - Print the value of this option and it's default.
1113//
1114// "Generic" options have each value mapped to a name.
1115void generic_parser_base::
1116printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1117 const GenericOptionValue &Default,
1118 size_t GlobalWidth) const {
1119 outs() << " -" << O.ArgStr;
1120 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1121
1122 unsigned NumOpts = getNumOptions();
1123 for (unsigned i = 0; i != NumOpts; ++i) {
1124 if (Value.compare(getOptionValue(i)))
1125 continue;
1126
1127 outs() << "= " << getOption(i);
1128 size_t L = std::strlen(getOption(i));
1129 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1130 outs().indent(NumSpaces) << " (default: ";
1131 for (unsigned j = 0; j != NumOpts; ++j) {
1132 if (Default.compare(getOptionValue(j)))
1133 continue;
1134 outs() << getOption(j);
1135 break;
1136 }
1137 outs() << ")\n";
1138 return;
1139 }
1140 outs() << "= *unknown option value*\n";
1141}
1142
1143// printOptionDiff - Specializations for printing basic value types.
1144//
1145#define PRINT_OPT_DIFF(T) \
1146 void parser<T>:: \
1147 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1148 size_t GlobalWidth) const { \
1149 printOptionName(O, GlobalWidth); \
1150 std::string Str; \
1151 { \
1152 raw_string_ostream SS(Str); \
1153 SS << V; \
1154 } \
1155 outs() << "= " << Str; \
1156 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1157 outs().indent(NumSpaces) << " (default: "; \
1158 if (D.hasValue()) \
1159 outs() << D.getValue(); \
1160 else \
1161 outs() << "*no default*"; \
1162 outs() << ")\n"; \
1163 } \
1164
Frits van Bommel090771f2011-04-06 12:29:56 +00001165PRINT_OPT_DIFF(bool)
1166PRINT_OPT_DIFF(boolOrDefault)
1167PRINT_OPT_DIFF(int)
1168PRINT_OPT_DIFF(unsigned)
Benjamin Kramerb3514562011-09-15 21:17:37 +00001169PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel090771f2011-04-06 12:29:56 +00001170PRINT_OPT_DIFF(double)
1171PRINT_OPT_DIFF(float)
1172PRINT_OPT_DIFF(char)
Andrew Trickce969022011-04-05 18:54:36 +00001173
1174void parser<std::string>::
1175printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1176 size_t GlobalWidth) const {
1177 printOptionName(O, GlobalWidth);
1178 outs() << "= " << V;
1179 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1180 outs().indent(NumSpaces) << " (default: ";
1181 if (D.hasValue())
1182 outs() << D.getValue();
1183 else
1184 outs() << "*no default*";
1185 outs() << ")\n";
1186}
1187
1188// Print a placeholder for options that don't yet support printOptionDiff().
1189void basic_parser_impl::
1190printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1191 printOptionName(O, GlobalWidth);
1192 outs() << "= *cannot print option value*\n";
1193}
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001194
1195//===----------------------------------------------------------------------===//
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001196// -help and -help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001197//
Reid Spencerad0846b2004-11-14 22:04:00 +00001198
Chris Lattner0fd48b12009-09-20 05:37:24 +00001199static int OptNameCompare(const void *LHS, const void *RHS) {
1200 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001201
Duncan Sandse840fef2012-03-12 10:51:06 +00001202 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner0fd48b12009-09-20 05:37:24 +00001203}
1204
Andrew Trickce969022011-04-05 18:54:36 +00001205// Copy Options into a vector so we can sort them as we like.
1206static void
1207sortOpts(StringMap<Option*> &OptMap,
1208 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1209 bool ShowHidden) {
1210 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1211
1212 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1213 I != E; ++I) {
1214 // Ignore really-hidden options.
1215 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1216 continue;
1217
1218 // Unless showhidden is set, ignore hidden flags.
1219 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1220 continue;
1221
1222 // If we've already seen this option, don't add it to the list again.
1223 if (!OptionSet.insert(I->second))
1224 continue;
1225
1226 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1227 I->second));
1228 }
1229
1230 // Sort the options list alphabetically.
1231 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1232}
1233
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001234namespace {
1235
Chris Lattner331de232002-07-22 02:07:59 +00001236class HelpPrinter {
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001237protected:
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001238 const bool ShowHidden;
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001239 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1240 // Print the options. Opts is assumed to be alphabetically sorted.
1241 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1242 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1243 Opts[i].second->printOptionInfo(MaxArgLen);
1244 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001245
Chris Lattner331de232002-07-22 02:07:59 +00001246public:
Craig Topperddde2082013-03-09 23:29:37 +00001247 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001248 virtual ~HelpPrinter() {}
Chris Lattner331de232002-07-22 02:07:59 +00001249
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001250 // Invoke the printer.
Chris Lattner331de232002-07-22 02:07:59 +00001251 void operator=(bool Value) {
1252 if (Value == false) return;
1253
Chris Lattner9878d6a2007-04-06 21:06:55 +00001254 // Get all the options.
Chris Lattner49b301c2009-09-20 06:18:38 +00001255 SmallVector<Option*, 4> PositionalOpts;
1256 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001257 StringMap<Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +00001258 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001259
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001260 StrOptionPairVector Opts;
Andrew Trickce969022011-04-05 18:54:36 +00001261 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001262
1263 if (ProgramOverview)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001264 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001265
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001266 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +00001267
Chris Lattner90aa8392006-10-04 21:52:35 +00001268 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +00001269 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001270 if (!PositionalOpts.empty() &&
Chris Lattner9878d6a2007-04-06 21:06:55 +00001271 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1272 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +00001273
Evan Cheng34cd4a42008-05-05 18:30:58 +00001274 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +00001275 if (PositionalOpts[i]->ArgStr[0])
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001276 outs() << " --" << PositionalOpts[i]->ArgStr;
1277 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +00001278 }
Chris Lattner331de232002-07-22 02:07:59 +00001279
1280 // Print the consume after option info if it exists...
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001281 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +00001282
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001283 outs() << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001284
1285 // Compute the maximum argument length...
Craig Topperddde2082013-03-09 23:29:37 +00001286 size_t MaxArgLen = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +00001287 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0fd48b12009-09-20 05:37:24 +00001288 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001289
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001290 outs() << "OPTIONS:\n";
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001291 printOptions(Opts, MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001292
Chris Lattnerc540ebb2004-11-19 17:08:15 +00001293 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +00001294 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001295 E = MoreHelp->end();
1296 I != E; ++I)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001297 outs() << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001298 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001299
Reid Spencer9bbba0912004-11-16 06:11:52 +00001300 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001301 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001302 }
1303};
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001304
1305class CategorizedHelpPrinter : public HelpPrinter {
1306public:
1307 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1308
1309 // Helper function for printOptions().
1310 // It shall return true if A's name should be lexographically
1311 // ordered before B's name. It returns false otherwise.
1312 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1313 int Length = strcmp(A->getName(), B->getName());
1314 assert(Length != 0 && "Duplicate option categories");
1315 return Length < 0;
1316 }
1317
1318 // Make sure we inherit our base class's operator=()
1319 using HelpPrinter::operator= ;
1320
1321protected:
1322 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1323 std::vector<OptionCategory *> SortedCategories;
1324 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1325
1326 // Collect registered option categories into vector in preperation for
1327 // sorting.
1328 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1329 E = RegisteredOptionCategories->end();
1330 I != E; ++I)
1331 SortedCategories.push_back(*I);
1332
1333 // Sort the different option categories alphabetically.
1334 assert(SortedCategories.size() > 0 && "No option categories registered!");
1335 std::sort(SortedCategories.begin(), SortedCategories.end(),
1336 OptionCategoryCompare);
1337
1338 // Create map to empty vectors.
1339 for (std::vector<OptionCategory *>::const_iterator
1340 I = SortedCategories.begin(),
1341 E = SortedCategories.end();
1342 I != E; ++I)
1343 CategorizedOptions[*I] = std::vector<Option *>();
1344
1345 // Walk through pre-sorted options and assign into categories.
1346 // Because the options are already alphabetically sorted the
1347 // options within categories will also be alphabetically sorted.
1348 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1349 Option *Opt = Opts[I].second;
1350 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1351 "Option has an unregistered category");
1352 CategorizedOptions[Opt->Category].push_back(Opt);
1353 }
1354
1355 // Now do printing.
1356 for (std::vector<OptionCategory *>::const_iterator
1357 Category = SortedCategories.begin(),
1358 E = SortedCategories.end();
1359 Category != E; ++Category) {
1360 // Hide empty categories for -help, but show for -help-hidden.
1361 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1362 if (!ShowHidden && IsEmptyCategory)
1363 continue;
1364
1365 // Print category information.
1366 outs() << "\n";
1367 outs() << (*Category)->getName() << ":\n";
1368
1369 // Check if description is set.
1370 if ((*Category)->getDescription() != 0)
1371 outs() << (*Category)->getDescription() << "\n\n";
1372 else
1373 outs() << "\n";
1374
1375 // When using -help-hidden explicitly state if the category has no
1376 // options associated with it.
1377 if (IsEmptyCategory) {
1378 outs() << " This option category has no options.\n";
1379 continue;
1380 }
1381 // Loop over the options in the category and print.
1382 for (std::vector<Option *>::const_iterator
1383 Opt = CategorizedOptions[*Category].begin(),
1384 E = CategorizedOptions[*Category].end();
1385 Opt != E; ++Opt)
1386 (*Opt)->printOptionInfo(MaxArgLen);
1387 }
1388 }
1389};
1390
1391// This wraps the Uncategorizing and Categorizing printers and decides
1392// at run time which should be invoked.
1393class HelpPrinterWrapper {
1394private:
1395 HelpPrinter &UncategorizedPrinter;
1396 CategorizedHelpPrinter &CategorizedPrinter;
1397
1398public:
1399 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1400 CategorizedHelpPrinter &CategorizedPrinter) :
1401 UncategorizedPrinter(UncategorizedPrinter),
1402 CategorizedPrinter(CategorizedPrinter) { }
1403
1404 // Invoke the printer.
1405 void operator=(bool Value);
1406};
1407
Chris Lattner500d8bf2006-10-12 22:09:17 +00001408} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001409
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001410// Declare the four HelpPrinter instances that are used to print out help, or
1411// help-hidden as an uncategorized list or in categories.
1412static HelpPrinter UncategorizedNormalPrinter(false);
1413static HelpPrinter UncategorizedHiddenPrinter(true);
1414static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1415static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1416
1417
1418// Declare HelpPrinter wrappers that will decide whether or not to invoke
1419// a categorizing help printer
1420static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1421 CategorizedNormalPrinter);
1422static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1423 CategorizedHiddenPrinter);
1424
1425// Define uncategorized help printers.
1426// -help-list is hidden by default because if Option categories are being used
1427// then -help behaves the same as -help-list.
1428static cl::opt<HelpPrinter, true, parser<bool> >
1429HLOp("help-list",
1430 cl::desc("Display list of available options (-help-list-hidden for more)"),
1431 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001432
Chris Lattner500d8bf2006-10-12 22:09:17 +00001433static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001434HLHOp("help-list-hidden",
1435 cl::desc("Display list of all available options"),
1436 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1437
1438// Define uncategorized/categorized help printers. These printers change their
1439// behaviour at runtime depending on whether one or more Option categories have
1440// been declared.
1441static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001442HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001443 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001444
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001445static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001446HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001447 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1448
1449
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001450
Andrew Trickce969022011-04-05 18:54:36 +00001451static cl::opt<bool>
1452PrintOptions("print-options",
1453 cl::desc("Print non-default options after command line parsing"),
1454 cl::Hidden, cl::init(false));
1455
1456static cl::opt<bool>
1457PrintAllOptions("print-all-options",
1458 cl::desc("Print all option values after command line parsing"),
1459 cl::Hidden, cl::init(false));
1460
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001461void HelpPrinterWrapper::operator=(bool Value) {
1462 if (Value == false)
1463 return;
1464
1465 // Decide which printer to invoke. If more than one option category is
1466 // registered then it is useful to show the categorized help instead of
1467 // uncategorized help.
1468 if (RegisteredOptionCategories->size() > 1) {
1469 // unhide -help-list option so user can have uncategorized output if they
1470 // want it.
1471 HLOp.setHiddenFlag(NotHidden);
1472
1473 CategorizedPrinter = true; // Invoke categorized printer
1474 }
1475 else
1476 UncategorizedPrinter = true; // Invoke uncategorized printer
1477}
1478
Andrew Trickce969022011-04-05 18:54:36 +00001479// Print the value of each option.
1480void cl::PrintOptionValues() {
1481 if (!PrintOptions && !PrintAllOptions) return;
1482
1483 // Get all the options.
1484 SmallVector<Option*, 4> PositionalOpts;
1485 SmallVector<Option*, 4> SinkOpts;
1486 StringMap<Option*> OptMap;
1487 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1488
1489 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1490 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1491
1492 // Compute the maximum argument length...
1493 size_t MaxArgLen = 0;
1494 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1495 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1496
1497 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1498 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1499}
1500
Chris Lattner500d8bf2006-10-12 22:09:17 +00001501static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001502
Chandler Carruth6d51d262011-07-22 07:50:40 +00001503static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1504
Chris Lattner500d8bf2006-10-12 22:09:17 +00001505namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001506class VersionPrinter {
1507public:
Devang Patelaed293d2007-02-01 01:43:37 +00001508 void print() {
Chris Lattner49b301c2009-09-20 06:18:38 +00001509 raw_ostream &OS = outs();
Jim Grosbachc48d4dc2012-01-25 22:00:23 +00001510 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner49b301c2009-09-20 06:18:38 +00001511 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001512#ifdef LLVM_VERSION_INFO
Chris Lattner49b301c2009-09-20 06:18:38 +00001513 OS << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001514#endif
Chris Lattner49b301c2009-09-20 06:18:38 +00001515 OS << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001516#ifndef __OPTIMIZE__
Chris Lattner49b301c2009-09-20 06:18:38 +00001517 OS << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001518#else
Chris Lattner49b301c2009-09-20 06:18:38 +00001519 OS << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001520#endif
1521#ifndef NDEBUG
Chris Lattner49b301c2009-09-20 06:18:38 +00001522 OS << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001523#endif
Daniel Dunbarba43e072009-11-14 21:36:07 +00001524 std::string CPU = sys::getHostCPUName();
Benjamin Kramer110e7bb2009-11-17 17:57:04 +00001525 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner49b301c2009-09-20 06:18:38 +00001526 OS << ".\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001527#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner49b301c2009-09-20 06:18:38 +00001528 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001529#endif
Sebastian Pop01738642011-11-01 21:32:20 +00001530 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth40393132011-07-22 07:50:48 +00001531 << " Host CPU: " << CPU << '\n';
Devang Patelaed293d2007-02-01 01:43:37 +00001532 }
1533 void operator=(bool OptionWasSpecified) {
Chris Lattner043b8b52009-09-20 05:48:01 +00001534 if (!OptionWasSpecified) return;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001535
Chandler Carruth6d51d262011-07-22 07:50:40 +00001536 if (OverrideVersionPrinter != 0) {
1537 (*OverrideVersionPrinter)();
Chris Lattner043b8b52009-09-20 05:48:01 +00001538 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001539 }
Chandler Carruth6d51d262011-07-22 07:50:40 +00001540 print();
1541
1542 // Iterate over any registered extra printers and call them to add further
1543 // information.
1544 if (ExtraVersionPrinters != 0) {
Chandler Carruth40393132011-07-22 07:50:48 +00001545 outs() << '\n';
Chandler Carruth6d51d262011-07-22 07:50:40 +00001546 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1547 E = ExtraVersionPrinters->end();
1548 I != E; ++I)
1549 (*I)();
1550 }
1551
Chris Lattner043b8b52009-09-20 05:48:01 +00001552 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001553 }
1554};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001555} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001556
1557
Reid Spencer69105f32004-08-04 00:36:06 +00001558// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001559static VersionPrinter VersionPrinterInstance;
1560
1561static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001562VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001563 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1564
Reid Spencer9bbba0912004-11-16 06:11:52 +00001565// Utility function for printing the help message.
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001566void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1567 // This looks weird, but it actually prints the help message. The Printers are
1568 // types of HelpPrinter and the help gets printed when its operator= is
1569 // invoked. That's because the "normal" usages of the help printer is to be
1570 // assigned true/false depending on whether -help or -help-hidden was given or
1571 // not. Since we're circumventing that we have to make it look like -help or
1572 // -help-hidden were given, so we assign true.
1573
1574 if (!Hidden && !Categorized)
1575 UncategorizedNormalPrinter = true;
1576 else if (!Hidden && Categorized)
1577 CategorizedNormalPrinter = true;
1578 else if (Hidden && !Categorized)
1579 UncategorizedHiddenPrinter = true;
1580 else
1581 CategorizedHiddenPrinter = true;
Reid Spencer9bbba0912004-11-16 06:11:52 +00001582}
Reid Spencer515b5b32006-06-05 16:22:56 +00001583
Devang Patelaed293d2007-02-01 01:43:37 +00001584/// Utility function for printing version number.
1585void cl::PrintVersionMessage() {
1586 VersionPrinterInstance.print();
1587}
1588
Reid Spencer515b5b32006-06-05 16:22:56 +00001589void cl::SetVersionPrinter(void (*func)()) {
1590 OverrideVersionPrinter = func;
1591}
Chandler Carruth6d51d262011-07-22 07:50:40 +00001592
1593void cl::AddExtraVersionPrinter(void (*func)()) {
1594 if (ExtraVersionPrinters == 0)
1595 ExtraVersionPrinters = new std::vector<void (*)()>;
1596
1597 ExtraVersionPrinters->push_back(func);
1598}