blob: a47af2729f359f4b4aff07abd3ccd543d10441c2 [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"
Reid Kleckner431b0a72013-07-18 16:52:05 +000020#include "llvm/ADT/ArrayRef.h"
Chris Lattnerca179342009-08-23 18:09:02 +000021#include "llvm/ADT/OwningPtr.h"
Chris Lattner67aead62009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner970e7df2009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner67aead62009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattnera460beb2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattnerca179342009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Kleckner431b0a72013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/system_error.h"
Brian Gaeke2d6a2362003-10-10 17:01:36 +000036#include <cerrno>
Chris Lattnerca179342009-08-23 18:09:02 +000037#include <cstdlib>
Andrew Trickb7ad33b2013-05-06 21:56:23 +000038#include <map>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000040using namespace cl;
41
Chris Lattner7422a762006-08-27 12:45:47 +000042//===----------------------------------------------------------------------===//
43// Template instantiations and anchors.
44//
Douglas Gregorb3587cf2009-11-25 06:04:18 +000045namespace llvm { namespace cl {
Chris Lattner7422a762006-08-27 12:45:47 +000046TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000047TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000048TEMPLATE_INSTANTIATION(class basic_parser<int>);
49TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramerb3514562011-09-15 21:17:37 +000050TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner7422a762006-08-27 12:45:47 +000051TEMPLATE_INSTANTIATION(class basic_parser<double>);
52TEMPLATE_INSTANTIATION(class basic_parser<float>);
53TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000054TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000055
56TEMPLATE_INSTANTIATION(class opt<unsigned>);
57TEMPLATE_INSTANTIATION(class opt<int>);
58TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000059TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000060TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregorb3587cf2009-11-25 06:04:18 +000061} } // end namespace llvm::cl
Chris Lattner7422a762006-08-27 12:45:47 +000062
David Blaikie0becc962011-12-01 08:00:17 +000063void 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
Reid Kleckner431b0a72013-07-18 16:52:05 +0000439static bool isWhitespace(char C) {
440 return strchr(" \t\n\r\f\v", C);
441}
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000442
Reid Kleckner431b0a72013-07-18 16:52:05 +0000443static bool isQuote(char C) {
444 return C == '\"' || C == '\'';
445}
446
447static bool isGNUSpecial(char C) {
448 return strchr("\\\"\' ", C);
449}
450
451void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
452 SmallVectorImpl<const char *> &NewArgv) {
453 SmallString<128> Token;
454 for (size_t I = 0, E = Src.size(); I != E; ++I) {
455 // Consume runs of whitespace.
456 if (Token.empty()) {
457 while (I != E && isWhitespace(Src[I]))
458 ++I;
459 if (I == E) break;
460 }
461
462 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
463 // they are literal. This makes it much easier to read Windows file paths.
464 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
465 ++I; // Skip the escape.
466 Token.push_back(Src[I]);
Chris Lattner63e944b2009-09-24 05:38:36 +0000467 continue;
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000468 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000469
Reid Kleckner431b0a72013-07-18 16:52:05 +0000470 // Consume a quoted string.
471 if (isQuote(Src[I])) {
472 char Quote = Src[I++];
473 while (I != E && Src[I] != Quote) {
474 // Backslashes are literal, unless they escape a special character.
475 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
476 ++I;
477 Token.push_back(Src[I]);
478 ++I;
479 }
480 if (I == E) break;
481 continue;
482 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000483
Reid Kleckner431b0a72013-07-18 16:52:05 +0000484 // End the token if this is whitespace.
485 if (isWhitespace(Src[I])) {
486 if (!Token.empty())
487 NewArgv.push_back(Saver.SaveString(Token.c_str()));
488 Token.clear();
489 continue;
490 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000491
Reid Kleckner431b0a72013-07-18 16:52:05 +0000492 // This is a normal character. Append it.
493 Token.push_back(Src[I]);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000494 }
Reid Kleckner431b0a72013-07-18 16:52:05 +0000495
496 // Append the last token after hitting EOF with no whitespace.
497 if (!Token.empty())
498 NewArgv.push_back(Saver.SaveString(Token.c_str()));
499}
500
Rui Ueyama264e92d2013-07-30 19:03:20 +0000501/// Backslashes are interpreted in a rather complicated way in the Windows-style
502/// command line, because backslashes are used both to separate path and to
503/// escape double quote. This method consumes runs of backslashes as well as the
504/// following double quote if it's escaped.
505///
506/// * If an even number of backslashes is followed by a double quote, one
507/// backslash is output for every pair of backslashes, and the last double
508/// quote remains unconsumed. The double quote will later be interpreted as
509/// the start or end of a quoted string in the main loop outside of this
510/// function.
511///
512/// * If an odd number of backslashes is followed by a double quote, one
513/// backslash is output for every pair of backslashes, and a double quote is
514/// output for the last pair of backslash-double quote. The double quote is
515/// consumed in this case.
516///
517/// * Otherwise, backslashes are interpreted literally.
518static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
519 size_t E = Src.size();
520 int BackslashCount = 0;
521 // Skip the backslashes.
522 do {
523 ++I;
524 ++BackslashCount;
525 } while (I != E && Src[I] == '\\');
526
527 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
528 if (FollowedByDoubleQuote) {
529 Token.append(BackslashCount / 2, '\\');
530 if (BackslashCount % 2 == 0)
531 return I - 1;
532 Token.push_back('"');
533 return I;
534 }
535 Token.append(BackslashCount, '\\');
536 return I - 1;
537}
538
Reid Kleckner431b0a72013-07-18 16:52:05 +0000539void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
540 SmallVectorImpl<const char *> &NewArgv) {
Rui Ueyama264e92d2013-07-30 19:03:20 +0000541 SmallString<128> Token;
542
543 // This is a small state machine to consume characters until it reaches the
544 // end of the source string.
545 enum { INIT, UNQUOTED, QUOTED } State = INIT;
546 for (size_t I = 0, E = Src.size(); I != E; ++I) {
547 // INIT state indicates that the current input index is at the start of
548 // the string or between tokens.
549 if (State == INIT) {
550 if (isWhitespace(Src[I]))
551 continue;
552 if (Src[I] == '"') {
553 State = QUOTED;
554 continue;
555 }
556 if (Src[I] == '\\') {
557 I = parseBackslash(Src, I, Token);
558 State = UNQUOTED;
559 continue;
560 }
561 Token.push_back(Src[I]);
562 State = UNQUOTED;
563 continue;
564 }
565
566 // UNQUOTED state means that it's reading a token not quoted by double
567 // quotes.
568 if (State == UNQUOTED) {
569 // Whitespace means the end of the token.
570 if (isWhitespace(Src[I])) {
571 NewArgv.push_back(Saver.SaveString(Token.c_str()));
572 Token.clear();
573 State = INIT;
574 continue;
575 }
576 if (Src[I] == '"') {
577 State = QUOTED;
578 continue;
579 }
580 if (Src[I] == '\\') {
581 I = parseBackslash(Src, I, Token);
582 continue;
583 }
584 Token.push_back(Src[I]);
585 continue;
586 }
587
588 // QUOTED state means that it's reading a token quoted by double quotes.
589 if (State == QUOTED) {
590 if (Src[I] == '"') {
591 State = UNQUOTED;
592 continue;
593 }
594 if (Src[I] == '\\') {
595 I = parseBackslash(Src, I, Token);
596 continue;
597 }
598 Token.push_back(Src[I]);
599 }
600 }
601 // Append the last token after hitting EOF with no whitespace.
602 if (!Token.empty())
603 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Kleckner431b0a72013-07-18 16:52:05 +0000604}
605
606static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
607 TokenizerCallback Tokenizer,
608 SmallVectorImpl<const char *> &NewArgv) {
609 OwningPtr<MemoryBuffer> MemBuf;
610 if (MemoryBuffer::getFile(FName, MemBuf))
611 return false;
612 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
613
614 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
615 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
616 std::string UTF8Buf;
617 if (hasUTF16ByteOrderMark(BufRef)) {
618 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
619 return false;
620 Str = StringRef(UTF8Buf);
621 }
622
623 // Tokenize the contents into NewArgv.
624 Tokenizer(Str, Saver, NewArgv);
625
626 return true;
627}
628
629/// \brief Expand response files on a command line recursively using the given
630/// StringSaver and tokenization strategy.
631bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
632 SmallVectorImpl<const char *> &Argv) {
633 unsigned RspFiles = 0;
634 bool AllExpanded = false;
635
636 // Don't cache Argv.size() because it can change.
637 for (unsigned I = 0; I != Argv.size(); ) {
638 const char *Arg = Argv[I];
639 if (Arg[0] != '@') {
640 ++I;
641 continue;
642 }
643
644 // If we have too many response files, leave some unexpanded. This avoids
645 // crashing on self-referential response files.
646 if (RspFiles++ > 20)
647 return false;
648
649 // Replace this response file argument with the tokenization of its
650 // contents. Nested response files are expanded in subsequent iterations.
651 // FIXME: If a nested response file uses a relative path, is it relative to
652 // the cwd of the process or the response file?
653 SmallVector<const char *, 0> ExpandedArgv;
654 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
655 AllExpanded = false;
656 continue;
657 }
658 Argv.erase(Argv.begin() + I);
659 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
660 }
661 return AllExpanded;
662}
663
664namespace {
665 class StrDupSaver : public StringSaver {
Rafael Espindola1e3c0a42013-07-24 14:32:01 +0000666 std::vector<char*> Dups;
667 public:
668 ~StrDupSaver() {
669 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
670 I != E; ++I) {
671 char *Dup = *I;
672 free(Dup);
673 }
674 }
Reid Kleckner431b0a72013-07-18 16:52:05 +0000675 const char *SaveString(const char *Str) LLVM_OVERRIDE {
Rafael Espindola1e3c0a42013-07-24 14:32:01 +0000676 char *Dup = strdup(Str);
677 Dups.push_back(Dup);
678 return Dup;
Reid Kleckner431b0a72013-07-18 16:52:05 +0000679 }
680 };
Brian Gaeke06b06c52003-08-14 22:00:59 +0000681}
682
683/// ParseEnvironmentOptions - An alternative entry point to the
684/// CommandLine library, which allows you to read the program's name
685/// from the caller (as PROGNAME) and its command-line arguments from
686/// an environment variable (whose name is given in ENVVAR).
687///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000688void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000689 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000690 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000691 assert(progName && "Program name not specified");
692 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000693
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000694 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000695 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000696 if (!envValue)
697 return;
698
Brian Gaeke06b06c52003-08-14 22:00:59 +0000699 // Get program's "name", which we wouldn't know without the caller
700 // telling us.
Reid Kleckner431b0a72013-07-18 16:52:05 +0000701 SmallVector<const char *, 20> newArgv;
Rafael Espindola1e3c0a42013-07-24 14:32:01 +0000702 StrDupSaver Saver;
703 newArgv.push_back(Saver.SaveString(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000704
705 // Parse the value of the environment variable into a "command line"
706 // and hand it off to ParseCommandLineOptions().
Reid Kleckner431b0a72013-07-18 16:52:05 +0000707 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000708 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000709 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000710}
711
David Blaikieebba0552012-02-07 19:36:01 +0000712void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000713 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000714 // Process all registered options.
Chris Lattner49b301c2009-09-20 06:18:38 +0000715 SmallVector<Option*, 4> PositionalOpts;
716 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +0000717 StringMap<Option*> Opts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000718 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000719
Chris Lattner9878d6a2007-04-06 21:06:55 +0000720 assert((!Opts.empty() || !PositionalOpts.empty()) &&
721 "No options specified!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000722
723 // Expand response files.
Reid Kleckner431b0a72013-07-18 16:52:05 +0000724 SmallVector<const char *, 20> newArgv;
725 for (int i = 0; i != argc; ++i)
Rafael Espindola1e3c0a42013-07-24 14:32:01 +0000726 newArgv.push_back(argv[i]);
Reid Kleckner431b0a72013-07-18 16:52:05 +0000727 StrDupSaver Saver;
728 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000729 argv = &newArgv[0];
730 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000731
Chris Lattnerefa3da52006-10-13 00:06:24 +0000732 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencerb3127bb2010-12-18 00:19:10 +0000733 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000734 size_t Len = std::min(ProgName.size(), size_t(79));
735 memcpy(ProgramName, ProgName.data(), Len);
736 ProgramName[Len] = '\0';
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000737
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000738 ProgramOverview = Overview;
739 bool ErrorParsing = false;
740
Chris Lattner331de232002-07-22 02:07:59 +0000741 // Check out the positional arguments to collect information about them.
742 unsigned NumPositionalRequired = 0;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000743
Chris Lattnerde013242005-08-08 17:25:38 +0000744 // Determine whether or not there are an unlimited number of positionals
745 bool HasUnlimitedPositionals = false;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000746
Chris Lattner331de232002-07-22 02:07:59 +0000747 Option *ConsumeAfterOpt = 0;
748 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000749 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000750 assert(PositionalOpts.size() > 1 &&
751 "Cannot specify cl::ConsumeAfter without a positional argument!");
752 ConsumeAfterOpt = PositionalOpts[0];
753 }
754
755 // Calculate how many positional values are _required_.
756 bool UnboundedFound = false;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000757 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner331de232002-07-22 02:07:59 +0000758 i != e; ++i) {
759 Option *Opt = PositionalOpts[i];
760 if (RequiresValue(Opt))
761 ++NumPositionalRequired;
762 else if (ConsumeAfterOpt) {
763 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000764 // unless there is only one positional argument...
765 if (PositionalOpts.size() > 2)
766 ErrorParsing |=
Benjamin Kramere6864c12009-08-02 12:13:02 +0000767 Opt->error("error - this positional option will never be matched, "
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000768 "because it does not Require a value, and a "
769 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000770 } else if (UnboundedFound && !Opt->ArgStr[0]) {
771 // This option does not "require" a value... Make sure this option is
772 // not specified after an option that eats all extra arguments, or this
773 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000774 //
Benjamin Kramere6864c12009-08-02 12:13:02 +0000775 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner331de232002-07-22 02:07:59 +0000776 "another positional argument will match an "
777 "unbounded number of values, and this option"
778 " does not require a value!");
779 }
780 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
781 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000782 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000783 }
784
Reid Spencer1e13fd22004-08-13 19:47:30 +0000785 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerba112292009-09-20 00:07:40 +0000786 // the process at the end.
Chris Lattner331de232002-07-22 02:07:59 +0000787 //
Chris Lattnerba112292009-09-20 00:07:40 +0000788 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000789
Chris Lattner9cf3d472003-07-30 17:34:02 +0000790 // If the program has named positional arguments, and the name has been run
791 // across, keep track of which positional argument was named. Otherwise put
792 // the positional args into the PositionalVals list...
793 Option *ActivePositionalArg = 0;
794
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000795 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000796 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000797 for (int i = 1; i < argc; ++i) {
798 Option *Handler = 0;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000799 Option *NearestHandler = 0;
Nick Lewycky95d206a2011-05-02 05:24:47 +0000800 std::string NearestHandlerString;
Chris Lattner4e247ec2009-09-20 01:53:12 +0000801 StringRef Value;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000802 StringRef ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000803
Chris Lattner69d6f132007-04-12 00:36:29 +0000804 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000805 // option has just been registered or deregistered. This can occur in
806 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000807 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000808 PositionalOpts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000809 SinkOpts.clear();
Chris Lattner159b0a432007-04-11 15:35:18 +0000810 Opts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000811 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000812 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000813 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000814
Chris Lattner331de232002-07-22 02:07:59 +0000815 // Check to see if this is a positional argument. This argument is
816 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000817 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000818 //
819 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
820 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000821 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000822 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000823 continue; // We are done!
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000824 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000825
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000826 if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000827 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000828
829 // All of the positional arguments have been fulfulled, give the rest to
830 // the consume after option... if it's specified...
831 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000832 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000833 ConsumeAfterOpt != 0) {
834 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000835 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000836 break; // Handle outside of the argument processing loop...
837 }
838
839 // Delay processing positional arguments until the end...
840 continue;
841 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000842 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
843 !DashDashFound) {
844 DashDashFound = true; // This is the mythical "--"?
845 continue; // Don't try to process it as an argument itself.
846 } else if (ActivePositionalArg &&
847 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
848 // If there is a positional argument eating options, check to see if this
849 // option is another positional argument. If so, treat it as an argument,
850 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000851 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000852 // Eat leading dashes.
853 while (!ArgName.empty() && ArgName[0] == '-')
854 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000855
Chris Lattner9878d6a2007-04-06 21:06:55 +0000856 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000857 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000858 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000859 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000860 }
861
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000862 } else { // We start with a '-', must be an argument.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000863 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000864 // Eat leading dashes.
865 while (!ArgName.empty() && ArgName[0] == '-')
866 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000867
Chris Lattner9878d6a2007-04-06 21:06:55 +0000868 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000869
Chris Lattnerbf455c22004-05-06 22:04:31 +0000870 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnerb1687372009-09-20 05:03:30 +0000871 if (Handler == 0)
872 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
873 ErrorParsing, Opts);
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000874
875 // Otherwise, look for the closest available option to report to the user
876 // in the upcoming error.
877 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000878 NearestHandler = LookupNearestOption(ArgName, Opts,
879 NearestHandlerString);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000880 }
881
882 if (Handler == 0) {
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000883 if (SinkOpts.empty()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000884 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000885 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000886
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000887 if (NearestHandler) {
888 // If we know a near match, report it as well.
889 errs() << ProgramName << ": Did you mean '-"
890 << NearestHandlerString << "'?\n";
891 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000892
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000893 ErrorParsing = true;
894 } else {
Chris Lattner49b301c2009-09-20 06:18:38 +0000895 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000896 E = SinkOpts.end(); I != E ; ++I)
897 (*I)->addOccurrence(i, "", argv[i]);
898 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000899 continue;
900 }
901
Chris Lattner9cf3d472003-07-30 17:34:02 +0000902 // If this is a named positional argument, just remember that it is the
903 // active one...
904 if (Handler->getFormattingFlag() == cl::Positional)
905 ActivePositionalArg = Handler;
Chris Lattner341620b2009-09-20 01:49:31 +0000906 else
Chris Lattner4e247ec2009-09-20 01:53:12 +0000907 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000908 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000909
Chris Lattner331de232002-07-22 02:07:59 +0000910 // Check and handle positional arguments now...
911 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000912 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000913 << ": Not enough positional command line arguments specified!\n"
914 << "Must specify at least " << NumPositionalRequired
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000915 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000916
Chris Lattner331de232002-07-22 02:07:59 +0000917 ErrorParsing = true;
Dan Gohman16e02092010-03-24 19:38:02 +0000918 } else if (!HasUnlimitedPositionals &&
919 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000920 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000921 << ": Too many positional arguments specified!\n"
922 << "Can specify at most " << PositionalOpts.size()
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000923 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000924 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000925
926 } else if (ConsumeAfterOpt == 0) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000927 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000928 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
929 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner331de232002-07-22 02:07:59 +0000930 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000931 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000932 PositionalVals[ValNo].second);
933 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000934 --NumPositionalRequired; // We fulfilled our duty...
935 }
936
937 // If we _can_ give this option more arguments, do so now, as long as we
938 // do not give it values that others need. 'Done' controls whether the
939 // option even _WANTS_ any more.
940 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000941 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000942 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000943 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000944 case cl::Optional:
945 Done = true; // Optional arguments want _at most_ one value
946 // FALL THROUGH
947 case cl::ZeroOrMore: // Zero or more will take all they can get...
948 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000949 ProvidePositionalOption(PositionalOpts[i],
950 PositionalVals[ValNo].first,
951 PositionalVals[ValNo].second);
952 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000953 break;
954 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000955 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000956 "positional argument processing!");
957 }
958 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000959 }
Chris Lattner331de232002-07-22 02:07:59 +0000960 } else {
961 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
962 unsigned ValNo = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000963 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000964 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000965 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000966 PositionalVals[ValNo].first,
967 PositionalVals[ValNo].second);
968 ValNo++;
969 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000970
971 // Handle the case where there is just one positional option, and it's
972 // optional. In this case, we want to give JUST THE FIRST option to the
973 // positional option and keep the rest for the consume after. The above
974 // loop would have assigned no values to positional options in this case.
975 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000976 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000977 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000978 PositionalVals[ValNo].first,
979 PositionalVals[ValNo].second);
980 ValNo++;
981 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000982
Chris Lattner331de232002-07-22 02:07:59 +0000983 // Handle over all of the rest of the arguments to the
984 // cl::ConsumeAfter command line option...
985 for (; ValNo != PositionalVals.size(); ++ValNo)
986 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000987 PositionalVals[ValNo].first,
988 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000989 }
990
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000991 // Loop over args and make sure all required args are specified!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000992 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000993 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000994 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000995 case Required:
996 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000997 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramere6864c12009-08-02 12:13:02 +0000998 I->second->error("must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000999 ErrorParsing = true;
1000 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +00001001 // Fall through
1002 default:
1003 break;
1004 }
1005 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001006
Rafael Espindolaa962b402010-11-19 21:14:29 +00001007 // Now that we know if -debug is specified, we can use it.
1008 // Note that if ReadResponseFiles == true, this must be done before the
1009 // memory allocated for the expanded command line is free()d below.
1010 DEBUG(dbgs() << "Args: ";
1011 for (int i = 0; i < argc; ++i)
1012 dbgs() << argv[i] << ' ';
1013 dbgs() << '\n';
1014 );
1015
Chris Lattner331de232002-07-22 02:07:59 +00001016 // Free all of the memory allocated to the map. Command line options may only
1017 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +00001018 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +00001019 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +00001020 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001021
1022 // If we had an error processing our arguments, don't let the program execute
1023 if (ErrorParsing) exit(1);
1024}
1025
1026//===----------------------------------------------------------------------===//
1027// Option Base class implementation
1028//
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001029
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001030bool Option::error(const Twine &Message, StringRef ArgName) {
1031 if (ArgName.data() == 0) ArgName = ArgStr;
1032 if (ArgName.empty())
Benjamin Kramerd227a3f2009-08-23 10:01:13 +00001033 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +00001034 else
Benjamin Kramerd227a3f2009-08-23 10:01:13 +00001035 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001036
Benjamin Kramerd227a3f2009-08-23 10:01:13 +00001037 errs() << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001038 return true;
1039}
1040
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001041bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001042 StringRef Value, bool MultiArg) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +00001043 if (!MultiArg)
1044 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001045
Misha Brukmandd6cb6a2003-07-10 16:49:51 +00001046 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001047 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +00001048 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001049 return error("may only occur zero or one times!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001050 break;
1051 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +00001052 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001053 return error("must occur exactly one time!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001054 // Fall through
1055 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +00001056 case ZeroOrMore:
1057 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001058 }
1059
Reid Spencer1e13fd22004-08-13 19:47:30 +00001060 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001061}
1062
Chris Lattner331de232002-07-22 02:07:59 +00001063
1064// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1065// has been specified yet.
1066//
1067static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1068 if (O.ValueStr[0] == 0) return DefaultMsg;
1069 return O.ValueStr;
1070}
1071
1072//===----------------------------------------------------------------------===//
1073// cl::alias class implementation
1074//
1075
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001076// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001077size_t alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001078 return std::strlen(ArgStr)+6;
1079}
1080
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001081static void printHelpStr(StringRef HelpStr, size_t Indent,
1082 size_t FirstLineIndentedBy) {
1083 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1084 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1085 while (!Split.second.empty()) {
1086 Split = Split.second.split('\n');
1087 outs().indent(Indent) << Split.first << "\n";
1088 }
1089}
1090
Chris Lattnera0de8432006-04-28 05:36:25 +00001091// Print out the option for the alias.
Evan Cheng34cd4a42008-05-05 18:30:58 +00001092void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Chengff276b42011-06-13 20:45:54 +00001093 outs() << " -" << ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001094 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001095}
1096
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001097//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +00001098// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001099//
1100
Chris Lattner9b14eb52002-08-07 18:36:37 +00001101// basic_parser implementation
1102//
1103
1104// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001105size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1106 size_t Len = std::strlen(O.ArgStr);
Chris Lattner9b14eb52002-08-07 18:36:37 +00001107 if (const char *ValName = getValueName())
1108 Len += std::strlen(getValueStr(O, ValName))+3;
1109
1110 return Len + 6;
1111}
1112
Misha Brukmanf976c852005-04-21 22:55:34 +00001113// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +00001114// to-be-maintained width is specified.
1115//
1116void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001117 size_t GlobalWidth) const {
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001118 outs() << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +00001119
1120 if (const char *ValName = getValueName())
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001121 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattner9b14eb52002-08-07 18:36:37 +00001122
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001123 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattner9b14eb52002-08-07 18:36:37 +00001124}
1125
Andrew Trickce969022011-04-05 18:54:36 +00001126void basic_parser_impl::printOptionName(const Option &O,
1127 size_t GlobalWidth) const {
1128 outs() << " -" << O.ArgStr;
1129 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1130}
Chris Lattner9b14eb52002-08-07 18:36:37 +00001131
1132
Chris Lattner331de232002-07-22 02:07:59 +00001133// parser<bool> implementation
1134//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001135bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001136 StringRef Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +00001137 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001138 Arg == "1") {
1139 Value = true;
Chris Lattnera460beb2009-09-19 18:55:05 +00001140 return false;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001141 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001142
Chris Lattnera460beb2009-09-19 18:55:05 +00001143 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1144 Value = false;
1145 return false;
1146 }
1147 return O.error("'" + Arg +
1148 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001149}
1150
Dale Johannesen81da02b2007-05-22 17:14:46 +00001151// parser<boolOrDefault> implementation
1152//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001153bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001154 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen81da02b2007-05-22 17:14:46 +00001155 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1156 Arg == "1") {
1157 Value = BOU_TRUE;
Chris Lattnera460beb2009-09-19 18:55:05 +00001158 return false;
Dale Johannesen81da02b2007-05-22 17:14:46 +00001159 }
Chris Lattnera460beb2009-09-19 18:55:05 +00001160 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1161 Value = BOU_FALSE;
1162 return false;
1163 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001164
Chris Lattnera460beb2009-09-19 18:55:05 +00001165 return O.error("'" + Arg +
1166 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen81da02b2007-05-22 17:14:46 +00001167}
1168
Chris Lattner331de232002-07-22 02:07:59 +00001169// parser<int> implementation
1170//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001171bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001172 StringRef Arg, int &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001173 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001174 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001175 return false;
1176}
1177
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001178// parser<unsigned> implementation
1179//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001180bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001181 StringRef Arg, unsigned &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001182
1183 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001184 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001185 return false;
1186}
1187
Benjamin Kramerb3514562011-09-15 21:17:37 +00001188// parser<unsigned long long> implementation
1189//
1190bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1191 StringRef Arg, unsigned long long &Value){
1192
1193 if (Arg.getAsInteger(0, Value))
1194 return O.error("'" + Arg + "' value invalid for uint argument!");
1195 return false;
1196}
1197
Chris Lattner9b14eb52002-08-07 18:36:37 +00001198// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +00001199//
Chris Lattnera460beb2009-09-19 18:55:05 +00001200static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001201 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1202 const char *ArgStart = TmpStr.c_str();
Chris Lattner331de232002-07-22 02:07:59 +00001203 char *End;
1204 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +00001205 if (*End != 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001206 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +00001207 return false;
1208}
1209
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001210bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001211 StringRef Arg, double &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001212 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +00001213}
1214
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001215bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001216 StringRef Arg, float &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001217 double dVal;
1218 if (parseDouble(O, Arg, dVal))
1219 return true;
1220 Val = (float)dVal;
1221 return false;
Chris Lattner331de232002-07-22 02:07:59 +00001222}
1223
1224
Chris Lattner331de232002-07-22 02:07:59 +00001225
1226// generic_parser_base implementation
1227//
1228
Chris Lattneraa852bb2002-07-23 17:15:12 +00001229// findOption - Return the option number corresponding to the specified
1230// argument string. If the option is not found, getNumOptions() is returned.
1231//
1232unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer461c8762009-09-19 10:01:45 +00001233 unsigned e = getNumOptions();
Chris Lattneraa852bb2002-07-23 17:15:12 +00001234
Benjamin Kramer461c8762009-09-19 10:01:45 +00001235 for (unsigned i = 0; i != e; ++i) {
1236 if (strcmp(getOption(i), Name) == 0)
Chris Lattneraa852bb2002-07-23 17:15:12 +00001237 return i;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001238 }
Chris Lattneraa852bb2002-07-23 17:15:12 +00001239 return e;
1240}
1241
1242
Chris Lattner331de232002-07-22 02:07:59 +00001243// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001244size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner331de232002-07-22 02:07:59 +00001245 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001246 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner331de232002-07-22 02:07:59 +00001247 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001248 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001249 return Size;
1250 } else {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001251 size_t BaseSize = 0;
Chris Lattner331de232002-07-22 02:07:59 +00001252 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001253 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001254 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001255 }
1256}
1257
Misha Brukmanf976c852005-04-21 22:55:34 +00001258// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +00001259// to-be-maintained width is specified.
1260//
1261void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001262 size_t GlobalWidth) const {
Chris Lattner331de232002-07-22 02:07:59 +00001263 if (O.hasArgStr()) {
Chris Lattnerb1687372009-09-20 05:03:30 +00001264 outs() << " -" << O.ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001265 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001266
Chris Lattner331de232002-07-22 02:07:59 +00001267 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001268 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerb1687372009-09-20 05:03:30 +00001269 outs() << " =" << getOption(i);
1270 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattner9c9be482002-01-31 00:42:56 +00001271 }
Chris Lattner331de232002-07-22 02:07:59 +00001272 } else {
1273 if (O.HelpStr[0])
Chris Lattnerb1687372009-09-20 05:03:30 +00001274 outs() << " " << O.HelpStr << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001275 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001276 const char *Option = getOption(i);
1277 outs() << " -" << Option;
1278 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner331de232002-07-22 02:07:59 +00001279 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001280 }
1281}
1282
Andrew Trickce969022011-04-05 18:54:36 +00001283static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1284
1285// printGenericOptionDiff - Print the value of this option and it's default.
1286//
1287// "Generic" options have each value mapped to a name.
1288void generic_parser_base::
1289printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1290 const GenericOptionValue &Default,
1291 size_t GlobalWidth) const {
1292 outs() << " -" << O.ArgStr;
1293 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1294
1295 unsigned NumOpts = getNumOptions();
1296 for (unsigned i = 0; i != NumOpts; ++i) {
1297 if (Value.compare(getOptionValue(i)))
1298 continue;
1299
1300 outs() << "= " << getOption(i);
1301 size_t L = std::strlen(getOption(i));
1302 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1303 outs().indent(NumSpaces) << " (default: ";
1304 for (unsigned j = 0; j != NumOpts; ++j) {
1305 if (Default.compare(getOptionValue(j)))
1306 continue;
1307 outs() << getOption(j);
1308 break;
1309 }
1310 outs() << ")\n";
1311 return;
1312 }
1313 outs() << "= *unknown option value*\n";
1314}
1315
1316// printOptionDiff - Specializations for printing basic value types.
1317//
1318#define PRINT_OPT_DIFF(T) \
1319 void parser<T>:: \
1320 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1321 size_t GlobalWidth) const { \
1322 printOptionName(O, GlobalWidth); \
1323 std::string Str; \
1324 { \
1325 raw_string_ostream SS(Str); \
1326 SS << V; \
1327 } \
1328 outs() << "= " << Str; \
1329 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1330 outs().indent(NumSpaces) << " (default: "; \
1331 if (D.hasValue()) \
1332 outs() << D.getValue(); \
1333 else \
1334 outs() << "*no default*"; \
1335 outs() << ")\n"; \
1336 } \
1337
Frits van Bommel090771f2011-04-06 12:29:56 +00001338PRINT_OPT_DIFF(bool)
1339PRINT_OPT_DIFF(boolOrDefault)
1340PRINT_OPT_DIFF(int)
1341PRINT_OPT_DIFF(unsigned)
Benjamin Kramerb3514562011-09-15 21:17:37 +00001342PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel090771f2011-04-06 12:29:56 +00001343PRINT_OPT_DIFF(double)
1344PRINT_OPT_DIFF(float)
1345PRINT_OPT_DIFF(char)
Andrew Trickce969022011-04-05 18:54:36 +00001346
1347void parser<std::string>::
1348printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1349 size_t GlobalWidth) const {
1350 printOptionName(O, GlobalWidth);
1351 outs() << "= " << V;
1352 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1353 outs().indent(NumSpaces) << " (default: ";
1354 if (D.hasValue())
1355 outs() << D.getValue();
1356 else
1357 outs() << "*no default*";
1358 outs() << ")\n";
1359}
1360
1361// Print a placeholder for options that don't yet support printOptionDiff().
1362void basic_parser_impl::
1363printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1364 printOptionName(O, GlobalWidth);
1365 outs() << "= *cannot print option value*\n";
1366}
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001367
1368//===----------------------------------------------------------------------===//
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001369// -help and -help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001370//
Reid Spencerad0846b2004-11-14 22:04:00 +00001371
Chris Lattner0fd48b12009-09-20 05:37:24 +00001372static int OptNameCompare(const void *LHS, const void *RHS) {
1373 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001374
Duncan Sandse840fef2012-03-12 10:51:06 +00001375 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner0fd48b12009-09-20 05:37:24 +00001376}
1377
Andrew Trickce969022011-04-05 18:54:36 +00001378// Copy Options into a vector so we can sort them as we like.
1379static void
1380sortOpts(StringMap<Option*> &OptMap,
1381 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1382 bool ShowHidden) {
1383 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1384
1385 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1386 I != E; ++I) {
1387 // Ignore really-hidden options.
1388 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1389 continue;
1390
1391 // Unless showhidden is set, ignore hidden flags.
1392 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1393 continue;
1394
1395 // If we've already seen this option, don't add it to the list again.
1396 if (!OptionSet.insert(I->second))
1397 continue;
1398
1399 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1400 I->second));
1401 }
1402
1403 // Sort the options list alphabetically.
1404 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1405}
1406
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001407namespace {
1408
Chris Lattner331de232002-07-22 02:07:59 +00001409class HelpPrinter {
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001410protected:
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001411 const bool ShowHidden;
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001412 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1413 // Print the options. Opts is assumed to be alphabetically sorted.
1414 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1415 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1416 Opts[i].second->printOptionInfo(MaxArgLen);
1417 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001418
Chris Lattner331de232002-07-22 02:07:59 +00001419public:
Craig Topperddde2082013-03-09 23:29:37 +00001420 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001421 virtual ~HelpPrinter() {}
Chris Lattner331de232002-07-22 02:07:59 +00001422
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001423 // Invoke the printer.
Chris Lattner331de232002-07-22 02:07:59 +00001424 void operator=(bool Value) {
1425 if (Value == false) return;
1426
Chris Lattner9878d6a2007-04-06 21:06:55 +00001427 // Get all the options.
Chris Lattner49b301c2009-09-20 06:18:38 +00001428 SmallVector<Option*, 4> PositionalOpts;
1429 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001430 StringMap<Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +00001431 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001432
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001433 StrOptionPairVector Opts;
Andrew Trickce969022011-04-05 18:54:36 +00001434 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001435
1436 if (ProgramOverview)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001437 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001438
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001439 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +00001440
Chris Lattner90aa8392006-10-04 21:52:35 +00001441 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +00001442 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001443 if (!PositionalOpts.empty() &&
Chris Lattner9878d6a2007-04-06 21:06:55 +00001444 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1445 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +00001446
Evan Cheng34cd4a42008-05-05 18:30:58 +00001447 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +00001448 if (PositionalOpts[i]->ArgStr[0])
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001449 outs() << " --" << PositionalOpts[i]->ArgStr;
1450 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +00001451 }
Chris Lattner331de232002-07-22 02:07:59 +00001452
1453 // Print the consume after option info if it exists...
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001454 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +00001455
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001456 outs() << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001457
1458 // Compute the maximum argument length...
Craig Topperddde2082013-03-09 23:29:37 +00001459 size_t MaxArgLen = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +00001460 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0fd48b12009-09-20 05:37:24 +00001461 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001462
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001463 outs() << "OPTIONS:\n";
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001464 printOptions(Opts, MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001465
Chris Lattnerc540ebb2004-11-19 17:08:15 +00001466 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +00001467 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001468 E = MoreHelp->end();
1469 I != E; ++I)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001470 outs() << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001471 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001472
Reid Spencer9bbba0912004-11-16 06:11:52 +00001473 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001474 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001475 }
1476};
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001477
1478class CategorizedHelpPrinter : public HelpPrinter {
1479public:
1480 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1481
1482 // Helper function for printOptions().
1483 // It shall return true if A's name should be lexographically
1484 // ordered before B's name. It returns false otherwise.
1485 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1486 int Length = strcmp(A->getName(), B->getName());
1487 assert(Length != 0 && "Duplicate option categories");
1488 return Length < 0;
1489 }
1490
1491 // Make sure we inherit our base class's operator=()
1492 using HelpPrinter::operator= ;
1493
1494protected:
1495 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1496 std::vector<OptionCategory *> SortedCategories;
1497 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1498
1499 // Collect registered option categories into vector in preperation for
1500 // sorting.
1501 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1502 E = RegisteredOptionCategories->end();
1503 I != E; ++I)
1504 SortedCategories.push_back(*I);
1505
1506 // Sort the different option categories alphabetically.
1507 assert(SortedCategories.size() > 0 && "No option categories registered!");
1508 std::sort(SortedCategories.begin(), SortedCategories.end(),
1509 OptionCategoryCompare);
1510
1511 // Create map to empty vectors.
1512 for (std::vector<OptionCategory *>::const_iterator
1513 I = SortedCategories.begin(),
1514 E = SortedCategories.end();
1515 I != E; ++I)
1516 CategorizedOptions[*I] = std::vector<Option *>();
1517
1518 // Walk through pre-sorted options and assign into categories.
1519 // Because the options are already alphabetically sorted the
1520 // options within categories will also be alphabetically sorted.
1521 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1522 Option *Opt = Opts[I].second;
1523 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1524 "Option has an unregistered category");
1525 CategorizedOptions[Opt->Category].push_back(Opt);
1526 }
1527
1528 // Now do printing.
1529 for (std::vector<OptionCategory *>::const_iterator
1530 Category = SortedCategories.begin(),
1531 E = SortedCategories.end();
1532 Category != E; ++Category) {
1533 // Hide empty categories for -help, but show for -help-hidden.
1534 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1535 if (!ShowHidden && IsEmptyCategory)
1536 continue;
1537
1538 // Print category information.
1539 outs() << "\n";
1540 outs() << (*Category)->getName() << ":\n";
1541
1542 // Check if description is set.
1543 if ((*Category)->getDescription() != 0)
1544 outs() << (*Category)->getDescription() << "\n\n";
1545 else
1546 outs() << "\n";
1547
1548 // When using -help-hidden explicitly state if the category has no
1549 // options associated with it.
1550 if (IsEmptyCategory) {
1551 outs() << " This option category has no options.\n";
1552 continue;
1553 }
1554 // Loop over the options in the category and print.
1555 for (std::vector<Option *>::const_iterator
1556 Opt = CategorizedOptions[*Category].begin(),
1557 E = CategorizedOptions[*Category].end();
1558 Opt != E; ++Opt)
1559 (*Opt)->printOptionInfo(MaxArgLen);
1560 }
1561 }
1562};
1563
1564// This wraps the Uncategorizing and Categorizing printers and decides
1565// at run time which should be invoked.
1566class HelpPrinterWrapper {
1567private:
1568 HelpPrinter &UncategorizedPrinter;
1569 CategorizedHelpPrinter &CategorizedPrinter;
1570
1571public:
1572 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1573 CategorizedHelpPrinter &CategorizedPrinter) :
1574 UncategorizedPrinter(UncategorizedPrinter),
1575 CategorizedPrinter(CategorizedPrinter) { }
1576
1577 // Invoke the printer.
1578 void operator=(bool Value);
1579};
1580
Chris Lattner500d8bf2006-10-12 22:09:17 +00001581} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001582
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001583// Declare the four HelpPrinter instances that are used to print out help, or
1584// help-hidden as an uncategorized list or in categories.
1585static HelpPrinter UncategorizedNormalPrinter(false);
1586static HelpPrinter UncategorizedHiddenPrinter(true);
1587static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1588static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1589
1590
1591// Declare HelpPrinter wrappers that will decide whether or not to invoke
1592// a categorizing help printer
1593static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1594 CategorizedNormalPrinter);
1595static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1596 CategorizedHiddenPrinter);
1597
1598// Define uncategorized help printers.
1599// -help-list is hidden by default because if Option categories are being used
1600// then -help behaves the same as -help-list.
1601static cl::opt<HelpPrinter, true, parser<bool> >
1602HLOp("help-list",
1603 cl::desc("Display list of available options (-help-list-hidden for more)"),
1604 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001605
Chris Lattner500d8bf2006-10-12 22:09:17 +00001606static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001607HLHOp("help-list-hidden",
1608 cl::desc("Display list of all available options"),
1609 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1610
1611// Define uncategorized/categorized help printers. These printers change their
1612// behaviour at runtime depending on whether one or more Option categories have
1613// been declared.
1614static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001615HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001616 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001617
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001618static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001619HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001620 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1621
1622
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001623
Andrew Trickce969022011-04-05 18:54:36 +00001624static cl::opt<bool>
1625PrintOptions("print-options",
1626 cl::desc("Print non-default options after command line parsing"),
1627 cl::Hidden, cl::init(false));
1628
1629static cl::opt<bool>
1630PrintAllOptions("print-all-options",
1631 cl::desc("Print all option values after command line parsing"),
1632 cl::Hidden, cl::init(false));
1633
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001634void HelpPrinterWrapper::operator=(bool Value) {
1635 if (Value == false)
1636 return;
1637
1638 // Decide which printer to invoke. If more than one option category is
1639 // registered then it is useful to show the categorized help instead of
1640 // uncategorized help.
1641 if (RegisteredOptionCategories->size() > 1) {
1642 // unhide -help-list option so user can have uncategorized output if they
1643 // want it.
1644 HLOp.setHiddenFlag(NotHidden);
1645
1646 CategorizedPrinter = true; // Invoke categorized printer
1647 }
1648 else
1649 UncategorizedPrinter = true; // Invoke uncategorized printer
1650}
1651
Andrew Trickce969022011-04-05 18:54:36 +00001652// Print the value of each option.
1653void cl::PrintOptionValues() {
1654 if (!PrintOptions && !PrintAllOptions) return;
1655
1656 // Get all the options.
1657 SmallVector<Option*, 4> PositionalOpts;
1658 SmallVector<Option*, 4> SinkOpts;
1659 StringMap<Option*> OptMap;
1660 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1661
1662 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1663 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1664
1665 // Compute the maximum argument length...
1666 size_t MaxArgLen = 0;
1667 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1668 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1669
1670 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1671 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1672}
1673
Chris Lattner500d8bf2006-10-12 22:09:17 +00001674static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001675
Chandler Carruth6d51d262011-07-22 07:50:40 +00001676static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1677
Chris Lattner500d8bf2006-10-12 22:09:17 +00001678namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001679class VersionPrinter {
1680public:
Devang Patelaed293d2007-02-01 01:43:37 +00001681 void print() {
Chris Lattner49b301c2009-09-20 06:18:38 +00001682 raw_ostream &OS = outs();
Jim Grosbachc48d4dc2012-01-25 22:00:23 +00001683 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner49b301c2009-09-20 06:18:38 +00001684 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001685#ifdef LLVM_VERSION_INFO
Chris Lattner49b301c2009-09-20 06:18:38 +00001686 OS << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001687#endif
Chris Lattner49b301c2009-09-20 06:18:38 +00001688 OS << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001689#ifndef __OPTIMIZE__
Chris Lattner49b301c2009-09-20 06:18:38 +00001690 OS << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001691#else
Chris Lattner49b301c2009-09-20 06:18:38 +00001692 OS << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001693#endif
1694#ifndef NDEBUG
Chris Lattner49b301c2009-09-20 06:18:38 +00001695 OS << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001696#endif
Daniel Dunbarba43e072009-11-14 21:36:07 +00001697 std::string CPU = sys::getHostCPUName();
Benjamin Kramer110e7bb2009-11-17 17:57:04 +00001698 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner49b301c2009-09-20 06:18:38 +00001699 OS << ".\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001700#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner49b301c2009-09-20 06:18:38 +00001701 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001702#endif
Sebastian Pop01738642011-11-01 21:32:20 +00001703 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth40393132011-07-22 07:50:48 +00001704 << " Host CPU: " << CPU << '\n';
Devang Patelaed293d2007-02-01 01:43:37 +00001705 }
1706 void operator=(bool OptionWasSpecified) {
Chris Lattner043b8b52009-09-20 05:48:01 +00001707 if (!OptionWasSpecified) return;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001708
Chandler Carruth6d51d262011-07-22 07:50:40 +00001709 if (OverrideVersionPrinter != 0) {
1710 (*OverrideVersionPrinter)();
Chris Lattner043b8b52009-09-20 05:48:01 +00001711 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001712 }
Chandler Carruth6d51d262011-07-22 07:50:40 +00001713 print();
1714
1715 // Iterate over any registered extra printers and call them to add further
1716 // information.
1717 if (ExtraVersionPrinters != 0) {
Chandler Carruth40393132011-07-22 07:50:48 +00001718 outs() << '\n';
Chandler Carruth6d51d262011-07-22 07:50:40 +00001719 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1720 E = ExtraVersionPrinters->end();
1721 I != E; ++I)
1722 (*I)();
1723 }
1724
Chris Lattner043b8b52009-09-20 05:48:01 +00001725 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001726 }
1727};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001728} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001729
1730
Reid Spencer69105f32004-08-04 00:36:06 +00001731// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001732static VersionPrinter VersionPrinterInstance;
1733
1734static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001735VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001736 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1737
Reid Spencer9bbba0912004-11-16 06:11:52 +00001738// Utility function for printing the help message.
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001739void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1740 // This looks weird, but it actually prints the help message. The Printers are
1741 // types of HelpPrinter and the help gets printed when its operator= is
1742 // invoked. That's because the "normal" usages of the help printer is to be
1743 // assigned true/false depending on whether -help or -help-hidden was given or
1744 // not. Since we're circumventing that we have to make it look like -help or
1745 // -help-hidden were given, so we assign true.
1746
1747 if (!Hidden && !Categorized)
1748 UncategorizedNormalPrinter = true;
1749 else if (!Hidden && Categorized)
1750 CategorizedNormalPrinter = true;
1751 else if (Hidden && !Categorized)
1752 UncategorizedHiddenPrinter = true;
1753 else
1754 CategorizedHiddenPrinter = true;
Reid Spencer9bbba0912004-11-16 06:11:52 +00001755}
Reid Spencer515b5b32006-06-05 16:22:56 +00001756
Devang Patelaed293d2007-02-01 01:43:37 +00001757/// Utility function for printing version number.
1758void cl::PrintVersionMessage() {
1759 VersionPrinterInstance.print();
1760}
1761
Reid Spencer515b5b32006-06-05 16:22:56 +00001762void cl::SetVersionPrinter(void (*func)()) {
1763 OverrideVersionPrinter = func;
1764}
Chandler Carruth6d51d262011-07-22 07:50:40 +00001765
1766void cl::AddExtraVersionPrinter(void (*func)()) {
1767 if (ExtraVersionPrinters == 0)
1768 ExtraVersionPrinters = new std::vector<void (*)()>;
1769
1770 ExtraVersionPrinters->push_back(func);
1771}
Andrew Trick61e01722013-05-06 21:56:35 +00001772
1773void cl::getRegisteredOptions(StringMap<Option*> &Map)
1774{
1775 // Get all the options.
1776 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1777 SmallVector<Option*, 4> SinkOpts; //NOT USED
1778 assert(Map.size() == 0 && "StringMap must be empty");
1779 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1780 return;
1781}