blob: 63d0b739c003a95d4d5912e770b7581ca2defdc5 [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"
Rafael Espindolaf3e397e2013-06-11 20:00:56 +000032#include "llvm/Support/PathV1.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
34#include "llvm/Support/system_error.h"
Brian Gaeke2d6a2362003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattnerca179342009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trickb7ad33b2013-05-06 21:56:23 +000037#include <map>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000038using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000039using namespace cl;
40
Chris Lattner7422a762006-08-27 12:45:47 +000041//===----------------------------------------------------------------------===//
42// Template instantiations and anchors.
43//
Douglas Gregorb3587cf2009-11-25 06:04:18 +000044namespace llvm { namespace cl {
Chris Lattner7422a762006-08-27 12:45:47 +000045TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000046TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000047TEMPLATE_INSTANTIATION(class basic_parser<int>);
48TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramerb3514562011-09-15 21:17:37 +000049TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner7422a762006-08-27 12:45:47 +000050TEMPLATE_INSTANTIATION(class basic_parser<double>);
51TEMPLATE_INSTANTIATION(class basic_parser<float>);
52TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000053TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000054
55TEMPLATE_INSTANTIATION(class opt<unsigned>);
56TEMPLATE_INSTANTIATION(class opt<int>);
57TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000058TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000059TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregorb3587cf2009-11-25 06:04:18 +000060} } // end namespace llvm::cl
Chris Lattner7422a762006-08-27 12:45:47 +000061
David Blaikie0becc962011-12-01 08:00:17 +000062void GenericOptionValue::anchor() {}
63void OptionValue<boolOrDefault>::anchor() {}
64void OptionValue<std::string>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000065void Option::anchor() {}
66void basic_parser_impl::anchor() {}
67void parser<bool>::anchor() {}
Dale Johannesen81da02b2007-05-22 17:14:46 +000068void parser<boolOrDefault>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000069void parser<int>::anchor() {}
70void parser<unsigned>::anchor() {}
Benjamin Kramerb3514562011-09-15 21:17:37 +000071void parser<unsigned long long>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000072void parser<double>::anchor() {}
73void parser<float>::anchor() {}
74void parser<std::string>::anchor() {}
Bill Wendlingb587f962009-04-29 23:26:16 +000075void parser<char>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000076
77//===----------------------------------------------------------------------===//
78
Chris Lattnerefa3da52006-10-13 00:06:24 +000079// Globals for name and overview of program. Program name is not a string to
80// avoid static ctor/dtor issues.
81static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000082static const char *ProgramOverview = 0;
83
Chris Lattnerc540ebb2004-11-19 17:08:15 +000084// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000085static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000086
Chris Lattner90aa8392006-10-04 21:52:35 +000087extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000088 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000089 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000090}
91
Chris Lattner69d6f132007-04-12 00:36:29 +000092static bool OptionListChanged = false;
93
94// MarkOptionsChanged - Internal helper function.
95void cl::MarkOptionsChanged() {
96 OptionListChanged = true;
97}
98
Chris Lattner9878d6a2007-04-06 21:06:55 +000099/// RegisteredOptionList - This is the list of the command line options that
100/// have statically constructed themselves.
101static Option *RegisteredOptionList = 0;
102
103void Option::addArgument() {
104 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000105
Chris Lattner9878d6a2007-04-06 21:06:55 +0000106 NextRegistered = RegisteredOptionList;
107 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +0000108 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000109}
110
Andrew Trickb7ad33b2013-05-06 21:56:23 +0000111// This collects the different option categories that have been registered.
112typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
113static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
114
115// Initialise the general option category.
116OptionCategory llvm::cl::GeneralCategory("General options");
117
118void OptionCategory::registerCategory()
119{
120 RegisteredOptionCategories->insert(this);
121}
Chris Lattner69d6f132007-04-12 00:36:29 +0000122
Chris Lattner331de232002-07-22 02:07:59 +0000123//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +0000124// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +0000125//
126
Chris Lattner9878d6a2007-04-06 21:06:55 +0000127/// GetOptionInfo - Scan the list of registered options, turning them into data
128/// structures that are easier to handle.
Chris Lattner49b301c2009-09-20 06:18:38 +0000129static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
130 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer461c8762009-09-19 10:01:45 +0000131 StringMap<Option*> &OptionsMap) {
Chris Lattner1908aea2009-09-20 06:21:43 +0000132 SmallVector<const char*, 16> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000133 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000134 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
135 // If this option wants to handle multiple option names, get the full set.
136 // This handles enum options like "-O1 -O2" etc.
137 O->getExtraOptionNames(OptionNames);
138 if (O->ArgStr[0])
139 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000140
Chris Lattner9878d6a2007-04-06 21:06:55 +0000141 // Handle named options.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000142 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000143 // Add argument to the argument map!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000144 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000145 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijman33540ad2008-05-30 13:26:11 +0000146 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner9878d6a2007-04-06 21:06:55 +0000147 }
148 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000149
Chris Lattner9878d6a2007-04-06 21:06:55 +0000150 OptionNames.clear();
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000151
Chris Lattner9878d6a2007-04-06 21:06:55 +0000152 // Remember information about positional options.
153 if (O->getFormattingFlag() == cl::Positional)
154 PositionalOpts.push_back(O);
Dan Gohman61e015f2008-02-23 01:55:25 +0000155 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000156 SinkOpts.push_back(O);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000157 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000158 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000159 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000160 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000161 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000162 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000163
Chris Lattneree2b3202007-04-07 05:38:53 +0000164 if (CAOpt)
165 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000166
Chris Lattneree2b3202007-04-07 05:38:53 +0000167 // Make sure that they are in order of registration not backwards.
168 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000169}
170
Chris Lattner9878d6a2007-04-06 21:06:55 +0000171
Chris Lattneraf035f32007-04-05 21:58:17 +0000172/// LookupOption - Lookup the option specified by the specified option on the
173/// command line. If there is a value specified (after an equal sign) return
Chris Lattnerb1687372009-09-20 05:03:30 +0000174/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner8a7a0582009-09-20 02:02:24 +0000175static Option *LookupOption(StringRef &Arg, StringRef &Value,
176 const StringMap<Option*> &OptionsMap) {
Chris Lattner8a7a0582009-09-20 02:02:24 +0000177 // Reject all dashes.
178 if (Arg.empty()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000179
Chris Lattner8a7a0582009-09-20 02:02:24 +0000180 size_t EqualPos = Arg.find('=');
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000181
Chris Lattner4e247ec2009-09-20 01:53:12 +0000182 // If we have an equals sign, remember the value.
Chris Lattnerb1687372009-09-20 05:03:30 +0000183 if (EqualPos == StringRef::npos) {
184 // Look up the option.
185 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
186 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000187 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000188
Chris Lattnerb1687372009-09-20 05:03:30 +0000189 // If the argument before the = is a valid option name, we match. If not,
190 // return Arg unmolested.
191 StringMap<Option*>::const_iterator I =
192 OptionsMap.find(Arg.substr(0, EqualPos));
193 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000194
Chris Lattnerb1687372009-09-20 05:03:30 +0000195 Value = Arg.substr(EqualPos+1);
196 Arg = Arg.substr(0, EqualPos);
197 return I->second;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000198}
199
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000200/// LookupNearestOption - Lookup the closest match to the option specified by
201/// the specified option on the command line. If there is a value specified
202/// (after an equal sign) return that as well. This assumes that leading dashes
203/// have already been stripped.
204static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000205 const StringMap<Option*> &OptionsMap,
Nick Lewycky95d206a2011-05-02 05:24:47 +0000206 std::string &NearestString) {
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000207 // Reject all dashes.
208 if (Arg.empty()) return 0;
209
210 // Split on any equal sign.
Nick Lewycky95d206a2011-05-02 05:24:47 +0000211 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
212 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
213 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000214
215 // Find the closest match.
216 Option *Best = 0;
217 unsigned BestDistance = 0;
218 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
219 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000220 Option *O = it->second;
221 SmallVector<const char*, 16> OptionNames;
222 O->getExtraOptionNames(OptionNames);
223 if (O->ArgStr[0])
224 OptionNames.push_back(O->ArgStr);
225
Nick Lewycky95d206a2011-05-02 05:24:47 +0000226 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
227 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000228 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
229 StringRef Name = OptionNames[i];
230 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewycky95d206a2011-05-02 05:24:47 +0000231 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000232 if (!Best || Distance < BestDistance) {
233 Best = O;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000234 BestDistance = Distance;
Bill Wendling2127c9b2012-07-19 00:15:11 +0000235 if (RHS.empty() || !PermitValue)
236 NearestString = OptionNames[i];
237 else
238 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000239 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000240 }
241 }
242
243 return Best;
244}
245
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000246/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
247/// does special handling of cl::CommaSeparated options.
248static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
249 StringRef ArgName,
250 StringRef Value, bool MultiArg = false)
251{
252 // Check to see if this option accepts a comma separated list of values. If
253 // it does, we have to split up the value into multiple values.
254 if (Handler->getMiscFlags() & CommaSeparated) {
255 StringRef Val(Value);
256 StringRef::size_type Pos = Val.find(',');
Chris Lattnerb1687372009-09-20 05:03:30 +0000257
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000258 while (Pos != StringRef::npos) {
259 // Process the portion before the comma.
260 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
261 return true;
262 // Erase the portion before the comma, AND the comma.
263 Val = Val.substr(Pos+1);
264 Value.substr(Pos+1); // Increment the original value pointer as well.
265 // Check for another comma.
266 Pos = Val.find(',');
267 }
268
269 Value = Val;
270 }
271
272 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
273 return true;
274
275 return false;
276}
Chris Lattnerb1687372009-09-20 05:03:30 +0000277
Chris Lattner341620b2009-09-20 01:49:31 +0000278/// ProvideOption - For Value, this differentiates between an empty value ("")
279/// and a null value (StringRef()). The later is accepted for arguments that
280/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000281static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikieebba0552012-02-07 19:36:01 +0000282 StringRef Value, int argc,
283 const char *const *argv, int &i) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000284 // Is this a multi-argument option?
285 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
286
Chris Lattnercaccd762001-10-27 05:54:17 +0000287 // Enforce value requirements
288 switch (Handler->getValueExpectedFlag()) {
289 case ValueRequired:
Chris Lattner341620b2009-09-20 01:49:31 +0000290 if (Value.data() == 0) { // No value specified?
Chris Lattnerba112292009-09-20 00:07:40 +0000291 if (i+1 >= argc)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000292 return Handler->error("requires a value!");
Chris Lattnerba112292009-09-20 00:07:40 +0000293 // Steal the next argument, like for '-o filename'
294 Value = argv[++i];
Chris Lattnercaccd762001-10-27 05:54:17 +0000295 }
296 break;
297 case ValueDisallowed:
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000298 if (NumAdditionalVals > 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000299 return Handler->error("multi-valued option specified"
Chris Lattnerba112292009-09-20 00:07:40 +0000300 " with ValueDisallowed modifier!");
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000301
Chris Lattner341620b2009-09-20 01:49:31 +0000302 if (Value.data())
Benjamin Kramere6864c12009-08-02 12:13:02 +0000303 return Handler->error("does not allow a value! '" +
Chris Lattnera460beb2009-09-19 18:55:05 +0000304 Twine(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000305 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000306 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000307 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000308 }
309
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000310 // If this isn't a multi-arg option, just run the handler.
Chris Lattnera460beb2009-09-19 18:55:05 +0000311 if (NumAdditionalVals == 0)
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000312 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
Chris Lattnera460beb2009-09-19 18:55:05 +0000313
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000314 // If it is, run the handle several times.
Chris Lattnera460beb2009-09-19 18:55:05 +0000315 bool MultiArg = false;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000316
Chris Lattner341620b2009-09-20 01:49:31 +0000317 if (Value.data()) {
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000318 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000319 return true;
320 --NumAdditionalVals;
321 MultiArg = true;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000322 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000323
324 while (NumAdditionalVals > 0) {
Chris Lattnera460beb2009-09-19 18:55:05 +0000325 if (i+1 >= argc)
326 return Handler->error("not enough values!");
327 Value = argv[++i];
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000328
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000329 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000330 return true;
331 MultiArg = true;
332 --NumAdditionalVals;
333 }
334 return false;
Chris Lattnercaccd762001-10-27 05:54:17 +0000335}
336
Chris Lattnerba112292009-09-20 00:07:40 +0000337static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000338 int Dummy = i;
Chris Lattner341620b2009-09-20 01:49:31 +0000339 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000340}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000341
Chris Lattner331de232002-07-22 02:07:59 +0000342
343// Option predicates...
344static inline bool isGrouping(const Option *O) {
345 return O->getFormattingFlag() == cl::Grouping;
346}
347static inline bool isPrefixedOrGrouping(const Option *O) {
348 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
349}
350
351// getOptionPred - Check to see if there are any options that satisfy the
352// specified predicate with names that are the prefixes in Name. This is
353// checked by progressively stripping characters off of the name, checking to
354// see if there options that satisfy the predicate. If we find one, return it,
355// otherwise return null.
356//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000357static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000358 bool (*Pred)(const Option*),
Chris Lattnerb1687372009-09-20 05:03:30 +0000359 const StringMap<Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000360
Chris Lattnerb1687372009-09-20 05:03:30 +0000361 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000362
Chris Lattnerb1687372009-09-20 05:03:30 +0000363 // Loop while we haven't found an option and Name still has at least two
364 // characters in it (so that the next iteration will not be the empty
365 // string.
366 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000367 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000368 OMI = OptionsMap.find(Name);
Chris Lattnerb1687372009-09-20 05:03:30 +0000369 }
Chris Lattner331de232002-07-22 02:07:59 +0000370
Chris Lattner9878d6a2007-04-06 21:06:55 +0000371 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000372 Length = Name.size();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000373 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000374 }
375 return 0; // No option found!
376}
377
Chris Lattnerb1687372009-09-20 05:03:30 +0000378/// HandlePrefixedOrGroupedOption - The specified argument string (which started
379/// with at least one '-') does not fully match an available option. Check to
380/// see if this is a prefix or grouped option. If so, split arg into output an
381/// Arg/Value pair and return the Option to parse it with.
382static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
383 bool &ErrorParsing,
384 const StringMap<Option*> &OptionsMap) {
385 if (Arg.size() == 1) return 0;
386
387 // Do the lookup!
388 size_t Length = 0;
389 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
390 if (PGOpt == 0) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000391
Chris Lattnerb1687372009-09-20 05:03:30 +0000392 // If the option is a prefixed option, then the value is simply the
393 // rest of the name... so fall through to later processing, by
394 // setting up the argument name flags and value fields.
395 if (PGOpt->getFormattingFlag() == cl::Prefix) {
396 Value = Arg.substr(Length);
397 Arg = Arg.substr(0, Length);
398 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
399 return PGOpt;
400 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000401
Chris Lattnerb1687372009-09-20 05:03:30 +0000402 // This must be a grouped option... handle them now. Grouping options can't
403 // have values.
404 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000405
Chris Lattnerb1687372009-09-20 05:03:30 +0000406 do {
407 // Move current arg name out of Arg into OneArgName.
408 StringRef OneArgName = Arg.substr(0, Length);
409 Arg = Arg.substr(Length);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000410
Chris Lattnerb1687372009-09-20 05:03:30 +0000411 // Because ValueRequired is an invalid flag for grouped arguments,
412 // we don't need to pass argc/argv in.
413 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
414 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sands1fa8b002010-01-09 08:30:33 +0000415 int Dummy = 0;
Chris Lattnerb1687372009-09-20 05:03:30 +0000416 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
417 StringRef(), 0, 0, Dummy);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000418
Chris Lattnerb1687372009-09-20 05:03:30 +0000419 // Get the next grouping option.
420 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
421 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000422
Chris Lattnerb1687372009-09-20 05:03:30 +0000423 // Return the last option with Arg cut down to just the last one.
424 return PGOpt;
425}
426
427
428
Chris Lattner331de232002-07-22 02:07:59 +0000429static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000430 return O->getNumOccurrencesFlag() == cl::Required ||
431 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000432}
433
434static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000435 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
436 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000437}
Chris Lattnercaccd762001-10-27 05:54:17 +0000438
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000439/// ParseCStringVector - Break INPUT up wherever one or more
440/// whitespace characters are found, and store the resulting tokens in
441/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000442/// using strdup(), so it is the caller's responsibility to free()
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000443/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000444///
Chris Lattner63e944b2009-09-24 05:38:36 +0000445static void ParseCStringVector(std::vector<char *> &OutputVector,
446 const char *Input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000447 // Characters which will be treated as token separators:
Chris Lattner63e944b2009-09-24 05:38:36 +0000448 StringRef Delims = " \v\f\t\r\n";
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000449
Chris Lattner63e944b2009-09-24 05:38:36 +0000450 StringRef WorkStr(Input);
451 while (!WorkStr.empty()) {
452 // If the first character is a delimiter, strip them off.
453 if (Delims.find(WorkStr[0]) != StringRef::npos) {
454 size_t Pos = WorkStr.find_first_not_of(Delims);
455 if (Pos == StringRef::npos) Pos = WorkStr.size();
456 WorkStr = WorkStr.substr(Pos);
457 continue;
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000458 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000459
Chris Lattner63e944b2009-09-24 05:38:36 +0000460 // Find position of first delimiter.
461 size_t Pos = WorkStr.find_first_of(Delims);
462 if (Pos == StringRef::npos) Pos = WorkStr.size();
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000463
Chris Lattner63e944b2009-09-24 05:38:36 +0000464 // Everything from 0 to Pos is the next word to copy.
465 char *NewStr = (char*)malloc(Pos+1);
466 memcpy(NewStr, WorkStr.data(), Pos);
467 NewStr[Pos] = 0;
468 OutputVector.push_back(NewStr);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000469
Chris Lattner63e944b2009-09-24 05:38:36 +0000470 WorkStr = WorkStr.substr(Pos);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000471 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000472}
473
474/// ParseEnvironmentOptions - An alternative entry point to the
475/// CommandLine library, which allows you to read the program's name
476/// from the caller (as PROGNAME) and its command-line arguments from
477/// an environment variable (whose name is given in ENVVAR).
478///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000479void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000480 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000481 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000482 assert(progName && "Program name not specified");
483 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000484
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000485 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000486 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000487 if (!envValue)
488 return;
489
Brian Gaeke06b06c52003-08-14 22:00:59 +0000490 // Get program's "name", which we wouldn't know without the caller
491 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000492 std::vector<char*> newArgv;
493 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000494
495 // Parse the value of the environment variable into a "command line"
496 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000497 ParseCStringVector(newArgv, envValue);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000498 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000499 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000500
501 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000502 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
503 i != e; ++i)
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000504 free(*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000505}
506
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000507
508/// ExpandResponseFiles - Copy the contents of argv into newArgv,
509/// substituting the contents of the response files for the arguments
510/// of type @file.
David Blaikieebba0552012-02-07 19:36:01 +0000511static void ExpandResponseFiles(unsigned argc, const char*const* argv,
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000512 std::vector<char*>& newArgv) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000513 for (unsigned i = 1; i != argc; ++i) {
David Blaikieebba0552012-02-07 19:36:01 +0000514 const char *arg = argv[i];
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000515
516 if (arg[0] == '@') {
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000517 sys::PathWithStatus respFile(++arg);
518
519 // Check that the response file is not empty (mmap'ing empty
520 // files can be problematic).
521 const sys::FileStatus *FileStat = respFile.getFileStatus();
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000522 if (FileStat && FileStat->getSize() != 0) {
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000523
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000524 // If we could open the file, parse its contents, otherwise
525 // pass the @file option verbatim.
Mikhail Glushenkov6c55b1c2009-01-28 03:46:22 +0000526
527 // TODO: we should also support recursive loading of response files,
528 // since this is how gcc behaves. (From their man page: "The file may
529 // itself contain additional @file options; any such options will be
530 // processed recursively.")
531
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000532 // Mmap the response file into memory.
533 OwningPtr<MemoryBuffer> respFilePtr;
534 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000535 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
536 continue;
537 }
538 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000539 }
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000540 newArgv.push_back(strdup(arg));
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000541 }
542}
543
David Blaikieebba0552012-02-07 19:36:01 +0000544void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000545 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000546 // Process all registered options.
Chris Lattner49b301c2009-09-20 06:18:38 +0000547 SmallVector<Option*, 4> PositionalOpts;
548 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +0000549 StringMap<Option*> Opts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000550 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000551
Chris Lattner9878d6a2007-04-06 21:06:55 +0000552 assert((!Opts.empty() || !PositionalOpts.empty()) &&
553 "No options specified!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000554
555 // Expand response files.
556 std::vector<char*> newArgv;
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000557 newArgv.push_back(strdup(argv[0]));
558 ExpandResponseFiles(argc, argv, newArgv);
559 argv = &newArgv[0];
560 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000561
Chris Lattnerefa3da52006-10-13 00:06:24 +0000562 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencerb3127bb2010-12-18 00:19:10 +0000563 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000564 size_t Len = std::min(ProgName.size(), size_t(79));
565 memcpy(ProgramName, ProgName.data(), Len);
566 ProgramName[Len] = '\0';
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000567
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000568 ProgramOverview = Overview;
569 bool ErrorParsing = false;
570
Chris Lattner331de232002-07-22 02:07:59 +0000571 // Check out the positional arguments to collect information about them.
572 unsigned NumPositionalRequired = 0;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000573
Chris Lattnerde013242005-08-08 17:25:38 +0000574 // Determine whether or not there are an unlimited number of positionals
575 bool HasUnlimitedPositionals = false;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000576
Chris Lattner331de232002-07-22 02:07:59 +0000577 Option *ConsumeAfterOpt = 0;
578 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000579 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000580 assert(PositionalOpts.size() > 1 &&
581 "Cannot specify cl::ConsumeAfter without a positional argument!");
582 ConsumeAfterOpt = PositionalOpts[0];
583 }
584
585 // Calculate how many positional values are _required_.
586 bool UnboundedFound = false;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000587 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner331de232002-07-22 02:07:59 +0000588 i != e; ++i) {
589 Option *Opt = PositionalOpts[i];
590 if (RequiresValue(Opt))
591 ++NumPositionalRequired;
592 else if (ConsumeAfterOpt) {
593 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000594 // unless there is only one positional argument...
595 if (PositionalOpts.size() > 2)
596 ErrorParsing |=
Benjamin Kramere6864c12009-08-02 12:13:02 +0000597 Opt->error("error - this positional option will never be matched, "
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000598 "because it does not Require a value, and a "
599 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000600 } else if (UnboundedFound && !Opt->ArgStr[0]) {
601 // This option does not "require" a value... Make sure this option is
602 // not specified after an option that eats all extra arguments, or this
603 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000604 //
Benjamin Kramere6864c12009-08-02 12:13:02 +0000605 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner331de232002-07-22 02:07:59 +0000606 "another positional argument will match an "
607 "unbounded number of values, and this option"
608 " does not require a value!");
609 }
610 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
611 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000612 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000613 }
614
Reid Spencer1e13fd22004-08-13 19:47:30 +0000615 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerba112292009-09-20 00:07:40 +0000616 // the process at the end.
Chris Lattner331de232002-07-22 02:07:59 +0000617 //
Chris Lattnerba112292009-09-20 00:07:40 +0000618 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000619
Chris Lattner9cf3d472003-07-30 17:34:02 +0000620 // If the program has named positional arguments, and the name has been run
621 // across, keep track of which positional argument was named. Otherwise put
622 // the positional args into the PositionalVals list...
623 Option *ActivePositionalArg = 0;
624
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000625 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000626 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000627 for (int i = 1; i < argc; ++i) {
628 Option *Handler = 0;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000629 Option *NearestHandler = 0;
Nick Lewycky95d206a2011-05-02 05:24:47 +0000630 std::string NearestHandlerString;
Chris Lattner4e247ec2009-09-20 01:53:12 +0000631 StringRef Value;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000632 StringRef ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000633
Chris Lattner69d6f132007-04-12 00:36:29 +0000634 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000635 // option has just been registered or deregistered. This can occur in
636 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000637 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000638 PositionalOpts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000639 SinkOpts.clear();
Chris Lattner159b0a432007-04-11 15:35:18 +0000640 Opts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000641 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000642 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000643 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000644
Chris Lattner331de232002-07-22 02:07:59 +0000645 // Check to see if this is a positional argument. This argument is
646 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000647 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000648 //
649 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
650 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000651 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000652 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000653 continue; // We are done!
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000654 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000655
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000656 if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000657 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000658
659 // All of the positional arguments have been fulfulled, give the rest to
660 // the consume after option... if it's specified...
661 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000662 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000663 ConsumeAfterOpt != 0) {
664 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000665 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000666 break; // Handle outside of the argument processing loop...
667 }
668
669 // Delay processing positional arguments until the end...
670 continue;
671 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000672 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
673 !DashDashFound) {
674 DashDashFound = true; // This is the mythical "--"?
675 continue; // Don't try to process it as an argument itself.
676 } else if (ActivePositionalArg &&
677 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
678 // If there is a positional argument eating options, check to see if this
679 // option is another positional argument. If so, treat it as an argument,
680 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000681 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000682 // Eat leading dashes.
683 while (!ArgName.empty() && ArgName[0] == '-')
684 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000685
Chris Lattner9878d6a2007-04-06 21:06:55 +0000686 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000687 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000688 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000689 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000690 }
691
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000692 } else { // We start with a '-', must be an argument.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000693 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000694 // Eat leading dashes.
695 while (!ArgName.empty() && ArgName[0] == '-')
696 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000697
Chris Lattner9878d6a2007-04-06 21:06:55 +0000698 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000699
Chris Lattnerbf455c22004-05-06 22:04:31 +0000700 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnerb1687372009-09-20 05:03:30 +0000701 if (Handler == 0)
702 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
703 ErrorParsing, Opts);
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000704
705 // Otherwise, look for the closest available option to report to the user
706 // in the upcoming error.
707 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000708 NearestHandler = LookupNearestOption(ArgName, Opts,
709 NearestHandlerString);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000710 }
711
712 if (Handler == 0) {
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000713 if (SinkOpts.empty()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000714 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000715 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000716
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000717 if (NearestHandler) {
718 // If we know a near match, report it as well.
719 errs() << ProgramName << ": Did you mean '-"
720 << NearestHandlerString << "'?\n";
721 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000722
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000723 ErrorParsing = true;
724 } else {
Chris Lattner49b301c2009-09-20 06:18:38 +0000725 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000726 E = SinkOpts.end(); I != E ; ++I)
727 (*I)->addOccurrence(i, "", argv[i]);
728 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000729 continue;
730 }
731
Chris Lattner9cf3d472003-07-30 17:34:02 +0000732 // If this is a named positional argument, just remember that it is the
733 // active one...
734 if (Handler->getFormattingFlag() == cl::Positional)
735 ActivePositionalArg = Handler;
Chris Lattner341620b2009-09-20 01:49:31 +0000736 else
Chris Lattner4e247ec2009-09-20 01:53:12 +0000737 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000738 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000739
Chris Lattner331de232002-07-22 02:07:59 +0000740 // Check and handle positional arguments now...
741 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000742 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000743 << ": Not enough positional command line arguments specified!\n"
744 << "Must specify at least " << NumPositionalRequired
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000745 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000746
Chris Lattner331de232002-07-22 02:07:59 +0000747 ErrorParsing = true;
Dan Gohman16e02092010-03-24 19:38:02 +0000748 } else if (!HasUnlimitedPositionals &&
749 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000750 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000751 << ": Too many positional arguments specified!\n"
752 << "Can specify at most " << PositionalOpts.size()
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000753 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000754 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000755
756 } else if (ConsumeAfterOpt == 0) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000757 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000758 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
759 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner331de232002-07-22 02:07:59 +0000760 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000761 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000762 PositionalVals[ValNo].second);
763 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000764 --NumPositionalRequired; // We fulfilled our duty...
765 }
766
767 // If we _can_ give this option more arguments, do so now, as long as we
768 // do not give it values that others need. 'Done' controls whether the
769 // option even _WANTS_ any more.
770 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000771 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000772 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000773 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000774 case cl::Optional:
775 Done = true; // Optional arguments want _at most_ one value
776 // FALL THROUGH
777 case cl::ZeroOrMore: // Zero or more will take all they can get...
778 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000779 ProvidePositionalOption(PositionalOpts[i],
780 PositionalVals[ValNo].first,
781 PositionalVals[ValNo].second);
782 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000783 break;
784 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000785 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000786 "positional argument processing!");
787 }
788 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000789 }
Chris Lattner331de232002-07-22 02:07:59 +0000790 } else {
791 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
792 unsigned ValNo = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000793 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000794 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000795 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000796 PositionalVals[ValNo].first,
797 PositionalVals[ValNo].second);
798 ValNo++;
799 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000800
801 // Handle the case where there is just one positional option, and it's
802 // optional. In this case, we want to give JUST THE FIRST option to the
803 // positional option and keep the rest for the consume after. The above
804 // loop would have assigned no values to positional options in this case.
805 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000806 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000807 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000808 PositionalVals[ValNo].first,
809 PositionalVals[ValNo].second);
810 ValNo++;
811 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000812
Chris Lattner331de232002-07-22 02:07:59 +0000813 // Handle over all of the rest of the arguments to the
814 // cl::ConsumeAfter command line option...
815 for (; ValNo != PositionalVals.size(); ++ValNo)
816 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000817 PositionalVals[ValNo].first,
818 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000819 }
820
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000821 // Loop over args and make sure all required args are specified!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000822 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000823 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000824 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000825 case Required:
826 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000827 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramere6864c12009-08-02 12:13:02 +0000828 I->second->error("must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000829 ErrorParsing = true;
830 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000831 // Fall through
832 default:
833 break;
834 }
835 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000836
Rafael Espindolaa962b402010-11-19 21:14:29 +0000837 // Now that we know if -debug is specified, we can use it.
838 // Note that if ReadResponseFiles == true, this must be done before the
839 // memory allocated for the expanded command line is free()d below.
840 DEBUG(dbgs() << "Args: ";
841 for (int i = 0; i < argc; ++i)
842 dbgs() << argv[i] << ' ';
843 dbgs() << '\n';
844 );
845
Chris Lattner331de232002-07-22 02:07:59 +0000846 // Free all of the memory allocated to the map. Command line options may only
847 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000848 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000849 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000850 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000851
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000852 // Free the memory allocated by ExpandResponseFiles.
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000853 // Free all the strdup()ed strings.
854 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
855 i != e; ++i)
856 free(*i);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000857
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000858 // If we had an error processing our arguments, don't let the program execute
859 if (ErrorParsing) exit(1);
860}
861
862//===----------------------------------------------------------------------===//
863// Option Base class implementation
864//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000865
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000866bool Option::error(const Twine &Message, StringRef ArgName) {
867 if (ArgName.data() == 0) ArgName = ArgStr;
868 if (ArgName.empty())
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000869 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000870 else
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000871 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000872
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000873 errs() << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000874 return true;
875}
876
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000877bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000878 StringRef Value, bool MultiArg) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000879 if (!MultiArg)
880 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000881
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000882 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000883 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000884 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000885 return error("may only occur zero or one times!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000886 break;
887 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000888 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000889 return error("must occur exactly one time!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000890 // Fall through
891 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000892 case ZeroOrMore:
893 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000894 }
895
Reid Spencer1e13fd22004-08-13 19:47:30 +0000896 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000897}
898
Chris Lattner331de232002-07-22 02:07:59 +0000899
900// getValueStr - Get the value description string, using "DefaultMsg" if nothing
901// has been specified yet.
902//
903static const char *getValueStr(const Option &O, const char *DefaultMsg) {
904 if (O.ValueStr[0] == 0) return DefaultMsg;
905 return O.ValueStr;
906}
907
908//===----------------------------------------------------------------------===//
909// cl::alias class implementation
910//
911
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000912// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000913size_t alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000914 return std::strlen(ArgStr)+6;
915}
916
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000917static void printHelpStr(StringRef HelpStr, size_t Indent,
918 size_t FirstLineIndentedBy) {
919 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
920 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
921 while (!Split.second.empty()) {
922 Split = Split.second.split('\n');
923 outs().indent(Indent) << Split.first << "\n";
924 }
925}
926
Chris Lattnera0de8432006-04-28 05:36:25 +0000927// Print out the option for the alias.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000928void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Chengff276b42011-06-13 20:45:54 +0000929 outs() << " -" << ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000930 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000931}
932
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000933//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000934// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000935//
936
Chris Lattner9b14eb52002-08-07 18:36:37 +0000937// basic_parser implementation
938//
939
940// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000941size_t basic_parser_impl::getOptionWidth(const Option &O) const {
942 size_t Len = std::strlen(O.ArgStr);
Chris Lattner9b14eb52002-08-07 18:36:37 +0000943 if (const char *ValName = getValueName())
944 Len += std::strlen(getValueStr(O, ValName))+3;
945
946 return Len + 6;
947}
948
Misha Brukmanf976c852005-04-21 22:55:34 +0000949// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000950// to-be-maintained width is specified.
951//
952void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +0000953 size_t GlobalWidth) const {
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000954 outs() << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000955
956 if (const char *ValName = getValueName())
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000957 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattner9b14eb52002-08-07 18:36:37 +0000958
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000959 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattner9b14eb52002-08-07 18:36:37 +0000960}
961
Andrew Trickce969022011-04-05 18:54:36 +0000962void basic_parser_impl::printOptionName(const Option &O,
963 size_t GlobalWidth) const {
964 outs() << " -" << O.ArgStr;
965 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
966}
Chris Lattner9b14eb52002-08-07 18:36:37 +0000967
968
Chris Lattner331de232002-07-22 02:07:59 +0000969// parser<bool> implementation
970//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000971bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000972 StringRef Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000973 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000974 Arg == "1") {
975 Value = true;
Chris Lattnera460beb2009-09-19 18:55:05 +0000976 return false;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000977 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000978
Chris Lattnera460beb2009-09-19 18:55:05 +0000979 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
980 Value = false;
981 return false;
982 }
983 return O.error("'" + Arg +
984 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000985}
986
Dale Johannesen81da02b2007-05-22 17:14:46 +0000987// parser<boolOrDefault> implementation
988//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000989bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000990 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen81da02b2007-05-22 17:14:46 +0000991 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
992 Arg == "1") {
993 Value = BOU_TRUE;
Chris Lattnera460beb2009-09-19 18:55:05 +0000994 return false;
Dale Johannesen81da02b2007-05-22 17:14:46 +0000995 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000996 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
997 Value = BOU_FALSE;
998 return false;
999 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001000
Chris Lattnera460beb2009-09-19 18:55:05 +00001001 return O.error("'" + Arg +
1002 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen81da02b2007-05-22 17:14:46 +00001003}
1004
Chris Lattner331de232002-07-22 02:07:59 +00001005// parser<int> implementation
1006//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001007bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001008 StringRef Arg, int &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001009 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001010 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001011 return false;
1012}
1013
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001014// parser<unsigned> implementation
1015//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001016bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001017 StringRef Arg, unsigned &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001018
1019 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001020 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001021 return false;
1022}
1023
Benjamin Kramerb3514562011-09-15 21:17:37 +00001024// parser<unsigned long long> implementation
1025//
1026bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1027 StringRef Arg, unsigned long long &Value){
1028
1029 if (Arg.getAsInteger(0, Value))
1030 return O.error("'" + Arg + "' value invalid for uint argument!");
1031 return false;
1032}
1033
Chris Lattner9b14eb52002-08-07 18:36:37 +00001034// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +00001035//
Chris Lattnera460beb2009-09-19 18:55:05 +00001036static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001037 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1038 const char *ArgStart = TmpStr.c_str();
Chris Lattner331de232002-07-22 02:07:59 +00001039 char *End;
1040 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +00001041 if (*End != 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001042 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +00001043 return false;
1044}
1045
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001046bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001047 StringRef Arg, double &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001048 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +00001049}
1050
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001051bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001052 StringRef Arg, float &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001053 double dVal;
1054 if (parseDouble(O, Arg, dVal))
1055 return true;
1056 Val = (float)dVal;
1057 return false;
Chris Lattner331de232002-07-22 02:07:59 +00001058}
1059
1060
Chris Lattner331de232002-07-22 02:07:59 +00001061
1062// generic_parser_base implementation
1063//
1064
Chris Lattneraa852bb2002-07-23 17:15:12 +00001065// findOption - Return the option number corresponding to the specified
1066// argument string. If the option is not found, getNumOptions() is returned.
1067//
1068unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer461c8762009-09-19 10:01:45 +00001069 unsigned e = getNumOptions();
Chris Lattneraa852bb2002-07-23 17:15:12 +00001070
Benjamin Kramer461c8762009-09-19 10:01:45 +00001071 for (unsigned i = 0; i != e; ++i) {
1072 if (strcmp(getOption(i), Name) == 0)
Chris Lattneraa852bb2002-07-23 17:15:12 +00001073 return i;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001074 }
Chris Lattneraa852bb2002-07-23 17:15:12 +00001075 return e;
1076}
1077
1078
Chris Lattner331de232002-07-22 02:07:59 +00001079// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001080size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner331de232002-07-22 02:07:59 +00001081 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001082 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner331de232002-07-22 02:07:59 +00001083 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001084 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001085 return Size;
1086 } else {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001087 size_t BaseSize = 0;
Chris Lattner331de232002-07-22 02:07:59 +00001088 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001089 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001090 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001091 }
1092}
1093
Misha Brukmanf976c852005-04-21 22:55:34 +00001094// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +00001095// to-be-maintained width is specified.
1096//
1097void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001098 size_t GlobalWidth) const {
Chris Lattner331de232002-07-22 02:07:59 +00001099 if (O.hasArgStr()) {
Chris Lattnerb1687372009-09-20 05:03:30 +00001100 outs() << " -" << O.ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001101 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001102
Chris Lattner331de232002-07-22 02:07:59 +00001103 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001104 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerb1687372009-09-20 05:03:30 +00001105 outs() << " =" << getOption(i);
1106 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattner9c9be482002-01-31 00:42:56 +00001107 }
Chris Lattner331de232002-07-22 02:07:59 +00001108 } else {
1109 if (O.HelpStr[0])
Chris Lattnerb1687372009-09-20 05:03:30 +00001110 outs() << " " << O.HelpStr << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001111 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001112 const char *Option = getOption(i);
1113 outs() << " -" << Option;
1114 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner331de232002-07-22 02:07:59 +00001115 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001116 }
1117}
1118
Andrew Trickce969022011-04-05 18:54:36 +00001119static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1120
1121// printGenericOptionDiff - Print the value of this option and it's default.
1122//
1123// "Generic" options have each value mapped to a name.
1124void generic_parser_base::
1125printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1126 const GenericOptionValue &Default,
1127 size_t GlobalWidth) const {
1128 outs() << " -" << O.ArgStr;
1129 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1130
1131 unsigned NumOpts = getNumOptions();
1132 for (unsigned i = 0; i != NumOpts; ++i) {
1133 if (Value.compare(getOptionValue(i)))
1134 continue;
1135
1136 outs() << "= " << getOption(i);
1137 size_t L = std::strlen(getOption(i));
1138 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1139 outs().indent(NumSpaces) << " (default: ";
1140 for (unsigned j = 0; j != NumOpts; ++j) {
1141 if (Default.compare(getOptionValue(j)))
1142 continue;
1143 outs() << getOption(j);
1144 break;
1145 }
1146 outs() << ")\n";
1147 return;
1148 }
1149 outs() << "= *unknown option value*\n";
1150}
1151
1152// printOptionDiff - Specializations for printing basic value types.
1153//
1154#define PRINT_OPT_DIFF(T) \
1155 void parser<T>:: \
1156 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1157 size_t GlobalWidth) const { \
1158 printOptionName(O, GlobalWidth); \
1159 std::string Str; \
1160 { \
1161 raw_string_ostream SS(Str); \
1162 SS << V; \
1163 } \
1164 outs() << "= " << Str; \
1165 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1166 outs().indent(NumSpaces) << " (default: "; \
1167 if (D.hasValue()) \
1168 outs() << D.getValue(); \
1169 else \
1170 outs() << "*no default*"; \
1171 outs() << ")\n"; \
1172 } \
1173
Frits van Bommel090771f2011-04-06 12:29:56 +00001174PRINT_OPT_DIFF(bool)
1175PRINT_OPT_DIFF(boolOrDefault)
1176PRINT_OPT_DIFF(int)
1177PRINT_OPT_DIFF(unsigned)
Benjamin Kramerb3514562011-09-15 21:17:37 +00001178PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel090771f2011-04-06 12:29:56 +00001179PRINT_OPT_DIFF(double)
1180PRINT_OPT_DIFF(float)
1181PRINT_OPT_DIFF(char)
Andrew Trickce969022011-04-05 18:54:36 +00001182
1183void parser<std::string>::
1184printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1185 size_t GlobalWidth) const {
1186 printOptionName(O, GlobalWidth);
1187 outs() << "= " << V;
1188 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1189 outs().indent(NumSpaces) << " (default: ";
1190 if (D.hasValue())
1191 outs() << D.getValue();
1192 else
1193 outs() << "*no default*";
1194 outs() << ")\n";
1195}
1196
1197// Print a placeholder for options that don't yet support printOptionDiff().
1198void basic_parser_impl::
1199printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1200 printOptionName(O, GlobalWidth);
1201 outs() << "= *cannot print option value*\n";
1202}
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001203
1204//===----------------------------------------------------------------------===//
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001205// -help and -help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001206//
Reid Spencerad0846b2004-11-14 22:04:00 +00001207
Chris Lattner0fd48b12009-09-20 05:37:24 +00001208static int OptNameCompare(const void *LHS, const void *RHS) {
1209 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001210
Duncan Sandse840fef2012-03-12 10:51:06 +00001211 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner0fd48b12009-09-20 05:37:24 +00001212}
1213
Andrew Trickce969022011-04-05 18:54:36 +00001214// Copy Options into a vector so we can sort them as we like.
1215static void
1216sortOpts(StringMap<Option*> &OptMap,
1217 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1218 bool ShowHidden) {
1219 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1220
1221 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1222 I != E; ++I) {
1223 // Ignore really-hidden options.
1224 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1225 continue;
1226
1227 // Unless showhidden is set, ignore hidden flags.
1228 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1229 continue;
1230
1231 // If we've already seen this option, don't add it to the list again.
1232 if (!OptionSet.insert(I->second))
1233 continue;
1234
1235 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1236 I->second));
1237 }
1238
1239 // Sort the options list alphabetically.
1240 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1241}
1242
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001243namespace {
1244
Chris Lattner331de232002-07-22 02:07:59 +00001245class HelpPrinter {
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001246protected:
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001247 const bool ShowHidden;
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001248 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1249 // Print the options. Opts is assumed to be alphabetically sorted.
1250 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1251 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1252 Opts[i].second->printOptionInfo(MaxArgLen);
1253 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001254
Chris Lattner331de232002-07-22 02:07:59 +00001255public:
Craig Topperddde2082013-03-09 23:29:37 +00001256 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001257 virtual ~HelpPrinter() {}
Chris Lattner331de232002-07-22 02:07:59 +00001258
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001259 // Invoke the printer.
Chris Lattner331de232002-07-22 02:07:59 +00001260 void operator=(bool Value) {
1261 if (Value == false) return;
1262
Chris Lattner9878d6a2007-04-06 21:06:55 +00001263 // Get all the options.
Chris Lattner49b301c2009-09-20 06:18:38 +00001264 SmallVector<Option*, 4> PositionalOpts;
1265 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001266 StringMap<Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +00001267 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001268
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001269 StrOptionPairVector Opts;
Andrew Trickce969022011-04-05 18:54:36 +00001270 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001271
1272 if (ProgramOverview)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001273 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001274
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001275 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +00001276
Chris Lattner90aa8392006-10-04 21:52:35 +00001277 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +00001278 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001279 if (!PositionalOpts.empty() &&
Chris Lattner9878d6a2007-04-06 21:06:55 +00001280 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1281 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +00001282
Evan Cheng34cd4a42008-05-05 18:30:58 +00001283 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +00001284 if (PositionalOpts[i]->ArgStr[0])
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001285 outs() << " --" << PositionalOpts[i]->ArgStr;
1286 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +00001287 }
Chris Lattner331de232002-07-22 02:07:59 +00001288
1289 // Print the consume after option info if it exists...
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001290 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +00001291
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001292 outs() << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001293
1294 // Compute the maximum argument length...
Craig Topperddde2082013-03-09 23:29:37 +00001295 size_t MaxArgLen = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +00001296 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0fd48b12009-09-20 05:37:24 +00001297 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001298
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001299 outs() << "OPTIONS:\n";
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001300 printOptions(Opts, MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001301
Chris Lattnerc540ebb2004-11-19 17:08:15 +00001302 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +00001303 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001304 E = MoreHelp->end();
1305 I != E; ++I)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001306 outs() << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001307 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001308
Reid Spencer9bbba0912004-11-16 06:11:52 +00001309 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001310 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001311 }
1312};
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001313
1314class CategorizedHelpPrinter : public HelpPrinter {
1315public:
1316 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1317
1318 // Helper function for printOptions().
1319 // It shall return true if A's name should be lexographically
1320 // ordered before B's name. It returns false otherwise.
1321 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1322 int Length = strcmp(A->getName(), B->getName());
1323 assert(Length != 0 && "Duplicate option categories");
1324 return Length < 0;
1325 }
1326
1327 // Make sure we inherit our base class's operator=()
1328 using HelpPrinter::operator= ;
1329
1330protected:
1331 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1332 std::vector<OptionCategory *> SortedCategories;
1333 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1334
1335 // Collect registered option categories into vector in preperation for
1336 // sorting.
1337 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1338 E = RegisteredOptionCategories->end();
1339 I != E; ++I)
1340 SortedCategories.push_back(*I);
1341
1342 // Sort the different option categories alphabetically.
1343 assert(SortedCategories.size() > 0 && "No option categories registered!");
1344 std::sort(SortedCategories.begin(), SortedCategories.end(),
1345 OptionCategoryCompare);
1346
1347 // Create map to empty vectors.
1348 for (std::vector<OptionCategory *>::const_iterator
1349 I = SortedCategories.begin(),
1350 E = SortedCategories.end();
1351 I != E; ++I)
1352 CategorizedOptions[*I] = std::vector<Option *>();
1353
1354 // Walk through pre-sorted options and assign into categories.
1355 // Because the options are already alphabetically sorted the
1356 // options within categories will also be alphabetically sorted.
1357 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1358 Option *Opt = Opts[I].second;
1359 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1360 "Option has an unregistered category");
1361 CategorizedOptions[Opt->Category].push_back(Opt);
1362 }
1363
1364 // Now do printing.
1365 for (std::vector<OptionCategory *>::const_iterator
1366 Category = SortedCategories.begin(),
1367 E = SortedCategories.end();
1368 Category != E; ++Category) {
1369 // Hide empty categories for -help, but show for -help-hidden.
1370 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1371 if (!ShowHidden && IsEmptyCategory)
1372 continue;
1373
1374 // Print category information.
1375 outs() << "\n";
1376 outs() << (*Category)->getName() << ":\n";
1377
1378 // Check if description is set.
1379 if ((*Category)->getDescription() != 0)
1380 outs() << (*Category)->getDescription() << "\n\n";
1381 else
1382 outs() << "\n";
1383
1384 // When using -help-hidden explicitly state if the category has no
1385 // options associated with it.
1386 if (IsEmptyCategory) {
1387 outs() << " This option category has no options.\n";
1388 continue;
1389 }
1390 // Loop over the options in the category and print.
1391 for (std::vector<Option *>::const_iterator
1392 Opt = CategorizedOptions[*Category].begin(),
1393 E = CategorizedOptions[*Category].end();
1394 Opt != E; ++Opt)
1395 (*Opt)->printOptionInfo(MaxArgLen);
1396 }
1397 }
1398};
1399
1400// This wraps the Uncategorizing and Categorizing printers and decides
1401// at run time which should be invoked.
1402class HelpPrinterWrapper {
1403private:
1404 HelpPrinter &UncategorizedPrinter;
1405 CategorizedHelpPrinter &CategorizedPrinter;
1406
1407public:
1408 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1409 CategorizedHelpPrinter &CategorizedPrinter) :
1410 UncategorizedPrinter(UncategorizedPrinter),
1411 CategorizedPrinter(CategorizedPrinter) { }
1412
1413 // Invoke the printer.
1414 void operator=(bool Value);
1415};
1416
Chris Lattner500d8bf2006-10-12 22:09:17 +00001417} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001418
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001419// Declare the four HelpPrinter instances that are used to print out help, or
1420// help-hidden as an uncategorized list or in categories.
1421static HelpPrinter UncategorizedNormalPrinter(false);
1422static HelpPrinter UncategorizedHiddenPrinter(true);
1423static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1424static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1425
1426
1427// Declare HelpPrinter wrappers that will decide whether or not to invoke
1428// a categorizing help printer
1429static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1430 CategorizedNormalPrinter);
1431static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1432 CategorizedHiddenPrinter);
1433
1434// Define uncategorized help printers.
1435// -help-list is hidden by default because if Option categories are being used
1436// then -help behaves the same as -help-list.
1437static cl::opt<HelpPrinter, true, parser<bool> >
1438HLOp("help-list",
1439 cl::desc("Display list of available options (-help-list-hidden for more)"),
1440 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001441
Chris Lattner500d8bf2006-10-12 22:09:17 +00001442static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001443HLHOp("help-list-hidden",
1444 cl::desc("Display list of all available options"),
1445 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1446
1447// Define uncategorized/categorized help printers. These printers change their
1448// behaviour at runtime depending on whether one or more Option categories have
1449// been declared.
1450static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001451HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001452 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001453
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001454static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001455HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001456 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1457
1458
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001459
Andrew Trickce969022011-04-05 18:54:36 +00001460static cl::opt<bool>
1461PrintOptions("print-options",
1462 cl::desc("Print non-default options after command line parsing"),
1463 cl::Hidden, cl::init(false));
1464
1465static cl::opt<bool>
1466PrintAllOptions("print-all-options",
1467 cl::desc("Print all option values after command line parsing"),
1468 cl::Hidden, cl::init(false));
1469
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001470void HelpPrinterWrapper::operator=(bool Value) {
1471 if (Value == false)
1472 return;
1473
1474 // Decide which printer to invoke. If more than one option category is
1475 // registered then it is useful to show the categorized help instead of
1476 // uncategorized help.
1477 if (RegisteredOptionCategories->size() > 1) {
1478 // unhide -help-list option so user can have uncategorized output if they
1479 // want it.
1480 HLOp.setHiddenFlag(NotHidden);
1481
1482 CategorizedPrinter = true; // Invoke categorized printer
1483 }
1484 else
1485 UncategorizedPrinter = true; // Invoke uncategorized printer
1486}
1487
Andrew Trickce969022011-04-05 18:54:36 +00001488// Print the value of each option.
1489void cl::PrintOptionValues() {
1490 if (!PrintOptions && !PrintAllOptions) return;
1491
1492 // Get all the options.
1493 SmallVector<Option*, 4> PositionalOpts;
1494 SmallVector<Option*, 4> SinkOpts;
1495 StringMap<Option*> OptMap;
1496 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1497
1498 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1499 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1500
1501 // Compute the maximum argument length...
1502 size_t MaxArgLen = 0;
1503 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1504 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1505
1506 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1507 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1508}
1509
Chris Lattner500d8bf2006-10-12 22:09:17 +00001510static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001511
Chandler Carruth6d51d262011-07-22 07:50:40 +00001512static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1513
Chris Lattner500d8bf2006-10-12 22:09:17 +00001514namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001515class VersionPrinter {
1516public:
Devang Patelaed293d2007-02-01 01:43:37 +00001517 void print() {
Chris Lattner49b301c2009-09-20 06:18:38 +00001518 raw_ostream &OS = outs();
Jim Grosbachc48d4dc2012-01-25 22:00:23 +00001519 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner49b301c2009-09-20 06:18:38 +00001520 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001521#ifdef LLVM_VERSION_INFO
Chris Lattner49b301c2009-09-20 06:18:38 +00001522 OS << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001523#endif
Chris Lattner49b301c2009-09-20 06:18:38 +00001524 OS << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001525#ifndef __OPTIMIZE__
Chris Lattner49b301c2009-09-20 06:18:38 +00001526 OS << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001527#else
Chris Lattner49b301c2009-09-20 06:18:38 +00001528 OS << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001529#endif
1530#ifndef NDEBUG
Chris Lattner49b301c2009-09-20 06:18:38 +00001531 OS << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001532#endif
Daniel Dunbarba43e072009-11-14 21:36:07 +00001533 std::string CPU = sys::getHostCPUName();
Benjamin Kramer110e7bb2009-11-17 17:57:04 +00001534 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner49b301c2009-09-20 06:18:38 +00001535 OS << ".\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001536#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner49b301c2009-09-20 06:18:38 +00001537 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001538#endif
Sebastian Pop01738642011-11-01 21:32:20 +00001539 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth40393132011-07-22 07:50:48 +00001540 << " Host CPU: " << CPU << '\n';
Devang Patelaed293d2007-02-01 01:43:37 +00001541 }
1542 void operator=(bool OptionWasSpecified) {
Chris Lattner043b8b52009-09-20 05:48:01 +00001543 if (!OptionWasSpecified) return;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001544
Chandler Carruth6d51d262011-07-22 07:50:40 +00001545 if (OverrideVersionPrinter != 0) {
1546 (*OverrideVersionPrinter)();
Chris Lattner043b8b52009-09-20 05:48:01 +00001547 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001548 }
Chandler Carruth6d51d262011-07-22 07:50:40 +00001549 print();
1550
1551 // Iterate over any registered extra printers and call them to add further
1552 // information.
1553 if (ExtraVersionPrinters != 0) {
Chandler Carruth40393132011-07-22 07:50:48 +00001554 outs() << '\n';
Chandler Carruth6d51d262011-07-22 07:50:40 +00001555 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1556 E = ExtraVersionPrinters->end();
1557 I != E; ++I)
1558 (*I)();
1559 }
1560
Chris Lattner043b8b52009-09-20 05:48:01 +00001561 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001562 }
1563};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001564} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001565
1566
Reid Spencer69105f32004-08-04 00:36:06 +00001567// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001568static VersionPrinter VersionPrinterInstance;
1569
1570static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001571VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001572 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1573
Reid Spencer9bbba0912004-11-16 06:11:52 +00001574// Utility function for printing the help message.
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001575void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1576 // This looks weird, but it actually prints the help message. The Printers are
1577 // types of HelpPrinter and the help gets printed when its operator= is
1578 // invoked. That's because the "normal" usages of the help printer is to be
1579 // assigned true/false depending on whether -help or -help-hidden was given or
1580 // not. Since we're circumventing that we have to make it look like -help or
1581 // -help-hidden were given, so we assign true.
1582
1583 if (!Hidden && !Categorized)
1584 UncategorizedNormalPrinter = true;
1585 else if (!Hidden && Categorized)
1586 CategorizedNormalPrinter = true;
1587 else if (Hidden && !Categorized)
1588 UncategorizedHiddenPrinter = true;
1589 else
1590 CategorizedHiddenPrinter = true;
Reid Spencer9bbba0912004-11-16 06:11:52 +00001591}
Reid Spencer515b5b32006-06-05 16:22:56 +00001592
Devang Patelaed293d2007-02-01 01:43:37 +00001593/// Utility function for printing version number.
1594void cl::PrintVersionMessage() {
1595 VersionPrinterInstance.print();
1596}
1597
Reid Spencer515b5b32006-06-05 16:22:56 +00001598void cl::SetVersionPrinter(void (*func)()) {
1599 OverrideVersionPrinter = func;
1600}
Chandler Carruth6d51d262011-07-22 07:50:40 +00001601
1602void cl::AddExtraVersionPrinter(void (*func)()) {
1603 if (ExtraVersionPrinters == 0)
1604 ExtraVersionPrinters = new std::vector<void (*)()>;
1605
1606 ExtraVersionPrinters->push_back(func);
1607}
Andrew Trick61e01722013-05-06 21:56:35 +00001608
1609void cl::getRegisteredOptions(StringMap<Option*> &Map)
1610{
1611 // Get all the options.
1612 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1613 SmallVector<Option*, 4> SinkOpts; //NOT USED
1614 assert(Map.size() == 0 && "StringMap must be empty");
1615 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1616 return;
1617}