blob: 7568390d6442581553a974e3cd3d87ceee93e69f [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 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
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000916static void printHelpStr(StringRef HelpStr, size_t Indent,
917 size_t FirstLineIndentedBy) {
918 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
919 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
920 while (!Split.second.empty()) {
921 Split = Split.second.split('\n');
922 outs().indent(Indent) << Split.first << "\n";
923 }
924}
925
Chris Lattnera0de8432006-04-28 05:36:25 +0000926// Print out the option for the alias.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000927void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Chengff276b42011-06-13 20:45:54 +0000928 outs() << " -" << ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000929 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000930}
931
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000932//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000933// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000934//
935
Chris Lattner9b14eb52002-08-07 18:36:37 +0000936// basic_parser implementation
937//
938
939// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000940size_t basic_parser_impl::getOptionWidth(const Option &O) const {
941 size_t Len = std::strlen(O.ArgStr);
Chris Lattner9b14eb52002-08-07 18:36:37 +0000942 if (const char *ValName = getValueName())
943 Len += std::strlen(getValueStr(O, ValName))+3;
944
945 return Len + 6;
946}
947
Misha Brukmanf976c852005-04-21 22:55:34 +0000948// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000949// to-be-maintained width is specified.
950//
951void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +0000952 size_t GlobalWidth) const {
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000953 outs() << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000954
955 if (const char *ValName = getValueName())
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000956 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattner9b14eb52002-08-07 18:36:37 +0000957
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000958 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattner9b14eb52002-08-07 18:36:37 +0000959}
960
Andrew Trickce969022011-04-05 18:54:36 +0000961void basic_parser_impl::printOptionName(const Option &O,
962 size_t GlobalWidth) const {
963 outs() << " -" << O.ArgStr;
964 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
965}
Chris Lattner9b14eb52002-08-07 18:36:37 +0000966
967
Chris Lattner331de232002-07-22 02:07:59 +0000968// parser<bool> implementation
969//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000970bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000971 StringRef Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000972 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000973 Arg == "1") {
974 Value = true;
Chris Lattnera460beb2009-09-19 18:55:05 +0000975 return false;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000976 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000977
Chris Lattnera460beb2009-09-19 18:55:05 +0000978 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
979 Value = false;
980 return false;
981 }
982 return O.error("'" + Arg +
983 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000984}
985
Dale Johannesen81da02b2007-05-22 17:14:46 +0000986// parser<boolOrDefault> implementation
987//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000988bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000989 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen81da02b2007-05-22 17:14:46 +0000990 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
991 Arg == "1") {
992 Value = BOU_TRUE;
Chris Lattnera460beb2009-09-19 18:55:05 +0000993 return false;
Dale Johannesen81da02b2007-05-22 17:14:46 +0000994 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000995 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
996 Value = BOU_FALSE;
997 return false;
998 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000999
Chris Lattnera460beb2009-09-19 18:55:05 +00001000 return O.error("'" + Arg +
1001 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen81da02b2007-05-22 17:14:46 +00001002}
1003
Chris Lattner331de232002-07-22 02:07:59 +00001004// parser<int> implementation
1005//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001006bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001007 StringRef Arg, int &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001008 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001009 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001010 return false;
1011}
1012
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001013// parser<unsigned> implementation
1014//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001015bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001016 StringRef Arg, unsigned &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001017
1018 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001019 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001020 return false;
1021}
1022
Benjamin Kramerb3514562011-09-15 21:17:37 +00001023// parser<unsigned long long> implementation
1024//
1025bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1026 StringRef Arg, unsigned long long &Value){
1027
1028 if (Arg.getAsInteger(0, Value))
1029 return O.error("'" + Arg + "' value invalid for uint argument!");
1030 return false;
1031}
1032
Chris Lattner9b14eb52002-08-07 18:36:37 +00001033// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +00001034//
Chris Lattnera460beb2009-09-19 18:55:05 +00001035static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001036 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1037 const char *ArgStart = TmpStr.c_str();
Chris Lattner331de232002-07-22 02:07:59 +00001038 char *End;
1039 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +00001040 if (*End != 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001041 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +00001042 return false;
1043}
1044
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001045bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001046 StringRef Arg, double &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001047 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +00001048}
1049
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001050bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001051 StringRef Arg, float &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001052 double dVal;
1053 if (parseDouble(O, Arg, dVal))
1054 return true;
1055 Val = (float)dVal;
1056 return false;
Chris Lattner331de232002-07-22 02:07:59 +00001057}
1058
1059
Chris Lattner331de232002-07-22 02:07:59 +00001060
1061// generic_parser_base implementation
1062//
1063
Chris Lattneraa852bb2002-07-23 17:15:12 +00001064// findOption - Return the option number corresponding to the specified
1065// argument string. If the option is not found, getNumOptions() is returned.
1066//
1067unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer461c8762009-09-19 10:01:45 +00001068 unsigned e = getNumOptions();
Chris Lattneraa852bb2002-07-23 17:15:12 +00001069
Benjamin Kramer461c8762009-09-19 10:01:45 +00001070 for (unsigned i = 0; i != e; ++i) {
1071 if (strcmp(getOption(i), Name) == 0)
Chris Lattneraa852bb2002-07-23 17:15:12 +00001072 return i;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001073 }
Chris Lattneraa852bb2002-07-23 17:15:12 +00001074 return e;
1075}
1076
1077
Chris Lattner331de232002-07-22 02:07:59 +00001078// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001079size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner331de232002-07-22 02:07:59 +00001080 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001081 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner331de232002-07-22 02:07:59 +00001082 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001083 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001084 return Size;
1085 } else {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001086 size_t BaseSize = 0;
Chris Lattner331de232002-07-22 02:07:59 +00001087 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001088 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001089 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001090 }
1091}
1092
Misha Brukmanf976c852005-04-21 22:55:34 +00001093// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +00001094// to-be-maintained width is specified.
1095//
1096void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001097 size_t GlobalWidth) const {
Chris Lattner331de232002-07-22 02:07:59 +00001098 if (O.hasArgStr()) {
Chris Lattnerb1687372009-09-20 05:03:30 +00001099 outs() << " -" << O.ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001100 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001101
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 NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerb1687372009-09-20 05:03:30 +00001104 outs() << " =" << getOption(i);
1105 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattner9c9be482002-01-31 00:42:56 +00001106 }
Chris Lattner331de232002-07-22 02:07:59 +00001107 } else {
1108 if (O.HelpStr[0])
Chris Lattnerb1687372009-09-20 05:03:30 +00001109 outs() << " " << O.HelpStr << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001110 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001111 const char *Option = getOption(i);
1112 outs() << " -" << Option;
1113 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner331de232002-07-22 02:07:59 +00001114 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001115 }
1116}
1117
Andrew Trickce969022011-04-05 18:54:36 +00001118static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1119
1120// printGenericOptionDiff - Print the value of this option and it's default.
1121//
1122// "Generic" options have each value mapped to a name.
1123void generic_parser_base::
1124printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1125 const GenericOptionValue &Default,
1126 size_t GlobalWidth) const {
1127 outs() << " -" << O.ArgStr;
1128 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1129
1130 unsigned NumOpts = getNumOptions();
1131 for (unsigned i = 0; i != NumOpts; ++i) {
1132 if (Value.compare(getOptionValue(i)))
1133 continue;
1134
1135 outs() << "= " << getOption(i);
1136 size_t L = std::strlen(getOption(i));
1137 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1138 outs().indent(NumSpaces) << " (default: ";
1139 for (unsigned j = 0; j != NumOpts; ++j) {
1140 if (Default.compare(getOptionValue(j)))
1141 continue;
1142 outs() << getOption(j);
1143 break;
1144 }
1145 outs() << ")\n";
1146 return;
1147 }
1148 outs() << "= *unknown option value*\n";
1149}
1150
1151// printOptionDiff - Specializations for printing basic value types.
1152//
1153#define PRINT_OPT_DIFF(T) \
1154 void parser<T>:: \
1155 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1156 size_t GlobalWidth) const { \
1157 printOptionName(O, GlobalWidth); \
1158 std::string Str; \
1159 { \
1160 raw_string_ostream SS(Str); \
1161 SS << V; \
1162 } \
1163 outs() << "= " << Str; \
1164 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1165 outs().indent(NumSpaces) << " (default: "; \
1166 if (D.hasValue()) \
1167 outs() << D.getValue(); \
1168 else \
1169 outs() << "*no default*"; \
1170 outs() << ")\n"; \
1171 } \
1172
Frits van Bommel090771f2011-04-06 12:29:56 +00001173PRINT_OPT_DIFF(bool)
1174PRINT_OPT_DIFF(boolOrDefault)
1175PRINT_OPT_DIFF(int)
1176PRINT_OPT_DIFF(unsigned)
Benjamin Kramerb3514562011-09-15 21:17:37 +00001177PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel090771f2011-04-06 12:29:56 +00001178PRINT_OPT_DIFF(double)
1179PRINT_OPT_DIFF(float)
1180PRINT_OPT_DIFF(char)
Andrew Trickce969022011-04-05 18:54:36 +00001181
1182void parser<std::string>::
1183printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1184 size_t GlobalWidth) const {
1185 printOptionName(O, GlobalWidth);
1186 outs() << "= " << V;
1187 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1188 outs().indent(NumSpaces) << " (default: ";
1189 if (D.hasValue())
1190 outs() << D.getValue();
1191 else
1192 outs() << "*no default*";
1193 outs() << ")\n";
1194}
1195
1196// Print a placeholder for options that don't yet support printOptionDiff().
1197void basic_parser_impl::
1198printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1199 printOptionName(O, GlobalWidth);
1200 outs() << "= *cannot print option value*\n";
1201}
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001202
1203//===----------------------------------------------------------------------===//
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001204// -help and -help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001205//
Reid Spencerad0846b2004-11-14 22:04:00 +00001206
Chris Lattner0fd48b12009-09-20 05:37:24 +00001207static int OptNameCompare(const void *LHS, const void *RHS) {
1208 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001209
Duncan Sandse840fef2012-03-12 10:51:06 +00001210 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner0fd48b12009-09-20 05:37:24 +00001211}
1212
Andrew Trickce969022011-04-05 18:54:36 +00001213// Copy Options into a vector so we can sort them as we like.
1214static void
1215sortOpts(StringMap<Option*> &OptMap,
1216 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1217 bool ShowHidden) {
1218 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1219
1220 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1221 I != E; ++I) {
1222 // Ignore really-hidden options.
1223 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1224 continue;
1225
1226 // Unless showhidden is set, ignore hidden flags.
1227 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1228 continue;
1229
1230 // If we've already seen this option, don't add it to the list again.
1231 if (!OptionSet.insert(I->second))
1232 continue;
1233
1234 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1235 I->second));
1236 }
1237
1238 // Sort the options list alphabetically.
1239 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1240}
1241
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001242namespace {
1243
Chris Lattner331de232002-07-22 02:07:59 +00001244class HelpPrinter {
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001245protected:
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001246 const bool ShowHidden;
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001247 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1248 // Print the options. Opts is assumed to be alphabetically sorted.
1249 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1250 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1251 Opts[i].second->printOptionInfo(MaxArgLen);
1252 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001253
Chris Lattner331de232002-07-22 02:07:59 +00001254public:
Craig Topperddde2082013-03-09 23:29:37 +00001255 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001256 virtual ~HelpPrinter() {}
Chris Lattner331de232002-07-22 02:07:59 +00001257
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001258 // Invoke the printer.
Chris Lattner331de232002-07-22 02:07:59 +00001259 void operator=(bool Value) {
1260 if (Value == false) return;
1261
Chris Lattner9878d6a2007-04-06 21:06:55 +00001262 // Get all the options.
Chris Lattner49b301c2009-09-20 06:18:38 +00001263 SmallVector<Option*, 4> PositionalOpts;
1264 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001265 StringMap<Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +00001266 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001267
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001268 StrOptionPairVector Opts;
Andrew Trickce969022011-04-05 18:54:36 +00001269 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001270
1271 if (ProgramOverview)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001272 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001273
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001274 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +00001275
Chris Lattner90aa8392006-10-04 21:52:35 +00001276 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +00001277 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001278 if (!PositionalOpts.empty() &&
Chris Lattner9878d6a2007-04-06 21:06:55 +00001279 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1280 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +00001281
Evan Cheng34cd4a42008-05-05 18:30:58 +00001282 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +00001283 if (PositionalOpts[i]->ArgStr[0])
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001284 outs() << " --" << PositionalOpts[i]->ArgStr;
1285 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +00001286 }
Chris Lattner331de232002-07-22 02:07:59 +00001287
1288 // Print the consume after option info if it exists...
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001289 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +00001290
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001291 outs() << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001292
1293 // Compute the maximum argument length...
Craig Topperddde2082013-03-09 23:29:37 +00001294 size_t MaxArgLen = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +00001295 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0fd48b12009-09-20 05:37:24 +00001296 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001297
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001298 outs() << "OPTIONS:\n";
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001299 printOptions(Opts, MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001300
Chris Lattnerc540ebb2004-11-19 17:08:15 +00001301 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +00001302 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001303 E = MoreHelp->end();
1304 I != E; ++I)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001305 outs() << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001306 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001307
Reid Spencer9bbba0912004-11-16 06:11:52 +00001308 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001309 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001310 }
1311};
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001312
1313class CategorizedHelpPrinter : public HelpPrinter {
1314public:
1315 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1316
1317 // Helper function for printOptions().
1318 // It shall return true if A's name should be lexographically
1319 // ordered before B's name. It returns false otherwise.
1320 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1321 int Length = strcmp(A->getName(), B->getName());
1322 assert(Length != 0 && "Duplicate option categories");
1323 return Length < 0;
1324 }
1325
1326 // Make sure we inherit our base class's operator=()
1327 using HelpPrinter::operator= ;
1328
1329protected:
1330 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1331 std::vector<OptionCategory *> SortedCategories;
1332 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1333
1334 // Collect registered option categories into vector in preperation for
1335 // sorting.
1336 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1337 E = RegisteredOptionCategories->end();
1338 I != E; ++I)
1339 SortedCategories.push_back(*I);
1340
1341 // Sort the different option categories alphabetically.
1342 assert(SortedCategories.size() > 0 && "No option categories registered!");
1343 std::sort(SortedCategories.begin(), SortedCategories.end(),
1344 OptionCategoryCompare);
1345
1346 // Create map to empty vectors.
1347 for (std::vector<OptionCategory *>::const_iterator
1348 I = SortedCategories.begin(),
1349 E = SortedCategories.end();
1350 I != E; ++I)
1351 CategorizedOptions[*I] = std::vector<Option *>();
1352
1353 // Walk through pre-sorted options and assign into categories.
1354 // Because the options are already alphabetically sorted the
1355 // options within categories will also be alphabetically sorted.
1356 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1357 Option *Opt = Opts[I].second;
1358 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1359 "Option has an unregistered category");
1360 CategorizedOptions[Opt->Category].push_back(Opt);
1361 }
1362
1363 // Now do printing.
1364 for (std::vector<OptionCategory *>::const_iterator
1365 Category = SortedCategories.begin(),
1366 E = SortedCategories.end();
1367 Category != E; ++Category) {
1368 // Hide empty categories for -help, but show for -help-hidden.
1369 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1370 if (!ShowHidden && IsEmptyCategory)
1371 continue;
1372
1373 // Print category information.
1374 outs() << "\n";
1375 outs() << (*Category)->getName() << ":\n";
1376
1377 // Check if description is set.
1378 if ((*Category)->getDescription() != 0)
1379 outs() << (*Category)->getDescription() << "\n\n";
1380 else
1381 outs() << "\n";
1382
1383 // When using -help-hidden explicitly state if the category has no
1384 // options associated with it.
1385 if (IsEmptyCategory) {
1386 outs() << " This option category has no options.\n";
1387 continue;
1388 }
1389 // Loop over the options in the category and print.
1390 for (std::vector<Option *>::const_iterator
1391 Opt = CategorizedOptions[*Category].begin(),
1392 E = CategorizedOptions[*Category].end();
1393 Opt != E; ++Opt)
1394 (*Opt)->printOptionInfo(MaxArgLen);
1395 }
1396 }
1397};
1398
1399// This wraps the Uncategorizing and Categorizing printers and decides
1400// at run time which should be invoked.
1401class HelpPrinterWrapper {
1402private:
1403 HelpPrinter &UncategorizedPrinter;
1404 CategorizedHelpPrinter &CategorizedPrinter;
1405
1406public:
1407 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1408 CategorizedHelpPrinter &CategorizedPrinter) :
1409 UncategorizedPrinter(UncategorizedPrinter),
1410 CategorizedPrinter(CategorizedPrinter) { }
1411
1412 // Invoke the printer.
1413 void operator=(bool Value);
1414};
1415
Chris Lattner500d8bf2006-10-12 22:09:17 +00001416} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001417
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001418// Declare the four HelpPrinter instances that are used to print out help, or
1419// help-hidden as an uncategorized list or in categories.
1420static HelpPrinter UncategorizedNormalPrinter(false);
1421static HelpPrinter UncategorizedHiddenPrinter(true);
1422static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1423static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1424
1425
1426// Declare HelpPrinter wrappers that will decide whether or not to invoke
1427// a categorizing help printer
1428static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1429 CategorizedNormalPrinter);
1430static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1431 CategorizedHiddenPrinter);
1432
1433// Define uncategorized help printers.
1434// -help-list is hidden by default because if Option categories are being used
1435// then -help behaves the same as -help-list.
1436static cl::opt<HelpPrinter, true, parser<bool> >
1437HLOp("help-list",
1438 cl::desc("Display list of available options (-help-list-hidden for more)"),
1439 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001440
Chris Lattner500d8bf2006-10-12 22:09:17 +00001441static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001442HLHOp("help-list-hidden",
1443 cl::desc("Display list of all available options"),
1444 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1445
1446// Define uncategorized/categorized help printers. These printers change their
1447// behaviour at runtime depending on whether one or more Option categories have
1448// been declared.
1449static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001450HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001451 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001452
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001453static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001454HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001455 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1456
1457
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001458
Andrew Trickce969022011-04-05 18:54:36 +00001459static cl::opt<bool>
1460PrintOptions("print-options",
1461 cl::desc("Print non-default options after command line parsing"),
1462 cl::Hidden, cl::init(false));
1463
1464static cl::opt<bool>
1465PrintAllOptions("print-all-options",
1466 cl::desc("Print all option values after command line parsing"),
1467 cl::Hidden, cl::init(false));
1468
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001469void HelpPrinterWrapper::operator=(bool Value) {
1470 if (Value == false)
1471 return;
1472
1473 // Decide which printer to invoke. If more than one option category is
1474 // registered then it is useful to show the categorized help instead of
1475 // uncategorized help.
1476 if (RegisteredOptionCategories->size() > 1) {
1477 // unhide -help-list option so user can have uncategorized output if they
1478 // want it.
1479 HLOp.setHiddenFlag(NotHidden);
1480
1481 CategorizedPrinter = true; // Invoke categorized printer
1482 }
1483 else
1484 UncategorizedPrinter = true; // Invoke uncategorized printer
1485}
1486
Andrew Trickce969022011-04-05 18:54:36 +00001487// Print the value of each option.
1488void cl::PrintOptionValues() {
1489 if (!PrintOptions && !PrintAllOptions) return;
1490
1491 // Get all the options.
1492 SmallVector<Option*, 4> PositionalOpts;
1493 SmallVector<Option*, 4> SinkOpts;
1494 StringMap<Option*> OptMap;
1495 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1496
1497 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1498 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1499
1500 // Compute the maximum argument length...
1501 size_t MaxArgLen = 0;
1502 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1503 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1504
1505 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1506 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1507}
1508
Chris Lattner500d8bf2006-10-12 22:09:17 +00001509static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001510
Chandler Carruth6d51d262011-07-22 07:50:40 +00001511static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1512
Chris Lattner500d8bf2006-10-12 22:09:17 +00001513namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001514class VersionPrinter {
1515public:
Devang Patelaed293d2007-02-01 01:43:37 +00001516 void print() {
Chris Lattner49b301c2009-09-20 06:18:38 +00001517 raw_ostream &OS = outs();
Jim Grosbachc48d4dc2012-01-25 22:00:23 +00001518 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner49b301c2009-09-20 06:18:38 +00001519 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001520#ifdef LLVM_VERSION_INFO
Chris Lattner49b301c2009-09-20 06:18:38 +00001521 OS << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001522#endif
Chris Lattner49b301c2009-09-20 06:18:38 +00001523 OS << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001524#ifndef __OPTIMIZE__
Chris Lattner49b301c2009-09-20 06:18:38 +00001525 OS << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001526#else
Chris Lattner49b301c2009-09-20 06:18:38 +00001527 OS << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001528#endif
1529#ifndef NDEBUG
Chris Lattner49b301c2009-09-20 06:18:38 +00001530 OS << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001531#endif
Daniel Dunbarba43e072009-11-14 21:36:07 +00001532 std::string CPU = sys::getHostCPUName();
Benjamin Kramer110e7bb2009-11-17 17:57:04 +00001533 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner49b301c2009-09-20 06:18:38 +00001534 OS << ".\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001535#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner49b301c2009-09-20 06:18:38 +00001536 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001537#endif
Sebastian Pop01738642011-11-01 21:32:20 +00001538 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth40393132011-07-22 07:50:48 +00001539 << " Host CPU: " << CPU << '\n';
Devang Patelaed293d2007-02-01 01:43:37 +00001540 }
1541 void operator=(bool OptionWasSpecified) {
Chris Lattner043b8b52009-09-20 05:48:01 +00001542 if (!OptionWasSpecified) return;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001543
Chandler Carruth6d51d262011-07-22 07:50:40 +00001544 if (OverrideVersionPrinter != 0) {
1545 (*OverrideVersionPrinter)();
Chris Lattner043b8b52009-09-20 05:48:01 +00001546 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001547 }
Chandler Carruth6d51d262011-07-22 07:50:40 +00001548 print();
1549
1550 // Iterate over any registered extra printers and call them to add further
1551 // information.
1552 if (ExtraVersionPrinters != 0) {
Chandler Carruth40393132011-07-22 07:50:48 +00001553 outs() << '\n';
Chandler Carruth6d51d262011-07-22 07:50:40 +00001554 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1555 E = ExtraVersionPrinters->end();
1556 I != E; ++I)
1557 (*I)();
1558 }
1559
Chris Lattner043b8b52009-09-20 05:48:01 +00001560 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001561 }
1562};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001563} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001564
1565
Reid Spencer69105f32004-08-04 00:36:06 +00001566// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001567static VersionPrinter VersionPrinterInstance;
1568
1569static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001570VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001571 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1572
Reid Spencer9bbba0912004-11-16 06:11:52 +00001573// Utility function for printing the help message.
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001574void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1575 // This looks weird, but it actually prints the help message. The Printers are
1576 // types of HelpPrinter and the help gets printed when its operator= is
1577 // invoked. That's because the "normal" usages of the help printer is to be
1578 // assigned true/false depending on whether -help or -help-hidden was given or
1579 // not. Since we're circumventing that we have to make it look like -help or
1580 // -help-hidden were given, so we assign true.
1581
1582 if (!Hidden && !Categorized)
1583 UncategorizedNormalPrinter = true;
1584 else if (!Hidden && Categorized)
1585 CategorizedNormalPrinter = true;
1586 else if (Hidden && !Categorized)
1587 UncategorizedHiddenPrinter = true;
1588 else
1589 CategorizedHiddenPrinter = true;
Reid Spencer9bbba0912004-11-16 06:11:52 +00001590}
Reid Spencer515b5b32006-06-05 16:22:56 +00001591
Devang Patelaed293d2007-02-01 01:43:37 +00001592/// Utility function for printing version number.
1593void cl::PrintVersionMessage() {
1594 VersionPrinterInstance.print();
1595}
1596
Reid Spencer515b5b32006-06-05 16:22:56 +00001597void cl::SetVersionPrinter(void (*func)()) {
1598 OverrideVersionPrinter = func;
1599}
Chandler Carruth6d51d262011-07-22 07:50:40 +00001600
1601void cl::AddExtraVersionPrinter(void (*func)()) {
1602 if (ExtraVersionPrinters == 0)
1603 ExtraVersionPrinters = new std::vector<void (*)()>;
1604
1605 ExtraVersionPrinters->push_back(func);
1606}
Andrew Trick61e01722013-05-06 21:56:35 +00001607
1608void cl::getRegisteredOptions(StringMap<Option*> &Map)
1609{
1610 // Get all the options.
1611 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1612 SmallVector<Option*, 4> SinkOpts; //NOT USED
1613 assert(Map.size() == 0 && "StringMap must be empty");
1614 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1615 return;
1616}