blob: e1317a25986d918c8761824b1cf856cc6475543b [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-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 Lattner81cc83d2001-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 Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000020#include "llvm/ADT/ArrayRef.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000021#include "llvm/ADT/OwningPtr.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-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 Gaekee5e53222003-10-10 17:01:36 +000036#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000037#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000038#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chris Lattner3e5d60f2006-08-27 12:45:47 +000042//===----------------------------------------------------------------------===//
43// Template instantiations and anchors.
44//
Douglas Gregor7baad732009-11-25 06:04:18 +000045namespace llvm { namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000046TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000047TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000048TEMPLATE_INSTANTIATION(class basic_parser<int>);
49TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000050TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-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 Wendlingdb59fda2009-04-29 23:26:16 +000054TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000055
56TEMPLATE_INSTANTIATION(class opt<unsigned>);
57TEMPLATE_INSTANTIATION(class opt<int>);
58TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000059TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000060TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor7baad732009-11-25 06:04:18 +000061} } // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000062
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000063// Pin the vtables to this file.
64void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000065void OptionValue<boolOrDefault>::anchor() {}
66void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000067void Option::anchor() {}
68void basic_parser_impl::anchor() {}
69void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000070void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000071void parser<int>::anchor() {}
72void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000073void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000074void parser<double>::anchor() {}
75void parser<float>::anchor() {}
76void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000077void parser<char>::anchor() {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000078void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000079
80//===----------------------------------------------------------------------===//
81
Chris Lattner5af1cbc2006-10-13 00:06:24 +000082// Globals for name and overview of program. Program name is not a string to
83// avoid static ctor/dtor issues.
84static char ProgramName[80] = "<premain>";
Reid Spencer9501b9b2004-09-01 04:41:28 +000085static const char *ProgramOverview = 0;
86
Chris Lattner37bcd992004-11-19 17:08:15 +000087// This collects additional help to be printed.
Chris Lattner8111c592006-10-04 21:52:35 +000088static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000089
Chris Lattner8111c592006-10-04 21:52:35 +000090extrahelp::extrahelp(const char *Help)
Chris Lattner37bcd992004-11-19 17:08:15 +000091 : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000092 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000093}
94
Chris Lattneraf039c52007-04-12 00:36:29 +000095static bool OptionListChanged = false;
96
97// MarkOptionsChanged - Internal helper function.
98void cl::MarkOptionsChanged() {
99 OptionListChanged = true;
100}
101
Chris Lattner5247f602007-04-06 21:06:55 +0000102/// RegisteredOptionList - This is the list of the command line options that
103/// have statically constructed themselves.
104static Option *RegisteredOptionList = 0;
105
106void Option::addArgument() {
107 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000108
Chris Lattner5247f602007-04-06 21:06:55 +0000109 NextRegistered = RegisteredOptionList;
110 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000111 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000112}
113
Jordan Rosec25b0c72014-01-29 18:54:17 +0000114void Option::removeArgument() {
115 assert(NextRegistered != 0 && "argument never registered");
116 assert(RegisteredOptionList == this && "argument is not the last registered");
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
119}
120
Andrew Trick0537a982013-05-06 21:56:23 +0000121// This collects the different option categories that have been registered.
122typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
123static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
124
125// Initialise the general option category.
126OptionCategory llvm::cl::GeneralCategory("General options");
127
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000128struct HasName {
129 HasName(StringRef Name) : Name(Name) {}
130 bool operator()(const OptionCategory *Category) const {
131 return Name == Category->getName();
132 }
133 StringRef Name;
134};
135
Andrew Trick0537a982013-05-06 21:56:23 +0000136void OptionCategory::registerCategory()
137{
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000138 assert(std::count_if(RegisteredOptionCategories->begin(),
139 RegisteredOptionCategories->end(),
140 HasName(getName())) == 0 &&
141 "Duplicate option categories");
142
Andrew Trick0537a982013-05-06 21:56:23 +0000143 RegisteredOptionCategories->insert(this);
144}
Chris Lattneraf039c52007-04-12 00:36:29 +0000145
Chris Lattner5df56c42002-07-22 02:07:59 +0000146//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000147// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000148//
149
Chris Lattner5247f602007-04-06 21:06:55 +0000150/// GetOptionInfo - Scan the list of registered options, turning them into data
151/// structures that are easier to handle.
Chris Lattner131dca92009-09-20 06:18:38 +0000152static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
153 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000154 StringMap<Option*> &OptionsMap) {
Chris Lattner56efff07f2009-09-20 06:21:43 +0000155 SmallVector<const char*, 16> OptionNames;
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000156 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000157 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
158 // If this option wants to handle multiple option names, get the full set.
159 // This handles enum options like "-O1 -O2" etc.
160 O->getExtraOptionNames(OptionNames);
161 if (O->ArgStr[0])
162 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000163
Chris Lattner5247f602007-04-06 21:06:55 +0000164 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000165 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000166 // Add argument to the argument map!
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000167 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000168 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijmanc9c67152008-05-30 13:26:11 +0000169 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner5247f602007-04-06 21:06:55 +0000170 }
171 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000172
Chris Lattner5247f602007-04-06 21:06:55 +0000173 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000174
Chris Lattner5247f602007-04-06 21:06:55 +0000175 // Remember information about positional options.
176 if (O->getFormattingFlag() == cl::Positional)
177 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000178 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000179 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000180 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000181 if (CAOpt)
Chris Lattner5247f602007-04-06 21:06:55 +0000182 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000183 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000184 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000185 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000186
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000187 if (CAOpt)
188 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000189
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000190 // Make sure that they are in order of registration not backwards.
191 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattner1f790af2002-07-29 20:58:42 +0000192}
193
Chris Lattner5247f602007-04-06 21:06:55 +0000194
Chris Lattner2031b022007-04-05 21:58:17 +0000195/// LookupOption - Lookup the option specified by the specified option on the
196/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000197/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000198static Option *LookupOption(StringRef &Arg, StringRef &Value,
199 const StringMap<Option*> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000200 // Reject all dashes.
201 if (Arg.empty()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000202
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000203 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000204
Chris Lattner0a40a972009-09-20 01:53:12 +0000205 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000206 if (EqualPos == StringRef::npos) {
207 // Look up the option.
208 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
209 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000210 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000211
Chris Lattnere7c1e212009-09-20 05:03:30 +0000212 // If the argument before the = is a valid option name, we match. If not,
213 // return Arg unmolested.
214 StringMap<Option*>::const_iterator I =
215 OptionsMap.find(Arg.substr(0, EqualPos));
216 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000217
Chris Lattnere7c1e212009-09-20 05:03:30 +0000218 Value = Arg.substr(EqualPos+1);
219 Arg = Arg.substr(0, EqualPos);
220 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000221}
222
Daniel Dunbarf4132132011-01-18 01:59:24 +0000223/// LookupNearestOption - Lookup the closest match to the option specified by
224/// the specified option on the command line. If there is a value specified
225/// (after an equal sign) return that as well. This assumes that leading dashes
226/// have already been stripped.
227static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000228 const StringMap<Option*> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000229 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000230 // Reject all dashes.
231 if (Arg.empty()) return 0;
232
233 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000234 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
235 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
236 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000237
238 // Find the closest match.
239 Option *Best = 0;
240 unsigned BestDistance = 0;
241 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
242 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000243 Option *O = it->second;
244 SmallVector<const char*, 16> OptionNames;
245 O->getExtraOptionNames(OptionNames);
246 if (O->ArgStr[0])
247 OptionNames.push_back(O->ArgStr);
248
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000249 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
250 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000251 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
252 StringRef Name = OptionNames[i];
253 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000254 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000255 if (!Best || Distance < BestDistance) {
256 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000257 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000258 if (RHS.empty() || !PermitValue)
259 NearestString = OptionNames[i];
260 else
261 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000262 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000263 }
264 }
265
266 return Best;
267}
268
Alp Tokercb402912014-01-24 17:20:08 +0000269/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
270/// that does special handling of cl::CommaSeparated options.
271static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
272 StringRef ArgName, StringRef Value,
273 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000274 // Check to see if this option accepts a comma separated list of values. If
275 // it does, we have to split up the value into multiple values.
276 if (Handler->getMiscFlags() & CommaSeparated) {
277 StringRef Val(Value);
278 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000279
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000280 while (Pos != StringRef::npos) {
281 // Process the portion before the comma.
282 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
283 return true;
284 // Erase the portion before the comma, AND the comma.
285 Val = Val.substr(Pos+1);
286 Value.substr(Pos+1); // Increment the original value pointer as well.
287 // Check for another comma.
288 Pos = Val.find(',');
289 }
290
291 Value = Val;
292 }
293
294 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
295 return true;
296
297 return false;
298}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000299
Chris Lattner40fef802009-09-20 01:49:31 +0000300/// ProvideOption - For Value, this differentiates between an empty value ("")
301/// and a null value (StringRef()). The later is accepted for arguments that
302/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000303static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000304 StringRef Value, int argc,
305 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000306 // Is this a multi-argument option?
307 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
308
Chris Lattnere81c4092001-10-27 05:54:17 +0000309 // Enforce value requirements
310 switch (Handler->getValueExpectedFlag()) {
311 case ValueRequired:
Chris Lattner40fef802009-09-20 01:49:31 +0000312 if (Value.data() == 0) { // No value specified?
Chris Lattnerca2552d2009-09-20 00:07:40 +0000313 if (i+1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000314 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000315 // Steal the next argument, like for '-o filename'
316 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000317 }
318 break;
319 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000320 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000321 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000322 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000323
Chris Lattner40fef802009-09-20 01:49:31 +0000324 if (Value.data())
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000325 return Handler->error("does not allow a value! '" +
Chris Lattneraecd74d2009-09-19 18:55:05 +0000326 Twine(Value) + "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000327 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000328 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000329 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000330 }
331
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000332 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000333 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000334 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000335
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000336 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000337 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000338
Chris Lattner40fef802009-09-20 01:49:31 +0000339 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000340 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000341 return true;
342 --NumAdditionalVals;
343 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000344 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000345
346 while (NumAdditionalVals > 0) {
Chris Lattneraecd74d2009-09-19 18:55:05 +0000347 if (i+1 >= argc)
348 return Handler->error("not enough values!");
349 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000350
Alp Tokercb402912014-01-24 17:20:08 +0000351 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000352 return true;
353 MultiArg = true;
354 --NumAdditionalVals;
355 }
356 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000357}
358
Chris Lattnerca2552d2009-09-20 00:07:40 +0000359static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000360 int Dummy = i;
Chris Lattner40fef802009-09-20 01:49:31 +0000361 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000362}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000363
Chris Lattner5df56c42002-07-22 02:07:59 +0000364
365// Option predicates...
366static inline bool isGrouping(const Option *O) {
367 return O->getFormattingFlag() == cl::Grouping;
368}
369static inline bool isPrefixedOrGrouping(const Option *O) {
370 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
371}
372
373// getOptionPred - Check to see if there are any options that satisfy the
374// specified predicate with names that are the prefixes in Name. This is
375// checked by progressively stripping characters off of the name, checking to
376// see if there options that satisfy the predicate. If we find one, return it,
377// otherwise return null.
378//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000379static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner5247f602007-04-06 21:06:55 +0000380 bool (*Pred)(const Option*),
Chris Lattnere7c1e212009-09-20 05:03:30 +0000381 const StringMap<Option*> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000382
Chris Lattnere7c1e212009-09-20 05:03:30 +0000383 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000384
Chris Lattnere7c1e212009-09-20 05:03:30 +0000385 // Loop while we haven't found an option and Name still has at least two
386 // characters in it (so that the next iteration will not be the empty
387 // string.
388 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000389 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000390 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000391 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000392
Chris Lattner5247f602007-04-06 21:06:55 +0000393 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000394 Length = Name.size();
Chris Lattner5247f602007-04-06 21:06:55 +0000395 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000396 }
397 return 0; // No option found!
398}
399
Chris Lattnere7c1e212009-09-20 05:03:30 +0000400/// HandlePrefixedOrGroupedOption - The specified argument string (which started
401/// with at least one '-') does not fully match an available option. Check to
402/// see if this is a prefix or grouped option. If so, split arg into output an
403/// Arg/Value pair and return the Option to parse it with.
404static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
405 bool &ErrorParsing,
406 const StringMap<Option*> &OptionsMap) {
407 if (Arg.size() == 1) return 0;
408
409 // Do the lookup!
410 size_t Length = 0;
411 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
412 if (PGOpt == 0) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000413
Chris Lattnere7c1e212009-09-20 05:03:30 +0000414 // If the option is a prefixed option, then the value is simply the
415 // rest of the name... so fall through to later processing, by
416 // setting up the argument name flags and value fields.
417 if (PGOpt->getFormattingFlag() == cl::Prefix) {
418 Value = Arg.substr(Length);
419 Arg = Arg.substr(0, Length);
420 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
421 return PGOpt;
422 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000423
Chris Lattnere7c1e212009-09-20 05:03:30 +0000424 // This must be a grouped option... handle them now. Grouping options can't
425 // have values.
426 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000427
Chris Lattnere7c1e212009-09-20 05:03:30 +0000428 do {
429 // Move current arg name out of Arg into OneArgName.
430 StringRef OneArgName = Arg.substr(0, Length);
431 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000432
Chris Lattnere7c1e212009-09-20 05:03:30 +0000433 // Because ValueRequired is an invalid flag for grouped arguments,
434 // we don't need to pass argc/argv in.
435 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
436 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000437 int Dummy = 0;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000438 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
439 StringRef(), 0, 0, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000440
Chris Lattnere7c1e212009-09-20 05:03:30 +0000441 // Get the next grouping option.
442 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
443 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000444
Chris Lattnere7c1e212009-09-20 05:03:30 +0000445 // Return the last option with Arg cut down to just the last one.
446 return PGOpt;
447}
448
449
450
Chris Lattner5df56c42002-07-22 02:07:59 +0000451static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000452 return O->getNumOccurrencesFlag() == cl::Required ||
453 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000454}
455
456static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000457 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
458 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000459}
Chris Lattnere81c4092001-10-27 05:54:17 +0000460
Reid Klecknera73c7782013-07-18 16:52:05 +0000461static bool isWhitespace(char C) {
462 return strchr(" \t\n\r\f\v", C);
463}
Brian Gaeke497216d2003-08-15 21:05:57 +0000464
Reid Klecknera73c7782013-07-18 16:52:05 +0000465static bool isQuote(char C) {
466 return C == '\"' || C == '\'';
467}
468
469static bool isGNUSpecial(char C) {
470 return strchr("\\\"\' ", C);
471}
472
473void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
474 SmallVectorImpl<const char *> &NewArgv) {
475 SmallString<128> Token;
476 for (size_t I = 0, E = Src.size(); I != E; ++I) {
477 // Consume runs of whitespace.
478 if (Token.empty()) {
479 while (I != E && isWhitespace(Src[I]))
480 ++I;
481 if (I == E) break;
482 }
483
484 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
485 // they are literal. This makes it much easier to read Windows file paths.
486 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
487 ++I; // Skip the escape.
488 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000489 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000490 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000491
Reid Klecknera73c7782013-07-18 16:52:05 +0000492 // Consume a quoted string.
493 if (isQuote(Src[I])) {
494 char Quote = Src[I++];
495 while (I != E && Src[I] != Quote) {
496 // Backslashes are literal, unless they escape a special character.
497 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
498 ++I;
499 Token.push_back(Src[I]);
500 ++I;
501 }
502 if (I == E) break;
503 continue;
504 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000505
Reid Klecknera73c7782013-07-18 16:52:05 +0000506 // End the token if this is whitespace.
507 if (isWhitespace(Src[I])) {
508 if (!Token.empty())
509 NewArgv.push_back(Saver.SaveString(Token.c_str()));
510 Token.clear();
511 continue;
512 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000513
Reid Klecknera73c7782013-07-18 16:52:05 +0000514 // This is a normal character. Append it.
515 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000516 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000517
518 // Append the last token after hitting EOF with no whitespace.
519 if (!Token.empty())
520 NewArgv.push_back(Saver.SaveString(Token.c_str()));
521}
522
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000523/// Backslashes are interpreted in a rather complicated way in the Windows-style
524/// command line, because backslashes are used both to separate path and to
525/// escape double quote. This method consumes runs of backslashes as well as the
526/// following double quote if it's escaped.
527///
528/// * If an even number of backslashes is followed by a double quote, one
529/// backslash is output for every pair of backslashes, and the last double
530/// quote remains unconsumed. The double quote will later be interpreted as
531/// the start or end of a quoted string in the main loop outside of this
532/// function.
533///
534/// * If an odd number of backslashes is followed by a double quote, one
535/// backslash is output for every pair of backslashes, and a double quote is
536/// output for the last pair of backslash-double quote. The double quote is
537/// consumed in this case.
538///
539/// * Otherwise, backslashes are interpreted literally.
540static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
541 size_t E = Src.size();
542 int BackslashCount = 0;
543 // Skip the backslashes.
544 do {
545 ++I;
546 ++BackslashCount;
547 } while (I != E && Src[I] == '\\');
548
549 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
550 if (FollowedByDoubleQuote) {
551 Token.append(BackslashCount / 2, '\\');
552 if (BackslashCount % 2 == 0)
553 return I - 1;
554 Token.push_back('"');
555 return I;
556 }
557 Token.append(BackslashCount, '\\');
558 return I - 1;
559}
560
Reid Klecknera73c7782013-07-18 16:52:05 +0000561void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
562 SmallVectorImpl<const char *> &NewArgv) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000563 SmallString<128> Token;
564
565 // This is a small state machine to consume characters until it reaches the
566 // end of the source string.
567 enum { INIT, UNQUOTED, QUOTED } State = INIT;
568 for (size_t I = 0, E = Src.size(); I != E; ++I) {
569 // INIT state indicates that the current input index is at the start of
570 // the string or between tokens.
571 if (State == INIT) {
572 if (isWhitespace(Src[I]))
573 continue;
574 if (Src[I] == '"') {
575 State = QUOTED;
576 continue;
577 }
578 if (Src[I] == '\\') {
579 I = parseBackslash(Src, I, Token);
580 State = UNQUOTED;
581 continue;
582 }
583 Token.push_back(Src[I]);
584 State = UNQUOTED;
585 continue;
586 }
587
588 // UNQUOTED state means that it's reading a token not quoted by double
589 // quotes.
590 if (State == UNQUOTED) {
591 // Whitespace means the end of the token.
592 if (isWhitespace(Src[I])) {
593 NewArgv.push_back(Saver.SaveString(Token.c_str()));
594 Token.clear();
595 State = INIT;
596 continue;
597 }
598 if (Src[I] == '"') {
599 State = QUOTED;
600 continue;
601 }
602 if (Src[I] == '\\') {
603 I = parseBackslash(Src, I, Token);
604 continue;
605 }
606 Token.push_back(Src[I]);
607 continue;
608 }
609
610 // QUOTED state means that it's reading a token quoted by double quotes.
611 if (State == QUOTED) {
612 if (Src[I] == '"') {
613 State = UNQUOTED;
614 continue;
615 }
616 if (Src[I] == '\\') {
617 I = parseBackslash(Src, I, Token);
618 continue;
619 }
620 Token.push_back(Src[I]);
621 }
622 }
623 // Append the last token after hitting EOF with no whitespace.
624 if (!Token.empty())
625 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000626}
627
628static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
629 TokenizerCallback Tokenizer,
630 SmallVectorImpl<const char *> &NewArgv) {
631 OwningPtr<MemoryBuffer> MemBuf;
632 if (MemoryBuffer::getFile(FName, MemBuf))
633 return false;
634 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
635
636 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
637 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
638 std::string UTF8Buf;
639 if (hasUTF16ByteOrderMark(BufRef)) {
640 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
641 return false;
642 Str = StringRef(UTF8Buf);
643 }
644
645 // Tokenize the contents into NewArgv.
646 Tokenizer(Str, Saver, NewArgv);
647
648 return true;
649}
650
651/// \brief Expand response files on a command line recursively using the given
652/// StringSaver and tokenization strategy.
653bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
654 SmallVectorImpl<const char *> &Argv) {
655 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000656 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000657
658 // Don't cache Argv.size() because it can change.
659 for (unsigned I = 0; I != Argv.size(); ) {
660 const char *Arg = Argv[I];
661 if (Arg[0] != '@') {
662 ++I;
663 continue;
664 }
665
666 // If we have too many response files, leave some unexpanded. This avoids
667 // crashing on self-referential response files.
668 if (RspFiles++ > 20)
669 return false;
670
671 // Replace this response file argument with the tokenization of its
672 // contents. Nested response files are expanded in subsequent iterations.
673 // FIXME: If a nested response file uses a relative path, is it relative to
674 // the cwd of the process or the response file?
675 SmallVector<const char *, 0> ExpandedArgv;
676 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000677 // We couldn't read this file, so we leave it in the argument stream and
678 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000679 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000680 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000681 continue;
682 }
683 Argv.erase(Argv.begin() + I);
684 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
685 }
686 return AllExpanded;
687}
688
689namespace {
690 class StrDupSaver : public StringSaver {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000691 std::vector<char*> Dups;
692 public:
693 ~StrDupSaver() {
694 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
695 I != E; ++I) {
696 char *Dup = *I;
697 free(Dup);
698 }
699 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000700 const char *SaveString(const char *Str) LLVM_OVERRIDE {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000701 char *Dup = strdup(Str);
702 Dups.push_back(Dup);
703 return Dup;
Reid Klecknera73c7782013-07-18 16:52:05 +0000704 }
705 };
Brian Gaekeca782d92003-08-14 22:00:59 +0000706}
707
708/// ParseEnvironmentOptions - An alternative entry point to the
709/// CommandLine library, which allows you to read the program's name
710/// from the caller (as PROGNAME) and its command-line arguments from
711/// an environment variable (whose name is given in ENVVAR).
712///
Chris Lattnera60f3552004-05-06 22:04:31 +0000713void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000714 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000715 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000716 assert(progName && "Program name not specified");
717 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000718
Brian Gaeke497216d2003-08-15 21:05:57 +0000719 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000720 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000721 if (!envValue)
722 return;
723
Brian Gaekeca782d92003-08-14 22:00:59 +0000724 // Get program's "name", which we wouldn't know without the caller
725 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000726 SmallVector<const char *, 20> newArgv;
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000727 StrDupSaver Saver;
728 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000729
730 // Parse the value of the environment variable into a "command line"
731 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000732 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000733 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000734 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000735}
736
David Blaikie0210e972012-02-07 19:36:01 +0000737void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000738 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000739 // Process all registered options.
Chris Lattner131dca92009-09-20 06:18:38 +0000740 SmallVector<Option*, 4> PositionalOpts;
741 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000742 StringMap<Option*> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000743 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000744
Chris Lattner5247f602007-04-06 21:06:55 +0000745 assert((!Opts.empty() || !PositionalOpts.empty()) &&
746 "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000747
748 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000749 SmallVector<const char *, 20> newArgv;
750 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000751 newArgv.push_back(argv[i]);
Reid Klecknera73c7782013-07-18 16:52:05 +0000752 StrDupSaver Saver;
753 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000754 argv = &newArgv[0];
755 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000756
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000757 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencer762a55b2010-12-18 00:19:10 +0000758 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000759 size_t Len = std::min(ProgName.size(), size_t(79));
760 memcpy(ProgramName, ProgName.data(), Len);
761 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000762
Chris Lattner36a57d32001-07-23 17:17:47 +0000763 ProgramOverview = Overview;
764 bool ErrorParsing = false;
765
Chris Lattner5df56c42002-07-22 02:07:59 +0000766 // Check out the positional arguments to collect information about them.
767 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000768
Chris Lattnerd380d842005-08-08 17:25:38 +0000769 // Determine whether or not there are an unlimited number of positionals
770 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000771
Chris Lattner5df56c42002-07-22 02:07:59 +0000772 Option *ConsumeAfterOpt = 0;
773 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000774 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000775 assert(PositionalOpts.size() > 1 &&
776 "Cannot specify cl::ConsumeAfter without a positional argument!");
777 ConsumeAfterOpt = PositionalOpts[0];
778 }
779
780 // Calculate how many positional values are _required_.
781 bool UnboundedFound = false;
Evan Cheng86cb3182008-05-05 18:30:58 +0000782 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000783 i != e; ++i) {
784 Option *Opt = PositionalOpts[i];
785 if (RequiresValue(Opt))
786 ++NumPositionalRequired;
787 else if (ConsumeAfterOpt) {
788 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000789 // unless there is only one positional argument...
790 if (PositionalOpts.size() > 2)
791 ErrorParsing |=
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000792 Opt->error("error - this positional option will never be matched, "
Chris Lattnerd49ea882002-07-22 02:21:57 +0000793 "because it does not Require a value, and a "
794 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000795 } else if (UnboundedFound && !Opt->ArgStr[0]) {
796 // This option does not "require" a value... Make sure this option is
797 // not specified after an option that eats all extra arguments, or this
798 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000799 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000800 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000801 "another positional argument will match an "
802 "unbounded number of values, and this option"
803 " does not require a value!");
804 }
805 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
806 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000807 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000808 }
809
Reid Spencer2027a6f2004-08-13 19:47:30 +0000810 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000811 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000812 //
Chris Lattnerca2552d2009-09-20 00:07:40 +0000813 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000814
Chris Lattner2da046f2003-07-30 17:34:02 +0000815 // If the program has named positional arguments, and the name has been run
816 // across, keep track of which positional argument was named. Otherwise put
817 // the positional args into the PositionalVals list...
818 Option *ActivePositionalArg = 0;
819
Chris Lattner36a57d32001-07-23 17:17:47 +0000820 // Loop over all of the arguments... processing them.
Chris Lattner5df56c42002-07-22 02:07:59 +0000821 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000822 for (int i = 1; i < argc; ++i) {
823 Option *Handler = 0;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000824 Option *NearestHandler = 0;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000825 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000826 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000827 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000828
Chris Lattneraf039c52007-04-12 00:36:29 +0000829 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000830 // option has just been registered or deregistered. This can occur in
831 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000832 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000833 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000834 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000835 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000836 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000837 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000838 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000839
Chris Lattner5df56c42002-07-22 02:07:59 +0000840 // Check to see if this is a positional argument. This argument is
841 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000842 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000843 //
844 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
845 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000846 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000847 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner2da046f2003-07-30 17:34:02 +0000848 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000849 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000850
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000851 if (!PositionalOpts.empty()) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000852 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000853
854 // All of the positional arguments have been fulfulled, give the rest to
855 // the consume after option... if it's specified...
856 //
Misha Brukman10468d82005-04-21 22:55:34 +0000857 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner5df56c42002-07-22 02:07:59 +0000858 ConsumeAfterOpt != 0) {
859 for (++i; i < argc; ++i)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000860 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000861 break; // Handle outside of the argument processing loop...
862 }
863
864 // Delay processing positional arguments until the end...
865 continue;
866 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000867 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
868 !DashDashFound) {
869 DashDashFound = true; // This is the mythical "--"?
870 continue; // Don't try to process it as an argument itself.
871 } else if (ActivePositionalArg &&
872 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
873 // If there is a positional argument eating options, check to see if this
874 // option is another positional argument. If so, treat it as an argument,
875 // otherwise feed it to the eating positional.
Chris Lattner36a57d32001-07-23 17:17:47 +0000876 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000877 // Eat leading dashes.
878 while (!ArgName.empty() && ArgName[0] == '-')
879 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000880
Chris Lattner5247f602007-04-06 21:06:55 +0000881 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000882 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000883 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnera60f3552004-05-06 22:04:31 +0000884 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000885 }
886
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000887 } else { // We start with a '-', must be an argument.
Chris Lattnera60f3552004-05-06 22:04:31 +0000888 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000889 // Eat leading dashes.
890 while (!ArgName.empty() && ArgName[0] == '-')
891 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000892
Chris Lattner5247f602007-04-06 21:06:55 +0000893 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000894
Chris Lattnera60f3552004-05-06 22:04:31 +0000895 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000896 if (Handler == 0)
897 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
898 ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000899
900 // Otherwise, look for the closest available option to report to the user
901 // in the upcoming error.
902 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000903 NearestHandler = LookupNearestOption(ArgName, Opts,
904 NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000905 }
906
907 if (Handler == 0) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000908 if (SinkOpts.empty()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000909 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands142b9ed2010-02-18 14:08:13 +0000910 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000911
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000912 if (NearestHandler) {
913 // If we know a near match, report it as well.
914 errs() << ProgramName << ": Did you mean '-"
915 << NearestHandlerString << "'?\n";
916 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000917
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000918 ErrorParsing = true;
919 } else {
Chris Lattner131dca92009-09-20 06:18:38 +0000920 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000921 E = SinkOpts.end(); I != E ; ++I)
922 (*I)->addOccurrence(i, "", argv[i]);
923 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000924 continue;
925 }
926
Chris Lattner2da046f2003-07-30 17:34:02 +0000927 // If this is a named positional argument, just remember that it is the
928 // active one...
929 if (Handler->getFormattingFlag() == cl::Positional)
930 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000931 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000932 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000933 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000934
Chris Lattner5df56c42002-07-22 02:07:59 +0000935 // Check and handle positional arguments now...
936 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000937 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000938 << ": Not enough positional command line arguments specified!\n"
939 << "Must specify at least " << NumPositionalRequired
Duncan Sands142b9ed2010-02-18 14:08:13 +0000940 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000941
Chris Lattner5df56c42002-07-22 02:07:59 +0000942 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000943 } else if (!HasUnlimitedPositionals &&
944 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000945 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000946 << ": Too many positional arguments specified!\n"
947 << "Can specify at most " << PositionalOpts.size()
Duncan Sands142b9ed2010-02-18 14:08:13 +0000948 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +0000949 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +0000950
951 } else if (ConsumeAfterOpt == 0) {
Chris Lattnere7c1e212009-09-20 05:03:30 +0000952 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +0000953 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
954 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000955 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +0000956 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000957 PositionalVals[ValNo].second);
958 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000959 --NumPositionalRequired; // We fulfilled our duty...
960 }
961
962 // If we _can_ give this option more arguments, do so now, as long as we
963 // do not give it values that others need. 'Done' controls whether the
964 // option even _WANTS_ any more.
965 //
Misha Brukman069e6b52003-07-10 16:49:51 +0000966 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner5df56c42002-07-22 02:07:59 +0000967 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000968 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000969 case cl::Optional:
970 Done = true; // Optional arguments want _at most_ one value
971 // FALL THROUGH
972 case cl::ZeroOrMore: // Zero or more will take all they can get...
973 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +0000974 ProvidePositionalOption(PositionalOpts[i],
975 PositionalVals[ValNo].first,
976 PositionalVals[ValNo].second);
977 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000978 break;
979 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000980 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner5df56c42002-07-22 02:07:59 +0000981 "positional argument processing!");
982 }
983 }
Chris Lattnere81c4092001-10-27 05:54:17 +0000984 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000985 } else {
986 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
987 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +0000988 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000989 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000990 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000991 PositionalVals[ValNo].first,
992 PositionalVals[ValNo].second);
993 ValNo++;
994 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000995
996 // Handle the case where there is just one positional option, and it's
997 // optional. In this case, we want to give JUST THE FIRST option to the
998 // positional option and keep the rest for the consume after. The above
999 // loop would have assigned no values to positional options in this case.
1000 //
Reid Spencer2027a6f2004-08-13 19:47:30 +00001001 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001002 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001003 PositionalVals[ValNo].first,
1004 PositionalVals[ValNo].second);
1005 ValNo++;
1006 }
Misha Brukman10468d82005-04-21 22:55:34 +00001007
Chris Lattner5df56c42002-07-22 02:07:59 +00001008 // Handle over all of the rest of the arguments to the
1009 // cl::ConsumeAfter command line option...
1010 for (; ValNo != PositionalVals.size(); ++ValNo)
1011 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001012 PositionalVals[ValNo].first,
1013 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001014 }
1015
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001016 // Loop over args and make sure all required args are specified!
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001017 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanc18333a2003-07-10 17:05:26 +00001018 E = Opts.end(); I != E; ++I) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001019 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001020 case Required:
1021 case OneOrMore:
Misha Brukman069e6b52003-07-10 16:49:51 +00001022 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001023 I->second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001024 ErrorParsing = true;
1025 }
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001026 // Fall through
1027 default:
1028 break;
1029 }
1030 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001031
Rafael Espindolacf14a382010-11-19 21:14:29 +00001032 // Now that we know if -debug is specified, we can use it.
1033 // Note that if ReadResponseFiles == true, this must be done before the
1034 // memory allocated for the expanded command line is free()d below.
1035 DEBUG(dbgs() << "Args: ";
1036 for (int i = 0; i < argc; ++i)
1037 dbgs() << argv[i] << ' ';
1038 dbgs() << '\n';
1039 );
1040
Chris Lattner5df56c42002-07-22 02:07:59 +00001041 // Free all of the memory allocated to the map. Command line options may only
1042 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001043 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001044 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001045 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001046
1047 // If we had an error processing our arguments, don't let the program execute
1048 if (ErrorParsing) exit(1);
1049}
1050
1051//===----------------------------------------------------------------------===//
1052// Option Base class implementation
1053//
Chris Lattner36a57d32001-07-23 17:17:47 +00001054
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001055bool Option::error(const Twine &Message, StringRef ArgName) {
1056 if (ArgName.data() == 0) ArgName = ArgStr;
1057 if (ArgName.empty())
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001058 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001059 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001060 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001061
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001062 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001063 return true;
1064}
1065
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001066bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001067 StringRef Value, bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001068 if (!MultiArg)
1069 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001070
Misha Brukman069e6b52003-07-10 16:49:51 +00001071 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001072 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001073 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001074 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001075 break;
1076 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001077 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001078 return error("must occur exactly one time!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001079 // Fall through
1080 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001081 case ZeroOrMore:
1082 case ConsumeAfter: break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001083 }
1084
Reid Spencer2027a6f2004-08-13 19:47:30 +00001085 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001086}
1087
Chris Lattner5df56c42002-07-22 02:07:59 +00001088
1089// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1090// has been specified yet.
1091//
1092static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1093 if (O.ValueStr[0] == 0) return DefaultMsg;
1094 return O.ValueStr;
1095}
1096
1097//===----------------------------------------------------------------------===//
1098// cl::alias class implementation
1099//
1100
Chris Lattner36a57d32001-07-23 17:17:47 +00001101// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001102size_t alias::getOptionWidth() const {
Chris Lattner36a57d32001-07-23 17:17:47 +00001103 return std::strlen(ArgStr)+6;
1104}
1105
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001106static void printHelpStr(StringRef HelpStr, size_t Indent,
1107 size_t FirstLineIndentedBy) {
1108 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1109 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1110 while (!Split.second.empty()) {
1111 Split = Split.second.split('\n');
1112 outs().indent(Indent) << Split.first << "\n";
1113 }
1114}
1115
Chris Lattner1b7a5152006-04-28 05:36:25 +00001116// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001117void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001118 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001119 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001120}
1121
Chris Lattner36a57d32001-07-23 17:17:47 +00001122//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001123// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001124//
1125
Chris Lattnerb4101b12002-08-07 18:36:37 +00001126// basic_parser implementation
1127//
1128
1129// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001130size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1131 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001132 if (const char *ValName = getValueName())
1133 Len += std::strlen(getValueStr(O, ValName))+3;
1134
1135 return Len + 6;
1136}
1137
Misha Brukman10468d82005-04-21 22:55:34 +00001138// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001139// to-be-maintained width is specified.
1140//
1141void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001142 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001143 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001144
1145 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001146 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001147
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001148 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001149}
1150
Andrew Trick12004012011-04-05 18:54:36 +00001151void basic_parser_impl::printOptionName(const Option &O,
1152 size_t GlobalWidth) const {
1153 outs() << " -" << O.ArgStr;
1154 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1155}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001156
1157
Chris Lattner5df56c42002-07-22 02:07:59 +00001158// parser<bool> implementation
1159//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001160bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001161 StringRef Arg, bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001162 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001163 Arg == "1") {
1164 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001165 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001166 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001167
Chris Lattneraecd74d2009-09-19 18:55:05 +00001168 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1169 Value = false;
1170 return false;
1171 }
1172 return O.error("'" + Arg +
1173 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001174}
1175
Dale Johannesen82810c82007-05-22 17:14:46 +00001176// parser<boolOrDefault> implementation
1177//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001178bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001179 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001180 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1181 Arg == "1") {
1182 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001183 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001184 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001185 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1186 Value = BOU_FALSE;
1187 return false;
1188 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001189
Chris Lattneraecd74d2009-09-19 18:55:05 +00001190 return O.error("'" + Arg +
1191 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001192}
1193
Chris Lattner5df56c42002-07-22 02:07:59 +00001194// parser<int> implementation
1195//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001196bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001197 StringRef Arg, int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001198 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001199 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001200 return false;
1201}
1202
Chris Lattner719c7152003-06-28 15:47:20 +00001203// parser<unsigned> implementation
1204//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001205bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001206 StringRef Arg, unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001207
1208 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001209 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001210 return false;
1211}
1212
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001213// parser<unsigned long long> implementation
1214//
1215bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1216 StringRef Arg, unsigned long long &Value){
1217
1218 if (Arg.getAsInteger(0, Value))
1219 return O.error("'" + Arg + "' value invalid for uint argument!");
1220 return false;
1221}
1222
Chris Lattnerb4101b12002-08-07 18:36:37 +00001223// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001224//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001225static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001226 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1227 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001228 char *End;
1229 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001230 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001231 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001232 return false;
1233}
1234
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001235bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001236 StringRef Arg, double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001237 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001238}
1239
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001240bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001241 StringRef Arg, float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001242 double dVal;
1243 if (parseDouble(O, Arg, dVal))
1244 return true;
1245 Val = (float)dVal;
1246 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001247}
1248
1249
Chris Lattner5df56c42002-07-22 02:07:59 +00001250
1251// generic_parser_base implementation
1252//
1253
Chris Lattner494c0b02002-07-23 17:15:12 +00001254// findOption - Return the option number corresponding to the specified
1255// argument string. If the option is not found, getNumOptions() is returned.
1256//
1257unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001258 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001259
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001260 for (unsigned i = 0; i != e; ++i) {
1261 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001262 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001263 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001264 return e;
1265}
1266
1267
Chris Lattner5df56c42002-07-22 02:07:59 +00001268// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001269size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001270 if (O.hasArgStr()) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001271 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001272 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001273 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001274 return Size;
1275 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001276 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001277 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001278 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001279 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001280 }
1281}
1282
Misha Brukman10468d82005-04-21 22:55:34 +00001283// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001284// to-be-maintained width is specified.
1285//
1286void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001287 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001288 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001289 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001290 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001291
Chris Lattner5df56c42002-07-22 02:07:59 +00001292 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001293 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001294 outs() << " =" << getOption(i);
1295 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001296 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001297 } else {
1298 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001299 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001300 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001301 const char *Option = getOption(i);
1302 outs() << " -" << Option;
1303 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001304 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001305 }
1306}
1307
Andrew Trick12004012011-04-05 18:54:36 +00001308static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1309
1310// printGenericOptionDiff - Print the value of this option and it's default.
1311//
1312// "Generic" options have each value mapped to a name.
1313void generic_parser_base::
1314printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1315 const GenericOptionValue &Default,
1316 size_t GlobalWidth) const {
1317 outs() << " -" << O.ArgStr;
1318 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1319
1320 unsigned NumOpts = getNumOptions();
1321 for (unsigned i = 0; i != NumOpts; ++i) {
1322 if (Value.compare(getOptionValue(i)))
1323 continue;
1324
1325 outs() << "= " << getOption(i);
1326 size_t L = std::strlen(getOption(i));
1327 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1328 outs().indent(NumSpaces) << " (default: ";
1329 for (unsigned j = 0; j != NumOpts; ++j) {
1330 if (Default.compare(getOptionValue(j)))
1331 continue;
1332 outs() << getOption(j);
1333 break;
1334 }
1335 outs() << ")\n";
1336 return;
1337 }
1338 outs() << "= *unknown option value*\n";
1339}
1340
1341// printOptionDiff - Specializations for printing basic value types.
1342//
1343#define PRINT_OPT_DIFF(T) \
1344 void parser<T>:: \
1345 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1346 size_t GlobalWidth) const { \
1347 printOptionName(O, GlobalWidth); \
1348 std::string Str; \
1349 { \
1350 raw_string_ostream SS(Str); \
1351 SS << V; \
1352 } \
1353 outs() << "= " << Str; \
1354 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1355 outs().indent(NumSpaces) << " (default: "; \
1356 if (D.hasValue()) \
1357 outs() << D.getValue(); \
1358 else \
1359 outs() << "*no default*"; \
1360 outs() << ")\n"; \
1361 } \
1362
Frits van Bommel87e33672011-04-06 12:29:56 +00001363PRINT_OPT_DIFF(bool)
1364PRINT_OPT_DIFF(boolOrDefault)
1365PRINT_OPT_DIFF(int)
1366PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001367PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001368PRINT_OPT_DIFF(double)
1369PRINT_OPT_DIFF(float)
1370PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001371
1372void parser<std::string>::
1373printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1374 size_t GlobalWidth) const {
1375 printOptionName(O, GlobalWidth);
1376 outs() << "= " << V;
1377 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1378 outs().indent(NumSpaces) << " (default: ";
1379 if (D.hasValue())
1380 outs() << D.getValue();
1381 else
1382 outs() << "*no default*";
1383 outs() << ")\n";
1384}
1385
1386// Print a placeholder for options that don't yet support printOptionDiff().
1387void basic_parser_impl::
1388printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1389 printOptionName(O, GlobalWidth);
1390 outs() << "= *cannot print option value*\n";
1391}
Chris Lattner36a57d32001-07-23 17:17:47 +00001392
1393//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001394// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001395//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001396
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001397static int OptNameCompare(const void *LHS, const void *RHS) {
1398 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001399
Duncan Sands79d793e2012-03-12 10:51:06 +00001400 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001401}
1402
Andrew Trick12004012011-04-05 18:54:36 +00001403// Copy Options into a vector so we can sort them as we like.
1404static void
1405sortOpts(StringMap<Option*> &OptMap,
1406 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1407 bool ShowHidden) {
1408 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1409
1410 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1411 I != E; ++I) {
1412 // Ignore really-hidden options.
1413 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1414 continue;
1415
1416 // Unless showhidden is set, ignore hidden flags.
1417 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1418 continue;
1419
1420 // If we've already seen this option, don't add it to the list again.
1421 if (!OptionSet.insert(I->second))
1422 continue;
1423
1424 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1425 I->second));
1426 }
1427
1428 // Sort the options list alphabetically.
1429 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1430}
1431
Chris Lattner36a57d32001-07-23 17:17:47 +00001432namespace {
1433
Chris Lattner5df56c42002-07-22 02:07:59 +00001434class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001435protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001436 const bool ShowHidden;
Andrew Trick0537a982013-05-06 21:56:23 +00001437 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1438 // Print the options. Opts is assumed to be alphabetically sorted.
1439 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1440 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1441 Opts[i].second->printOptionInfo(MaxArgLen);
1442 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001443
Chris Lattner5df56c42002-07-22 02:07:59 +00001444public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001445 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001446 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001447
Andrew Trick0537a982013-05-06 21:56:23 +00001448 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001449 void operator=(bool Value) {
1450 if (Value == false) return;
1451
Chris Lattner5247f602007-04-06 21:06:55 +00001452 // Get all the options.
Chris Lattner131dca92009-09-20 06:18:38 +00001453 SmallVector<Option*, 4> PositionalOpts;
1454 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001455 StringMap<Option*> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001456 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001457
Andrew Trick0537a982013-05-06 21:56:23 +00001458 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001459 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001460
1461 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001462 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001463
Chris Lattner471ba482009-08-23 08:43:55 +00001464 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001465
Chris Lattner8111c592006-10-04 21:52:35 +00001466 // Print out the positional options.
Chris Lattner5df56c42002-07-22 02:07:59 +00001467 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001468 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001469 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1470 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001471
Evan Cheng86cb3182008-05-05 18:30:58 +00001472 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001473 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001474 outs() << " --" << PositionalOpts[i]->ArgStr;
1475 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001476 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001477
1478 // Print the consume after option info if it exists...
Chris Lattner471ba482009-08-23 08:43:55 +00001479 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001480
Chris Lattner471ba482009-08-23 08:43:55 +00001481 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001482
1483 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001484 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001485 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001486 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001487
Chris Lattner471ba482009-08-23 08:43:55 +00001488 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001489 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001490
Chris Lattner37bcd992004-11-19 17:08:15 +00001491 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001492 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001493 E = MoreHelp->end();
1494 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001495 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001496 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001497
Reid Spencer5e554702004-11-16 06:11:52 +00001498 // Halt the program since help information was printed
Chris Lattner5df56c42002-07-22 02:07:59 +00001499 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001500 }
1501};
Andrew Trick0537a982013-05-06 21:56:23 +00001502
1503class CategorizedHelpPrinter : public HelpPrinter {
1504public:
1505 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1506
1507 // Helper function for printOptions().
1508 // It shall return true if A's name should be lexographically
1509 // ordered before B's name. It returns false otherwise.
1510 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001511 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001512 }
1513
1514 // Make sure we inherit our base class's operator=()
1515 using HelpPrinter::operator= ;
1516
1517protected:
1518 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1519 std::vector<OptionCategory *> SortedCategories;
1520 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1521
Alp Tokercb402912014-01-24 17:20:08 +00001522 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001523 // sorting.
1524 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1525 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001526 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001527 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001528 }
Andrew Trick0537a982013-05-06 21:56:23 +00001529
1530 // Sort the different option categories alphabetically.
1531 assert(SortedCategories.size() > 0 && "No option categories registered!");
1532 std::sort(SortedCategories.begin(), SortedCategories.end(),
1533 OptionCategoryCompare);
1534
1535 // Create map to empty vectors.
1536 for (std::vector<OptionCategory *>::const_iterator
1537 I = SortedCategories.begin(),
1538 E = SortedCategories.end();
1539 I != E; ++I)
1540 CategorizedOptions[*I] = std::vector<Option *>();
1541
1542 // Walk through pre-sorted options and assign into categories.
1543 // Because the options are already alphabetically sorted the
1544 // options within categories will also be alphabetically sorted.
1545 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1546 Option *Opt = Opts[I].second;
1547 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1548 "Option has an unregistered category");
1549 CategorizedOptions[Opt->Category].push_back(Opt);
1550 }
1551
1552 // Now do printing.
1553 for (std::vector<OptionCategory *>::const_iterator
1554 Category = SortedCategories.begin(),
1555 E = SortedCategories.end();
1556 Category != E; ++Category) {
1557 // Hide empty categories for -help, but show for -help-hidden.
1558 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1559 if (!ShowHidden && IsEmptyCategory)
1560 continue;
1561
1562 // Print category information.
1563 outs() << "\n";
1564 outs() << (*Category)->getName() << ":\n";
1565
1566 // Check if description is set.
1567 if ((*Category)->getDescription() != 0)
1568 outs() << (*Category)->getDescription() << "\n\n";
1569 else
1570 outs() << "\n";
1571
1572 // When using -help-hidden explicitly state if the category has no
1573 // options associated with it.
1574 if (IsEmptyCategory) {
1575 outs() << " This option category has no options.\n";
1576 continue;
1577 }
1578 // Loop over the options in the category and print.
1579 for (std::vector<Option *>::const_iterator
1580 Opt = CategorizedOptions[*Category].begin(),
1581 E = CategorizedOptions[*Category].end();
1582 Opt != E; ++Opt)
1583 (*Opt)->printOptionInfo(MaxArgLen);
1584 }
1585 }
1586};
1587
1588// This wraps the Uncategorizing and Categorizing printers and decides
1589// at run time which should be invoked.
1590class HelpPrinterWrapper {
1591private:
1592 HelpPrinter &UncategorizedPrinter;
1593 CategorizedHelpPrinter &CategorizedPrinter;
1594
1595public:
1596 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1597 CategorizedHelpPrinter &CategorizedPrinter) :
1598 UncategorizedPrinter(UncategorizedPrinter),
1599 CategorizedPrinter(CategorizedPrinter) { }
1600
1601 // Invoke the printer.
1602 void operator=(bool Value);
1603};
1604
Chris Lattneradb19d62006-10-12 22:09:17 +00001605} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001606
Andrew Trick0537a982013-05-06 21:56:23 +00001607// Declare the four HelpPrinter instances that are used to print out help, or
1608// help-hidden as an uncategorized list or in categories.
1609static HelpPrinter UncategorizedNormalPrinter(false);
1610static HelpPrinter UncategorizedHiddenPrinter(true);
1611static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1612static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1613
1614
1615// Declare HelpPrinter wrappers that will decide whether or not to invoke
1616// a categorizing help printer
1617static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1618 CategorizedNormalPrinter);
1619static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1620 CategorizedHiddenPrinter);
1621
1622// Define uncategorized help printers.
1623// -help-list is hidden by default because if Option categories are being used
1624// then -help behaves the same as -help-list.
1625static cl::opt<HelpPrinter, true, parser<bool> >
1626HLOp("help-list",
1627 cl::desc("Display list of available options (-help-list-hidden for more)"),
1628 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001629
Chris Lattneradb19d62006-10-12 22:09:17 +00001630static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trick0537a982013-05-06 21:56:23 +00001631HLHOp("help-list-hidden",
1632 cl::desc("Display list of all available options"),
1633 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1634
1635// Define uncategorized/categorized help printers. These printers change their
1636// behaviour at runtime depending on whether one or more Option categories have
1637// been declared.
1638static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands142b9ed2010-02-18 14:08:13 +00001639HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trick0537a982013-05-06 21:56:23 +00001640 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001641
Andrew Trick0537a982013-05-06 21:56:23 +00001642static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001643HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trick0537a982013-05-06 21:56:23 +00001644 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1645
1646
Chris Lattner36a57d32001-07-23 17:17:47 +00001647
Andrew Trick12004012011-04-05 18:54:36 +00001648static cl::opt<bool>
1649PrintOptions("print-options",
1650 cl::desc("Print non-default options after command line parsing"),
1651 cl::Hidden, cl::init(false));
1652
1653static cl::opt<bool>
1654PrintAllOptions("print-all-options",
1655 cl::desc("Print all option values after command line parsing"),
1656 cl::Hidden, cl::init(false));
1657
Andrew Trick0537a982013-05-06 21:56:23 +00001658void HelpPrinterWrapper::operator=(bool Value) {
1659 if (Value == false)
1660 return;
1661
1662 // Decide which printer to invoke. If more than one option category is
1663 // registered then it is useful to show the categorized help instead of
1664 // uncategorized help.
1665 if (RegisteredOptionCategories->size() > 1) {
1666 // unhide -help-list option so user can have uncategorized output if they
1667 // want it.
1668 HLOp.setHiddenFlag(NotHidden);
1669
1670 CategorizedPrinter = true; // Invoke categorized printer
1671 }
1672 else
1673 UncategorizedPrinter = true; // Invoke uncategorized printer
1674}
1675
Andrew Trick12004012011-04-05 18:54:36 +00001676// Print the value of each option.
1677void cl::PrintOptionValues() {
1678 if (!PrintOptions && !PrintAllOptions) return;
1679
1680 // Get all the options.
1681 SmallVector<Option*, 4> PositionalOpts;
1682 SmallVector<Option*, 4> SinkOpts;
1683 StringMap<Option*> OptMap;
1684 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1685
1686 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1687 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1688
1689 // Compute the maximum argument length...
1690 size_t MaxArgLen = 0;
1691 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1692 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1693
1694 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1695 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1696}
1697
Chris Lattneradb19d62006-10-12 22:09:17 +00001698static void (*OverrideVersionPrinter)() = 0;
Reid Spencerb3171672006-06-05 16:22:56 +00001699
Chandler Carruthea7e5522011-07-22 07:50:40 +00001700static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1701
Chris Lattneradb19d62006-10-12 22:09:17 +00001702namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001703class VersionPrinter {
1704public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001705 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001706 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001707 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001708 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001709#ifdef LLVM_VERSION_INFO
Chris Lattner131dca92009-09-20 06:18:38 +00001710 OS << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001711#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001712 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001713#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001714 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001715#else
Chris Lattner131dca92009-09-20 06:18:38 +00001716 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001717#endif
1718#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001719 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001720#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001721 std::string CPU = sys::getHostCPUName();
Benjamin Kramer713fd352009-11-17 17:57:04 +00001722 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001723 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001724#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001725 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001726#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001727 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001728 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001729 }
1730 void operator=(bool OptionWasSpecified) {
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001731 if (!OptionWasSpecified) return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001732
Chandler Carruthea7e5522011-07-22 07:50:40 +00001733 if (OverrideVersionPrinter != 0) {
1734 (*OverrideVersionPrinter)();
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001735 exit(1);
Reid Spencerb3171672006-06-05 16:22:56 +00001736 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001737 print();
1738
1739 // Iterate over any registered extra printers and call them to add further
1740 // information.
1741 if (ExtraVersionPrinters != 0) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001742 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001743 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1744 E = ExtraVersionPrinters->end();
1745 I != E; ++I)
1746 (*I)();
1747 }
1748
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001749 exit(1);
Reid Spencerb3171672006-06-05 16:22:56 +00001750 }
1751};
Chris Lattneradb19d62006-10-12 22:09:17 +00001752} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001753
1754
Reid Spencerff6cc122004-08-04 00:36:06 +00001755// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001756static VersionPrinter VersionPrinterInstance;
1757
1758static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001759VersOp("version", cl::desc("Display the version of this program"),
Reid Spencerff6cc122004-08-04 00:36:06 +00001760 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1761
Reid Spencer5e554702004-11-16 06:11:52 +00001762// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001763void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1764 // This looks weird, but it actually prints the help message. The Printers are
1765 // types of HelpPrinter and the help gets printed when its operator= is
1766 // invoked. That's because the "normal" usages of the help printer is to be
1767 // assigned true/false depending on whether -help or -help-hidden was given or
1768 // not. Since we're circumventing that we have to make it look like -help or
1769 // -help-hidden were given, so we assign true.
1770
1771 if (!Hidden && !Categorized)
1772 UncategorizedNormalPrinter = true;
1773 else if (!Hidden && Categorized)
1774 CategorizedNormalPrinter = true;
1775 else if (Hidden && !Categorized)
1776 UncategorizedHiddenPrinter = true;
1777 else
1778 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001779}
Reid Spencerb3171672006-06-05 16:22:56 +00001780
Devang Patel9eb2caae2007-02-01 01:43:37 +00001781/// Utility function for printing version number.
1782void cl::PrintVersionMessage() {
1783 VersionPrinterInstance.print();
1784}
1785
Reid Spencerb3171672006-06-05 16:22:56 +00001786void cl::SetVersionPrinter(void (*func)()) {
1787 OverrideVersionPrinter = func;
1788}
Chandler Carruthea7e5522011-07-22 07:50:40 +00001789
1790void cl::AddExtraVersionPrinter(void (*func)()) {
1791 if (ExtraVersionPrinters == 0)
1792 ExtraVersionPrinters = new std::vector<void (*)()>;
1793
1794 ExtraVersionPrinters->push_back(func);
1795}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001796
1797void cl::getRegisteredOptions(StringMap<Option*> &Map)
1798{
1799 // Get all the options.
1800 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1801 SmallVector<Option*, 4> SinkOpts; //NOT USED
1802 assert(Map.size() == 0 && "StringMap must be empty");
1803 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1804 return;
1805}