blob: 6ab03dc675d8327549a36460ec81c6c3a5276594 [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner03fe1bd2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Chris Lattnerca179342009-08-23 18:09:02 +000020#include "llvm/ADT/OwningPtr.h"
Chris Lattner67aead62009-09-20 05:12:14 +000021#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner970e7df2009-09-19 23:59:02 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner67aead62009-09-20 05:12:14 +000023#include "llvm/ADT/StringMap.h"
Chris Lattnera460beb2009-09-19 18:55:05 +000024#include "llvm/ADT/Twine.h"
Chris Lattnerca179342009-08-23 18:09:02 +000025#include "llvm/Config/config.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/Host.h"
29#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/Path.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/system_error.h"
Brian Gaeke2d6a2362003-10-10 17:01:36 +000034#include <cerrno>
Chris Lattnerca179342009-08-23 18:09:02 +000035#include <cstdlib>
Andrew Trickb7ad33b2013-05-06 21:56:23 +000036#include <map>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000037using namespace llvm;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000038using namespace cl;
39
Chris Lattner7422a762006-08-27 12:45:47 +000040//===----------------------------------------------------------------------===//
41// Template instantiations and anchors.
42//
Douglas Gregorb3587cf2009-11-25 06:04:18 +000043namespace llvm { namespace cl {
Chris Lattner7422a762006-08-27 12:45:47 +000044TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen81da02b2007-05-22 17:14:46 +000045TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner7422a762006-08-27 12:45:47 +000046TEMPLATE_INSTANTIATION(class basic_parser<int>);
47TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramerb3514562011-09-15 21:17:37 +000048TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner7422a762006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<double>);
50TEMPLATE_INSTANTIATION(class basic_parser<float>);
51TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000052TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000053
54TEMPLATE_INSTANTIATION(class opt<unsigned>);
55TEMPLATE_INSTANTIATION(class opt<int>);
56TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingb587f962009-04-29 23:26:16 +000057TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner7422a762006-08-27 12:45:47 +000058TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregorb3587cf2009-11-25 06:04:18 +000059} } // end namespace llvm::cl
Chris Lattner7422a762006-08-27 12:45:47 +000060
David Blaikie0becc962011-12-01 08:00:17 +000061void OptionValue<boolOrDefault>::anchor() {}
62void OptionValue<std::string>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000063void Option::anchor() {}
64void basic_parser_impl::anchor() {}
65void parser<bool>::anchor() {}
Dale Johannesen81da02b2007-05-22 17:14:46 +000066void parser<boolOrDefault>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000067void parser<int>::anchor() {}
68void parser<unsigned>::anchor() {}
Benjamin Kramerb3514562011-09-15 21:17:37 +000069void parser<unsigned long long>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000070void parser<double>::anchor() {}
71void parser<float>::anchor() {}
72void parser<std::string>::anchor() {}
Bill Wendlingb587f962009-04-29 23:26:16 +000073void parser<char>::anchor() {}
Chris Lattner7422a762006-08-27 12:45:47 +000074
75//===----------------------------------------------------------------------===//
76
Chris Lattnerefa3da52006-10-13 00:06:24 +000077// Globals for name and overview of program. Program name is not a string to
78// avoid static ctor/dtor issues.
79static char ProgramName[80] = "<premain>";
Reid Spencere1cc1502004-09-01 04:41:28 +000080static const char *ProgramOverview = 0;
81
Chris Lattnerc540ebb2004-11-19 17:08:15 +000082// This collects additional help to be printed.
Chris Lattner90aa8392006-10-04 21:52:35 +000083static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattnerc540ebb2004-11-19 17:08:15 +000084
Chris Lattner90aa8392006-10-04 21:52:35 +000085extrahelp::extrahelp(const char *Help)
Chris Lattnerc540ebb2004-11-19 17:08:15 +000086 : morehelp(Help) {
Chris Lattner90aa8392006-10-04 21:52:35 +000087 MoreHelp->push_back(Help);
Chris Lattnerc540ebb2004-11-19 17:08:15 +000088}
89
Chris Lattner69d6f132007-04-12 00:36:29 +000090static bool OptionListChanged = false;
91
92// MarkOptionsChanged - Internal helper function.
93void cl::MarkOptionsChanged() {
94 OptionListChanged = true;
95}
96
Chris Lattner9878d6a2007-04-06 21:06:55 +000097/// RegisteredOptionList - This is the list of the command line options that
98/// have statically constructed themselves.
99static Option *RegisteredOptionList = 0;
100
101void Option::addArgument() {
102 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000103
Chris Lattner9878d6a2007-04-06 21:06:55 +0000104 NextRegistered = RegisteredOptionList;
105 RegisteredOptionList = this;
Chris Lattner69d6f132007-04-12 00:36:29 +0000106 MarkOptionsChanged();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000107}
108
Andrew Trickb7ad33b2013-05-06 21:56:23 +0000109// This collects the different option categories that have been registered.
110typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
111static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
112
113// Initialise the general option category.
114OptionCategory llvm::cl::GeneralCategory("General options");
115
116void OptionCategory::registerCategory()
117{
118 RegisteredOptionCategories->insert(this);
119}
Chris Lattner69d6f132007-04-12 00:36:29 +0000120
Chris Lattner331de232002-07-22 02:07:59 +0000121//===----------------------------------------------------------------------===//
Chris Lattner7422a762006-08-27 12:45:47 +0000122// Basic, shared command line option processing machinery.
Chris Lattner331de232002-07-22 02:07:59 +0000123//
124
Chris Lattner9878d6a2007-04-06 21:06:55 +0000125/// GetOptionInfo - Scan the list of registered options, turning them into data
126/// structures that are easier to handle.
Chris Lattner49b301c2009-09-20 06:18:38 +0000127static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
128 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer461c8762009-09-19 10:01:45 +0000129 StringMap<Option*> &OptionsMap) {
Chris Lattner1908aea2009-09-20 06:21:43 +0000130 SmallVector<const char*, 16> OptionNames;
Chris Lattneree2b3202007-04-07 05:38:53 +0000131 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000132 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
133 // If this option wants to handle multiple option names, get the full set.
134 // This handles enum options like "-O1 -O2" etc.
135 O->getExtraOptionNames(OptionNames);
136 if (O->ArgStr[0])
137 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000138
Chris Lattner9878d6a2007-04-06 21:06:55 +0000139 // Handle named options.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000140 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000141 // Add argument to the argument map!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000142 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000143 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijman33540ad2008-05-30 13:26:11 +0000144 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner9878d6a2007-04-06 21:06:55 +0000145 }
146 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000147
Chris Lattner9878d6a2007-04-06 21:06:55 +0000148 OptionNames.clear();
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000149
Chris Lattner9878d6a2007-04-06 21:06:55 +0000150 // Remember information about positional options.
151 if (O->getFormattingFlag() == cl::Positional)
152 PositionalOpts.push_back(O);
Dan Gohman61e015f2008-02-23 01:55:25 +0000153 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000154 SinkOpts.push_back(O);
Chris Lattner9878d6a2007-04-06 21:06:55 +0000155 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattneree2b3202007-04-07 05:38:53 +0000156 if (CAOpt)
Chris Lattner9878d6a2007-04-06 21:06:55 +0000157 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattneree2b3202007-04-07 05:38:53 +0000158 CAOpt = O;
Chris Lattner9878d6a2007-04-06 21:06:55 +0000159 }
Chris Lattnere8e258b2002-07-29 20:58:42 +0000160 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000161
Chris Lattneree2b3202007-04-07 05:38:53 +0000162 if (CAOpt)
163 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000164
Chris Lattneree2b3202007-04-07 05:38:53 +0000165 // Make sure that they are in order of registration not backwards.
166 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattnere8e258b2002-07-29 20:58:42 +0000167}
168
Chris Lattner9878d6a2007-04-06 21:06:55 +0000169
Chris Lattneraf035f32007-04-05 21:58:17 +0000170/// LookupOption - Lookup the option specified by the specified option on the
171/// command line. If there is a value specified (after an equal sign) return
Chris Lattnerb1687372009-09-20 05:03:30 +0000172/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner8a7a0582009-09-20 02:02:24 +0000173static Option *LookupOption(StringRef &Arg, StringRef &Value,
174 const StringMap<Option*> &OptionsMap) {
Chris Lattner8a7a0582009-09-20 02:02:24 +0000175 // Reject all dashes.
176 if (Arg.empty()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000177
Chris Lattner8a7a0582009-09-20 02:02:24 +0000178 size_t EqualPos = Arg.find('=');
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000179
Chris Lattner4e247ec2009-09-20 01:53:12 +0000180 // If we have an equals sign, remember the value.
Chris Lattnerb1687372009-09-20 05:03:30 +0000181 if (EqualPos == StringRef::npos) {
182 // Look up the option.
183 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
184 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000185 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000186
Chris Lattnerb1687372009-09-20 05:03:30 +0000187 // If the argument before the = is a valid option name, we match. If not,
188 // return Arg unmolested.
189 StringMap<Option*>::const_iterator I =
190 OptionsMap.find(Arg.substr(0, EqualPos));
191 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000192
Chris Lattnerb1687372009-09-20 05:03:30 +0000193 Value = Arg.substr(EqualPos+1);
194 Arg = Arg.substr(0, EqualPos);
195 return I->second;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000196}
197
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000198/// LookupNearestOption - Lookup the closest match to the option specified by
199/// the specified option on the command line. If there is a value specified
200/// (after an equal sign) return that as well. This assumes that leading dashes
201/// have already been stripped.
202static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000203 const StringMap<Option*> &OptionsMap,
Nick Lewycky95d206a2011-05-02 05:24:47 +0000204 std::string &NearestString) {
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000205 // Reject all dashes.
206 if (Arg.empty()) return 0;
207
208 // Split on any equal sign.
Nick Lewycky95d206a2011-05-02 05:24:47 +0000209 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
210 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
211 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000212
213 // Find the closest match.
214 Option *Best = 0;
215 unsigned BestDistance = 0;
216 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
217 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000218 Option *O = it->second;
219 SmallVector<const char*, 16> OptionNames;
220 O->getExtraOptionNames(OptionNames);
221 if (O->ArgStr[0])
222 OptionNames.push_back(O->ArgStr);
223
Nick Lewycky95d206a2011-05-02 05:24:47 +0000224 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
225 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000226 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
227 StringRef Name = OptionNames[i];
228 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewycky95d206a2011-05-02 05:24:47 +0000229 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000230 if (!Best || Distance < BestDistance) {
231 Best = O;
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000232 BestDistance = Distance;
Bill Wendling2127c9b2012-07-19 00:15:11 +0000233 if (RHS.empty() || !PermitValue)
234 NearestString = OptionNames[i];
235 else
236 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000237 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000238 }
239 }
240
241 return Best;
242}
243
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000244/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
245/// does special handling of cl::CommaSeparated options.
246static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
247 StringRef ArgName,
248 StringRef Value, bool MultiArg = false)
249{
250 // Check to see if this option accepts a comma separated list of values. If
251 // it does, we have to split up the value into multiple values.
252 if (Handler->getMiscFlags() & CommaSeparated) {
253 StringRef Val(Value);
254 StringRef::size_type Pos = Val.find(',');
Chris Lattnerb1687372009-09-20 05:03:30 +0000255
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000256 while (Pos != StringRef::npos) {
257 // Process the portion before the comma.
258 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
259 return true;
260 // Erase the portion before the comma, AND the comma.
261 Val = Val.substr(Pos+1);
262 Value.substr(Pos+1); // Increment the original value pointer as well.
263 // Check for another comma.
264 Pos = Val.find(',');
265 }
266
267 Value = Val;
268 }
269
270 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
271 return true;
272
273 return false;
274}
Chris Lattnerb1687372009-09-20 05:03:30 +0000275
Chris Lattner341620b2009-09-20 01:49:31 +0000276/// ProvideOption - For Value, this differentiates between an empty value ("")
277/// and a null value (StringRef()). The later is accepted for arguments that
278/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000279static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikieebba0552012-02-07 19:36:01 +0000280 StringRef Value, int argc,
281 const char *const *argv, int &i) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000282 // Is this a multi-argument option?
283 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
284
Chris Lattnercaccd762001-10-27 05:54:17 +0000285 // Enforce value requirements
286 switch (Handler->getValueExpectedFlag()) {
287 case ValueRequired:
Chris Lattner341620b2009-09-20 01:49:31 +0000288 if (Value.data() == 0) { // No value specified?
Chris Lattnerba112292009-09-20 00:07:40 +0000289 if (i+1 >= argc)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000290 return Handler->error("requires a value!");
Chris Lattnerba112292009-09-20 00:07:40 +0000291 // Steal the next argument, like for '-o filename'
292 Value = argv[++i];
Chris Lattnercaccd762001-10-27 05:54:17 +0000293 }
294 break;
295 case ValueDisallowed:
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000296 if (NumAdditionalVals > 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000297 return Handler->error("multi-valued option specified"
Chris Lattnerba112292009-09-20 00:07:40 +0000298 " with ValueDisallowed modifier!");
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000299
Chris Lattner341620b2009-09-20 01:49:31 +0000300 if (Value.data())
Benjamin Kramere6864c12009-08-02 12:13:02 +0000301 return Handler->error("does not allow a value! '" +
Chris Lattnera460beb2009-09-19 18:55:05 +0000302 Twine(Value) + "' specified.");
Chris Lattnercaccd762001-10-27 05:54:17 +0000303 break;
Misha Brukmanf976c852005-04-21 22:55:34 +0000304 case ValueOptional:
Reid Spencere1cc1502004-09-01 04:41:28 +0000305 break;
Chris Lattnercaccd762001-10-27 05:54:17 +0000306 }
307
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000308 // If this isn't a multi-arg option, just run the handler.
Chris Lattnera460beb2009-09-19 18:55:05 +0000309 if (NumAdditionalVals == 0)
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000310 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
Chris Lattnera460beb2009-09-19 18:55:05 +0000311
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000312 // If it is, run the handle several times.
Chris Lattnera460beb2009-09-19 18:55:05 +0000313 bool MultiArg = false;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000314
Chris Lattner341620b2009-09-20 01:49:31 +0000315 if (Value.data()) {
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000316 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000317 return true;
318 --NumAdditionalVals;
319 MultiArg = true;
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000320 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000321
322 while (NumAdditionalVals > 0) {
Chris Lattnera460beb2009-09-19 18:55:05 +0000323 if (i+1 >= argc)
324 return Handler->error("not enough values!");
325 Value = argv[++i];
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000326
Mikhail Glushenkov37628e02009-11-20 17:23:17 +0000327 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattnera460beb2009-09-19 18:55:05 +0000328 return true;
329 MultiArg = true;
330 --NumAdditionalVals;
331 }
332 return false;
Chris Lattnercaccd762001-10-27 05:54:17 +0000333}
334
Chris Lattnerba112292009-09-20 00:07:40 +0000335static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000336 int Dummy = i;
Chris Lattner341620b2009-09-20 01:49:31 +0000337 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner331de232002-07-22 02:07:59 +0000338}
Chris Lattnerf78032f2001-11-26 18:58:34 +0000339
Chris Lattner331de232002-07-22 02:07:59 +0000340
341// Option predicates...
342static inline bool isGrouping(const Option *O) {
343 return O->getFormattingFlag() == cl::Grouping;
344}
345static inline bool isPrefixedOrGrouping(const Option *O) {
346 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
347}
348
349// getOptionPred - Check to see if there are any options that satisfy the
350// specified predicate with names that are the prefixes in Name. This is
351// checked by progressively stripping characters off of the name, checking to
352// see if there options that satisfy the predicate. If we find one, return it,
353// otherwise return null.
354//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000355static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner9878d6a2007-04-06 21:06:55 +0000356 bool (*Pred)(const Option*),
Chris Lattnerb1687372009-09-20 05:03:30 +0000357 const StringMap<Option*> &OptionsMap) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000358
Chris Lattnerb1687372009-09-20 05:03:30 +0000359 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf78032f2001-11-26 18:58:34 +0000360
Chris Lattnerb1687372009-09-20 05:03:30 +0000361 // Loop while we haven't found an option and Name still has at least two
362 // characters in it (so that the next iteration will not be the empty
363 // string.
364 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000365 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner9878d6a2007-04-06 21:06:55 +0000366 OMI = OptionsMap.find(Name);
Chris Lattnerb1687372009-09-20 05:03:30 +0000367 }
Chris Lattner331de232002-07-22 02:07:59 +0000368
Chris Lattner9878d6a2007-04-06 21:06:55 +0000369 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000370 Length = Name.size();
Chris Lattner9878d6a2007-04-06 21:06:55 +0000371 return OMI->second; // Found one!
Chris Lattner331de232002-07-22 02:07:59 +0000372 }
373 return 0; // No option found!
374}
375
Chris Lattnerb1687372009-09-20 05:03:30 +0000376/// HandlePrefixedOrGroupedOption - The specified argument string (which started
377/// with at least one '-') does not fully match an available option. Check to
378/// see if this is a prefix or grouped option. If so, split arg into output an
379/// Arg/Value pair and return the Option to parse it with.
380static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
381 bool &ErrorParsing,
382 const StringMap<Option*> &OptionsMap) {
383 if (Arg.size() == 1) return 0;
384
385 // Do the lookup!
386 size_t Length = 0;
387 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
388 if (PGOpt == 0) return 0;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000389
Chris Lattnerb1687372009-09-20 05:03:30 +0000390 // If the option is a prefixed option, then the value is simply the
391 // rest of the name... so fall through to later processing, by
392 // setting up the argument name flags and value fields.
393 if (PGOpt->getFormattingFlag() == cl::Prefix) {
394 Value = Arg.substr(Length);
395 Arg = Arg.substr(0, Length);
396 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
397 return PGOpt;
398 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000399
Chris Lattnerb1687372009-09-20 05:03:30 +0000400 // This must be a grouped option... handle them now. Grouping options can't
401 // have values.
402 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000403
Chris Lattnerb1687372009-09-20 05:03:30 +0000404 do {
405 // Move current arg name out of Arg into OneArgName.
406 StringRef OneArgName = Arg.substr(0, Length);
407 Arg = Arg.substr(Length);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000408
Chris Lattnerb1687372009-09-20 05:03:30 +0000409 // Because ValueRequired is an invalid flag for grouped arguments,
410 // we don't need to pass argc/argv in.
411 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
412 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sands1fa8b002010-01-09 08:30:33 +0000413 int Dummy = 0;
Chris Lattnerb1687372009-09-20 05:03:30 +0000414 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
415 StringRef(), 0, 0, Dummy);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000416
Chris Lattnerb1687372009-09-20 05:03:30 +0000417 // Get the next grouping option.
418 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
419 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000420
Chris Lattnerb1687372009-09-20 05:03:30 +0000421 // Return the last option with Arg cut down to just the last one.
422 return PGOpt;
423}
424
425
426
Chris Lattner331de232002-07-22 02:07:59 +0000427static bool RequiresValue(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000428 return O->getNumOccurrencesFlag() == cl::Required ||
429 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner331de232002-07-22 02:07:59 +0000430}
431
432static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000433 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
434 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf78032f2001-11-26 18:58:34 +0000435}
Chris Lattnercaccd762001-10-27 05:54:17 +0000436
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000437/// ParseCStringVector - Break INPUT up wherever one or more
438/// whitespace characters are found, and store the resulting tokens in
439/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000440/// using strdup(), so it is the caller's responsibility to free()
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000441/// them later.
Brian Gaeke06b06c52003-08-14 22:00:59 +0000442///
Chris Lattner63e944b2009-09-24 05:38:36 +0000443static void ParseCStringVector(std::vector<char *> &OutputVector,
444 const char *Input) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000445 // Characters which will be treated as token separators:
Chris Lattner63e944b2009-09-24 05:38:36 +0000446 StringRef Delims = " \v\f\t\r\n";
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000447
Chris Lattner63e944b2009-09-24 05:38:36 +0000448 StringRef WorkStr(Input);
449 while (!WorkStr.empty()) {
450 // If the first character is a delimiter, strip them off.
451 if (Delims.find(WorkStr[0]) != StringRef::npos) {
452 size_t Pos = WorkStr.find_first_not_of(Delims);
453 if (Pos == StringRef::npos) Pos = WorkStr.size();
454 WorkStr = WorkStr.substr(Pos);
455 continue;
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000456 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000457
Chris Lattner63e944b2009-09-24 05:38:36 +0000458 // Find position of first delimiter.
459 size_t Pos = WorkStr.find_first_of(Delims);
460 if (Pos == StringRef::npos) Pos = WorkStr.size();
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000461
Chris Lattner63e944b2009-09-24 05:38:36 +0000462 // Everything from 0 to Pos is the next word to copy.
463 char *NewStr = (char*)malloc(Pos+1);
464 memcpy(NewStr, WorkStr.data(), Pos);
465 NewStr[Pos] = 0;
466 OutputVector.push_back(NewStr);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000467
Chris Lattner63e944b2009-09-24 05:38:36 +0000468 WorkStr = WorkStr.substr(Pos);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000469 }
Brian Gaeke06b06c52003-08-14 22:00:59 +0000470}
471
472/// ParseEnvironmentOptions - An alternative entry point to the
473/// CommandLine library, which allows you to read the program's name
474/// from the caller (as PROGNAME) and its command-line arguments from
475/// an environment variable (whose name is given in ENVVAR).
476///
Chris Lattnerbf455c22004-05-06 22:04:31 +0000477void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000478 const char *Overview) {
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000479 // Check args.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000480 assert(progName && "Program name not specified");
481 assert(envVar && "Environment variable name missing");
Misha Brukmanf976c852005-04-21 22:55:34 +0000482
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000483 // Get the environment variable they want us to parse options out of.
Chris Lattner23288582006-08-27 22:10:29 +0000484 const char *envValue = getenv(envVar);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000485 if (!envValue)
486 return;
487
Brian Gaeke06b06c52003-08-14 22:00:59 +0000488 // Get program's "name", which we wouldn't know without the caller
489 // telling us.
Chris Lattner23288582006-08-27 22:10:29 +0000490 std::vector<char*> newArgv;
491 newArgv.push_back(strdup(progName));
Brian Gaeke06b06c52003-08-14 22:00:59 +0000492
493 // Parse the value of the environment variable into a "command line"
494 // and hand it off to ParseCommandLineOptions().
Chris Lattner23288582006-08-27 22:10:29 +0000495 ParseCStringVector(newArgv, envValue);
Evan Cheng34cd4a42008-05-05 18:30:58 +0000496 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000497 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Brian Gaekec48ef2a2003-08-15 21:05:57 +0000498
499 // Free all the strdup()ed strings.
Chris Lattner23288582006-08-27 22:10:29 +0000500 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
501 i != e; ++i)
Chris Lattnerfb2674d2009-09-20 01:11:23 +0000502 free(*i);
Brian Gaeke06b06c52003-08-14 22:00:59 +0000503}
504
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000505
506/// ExpandResponseFiles - Copy the contents of argv into newArgv,
507/// substituting the contents of the response files for the arguments
508/// of type @file.
David Blaikieebba0552012-02-07 19:36:01 +0000509static void ExpandResponseFiles(unsigned argc, const char*const* argv,
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000510 std::vector<char*>& newArgv) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000511 for (unsigned i = 1; i != argc; ++i) {
David Blaikieebba0552012-02-07 19:36:01 +0000512 const char *arg = argv[i];
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000513
514 if (arg[0] == '@') {
Rafael Espindola234cad72013-06-12 15:37:27 +0000515 // TODO: we should also support recursive loading of response files,
516 // since this is how gcc behaves. (From their man page: "The file may
517 // itself contain additional @file options; any such options will be
518 // processed recursively.")
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000519
Rafael Espindola234cad72013-06-12 15:37:27 +0000520 // Mmap the response file into memory.
521 OwningPtr<MemoryBuffer> respFilePtr;
522 if (!MemoryBuffer::getFile(arg + 1, respFilePtr)) {
523 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
524 continue;
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000525 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000526 }
Mikhail Glushenkov1421b7b2009-01-21 13:14:02 +0000527 newArgv.push_back(strdup(arg));
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000528 }
529}
530
David Blaikieebba0552012-02-07 19:36:01 +0000531void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000532 const char *Overview) {
Chris Lattner9878d6a2007-04-06 21:06:55 +0000533 // Process all registered options.
Chris Lattner49b301c2009-09-20 06:18:38 +0000534 SmallVector<Option*, 4> PositionalOpts;
535 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +0000536 StringMap<Option*> Opts;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000537 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000538
Chris Lattner9878d6a2007-04-06 21:06:55 +0000539 assert((!Opts.empty() || !PositionalOpts.empty()) &&
540 "No options specified!");
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000541
542 // Expand response files.
543 std::vector<char*> newArgv;
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000544 newArgv.push_back(strdup(argv[0]));
545 ExpandResponseFiles(argc, argv, newArgv);
546 argv = &newArgv[0];
547 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000548
Chris Lattnerefa3da52006-10-13 00:06:24 +0000549 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencerb3127bb2010-12-18 00:19:10 +0000550 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000551 size_t Len = std::min(ProgName.size(), size_t(79));
552 memcpy(ProgramName, ProgName.data(), Len);
553 ProgramName[Len] = '\0';
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000554
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000555 ProgramOverview = Overview;
556 bool ErrorParsing = false;
557
Chris Lattner331de232002-07-22 02:07:59 +0000558 // Check out the positional arguments to collect information about them.
559 unsigned NumPositionalRequired = 0;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000560
Chris Lattnerde013242005-08-08 17:25:38 +0000561 // Determine whether or not there are an unlimited number of positionals
562 bool HasUnlimitedPositionals = false;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000563
Chris Lattner331de232002-07-22 02:07:59 +0000564 Option *ConsumeAfterOpt = 0;
565 if (!PositionalOpts.empty()) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000566 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner331de232002-07-22 02:07:59 +0000567 assert(PositionalOpts.size() > 1 &&
568 "Cannot specify cl::ConsumeAfter without a positional argument!");
569 ConsumeAfterOpt = PositionalOpts[0];
570 }
571
572 // Calculate how many positional values are _required_.
573 bool UnboundedFound = false;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000574 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner331de232002-07-22 02:07:59 +0000575 i != e; ++i) {
576 Option *Opt = PositionalOpts[i];
577 if (RequiresValue(Opt))
578 ++NumPositionalRequired;
579 else if (ConsumeAfterOpt) {
580 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000581 // unless there is only one positional argument...
582 if (PositionalOpts.size() > 2)
583 ErrorParsing |=
Benjamin Kramere6864c12009-08-02 12:13:02 +0000584 Opt->error("error - this positional option will never be matched, "
Chris Lattner54ec7ae2002-07-22 02:21:57 +0000585 "because it does not Require a value, and a "
586 "cl::ConsumeAfter option is active!");
Chris Lattner9cf3d472003-07-30 17:34:02 +0000587 } else if (UnboundedFound && !Opt->ArgStr[0]) {
588 // This option does not "require" a value... Make sure this option is
589 // not specified after an option that eats all extra arguments, or this
590 // one will never get any!
Chris Lattner331de232002-07-22 02:07:59 +0000591 //
Benjamin Kramere6864c12009-08-02 12:13:02 +0000592 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner331de232002-07-22 02:07:59 +0000593 "another positional argument will match an "
594 "unbounded number of values, and this option"
595 " does not require a value!");
596 }
597 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
598 }
Chris Lattner21e1a792005-08-08 21:57:27 +0000599 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner331de232002-07-22 02:07:59 +0000600 }
601
Reid Spencer1e13fd22004-08-13 19:47:30 +0000602 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerba112292009-09-20 00:07:40 +0000603 // the process at the end.
Chris Lattner331de232002-07-22 02:07:59 +0000604 //
Chris Lattnerba112292009-09-20 00:07:40 +0000605 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner331de232002-07-22 02:07:59 +0000606
Chris Lattner9cf3d472003-07-30 17:34:02 +0000607 // If the program has named positional arguments, and the name has been run
608 // across, keep track of which positional argument was named. Otherwise put
609 // the positional args into the PositionalVals list...
610 Option *ActivePositionalArg = 0;
611
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000612 // Loop over all of the arguments... processing them.
Chris Lattner331de232002-07-22 02:07:59 +0000613 bool DashDashFound = false; // Have we read '--'?
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000614 for (int i = 1; i < argc; ++i) {
615 Option *Handler = 0;
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000616 Option *NearestHandler = 0;
Nick Lewycky95d206a2011-05-02 05:24:47 +0000617 std::string NearestHandlerString;
Chris Lattner4e247ec2009-09-20 01:53:12 +0000618 StringRef Value;
Chris Lattner8a7a0582009-09-20 02:02:24 +0000619 StringRef ArgName = "";
Chris Lattner331de232002-07-22 02:07:59 +0000620
Chris Lattner69d6f132007-04-12 00:36:29 +0000621 // If the option list changed, this means that some command line
Chris Lattner159b0a432007-04-11 15:35:18 +0000622 // option has just been registered or deregistered. This can occur in
623 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattner69d6f132007-04-12 00:36:29 +0000624 if (OptionListChanged) {
Chris Lattner159b0a432007-04-11 15:35:18 +0000625 PositionalOpts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000626 SinkOpts.clear();
Chris Lattner159b0a432007-04-11 15:35:18 +0000627 Opts.clear();
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000628 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattner69d6f132007-04-12 00:36:29 +0000629 OptionListChanged = false;
Chris Lattner159b0a432007-04-11 15:35:18 +0000630 }
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000631
Chris Lattner331de232002-07-22 02:07:59 +0000632 // Check to see if this is a positional argument. This argument is
633 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman1115e042003-07-10 21:38:28 +0000634 // itself, or if we have seen "--" already.
Chris Lattner331de232002-07-22 02:07:59 +0000635 //
636 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
637 // Positional argument!
Chris Lattner9cf3d472003-07-30 17:34:02 +0000638 if (ActivePositionalArg) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000639 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner9cf3d472003-07-30 17:34:02 +0000640 continue; // We are done!
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000641 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000642
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000643 if (!PositionalOpts.empty()) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000644 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000645
646 // All of the positional arguments have been fulfulled, give the rest to
647 // the consume after option... if it's specified...
648 //
Misha Brukmanf976c852005-04-21 22:55:34 +0000649 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner331de232002-07-22 02:07:59 +0000650 ConsumeAfterOpt != 0) {
651 for (++i; i < argc; ++i)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000652 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner331de232002-07-22 02:07:59 +0000653 break; // Handle outside of the argument processing loop...
654 }
655
656 // Delay processing positional arguments until the end...
657 continue;
658 }
Chris Lattnerbf455c22004-05-06 22:04:31 +0000659 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
660 !DashDashFound) {
661 DashDashFound = true; // This is the mythical "--"?
662 continue; // Don't try to process it as an argument itself.
663 } else if (ActivePositionalArg &&
664 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
665 // If there is a positional argument eating options, check to see if this
666 // option is another positional argument. If so, treat it as an argument,
667 // otherwise feed it to the eating positional.
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000668 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000669 // Eat leading dashes.
670 while (!ArgName.empty() && ArgName[0] == '-')
671 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000672
Chris Lattner9878d6a2007-04-06 21:06:55 +0000673 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000674 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer1e13fd22004-08-13 19:47:30 +0000675 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnerbf455c22004-05-06 22:04:31 +0000676 continue; // We are done!
Chris Lattner331de232002-07-22 02:07:59 +0000677 }
678
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000679 } else { // We start with a '-', must be an argument.
Chris Lattnerbf455c22004-05-06 22:04:31 +0000680 ArgName = argv[i]+1;
Chris Lattnerb1687372009-09-20 05:03:30 +0000681 // Eat leading dashes.
682 while (!ArgName.empty() && ArgName[0] == '-')
683 ArgName = ArgName.substr(1);
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000684
Chris Lattner9878d6a2007-04-06 21:06:55 +0000685 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000686
Chris Lattnerbf455c22004-05-06 22:04:31 +0000687 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnerb1687372009-09-20 05:03:30 +0000688 if (Handler == 0)
689 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
690 ErrorParsing, Opts);
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000691
692 // Otherwise, look for the closest available option to report to the user
693 // in the upcoming error.
694 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000695 NearestHandler = LookupNearestOption(ArgName, Opts,
696 NearestHandlerString);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000697 }
698
699 if (Handler == 0) {
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000700 if (SinkOpts.empty()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000701 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000702 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000703
Daniel Dunbarc98d82a2011-01-24 17:27:17 +0000704 if (NearestHandler) {
705 // If we know a near match, report it as well.
706 errs() << ProgramName << ": Did you mean '-"
707 << NearestHandlerString << "'?\n";
708 }
Daniel Dunbarf4fb66a2011-01-18 01:59:24 +0000709
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000710 ErrorParsing = true;
711 } else {
Chris Lattner49b301c2009-09-20 06:18:38 +0000712 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovd57160d2008-02-20 12:38:07 +0000713 E = SinkOpts.end(); I != E ; ++I)
714 (*I)->addOccurrence(i, "", argv[i]);
715 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000716 continue;
717 }
718
Chris Lattner9cf3d472003-07-30 17:34:02 +0000719 // If this is a named positional argument, just remember that it is the
720 // active one...
721 if (Handler->getFormattingFlag() == cl::Positional)
722 ActivePositionalArg = Handler;
Chris Lattner341620b2009-09-20 01:49:31 +0000723 else
Chris Lattner4e247ec2009-09-20 01:53:12 +0000724 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner331de232002-07-22 02:07:59 +0000725 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000726
Chris Lattner331de232002-07-22 02:07:59 +0000727 // Check and handle positional arguments now...
728 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000729 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000730 << ": Not enough positional command line arguments specified!\n"
731 << "Must specify at least " << NumPositionalRequired
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000732 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000733
Chris Lattner331de232002-07-22 02:07:59 +0000734 ErrorParsing = true;
Dan Gohman16e02092010-03-24 19:38:02 +0000735 } else if (!HasUnlimitedPositionals &&
736 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000737 errs() << ProgramName
Bill Wendlinge8156192006-12-07 01:30:32 +0000738 << ": Too many positional arguments specified!\n"
739 << "Can specify at most " << PositionalOpts.size()
Duncan Sands7e7ae5a2010-02-18 14:08:13 +0000740 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerde013242005-08-08 17:25:38 +0000741 ErrorParsing = true;
Chris Lattner331de232002-07-22 02:07:59 +0000742
743 } else if (ConsumeAfterOpt == 0) {
Chris Lattnerb1687372009-09-20 05:03:30 +0000744 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000745 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
746 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner331de232002-07-22 02:07:59 +0000747 if (RequiresValue(PositionalOpts[i])) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000748 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000749 PositionalVals[ValNo].second);
750 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000751 --NumPositionalRequired; // We fulfilled our duty...
752 }
753
754 // If we _can_ give this option more arguments, do so now, as long as we
755 // do not give it values that others need. 'Done' controls whether the
756 // option even _WANTS_ any more.
757 //
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000758 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner331de232002-07-22 02:07:59 +0000759 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000760 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner331de232002-07-22 02:07:59 +0000761 case cl::Optional:
762 Done = true; // Optional arguments want _at most_ one value
763 // FALL THROUGH
764 case cl::ZeroOrMore: // Zero or more will take all they can get...
765 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer1e13fd22004-08-13 19:47:30 +0000766 ProvidePositionalOption(PositionalOpts[i],
767 PositionalVals[ValNo].first,
768 PositionalVals[ValNo].second);
769 ValNo++;
Chris Lattner331de232002-07-22 02:07:59 +0000770 break;
771 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000772 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner331de232002-07-22 02:07:59 +0000773 "positional argument processing!");
774 }
775 }
Chris Lattnercaccd762001-10-27 05:54:17 +0000776 }
Chris Lattner331de232002-07-22 02:07:59 +0000777 } else {
778 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
779 unsigned ValNo = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +0000780 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer1e13fd22004-08-13 19:47:30 +0000781 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000782 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000783 PositionalVals[ValNo].first,
784 PositionalVals[ValNo].second);
785 ValNo++;
786 }
Chris Lattnerfaba8092002-07-24 20:15:13 +0000787
788 // Handle the case where there is just one positional option, and it's
789 // optional. In this case, we want to give JUST THE FIRST option to the
790 // positional option and keep the rest for the consume after. The above
791 // loop would have assigned no values to positional options in this case.
792 //
Reid Spencer1e13fd22004-08-13 19:47:30 +0000793 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerfaba8092002-07-24 20:15:13 +0000794 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer1e13fd22004-08-13 19:47:30 +0000795 PositionalVals[ValNo].first,
796 PositionalVals[ValNo].second);
797 ValNo++;
798 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000799
Chris Lattner331de232002-07-22 02:07:59 +0000800 // Handle over all of the rest of the arguments to the
801 // cl::ConsumeAfter command line option...
802 for (; ValNo != PositionalVals.size(); ++ValNo)
803 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer1e13fd22004-08-13 19:47:30 +0000804 PositionalVals[ValNo].first,
805 PositionalVals[ValNo].second);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000806 }
807
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000808 // Loop over args and make sure all required args are specified!
Benjamin Kramer461c8762009-09-19 10:01:45 +0000809 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanb5c520b2003-07-10 17:05:26 +0000810 E = Opts.end(); I != E; ++I) {
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000811 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000812 case Required:
813 case OneOrMore:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000814 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramere6864c12009-08-02 12:13:02 +0000815 I->second->error("must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000816 ErrorParsing = true;
817 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000818 // Fall through
819 default:
820 break;
821 }
822 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000823
Rafael Espindolaa962b402010-11-19 21:14:29 +0000824 // Now that we know if -debug is specified, we can use it.
825 // Note that if ReadResponseFiles == true, this must be done before the
826 // memory allocated for the expanded command line is free()d below.
827 DEBUG(dbgs() << "Args: ";
828 for (int i = 0; i < argc; ++i)
829 dbgs() << argv[i] << ' ';
830 dbgs() << '\n';
831 );
832
Chris Lattner331de232002-07-22 02:07:59 +0000833 // Free all of the memory allocated to the map. Command line options may only
834 // be processed once!
Chris Lattner90aa8392006-10-04 21:52:35 +0000835 Opts.clear();
Chris Lattner331de232002-07-22 02:07:59 +0000836 PositionalOpts.clear();
Chris Lattner90aa8392006-10-04 21:52:35 +0000837 MoreHelp->clear();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000838
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000839 // Free the memory allocated by ExpandResponseFiles.
Rafael Espindolab4e971f2012-10-09 19:52:10 +0000840 // Free all the strdup()ed strings.
841 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
842 i != e; ++i)
843 free(*i);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000844
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000845 // If we had an error processing our arguments, don't let the program execute
846 if (ErrorParsing) exit(1);
847}
848
849//===----------------------------------------------------------------------===//
850// Option Base class implementation
851//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000852
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000853bool Option::error(const Twine &Message, StringRef ArgName) {
854 if (ArgName.data() == 0) ArgName = ArgStr;
855 if (ArgName.empty())
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000856 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner331de232002-07-22 02:07:59 +0000857 else
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000858 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +0000859
Benjamin Kramerd227a3f2009-08-23 10:01:13 +0000860 errs() << " option: " << Message << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000861 return true;
862}
863
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000864bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000865 StringRef Value, bool MultiArg) {
Mikhail Glushenkov7059d472009-01-16 22:54:19 +0000866 if (!MultiArg)
867 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000868
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000869 switch (getNumOccurrencesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000870 case Optional:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000871 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000872 return error("may only occur zero or one times!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000873 break;
874 case Required:
Misha Brukmandd6cb6a2003-07-10 16:49:51 +0000875 if (NumOccurrences > 1)
Benjamin Kramere6864c12009-08-02 12:13:02 +0000876 return error("must occur exactly one time!", ArgName);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000877 // Fall through
878 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000879 case ZeroOrMore:
880 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000881 }
882
Reid Spencer1e13fd22004-08-13 19:47:30 +0000883 return handleOccurrence(pos, ArgName, Value);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000884}
885
Chris Lattner331de232002-07-22 02:07:59 +0000886
887// getValueStr - Get the value description string, using "DefaultMsg" if nothing
888// has been specified yet.
889//
890static const char *getValueStr(const Option &O, const char *DefaultMsg) {
891 if (O.ValueStr[0] == 0) return DefaultMsg;
892 return O.ValueStr;
893}
894
895//===----------------------------------------------------------------------===//
896// cl::alias class implementation
897//
898
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000899// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000900size_t alias::getOptionWidth() const {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000901 return std::strlen(ArgStr)+6;
902}
903
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000904static void printHelpStr(StringRef HelpStr, size_t Indent,
905 size_t FirstLineIndentedBy) {
906 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
907 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
908 while (!Split.second.empty()) {
909 Split = Split.second.split('\n');
910 outs().indent(Indent) << Split.first << "\n";
911 }
912}
913
Chris Lattnera0de8432006-04-28 05:36:25 +0000914// Print out the option for the alias.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000915void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Chengff276b42011-06-13 20:45:54 +0000916 outs() << " -" << ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000917 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000918}
919
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000920//===----------------------------------------------------------------------===//
Chris Lattner331de232002-07-22 02:07:59 +0000921// Parser Implementation code...
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000922//
923
Chris Lattner9b14eb52002-08-07 18:36:37 +0000924// basic_parser implementation
925//
926
927// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +0000928size_t basic_parser_impl::getOptionWidth(const Option &O) const {
929 size_t Len = std::strlen(O.ArgStr);
Chris Lattner9b14eb52002-08-07 18:36:37 +0000930 if (const char *ValName = getValueName())
931 Len += std::strlen(getValueStr(O, ValName))+3;
932
933 return Len + 6;
934}
935
Misha Brukmanf976c852005-04-21 22:55:34 +0000936// printOptionInfo - Print out information about this option. The
Chris Lattner9b14eb52002-08-07 18:36:37 +0000937// to-be-maintained width is specified.
938//
939void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +0000940 size_t GlobalWidth) const {
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000941 outs() << " -" << O.ArgStr;
Chris Lattner9b14eb52002-08-07 18:36:37 +0000942
943 if (const char *ValName = getValueName())
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000944 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattner9b14eb52002-08-07 18:36:37 +0000945
Alexander Kornienko2e24e192013-05-10 17:15:51 +0000946 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattner9b14eb52002-08-07 18:36:37 +0000947}
948
Andrew Trickce969022011-04-05 18:54:36 +0000949void basic_parser_impl::printOptionName(const Option &O,
950 size_t GlobalWidth) const {
951 outs() << " -" << O.ArgStr;
952 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
953}
Chris Lattner9b14eb52002-08-07 18:36:37 +0000954
955
Chris Lattner331de232002-07-22 02:07:59 +0000956// parser<bool> implementation
957//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000958bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000959 StringRef Arg, bool &Value) {
Misha Brukmanf976c852005-04-21 22:55:34 +0000960 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000961 Arg == "1") {
962 Value = true;
Chris Lattnera460beb2009-09-19 18:55:05 +0000963 return false;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000964 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000965
Chris Lattnera460beb2009-09-19 18:55:05 +0000966 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
967 Value = false;
968 return false;
969 }
970 return O.error("'" + Arg +
971 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000972}
973
Dale Johannesen81da02b2007-05-22 17:14:46 +0000974// parser<boolOrDefault> implementation
975//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000976bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000977 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen81da02b2007-05-22 17:14:46 +0000978 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
979 Arg == "1") {
980 Value = BOU_TRUE;
Chris Lattnera460beb2009-09-19 18:55:05 +0000981 return false;
Dale Johannesen81da02b2007-05-22 17:14:46 +0000982 }
Chris Lattnera460beb2009-09-19 18:55:05 +0000983 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
984 Value = BOU_FALSE;
985 return false;
986 }
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +0000987
Chris Lattnera460beb2009-09-19 18:55:05 +0000988 return O.error("'" + Arg +
989 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen81da02b2007-05-22 17:14:46 +0000990}
991
Chris Lattner331de232002-07-22 02:07:59 +0000992// parser<int> implementation
993//
Chris Lattner99c5c7b2009-09-20 00:40:49 +0000994bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +0000995 StringRef Arg, int &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +0000996 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +0000997 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000998 return false;
999}
1000
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001001// parser<unsigned> implementation
1002//
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001003bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001004 StringRef Arg, unsigned &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001005
1006 if (Arg.getAsInteger(0, Value))
Benjamin Kramere6864c12009-08-02 12:13:02 +00001007 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattnerd2a6fc32003-06-28 15:47:20 +00001008 return false;
1009}
1010
Benjamin Kramerb3514562011-09-15 21:17:37 +00001011// parser<unsigned long long> implementation
1012//
1013bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1014 StringRef Arg, unsigned long long &Value){
1015
1016 if (Arg.getAsInteger(0, Value))
1017 return O.error("'" + Arg + "' value invalid for uint argument!");
1018 return false;
1019}
1020
Chris Lattner9b14eb52002-08-07 18:36:37 +00001021// parser<double>/parser<float> implementation
Chris Lattnerd215fd12001-10-13 06:53:19 +00001022//
Chris Lattnera460beb2009-09-19 18:55:05 +00001023static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner970e7df2009-09-19 23:59:02 +00001024 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1025 const char *ArgStart = TmpStr.c_str();
Chris Lattner331de232002-07-22 02:07:59 +00001026 char *End;
1027 Value = strtod(ArgStart, &End);
Misha Brukmanf976c852005-04-21 22:55:34 +00001028 if (*End != 0)
Benjamin Kramere6864c12009-08-02 12:13:02 +00001029 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattnerd215fd12001-10-13 06:53:19 +00001030 return false;
1031}
1032
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001033bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001034 StringRef Arg, double &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001035 return parseDouble(O, Arg, Val);
Chris Lattner331de232002-07-22 02:07:59 +00001036}
1037
Chris Lattner99c5c7b2009-09-20 00:40:49 +00001038bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattnera460beb2009-09-19 18:55:05 +00001039 StringRef Arg, float &Val) {
Chris Lattner9b14eb52002-08-07 18:36:37 +00001040 double dVal;
1041 if (parseDouble(O, Arg, dVal))
1042 return true;
1043 Val = (float)dVal;
1044 return false;
Chris Lattner331de232002-07-22 02:07:59 +00001045}
1046
1047
Chris Lattner331de232002-07-22 02:07:59 +00001048
1049// generic_parser_base implementation
1050//
1051
Chris Lattneraa852bb2002-07-23 17:15:12 +00001052// findOption - Return the option number corresponding to the specified
1053// argument string. If the option is not found, getNumOptions() is returned.
1054//
1055unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer461c8762009-09-19 10:01:45 +00001056 unsigned e = getNumOptions();
Chris Lattneraa852bb2002-07-23 17:15:12 +00001057
Benjamin Kramer461c8762009-09-19 10:01:45 +00001058 for (unsigned i = 0; i != e; ++i) {
1059 if (strcmp(getOption(i), Name) == 0)
Chris Lattneraa852bb2002-07-23 17:15:12 +00001060 return i;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001061 }
Chris Lattneraa852bb2002-07-23 17:15:12 +00001062 return e;
1063}
1064
1065
Chris Lattner331de232002-07-22 02:07:59 +00001066// Return the width of the option tag for printing...
Evan Cheng34cd4a42008-05-05 18:30:58 +00001067size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner331de232002-07-22 02:07:59 +00001068 if (O.hasArgStr()) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001069 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner331de232002-07-22 02:07:59 +00001070 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001071 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001072 return Size;
1073 } else {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001074 size_t BaseSize = 0;
Chris Lattner331de232002-07-22 02:07:59 +00001075 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng34cd4a42008-05-05 18:30:58 +00001076 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner331de232002-07-22 02:07:59 +00001077 return BaseSize;
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001078 }
1079}
1080
Misha Brukmanf976c852005-04-21 22:55:34 +00001081// printOptionInfo - Print out information about this option. The
Chris Lattner331de232002-07-22 02:07:59 +00001082// to-be-maintained width is specified.
1083//
1084void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng34cd4a42008-05-05 18:30:58 +00001085 size_t GlobalWidth) const {
Chris Lattner331de232002-07-22 02:07:59 +00001086 if (O.hasArgStr()) {
Chris Lattnerb1687372009-09-20 05:03:30 +00001087 outs() << " -" << O.ArgStr;
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001088 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001089
Chris Lattner331de232002-07-22 02:07:59 +00001090 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng34cd4a42008-05-05 18:30:58 +00001091 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerb1687372009-09-20 05:03:30 +00001092 outs() << " =" << getOption(i);
1093 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattner9c9be482002-01-31 00:42:56 +00001094 }
Chris Lattner331de232002-07-22 02:07:59 +00001095 } else {
1096 if (O.HelpStr[0])
Chris Lattnerb1687372009-09-20 05:03:30 +00001097 outs() << " " << O.HelpStr << '\n';
Chris Lattner331de232002-07-22 02:07:59 +00001098 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko2e24e192013-05-10 17:15:51 +00001099 const char *Option = getOption(i);
1100 outs() << " -" << Option;
1101 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner331de232002-07-22 02:07:59 +00001102 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001103 }
1104}
1105
Andrew Trickce969022011-04-05 18:54:36 +00001106static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1107
1108// printGenericOptionDiff - Print the value of this option and it's default.
1109//
1110// "Generic" options have each value mapped to a name.
1111void generic_parser_base::
1112printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1113 const GenericOptionValue &Default,
1114 size_t GlobalWidth) const {
1115 outs() << " -" << O.ArgStr;
1116 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1117
1118 unsigned NumOpts = getNumOptions();
1119 for (unsigned i = 0; i != NumOpts; ++i) {
1120 if (Value.compare(getOptionValue(i)))
1121 continue;
1122
1123 outs() << "= " << getOption(i);
1124 size_t L = std::strlen(getOption(i));
1125 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1126 outs().indent(NumSpaces) << " (default: ";
1127 for (unsigned j = 0; j != NumOpts; ++j) {
1128 if (Default.compare(getOptionValue(j)))
1129 continue;
1130 outs() << getOption(j);
1131 break;
1132 }
1133 outs() << ")\n";
1134 return;
1135 }
1136 outs() << "= *unknown option value*\n";
1137}
1138
1139// printOptionDiff - Specializations for printing basic value types.
1140//
1141#define PRINT_OPT_DIFF(T) \
1142 void parser<T>:: \
1143 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1144 size_t GlobalWidth) const { \
1145 printOptionName(O, GlobalWidth); \
1146 std::string Str; \
1147 { \
1148 raw_string_ostream SS(Str); \
1149 SS << V; \
1150 } \
1151 outs() << "= " << Str; \
1152 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1153 outs().indent(NumSpaces) << " (default: "; \
1154 if (D.hasValue()) \
1155 outs() << D.getValue(); \
1156 else \
1157 outs() << "*no default*"; \
1158 outs() << ")\n"; \
1159 } \
1160
Frits van Bommel090771f2011-04-06 12:29:56 +00001161PRINT_OPT_DIFF(bool)
1162PRINT_OPT_DIFF(boolOrDefault)
1163PRINT_OPT_DIFF(int)
1164PRINT_OPT_DIFF(unsigned)
Benjamin Kramerb3514562011-09-15 21:17:37 +00001165PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel090771f2011-04-06 12:29:56 +00001166PRINT_OPT_DIFF(double)
1167PRINT_OPT_DIFF(float)
1168PRINT_OPT_DIFF(char)
Andrew Trickce969022011-04-05 18:54:36 +00001169
1170void parser<std::string>::
1171printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1172 size_t GlobalWidth) const {
1173 printOptionName(O, GlobalWidth);
1174 outs() << "= " << V;
1175 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1176 outs().indent(NumSpaces) << " (default: ";
1177 if (D.hasValue())
1178 outs() << D.getValue();
1179 else
1180 outs() << "*no default*";
1181 outs() << ")\n";
1182}
1183
1184// Print a placeholder for options that don't yet support printOptionDiff().
1185void basic_parser_impl::
1186printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1187 printOptionName(O, GlobalWidth);
1188 outs() << "= *cannot print option value*\n";
1189}
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001190
1191//===----------------------------------------------------------------------===//
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001192// -help and -help-hidden option implementation
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001193//
Reid Spencerad0846b2004-11-14 22:04:00 +00001194
Chris Lattner0fd48b12009-09-20 05:37:24 +00001195static int OptNameCompare(const void *LHS, const void *RHS) {
1196 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001197
Duncan Sandse840fef2012-03-12 10:51:06 +00001198 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner0fd48b12009-09-20 05:37:24 +00001199}
1200
Andrew Trickce969022011-04-05 18:54:36 +00001201// Copy Options into a vector so we can sort them as we like.
1202static void
1203sortOpts(StringMap<Option*> &OptMap,
1204 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1205 bool ShowHidden) {
1206 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1207
1208 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1209 I != E; ++I) {
1210 // Ignore really-hidden options.
1211 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1212 continue;
1213
1214 // Unless showhidden is set, ignore hidden flags.
1215 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1216 continue;
1217
1218 // If we've already seen this option, don't add it to the list again.
1219 if (!OptionSet.insert(I->second))
1220 continue;
1221
1222 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1223 I->second));
1224 }
1225
1226 // Sort the options list alphabetically.
1227 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1228}
1229
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001230namespace {
1231
Chris Lattner331de232002-07-22 02:07:59 +00001232class HelpPrinter {
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001233protected:
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001234 const bool ShowHidden;
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001235 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1236 // Print the options. Opts is assumed to be alphabetically sorted.
1237 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1238 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1239 Opts[i].second->printOptionInfo(MaxArgLen);
1240 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001241
Chris Lattner331de232002-07-22 02:07:59 +00001242public:
Craig Topperddde2082013-03-09 23:29:37 +00001243 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001244 virtual ~HelpPrinter() {}
Chris Lattner331de232002-07-22 02:07:59 +00001245
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001246 // Invoke the printer.
Chris Lattner331de232002-07-22 02:07:59 +00001247 void operator=(bool Value) {
1248 if (Value == false) return;
1249
Chris Lattner9878d6a2007-04-06 21:06:55 +00001250 // Get all the options.
Chris Lattner49b301c2009-09-20 06:18:38 +00001251 SmallVector<Option*, 4> PositionalOpts;
1252 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer461c8762009-09-19 10:01:45 +00001253 StringMap<Option*> OptMap;
Anton Korobeynikovd57160d2008-02-20 12:38:07 +00001254 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001255
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001256 StrOptionPairVector Opts;
Andrew Trickce969022011-04-05 18:54:36 +00001257 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001258
1259 if (ProgramOverview)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001260 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001261
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001262 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner331de232002-07-22 02:07:59 +00001263
Chris Lattner90aa8392006-10-04 21:52:35 +00001264 // Print out the positional options.
Chris Lattner331de232002-07-22 02:07:59 +00001265 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkovbeb4d822008-04-28 16:44:25 +00001266 if (!PositionalOpts.empty() &&
Chris Lattner9878d6a2007-04-06 21:06:55 +00001267 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1268 CAOpt = PositionalOpts[0];
Chris Lattner331de232002-07-22 02:07:59 +00001269
Evan Cheng34cd4a42008-05-05 18:30:58 +00001270 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner9878d6a2007-04-06 21:06:55 +00001271 if (PositionalOpts[i]->ArgStr[0])
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001272 outs() << " --" << PositionalOpts[i]->ArgStr;
1273 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner9cf3d472003-07-30 17:34:02 +00001274 }
Chris Lattner331de232002-07-22 02:07:59 +00001275
1276 // Print the consume after option info if it exists...
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001277 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner331de232002-07-22 02:07:59 +00001278
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001279 outs() << "\n\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001280
1281 // Compute the maximum argument length...
Craig Topperddde2082013-03-09 23:29:37 +00001282 size_t MaxArgLen = 0;
Evan Cheng34cd4a42008-05-05 18:30:58 +00001283 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0fd48b12009-09-20 05:37:24 +00001284 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001285
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001286 outs() << "OPTIONS:\n";
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001287 printOptions(Opts, MaxArgLen);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001288
Chris Lattnerc540ebb2004-11-19 17:08:15 +00001289 // Print any extra help the user has declared.
Chris Lattner90aa8392006-10-04 21:52:35 +00001290 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001291 E = MoreHelp->end();
1292 I != E; ++I)
Chris Lattnerd9ea85a2009-08-23 08:43:55 +00001293 outs() << *I;
Chris Lattner90aa8392006-10-04 21:52:35 +00001294 MoreHelp->clear();
Reid Spencerad0846b2004-11-14 22:04:00 +00001295
Reid Spencer9bbba0912004-11-16 06:11:52 +00001296 // Halt the program since help information was printed
Chris Lattner331de232002-07-22 02:07:59 +00001297 exit(1);
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001298 }
1299};
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001300
1301class CategorizedHelpPrinter : public HelpPrinter {
1302public:
1303 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1304
1305 // Helper function for printOptions().
1306 // It shall return true if A's name should be lexographically
1307 // ordered before B's name. It returns false otherwise.
1308 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1309 int Length = strcmp(A->getName(), B->getName());
1310 assert(Length != 0 && "Duplicate option categories");
1311 return Length < 0;
1312 }
1313
1314 // Make sure we inherit our base class's operator=()
1315 using HelpPrinter::operator= ;
1316
1317protected:
1318 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1319 std::vector<OptionCategory *> SortedCategories;
1320 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1321
1322 // Collect registered option categories into vector in preperation for
1323 // sorting.
1324 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1325 E = RegisteredOptionCategories->end();
1326 I != E; ++I)
1327 SortedCategories.push_back(*I);
1328
1329 // Sort the different option categories alphabetically.
1330 assert(SortedCategories.size() > 0 && "No option categories registered!");
1331 std::sort(SortedCategories.begin(), SortedCategories.end(),
1332 OptionCategoryCompare);
1333
1334 // Create map to empty vectors.
1335 for (std::vector<OptionCategory *>::const_iterator
1336 I = SortedCategories.begin(),
1337 E = SortedCategories.end();
1338 I != E; ++I)
1339 CategorizedOptions[*I] = std::vector<Option *>();
1340
1341 // Walk through pre-sorted options and assign into categories.
1342 // Because the options are already alphabetically sorted the
1343 // options within categories will also be alphabetically sorted.
1344 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1345 Option *Opt = Opts[I].second;
1346 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1347 "Option has an unregistered category");
1348 CategorizedOptions[Opt->Category].push_back(Opt);
1349 }
1350
1351 // Now do printing.
1352 for (std::vector<OptionCategory *>::const_iterator
1353 Category = SortedCategories.begin(),
1354 E = SortedCategories.end();
1355 Category != E; ++Category) {
1356 // Hide empty categories for -help, but show for -help-hidden.
1357 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1358 if (!ShowHidden && IsEmptyCategory)
1359 continue;
1360
1361 // Print category information.
1362 outs() << "\n";
1363 outs() << (*Category)->getName() << ":\n";
1364
1365 // Check if description is set.
1366 if ((*Category)->getDescription() != 0)
1367 outs() << (*Category)->getDescription() << "\n\n";
1368 else
1369 outs() << "\n";
1370
1371 // When using -help-hidden explicitly state if the category has no
1372 // options associated with it.
1373 if (IsEmptyCategory) {
1374 outs() << " This option category has no options.\n";
1375 continue;
1376 }
1377 // Loop over the options in the category and print.
1378 for (std::vector<Option *>::const_iterator
1379 Opt = CategorizedOptions[*Category].begin(),
1380 E = CategorizedOptions[*Category].end();
1381 Opt != E; ++Opt)
1382 (*Opt)->printOptionInfo(MaxArgLen);
1383 }
1384 }
1385};
1386
1387// This wraps the Uncategorizing and Categorizing printers and decides
1388// at run time which should be invoked.
1389class HelpPrinterWrapper {
1390private:
1391 HelpPrinter &UncategorizedPrinter;
1392 CategorizedHelpPrinter &CategorizedPrinter;
1393
1394public:
1395 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1396 CategorizedHelpPrinter &CategorizedPrinter) :
1397 UncategorizedPrinter(UncategorizedPrinter),
1398 CategorizedPrinter(CategorizedPrinter) { }
1399
1400 // Invoke the printer.
1401 void operator=(bool Value);
1402};
1403
Chris Lattner500d8bf2006-10-12 22:09:17 +00001404} // End anonymous namespace
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001405
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001406// Declare the four HelpPrinter instances that are used to print out help, or
1407// help-hidden as an uncategorized list or in categories.
1408static HelpPrinter UncategorizedNormalPrinter(false);
1409static HelpPrinter UncategorizedHiddenPrinter(true);
1410static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1411static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1412
1413
1414// Declare HelpPrinter wrappers that will decide whether or not to invoke
1415// a categorizing help printer
1416static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1417 CategorizedNormalPrinter);
1418static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1419 CategorizedHiddenPrinter);
1420
1421// Define uncategorized help printers.
1422// -help-list is hidden by default because if Option categories are being used
1423// then -help behaves the same as -help-list.
1424static cl::opt<HelpPrinter, true, parser<bool> >
1425HLOp("help-list",
1426 cl::desc("Display list of available options (-help-list-hidden for more)"),
1427 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001428
Chris Lattner500d8bf2006-10-12 22:09:17 +00001429static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001430HLHOp("help-list-hidden",
1431 cl::desc("Display list of all available options"),
1432 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1433
1434// Define uncategorized/categorized help printers. These printers change their
1435// behaviour at runtime depending on whether one or more Option categories have
1436// been declared.
1437static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands7e7ae5a2010-02-18 14:08:13 +00001438HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001439 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner331de232002-07-22 02:07:59 +00001440
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001441static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001442HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001443 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1444
1445
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001446
Andrew Trickce969022011-04-05 18:54:36 +00001447static cl::opt<bool>
1448PrintOptions("print-options",
1449 cl::desc("Print non-default options after command line parsing"),
1450 cl::Hidden, cl::init(false));
1451
1452static cl::opt<bool>
1453PrintAllOptions("print-all-options",
1454 cl::desc("Print all option values after command line parsing"),
1455 cl::Hidden, cl::init(false));
1456
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001457void HelpPrinterWrapper::operator=(bool Value) {
1458 if (Value == false)
1459 return;
1460
1461 // Decide which printer to invoke. If more than one option category is
1462 // registered then it is useful to show the categorized help instead of
1463 // uncategorized help.
1464 if (RegisteredOptionCategories->size() > 1) {
1465 // unhide -help-list option so user can have uncategorized output if they
1466 // want it.
1467 HLOp.setHiddenFlag(NotHidden);
1468
1469 CategorizedPrinter = true; // Invoke categorized printer
1470 }
1471 else
1472 UncategorizedPrinter = true; // Invoke uncategorized printer
1473}
1474
Andrew Trickce969022011-04-05 18:54:36 +00001475// Print the value of each option.
1476void cl::PrintOptionValues() {
1477 if (!PrintOptions && !PrintAllOptions) return;
1478
1479 // Get all the options.
1480 SmallVector<Option*, 4> PositionalOpts;
1481 SmallVector<Option*, 4> SinkOpts;
1482 StringMap<Option*> OptMap;
1483 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1484
1485 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1486 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1487
1488 // Compute the maximum argument length...
1489 size_t MaxArgLen = 0;
1490 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1491 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1492
1493 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1494 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1495}
1496
Chris Lattner500d8bf2006-10-12 22:09:17 +00001497static void (*OverrideVersionPrinter)() = 0;
Reid Spencer515b5b32006-06-05 16:22:56 +00001498
Chandler Carruth6d51d262011-07-22 07:50:40 +00001499static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1500
Chris Lattner500d8bf2006-10-12 22:09:17 +00001501namespace {
Reid Spencer515b5b32006-06-05 16:22:56 +00001502class VersionPrinter {
1503public:
Devang Patelaed293d2007-02-01 01:43:37 +00001504 void print() {
Chris Lattner49b301c2009-09-20 06:18:38 +00001505 raw_ostream &OS = outs();
Jim Grosbachc48d4dc2012-01-25 22:00:23 +00001506 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner49b301c2009-09-20 06:18:38 +00001507 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001508#ifdef LLVM_VERSION_INFO
Chris Lattner49b301c2009-09-20 06:18:38 +00001509 OS << LLVM_VERSION_INFO;
Reid Spencer515b5b32006-06-05 16:22:56 +00001510#endif
Chris Lattner49b301c2009-09-20 06:18:38 +00001511 OS << "\n ";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001512#ifndef __OPTIMIZE__
Chris Lattner49b301c2009-09-20 06:18:38 +00001513 OS << "DEBUG build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001514#else
Chris Lattner49b301c2009-09-20 06:18:38 +00001515 OS << "Optimized build";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001516#endif
1517#ifndef NDEBUG
Chris Lattner49b301c2009-09-20 06:18:38 +00001518 OS << " with assertions";
Chris Lattner3fc2f4e2006-07-06 18:33:03 +00001519#endif
Daniel Dunbarba43e072009-11-14 21:36:07 +00001520 std::string CPU = sys::getHostCPUName();
Benjamin Kramer110e7bb2009-11-17 17:57:04 +00001521 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner49b301c2009-09-20 06:18:38 +00001522 OS << ".\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001523#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner49b301c2009-09-20 06:18:38 +00001524 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardd464df2010-05-10 20:11:56 +00001525#endif
Sebastian Pop01738642011-11-01 21:32:20 +00001526 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth40393132011-07-22 07:50:48 +00001527 << " Host CPU: " << CPU << '\n';
Devang Patelaed293d2007-02-01 01:43:37 +00001528 }
1529 void operator=(bool OptionWasSpecified) {
Chris Lattner043b8b52009-09-20 05:48:01 +00001530 if (!OptionWasSpecified) return;
Mikhail Glushenkoveeebecf2009-11-19 17:29:36 +00001531
Chandler Carruth6d51d262011-07-22 07:50:40 +00001532 if (OverrideVersionPrinter != 0) {
1533 (*OverrideVersionPrinter)();
Chris Lattner043b8b52009-09-20 05:48:01 +00001534 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001535 }
Chandler Carruth6d51d262011-07-22 07:50:40 +00001536 print();
1537
1538 // Iterate over any registered extra printers and call them to add further
1539 // information.
1540 if (ExtraVersionPrinters != 0) {
Chandler Carruth40393132011-07-22 07:50:48 +00001541 outs() << '\n';
Chandler Carruth6d51d262011-07-22 07:50:40 +00001542 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1543 E = ExtraVersionPrinters->end();
1544 I != E; ++I)
1545 (*I)();
1546 }
1547
Chris Lattner043b8b52009-09-20 05:48:01 +00001548 exit(1);
Reid Spencer515b5b32006-06-05 16:22:56 +00001549 }
1550};
Chris Lattner500d8bf2006-10-12 22:09:17 +00001551} // End anonymous namespace
Reid Spencer515b5b32006-06-05 16:22:56 +00001552
1553
Reid Spencer69105f32004-08-04 00:36:06 +00001554// Define the --version option that prints out the LLVM version for the tool
Chris Lattner500d8bf2006-10-12 22:09:17 +00001555static VersionPrinter VersionPrinterInstance;
1556
1557static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner4bf7afc2005-05-13 19:49:09 +00001558VersOp("version", cl::desc("Display the version of this program"),
Reid Spencer69105f32004-08-04 00:36:06 +00001559 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1560
Reid Spencer9bbba0912004-11-16 06:11:52 +00001561// Utility function for printing the help message.
Andrew Trickb7ad33b2013-05-06 21:56:23 +00001562void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1563 // This looks weird, but it actually prints the help message. The Printers are
1564 // types of HelpPrinter and the help gets printed when its operator= is
1565 // invoked. That's because the "normal" usages of the help printer is to be
1566 // assigned true/false depending on whether -help or -help-hidden was given or
1567 // not. Since we're circumventing that we have to make it look like -help or
1568 // -help-hidden were given, so we assign true.
1569
1570 if (!Hidden && !Categorized)
1571 UncategorizedNormalPrinter = true;
1572 else if (!Hidden && Categorized)
1573 CategorizedNormalPrinter = true;
1574 else if (Hidden && !Categorized)
1575 UncategorizedHiddenPrinter = true;
1576 else
1577 CategorizedHiddenPrinter = true;
Reid Spencer9bbba0912004-11-16 06:11:52 +00001578}
Reid Spencer515b5b32006-06-05 16:22:56 +00001579
Devang Patelaed293d2007-02-01 01:43:37 +00001580/// Utility function for printing version number.
1581void cl::PrintVersionMessage() {
1582 VersionPrinterInstance.print();
1583}
1584
Reid Spencer515b5b32006-06-05 16:22:56 +00001585void cl::SetVersionPrinter(void (*func)()) {
1586 OverrideVersionPrinter = func;
1587}
Chandler Carruth6d51d262011-07-22 07:50:40 +00001588
1589void cl::AddExtraVersionPrinter(void (*func)()) {
1590 if (ExtraVersionPrinters == 0)
1591 ExtraVersionPrinters = new std::vector<void (*)()>;
1592
1593 ExtraVersionPrinters->push_back(func);
1594}
Andrew Trick61e01722013-05-06 21:56:35 +00001595
1596void cl::getRegisteredOptions(StringMap<Option*> &Map)
1597{
1598 // Get all the options.
1599 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1600 SmallVector<Option*, 4> SinkOpts; //NOT USED
1601 assert(Map.size() == 0 && "StringMap must be empty");
1602 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1603 return;
1604}