blob: b3c2614ec9648484922d851f884b0cc5a511066f [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 Lattner41f8b0b2009-09-20 05:12:14 +000021#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000023#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000024#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000025#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000026#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/Host.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Support/system_error.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000037#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000038using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000039using namespace cl;
40
Chris Lattner3e5d60f2006-08-27 12:45:47 +000041//===----------------------------------------------------------------------===//
42// Template instantiations and anchors.
43//
Douglas Gregor7baad732009-11-25 06:04:18 +000044namespace llvm { namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000045TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000046TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000047TEMPLATE_INSTANTIATION(class basic_parser<int>);
48TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000049TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000050TEMPLATE_INSTANTIATION(class basic_parser<double>);
51TEMPLATE_INSTANTIATION(class basic_parser<float>);
52TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000053TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000054
55TEMPLATE_INSTANTIATION(class opt<unsigned>);
56TEMPLATE_INSTANTIATION(class opt<int>);
57TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000058TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000059TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor7baad732009-11-25 06:04:18 +000060} } // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000061
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000062// Pin the vtables to this file.
63void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000064void OptionValue<boolOrDefault>::anchor() {}
65void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000066void Option::anchor() {}
67void basic_parser_impl::anchor() {}
68void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000069void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000070void parser<int>::anchor() {}
71void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000072void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000073void parser<double>::anchor() {}
74void parser<float>::anchor() {}
75void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000076void parser<char>::anchor() {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000077void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000078
79//===----------------------------------------------------------------------===//
80
Chris Lattner5af1cbc2006-10-13 00:06:24 +000081// Globals for name and overview of program. Program name is not a string to
82// avoid static ctor/dtor issues.
83static char ProgramName[80] = "<premain>";
Reid Spencer9501b9b2004-09-01 04:41:28 +000084static const char *ProgramOverview = 0;
85
Chris Lattner37bcd992004-11-19 17:08:15 +000086// This collects additional help to be printed.
Chris Lattner8111c592006-10-04 21:52:35 +000087static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000088
Chris Lattner8111c592006-10-04 21:52:35 +000089extrahelp::extrahelp(const char *Help)
Chris Lattner37bcd992004-11-19 17:08:15 +000090 : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000091 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000092}
93
Chris Lattneraf039c52007-04-12 00:36:29 +000094static bool OptionListChanged = false;
95
96// MarkOptionsChanged - Internal helper function.
97void cl::MarkOptionsChanged() {
98 OptionListChanged = true;
99}
100
Chris Lattner5247f602007-04-06 21:06:55 +0000101/// RegisteredOptionList - This is the list of the command line options that
102/// have statically constructed themselves.
103static Option *RegisteredOptionList = 0;
104
105void Option::addArgument() {
106 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000107
Chris Lattner5247f602007-04-06 21:06:55 +0000108 NextRegistered = RegisteredOptionList;
109 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000110 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000111}
112
Jordan Rosec25b0c72014-01-29 18:54:17 +0000113void Option::removeArgument() {
114 assert(NextRegistered != 0 && "argument never registered");
115 assert(RegisteredOptionList == this && "argument is not the last registered");
116 RegisteredOptionList = NextRegistered;
117 MarkOptionsChanged();
118}
119
Andrew Trick0537a982013-05-06 21:56:23 +0000120// This collects the different option categories that have been registered.
121typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
122static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
123
124// Initialise the general option category.
125OptionCategory llvm::cl::GeneralCategory("General options");
126
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000127void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000128 assert(std::count_if(RegisteredOptionCategories->begin(),
129 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000130 [this](const OptionCategory *Category) {
131 return getName() == Category->getName();
132 }) == 0 && "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000133
Andrew Trick0537a982013-05-06 21:56:23 +0000134 RegisteredOptionCategories->insert(this);
135}
Chris Lattneraf039c52007-04-12 00:36:29 +0000136
Chris Lattner5df56c42002-07-22 02:07:59 +0000137//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000138// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000139//
140
Chris Lattner5247f602007-04-06 21:06:55 +0000141/// GetOptionInfo - Scan the list of registered options, turning them into data
142/// structures that are easier to handle.
Chris Lattner131dca92009-09-20 06:18:38 +0000143static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
144 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000145 StringMap<Option*> &OptionsMap) {
Chris Lattner56efff07f2009-09-20 06:21:43 +0000146 SmallVector<const char*, 16> OptionNames;
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000147 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000148 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
149 // If this option wants to handle multiple option names, get the full set.
150 // This handles enum options like "-O1 -O2" etc.
151 O->getExtraOptionNames(OptionNames);
152 if (O->ArgStr[0])
153 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000154
Chris Lattner5247f602007-04-06 21:06:55 +0000155 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000156 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000157 // Add argument to the argument map!
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000158 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000159 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijmanc9c67152008-05-30 13:26:11 +0000160 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner5247f602007-04-06 21:06:55 +0000161 }
162 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000163
Chris Lattner5247f602007-04-06 21:06:55 +0000164 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000165
Chris Lattner5247f602007-04-06 21:06:55 +0000166 // Remember information about positional options.
167 if (O->getFormattingFlag() == cl::Positional)
168 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000169 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000170 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000171 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000172 if (CAOpt)
Chris Lattner5247f602007-04-06 21:06:55 +0000173 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000174 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000175 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000176 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000177
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000178 if (CAOpt)
179 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000180
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000181 // Make sure that they are in order of registration not backwards.
182 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattner1f790af2002-07-29 20:58:42 +0000183}
184
Chris Lattner5247f602007-04-06 21:06:55 +0000185
Chris Lattner2031b022007-04-05 21:58:17 +0000186/// LookupOption - Lookup the option specified by the specified option on the
187/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000188/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000189static Option *LookupOption(StringRef &Arg, StringRef &Value,
190 const StringMap<Option*> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000191 // Reject all dashes.
192 if (Arg.empty()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000193
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000194 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000195
Chris Lattner0a40a972009-09-20 01:53:12 +0000196 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000197 if (EqualPos == StringRef::npos) {
198 // Look up the option.
199 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
200 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000201 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000202
Chris Lattnere7c1e212009-09-20 05:03:30 +0000203 // If the argument before the = is a valid option name, we match. If not,
204 // return Arg unmolested.
205 StringMap<Option*>::const_iterator I =
206 OptionsMap.find(Arg.substr(0, EqualPos));
207 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000208
Chris Lattnere7c1e212009-09-20 05:03:30 +0000209 Value = Arg.substr(EqualPos+1);
210 Arg = Arg.substr(0, EqualPos);
211 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000212}
213
Daniel Dunbarf4132132011-01-18 01:59:24 +0000214/// LookupNearestOption - Lookup the closest match to the option specified by
215/// the specified option on the command line. If there is a value specified
216/// (after an equal sign) return that as well. This assumes that leading dashes
217/// have already been stripped.
218static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000219 const StringMap<Option*> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000220 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000221 // Reject all dashes.
222 if (Arg.empty()) return 0;
223
224 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000225 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
226 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
227 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000228
229 // Find the closest match.
230 Option *Best = 0;
231 unsigned BestDistance = 0;
232 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
233 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000234 Option *O = it->second;
235 SmallVector<const char*, 16> OptionNames;
236 O->getExtraOptionNames(OptionNames);
237 if (O->ArgStr[0])
238 OptionNames.push_back(O->ArgStr);
239
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000240 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
241 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000242 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
243 StringRef Name = OptionNames[i];
244 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000245 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000246 if (!Best || Distance < BestDistance) {
247 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000248 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000249 if (RHS.empty() || !PermitValue)
250 NearestString = OptionNames[i];
251 else
252 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000253 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000254 }
255 }
256
257 return Best;
258}
259
Alp Tokercb402912014-01-24 17:20:08 +0000260/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
261/// that does special handling of cl::CommaSeparated options.
262static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
263 StringRef ArgName, StringRef Value,
264 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000265 // Check to see if this option accepts a comma separated list of values. If
266 // it does, we have to split up the value into multiple values.
267 if (Handler->getMiscFlags() & CommaSeparated) {
268 StringRef Val(Value);
269 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000270
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000271 while (Pos != StringRef::npos) {
272 // Process the portion before the comma.
273 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
274 return true;
275 // Erase the portion before the comma, AND the comma.
276 Val = Val.substr(Pos+1);
277 Value.substr(Pos+1); // Increment the original value pointer as well.
278 // Check for another comma.
279 Pos = Val.find(',');
280 }
281
282 Value = Val;
283 }
284
285 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
286 return true;
287
288 return false;
289}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000290
Chris Lattner40fef802009-09-20 01:49:31 +0000291/// ProvideOption - For Value, this differentiates between an empty value ("")
292/// and a null value (StringRef()). The later is accepted for arguments that
293/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000294static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000295 StringRef Value, int argc,
296 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000297 // Is this a multi-argument option?
298 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
299
Chris Lattnere81c4092001-10-27 05:54:17 +0000300 // Enforce value requirements
301 switch (Handler->getValueExpectedFlag()) {
302 case ValueRequired:
Chris Lattner40fef802009-09-20 01:49:31 +0000303 if (Value.data() == 0) { // No value specified?
Chris Lattnerca2552d2009-09-20 00:07:40 +0000304 if (i+1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000305 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000306 // Steal the next argument, like for '-o filename'
307 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000308 }
309 break;
310 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000311 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000312 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000313 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000314
Chris Lattner40fef802009-09-20 01:49:31 +0000315 if (Value.data())
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000316 return Handler->error("does not allow a value! '" +
Chris Lattneraecd74d2009-09-19 18:55:05 +0000317 Twine(Value) + "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000318 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000319 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000320 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000321 }
322
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000323 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000324 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000325 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000326
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000327 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000328 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000329
Chris Lattner40fef802009-09-20 01:49:31 +0000330 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000331 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000332 return true;
333 --NumAdditionalVals;
334 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000335 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000336
337 while (NumAdditionalVals > 0) {
Chris Lattneraecd74d2009-09-19 18:55:05 +0000338 if (i+1 >= argc)
339 return Handler->error("not enough values!");
340 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000341
Alp Tokercb402912014-01-24 17:20:08 +0000342 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000343 return true;
344 MultiArg = true;
345 --NumAdditionalVals;
346 }
347 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000348}
349
Chris Lattnerca2552d2009-09-20 00:07:40 +0000350static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000351 int Dummy = i;
Chris Lattner40fef802009-09-20 01:49:31 +0000352 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000353}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000354
Chris Lattner5df56c42002-07-22 02:07:59 +0000355
356// Option predicates...
357static inline bool isGrouping(const Option *O) {
358 return O->getFormattingFlag() == cl::Grouping;
359}
360static inline bool isPrefixedOrGrouping(const Option *O) {
361 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
362}
363
364// getOptionPred - Check to see if there are any options that satisfy the
365// specified predicate with names that are the prefixes in Name. This is
366// checked by progressively stripping characters off of the name, checking to
367// see if there options that satisfy the predicate. If we find one, return it,
368// otherwise return null.
369//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000370static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner5247f602007-04-06 21:06:55 +0000371 bool (*Pred)(const Option*),
Chris Lattnere7c1e212009-09-20 05:03:30 +0000372 const StringMap<Option*> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000373
Chris Lattnere7c1e212009-09-20 05:03:30 +0000374 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000375
Chris Lattnere7c1e212009-09-20 05:03:30 +0000376 // Loop while we haven't found an option and Name still has at least two
377 // characters in it (so that the next iteration will not be the empty
378 // string.
379 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000380 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000381 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000382 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000383
Chris Lattner5247f602007-04-06 21:06:55 +0000384 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000385 Length = Name.size();
Chris Lattner5247f602007-04-06 21:06:55 +0000386 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000387 }
388 return 0; // No option found!
389}
390
Chris Lattnere7c1e212009-09-20 05:03:30 +0000391/// HandlePrefixedOrGroupedOption - The specified argument string (which started
392/// with at least one '-') does not fully match an available option. Check to
393/// see if this is a prefix or grouped option. If so, split arg into output an
394/// Arg/Value pair and return the Option to parse it with.
395static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
396 bool &ErrorParsing,
397 const StringMap<Option*> &OptionsMap) {
398 if (Arg.size() == 1) return 0;
399
400 // Do the lookup!
401 size_t Length = 0;
402 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
403 if (PGOpt == 0) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000404
Chris Lattnere7c1e212009-09-20 05:03:30 +0000405 // If the option is a prefixed option, then the value is simply the
406 // rest of the name... so fall through to later processing, by
407 // setting up the argument name flags and value fields.
408 if (PGOpt->getFormattingFlag() == cl::Prefix) {
409 Value = Arg.substr(Length);
410 Arg = Arg.substr(0, Length);
411 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
412 return PGOpt;
413 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000414
Chris Lattnere7c1e212009-09-20 05:03:30 +0000415 // This must be a grouped option... handle them now. Grouping options can't
416 // have values.
417 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000418
Chris Lattnere7c1e212009-09-20 05:03:30 +0000419 do {
420 // Move current arg name out of Arg into OneArgName.
421 StringRef OneArgName = Arg.substr(0, Length);
422 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000423
Chris Lattnere7c1e212009-09-20 05:03:30 +0000424 // Because ValueRequired is an invalid flag for grouped arguments,
425 // we don't need to pass argc/argv in.
426 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
427 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000428 int Dummy = 0;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000429 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
430 StringRef(), 0, 0, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000431
Chris Lattnere7c1e212009-09-20 05:03:30 +0000432 // Get the next grouping option.
433 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
434 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000435
Chris Lattnere7c1e212009-09-20 05:03:30 +0000436 // Return the last option with Arg cut down to just the last one.
437 return PGOpt;
438}
439
440
441
Chris Lattner5df56c42002-07-22 02:07:59 +0000442static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000443 return O->getNumOccurrencesFlag() == cl::Required ||
444 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000445}
446
447static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000448 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
449 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000450}
Chris Lattnere81c4092001-10-27 05:54:17 +0000451
Reid Klecknera73c7782013-07-18 16:52:05 +0000452static bool isWhitespace(char C) {
453 return strchr(" \t\n\r\f\v", C);
454}
Brian Gaeke497216d2003-08-15 21:05:57 +0000455
Reid Klecknera73c7782013-07-18 16:52:05 +0000456static bool isQuote(char C) {
457 return C == '\"' || C == '\'';
458}
459
460static bool isGNUSpecial(char C) {
461 return strchr("\\\"\' ", C);
462}
463
464void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
465 SmallVectorImpl<const char *> &NewArgv) {
466 SmallString<128> Token;
467 for (size_t I = 0, E = Src.size(); I != E; ++I) {
468 // Consume runs of whitespace.
469 if (Token.empty()) {
470 while (I != E && isWhitespace(Src[I]))
471 ++I;
472 if (I == E) break;
473 }
474
475 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
476 // they are literal. This makes it much easier to read Windows file paths.
477 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
478 ++I; // Skip the escape.
479 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000480 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000481 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000482
Reid Klecknera73c7782013-07-18 16:52:05 +0000483 // Consume a quoted string.
484 if (isQuote(Src[I])) {
485 char Quote = Src[I++];
486 while (I != E && Src[I] != Quote) {
487 // Backslashes are literal, unless they escape a special character.
488 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
489 ++I;
490 Token.push_back(Src[I]);
491 ++I;
492 }
493 if (I == E) break;
494 continue;
495 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000496
Reid Klecknera73c7782013-07-18 16:52:05 +0000497 // End the token if this is whitespace.
498 if (isWhitespace(Src[I])) {
499 if (!Token.empty())
500 NewArgv.push_back(Saver.SaveString(Token.c_str()));
501 Token.clear();
502 continue;
503 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000504
Reid Klecknera73c7782013-07-18 16:52:05 +0000505 // This is a normal character. Append it.
506 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000507 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000508
509 // Append the last token after hitting EOF with no whitespace.
510 if (!Token.empty())
511 NewArgv.push_back(Saver.SaveString(Token.c_str()));
512}
513
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000514/// Backslashes are interpreted in a rather complicated way in the Windows-style
515/// command line, because backslashes are used both to separate path and to
516/// escape double quote. This method consumes runs of backslashes as well as the
517/// following double quote if it's escaped.
518///
519/// * If an even number of backslashes is followed by a double quote, one
520/// backslash is output for every pair of backslashes, and the last double
521/// quote remains unconsumed. The double quote will later be interpreted as
522/// the start or end of a quoted string in the main loop outside of this
523/// function.
524///
525/// * If an odd number of backslashes is followed by a double quote, one
526/// backslash is output for every pair of backslashes, and a double quote is
527/// output for the last pair of backslash-double quote. The double quote is
528/// consumed in this case.
529///
530/// * Otherwise, backslashes are interpreted literally.
531static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
532 size_t E = Src.size();
533 int BackslashCount = 0;
534 // Skip the backslashes.
535 do {
536 ++I;
537 ++BackslashCount;
538 } while (I != E && Src[I] == '\\');
539
540 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
541 if (FollowedByDoubleQuote) {
542 Token.append(BackslashCount / 2, '\\');
543 if (BackslashCount % 2 == 0)
544 return I - 1;
545 Token.push_back('"');
546 return I;
547 }
548 Token.append(BackslashCount, '\\');
549 return I - 1;
550}
551
Reid Klecknera73c7782013-07-18 16:52:05 +0000552void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
553 SmallVectorImpl<const char *> &NewArgv) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000554 SmallString<128> Token;
555
556 // This is a small state machine to consume characters until it reaches the
557 // end of the source string.
558 enum { INIT, UNQUOTED, QUOTED } State = INIT;
559 for (size_t I = 0, E = Src.size(); I != E; ++I) {
560 // INIT state indicates that the current input index is at the start of
561 // the string or between tokens.
562 if (State == INIT) {
563 if (isWhitespace(Src[I]))
564 continue;
565 if (Src[I] == '"') {
566 State = QUOTED;
567 continue;
568 }
569 if (Src[I] == '\\') {
570 I = parseBackslash(Src, I, Token);
571 State = UNQUOTED;
572 continue;
573 }
574 Token.push_back(Src[I]);
575 State = UNQUOTED;
576 continue;
577 }
578
579 // UNQUOTED state means that it's reading a token not quoted by double
580 // quotes.
581 if (State == UNQUOTED) {
582 // Whitespace means the end of the token.
583 if (isWhitespace(Src[I])) {
584 NewArgv.push_back(Saver.SaveString(Token.c_str()));
585 Token.clear();
586 State = INIT;
587 continue;
588 }
589 if (Src[I] == '"') {
590 State = QUOTED;
591 continue;
592 }
593 if (Src[I] == '\\') {
594 I = parseBackslash(Src, I, Token);
595 continue;
596 }
597 Token.push_back(Src[I]);
598 continue;
599 }
600
601 // QUOTED state means that it's reading a token quoted by double quotes.
602 if (State == QUOTED) {
603 if (Src[I] == '"') {
604 State = UNQUOTED;
605 continue;
606 }
607 if (Src[I] == '\\') {
608 I = parseBackslash(Src, I, Token);
609 continue;
610 }
611 Token.push_back(Src[I]);
612 }
613 }
614 // Append the last token after hitting EOF with no whitespace.
615 if (!Token.empty())
616 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000617}
618
619static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
620 TokenizerCallback Tokenizer,
621 SmallVectorImpl<const char *> &NewArgv) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000622 std::unique_ptr<MemoryBuffer> MemBuf;
Reid Klecknera73c7782013-07-18 16:52:05 +0000623 if (MemoryBuffer::getFile(FName, MemBuf))
624 return false;
625 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
626
627 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
628 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
629 std::string UTF8Buf;
630 if (hasUTF16ByteOrderMark(BufRef)) {
631 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
632 return false;
633 Str = StringRef(UTF8Buf);
634 }
635
636 // Tokenize the contents into NewArgv.
637 Tokenizer(Str, Saver, NewArgv);
638
639 return true;
640}
641
642/// \brief Expand response files on a command line recursively using the given
643/// StringSaver and tokenization strategy.
644bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
645 SmallVectorImpl<const char *> &Argv) {
646 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000647 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000648
649 // Don't cache Argv.size() because it can change.
650 for (unsigned I = 0; I != Argv.size(); ) {
651 const char *Arg = Argv[I];
652 if (Arg[0] != '@') {
653 ++I;
654 continue;
655 }
656
657 // If we have too many response files, leave some unexpanded. This avoids
658 // crashing on self-referential response files.
659 if (RspFiles++ > 20)
660 return false;
661
662 // Replace this response file argument with the tokenization of its
663 // contents. Nested response files are expanded in subsequent iterations.
664 // FIXME: If a nested response file uses a relative path, is it relative to
665 // the cwd of the process or the response file?
666 SmallVector<const char *, 0> ExpandedArgv;
667 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000668 // We couldn't read this file, so we leave it in the argument stream and
669 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000670 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000671 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000672 continue;
673 }
674 Argv.erase(Argv.begin() + I);
675 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
676 }
677 return AllExpanded;
678}
679
680namespace {
681 class StrDupSaver : public StringSaver {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000682 std::vector<char*> Dups;
683 public:
684 ~StrDupSaver() {
685 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
686 I != E; ++I) {
687 char *Dup = *I;
688 free(Dup);
689 }
690 }
Craig Topper73156022014-03-02 09:09:27 +0000691 const char *SaveString(const char *Str) override {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000692 char *Dup = strdup(Str);
693 Dups.push_back(Dup);
694 return Dup;
Reid Klecknera73c7782013-07-18 16:52:05 +0000695 }
696 };
Brian Gaekeca782d92003-08-14 22:00:59 +0000697}
698
699/// ParseEnvironmentOptions - An alternative entry point to the
700/// CommandLine library, which allows you to read the program's name
701/// from the caller (as PROGNAME) and its command-line arguments from
702/// an environment variable (whose name is given in ENVVAR).
703///
Chris Lattnera60f3552004-05-06 22:04:31 +0000704void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000705 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000706 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000707 assert(progName && "Program name not specified");
708 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000709
Brian Gaeke497216d2003-08-15 21:05:57 +0000710 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000711 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000712 if (!envValue)
713 return;
714
Brian Gaekeca782d92003-08-14 22:00:59 +0000715 // Get program's "name", which we wouldn't know without the caller
716 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000717 SmallVector<const char *, 20> newArgv;
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000718 StrDupSaver Saver;
719 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000720
721 // Parse the value of the environment variable into a "command line"
722 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000723 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000724 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000725 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000726}
727
David Blaikie0210e972012-02-07 19:36:01 +0000728void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000729 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000730 // Process all registered options.
Chris Lattner131dca92009-09-20 06:18:38 +0000731 SmallVector<Option*, 4> PositionalOpts;
732 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000733 StringMap<Option*> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000734 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000735
Chris Lattner5247f602007-04-06 21:06:55 +0000736 assert((!Opts.empty() || !PositionalOpts.empty()) &&
737 "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000738
739 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000740 SmallVector<const char *, 20> newArgv;
741 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000742 newArgv.push_back(argv[i]);
Reid Klecknera73c7782013-07-18 16:52:05 +0000743 StrDupSaver Saver;
744 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000745 argv = &newArgv[0];
746 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000747
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000748 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencer762a55b2010-12-18 00:19:10 +0000749 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000750 size_t Len = std::min(ProgName.size(), size_t(79));
751 memcpy(ProgramName, ProgName.data(), Len);
752 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000753
Chris Lattner36a57d32001-07-23 17:17:47 +0000754 ProgramOverview = Overview;
755 bool ErrorParsing = false;
756
Chris Lattner5df56c42002-07-22 02:07:59 +0000757 // Check out the positional arguments to collect information about them.
758 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000759
Chris Lattnerd380d842005-08-08 17:25:38 +0000760 // Determine whether or not there are an unlimited number of positionals
761 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000762
Chris Lattner5df56c42002-07-22 02:07:59 +0000763 Option *ConsumeAfterOpt = 0;
764 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000765 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000766 assert(PositionalOpts.size() > 1 &&
767 "Cannot specify cl::ConsumeAfter without a positional argument!");
768 ConsumeAfterOpt = PositionalOpts[0];
769 }
770
771 // Calculate how many positional values are _required_.
772 bool UnboundedFound = false;
Evan Cheng86cb3182008-05-05 18:30:58 +0000773 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000774 i != e; ++i) {
775 Option *Opt = PositionalOpts[i];
776 if (RequiresValue(Opt))
777 ++NumPositionalRequired;
778 else if (ConsumeAfterOpt) {
779 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000780 // unless there is only one positional argument...
781 if (PositionalOpts.size() > 2)
782 ErrorParsing |=
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000783 Opt->error("error - this positional option will never be matched, "
Chris Lattnerd49ea882002-07-22 02:21:57 +0000784 "because it does not Require a value, and a "
785 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000786 } else if (UnboundedFound && !Opt->ArgStr[0]) {
787 // This option does not "require" a value... Make sure this option is
788 // not specified after an option that eats all extra arguments, or this
789 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000790 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000791 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000792 "another positional argument will match an "
793 "unbounded number of values, and this option"
794 " does not require a value!");
795 }
796 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
797 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000798 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000799 }
800
Reid Spencer2027a6f2004-08-13 19:47:30 +0000801 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000802 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000803 //
Chris Lattnerca2552d2009-09-20 00:07:40 +0000804 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000805
Chris Lattner2da046f2003-07-30 17:34:02 +0000806 // If the program has named positional arguments, and the name has been run
807 // across, keep track of which positional argument was named. Otherwise put
808 // the positional args into the PositionalVals list...
809 Option *ActivePositionalArg = 0;
810
Chris Lattner36a57d32001-07-23 17:17:47 +0000811 // Loop over all of the arguments... processing them.
Chris Lattner5df56c42002-07-22 02:07:59 +0000812 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000813 for (int i = 1; i < argc; ++i) {
814 Option *Handler = 0;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000815 Option *NearestHandler = 0;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000816 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000817 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000818 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000819
Chris Lattneraf039c52007-04-12 00:36:29 +0000820 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000821 // option has just been registered or deregistered. This can occur in
822 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000823 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000824 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000825 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000826 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000827 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000828 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000829 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000830
Chris Lattner5df56c42002-07-22 02:07:59 +0000831 // Check to see if this is a positional argument. This argument is
832 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000833 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000834 //
835 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
836 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000837 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000838 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner2da046f2003-07-30 17:34:02 +0000839 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000840 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000841
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000842 if (!PositionalOpts.empty()) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000843 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000844
845 // All of the positional arguments have been fulfulled, give the rest to
846 // the consume after option... if it's specified...
847 //
Misha Brukman10468d82005-04-21 22:55:34 +0000848 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner5df56c42002-07-22 02:07:59 +0000849 ConsumeAfterOpt != 0) {
850 for (++i; i < argc; ++i)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000851 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000852 break; // Handle outside of the argument processing loop...
853 }
854
855 // Delay processing positional arguments until the end...
856 continue;
857 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000858 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
859 !DashDashFound) {
860 DashDashFound = true; // This is the mythical "--"?
861 continue; // Don't try to process it as an argument itself.
862 } else if (ActivePositionalArg &&
863 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
864 // If there is a positional argument eating options, check to see if this
865 // option is another positional argument. If so, treat it as an argument,
866 // otherwise feed it to the eating positional.
Chris Lattner36a57d32001-07-23 17:17:47 +0000867 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000868 // Eat leading dashes.
869 while (!ArgName.empty() && ArgName[0] == '-')
870 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000871
Chris Lattner5247f602007-04-06 21:06:55 +0000872 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000873 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000874 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnera60f3552004-05-06 22:04:31 +0000875 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000876 }
877
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000878 } else { // We start with a '-', must be an argument.
Chris Lattnera60f3552004-05-06 22:04:31 +0000879 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000880 // Eat leading dashes.
881 while (!ArgName.empty() && ArgName[0] == '-')
882 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000883
Chris Lattner5247f602007-04-06 21:06:55 +0000884 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000885
Chris Lattnera60f3552004-05-06 22:04:31 +0000886 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000887 if (Handler == 0)
888 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
889 ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000890
891 // Otherwise, look for the closest available option to report to the user
892 // in the upcoming error.
893 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000894 NearestHandler = LookupNearestOption(ArgName, Opts,
895 NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000896 }
897
898 if (Handler == 0) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000899 if (SinkOpts.empty()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000900 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands142b9ed2010-02-18 14:08:13 +0000901 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000902
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000903 if (NearestHandler) {
904 // If we know a near match, report it as well.
905 errs() << ProgramName << ": Did you mean '-"
906 << NearestHandlerString << "'?\n";
907 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000908
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000909 ErrorParsing = true;
910 } else {
Chris Lattner131dca92009-09-20 06:18:38 +0000911 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000912 E = SinkOpts.end(); I != E ; ++I)
913 (*I)->addOccurrence(i, "", argv[i]);
914 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000915 continue;
916 }
917
Chris Lattner2da046f2003-07-30 17:34:02 +0000918 // If this is a named positional argument, just remember that it is the
919 // active one...
920 if (Handler->getFormattingFlag() == cl::Positional)
921 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000922 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000923 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000924 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000925
Chris Lattner5df56c42002-07-22 02:07:59 +0000926 // Check and handle positional arguments now...
927 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000928 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000929 << ": Not enough positional command line arguments specified!\n"
930 << "Must specify at least " << NumPositionalRequired
Duncan Sands142b9ed2010-02-18 14:08:13 +0000931 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000932
Chris Lattner5df56c42002-07-22 02:07:59 +0000933 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000934 } else if (!HasUnlimitedPositionals &&
935 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000936 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000937 << ": Too many positional arguments specified!\n"
938 << "Can specify at most " << PositionalOpts.size()
Duncan Sands142b9ed2010-02-18 14:08:13 +0000939 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +0000940 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +0000941
942 } else if (ConsumeAfterOpt == 0) {
Chris Lattnere7c1e212009-09-20 05:03:30 +0000943 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +0000944 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
945 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000946 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +0000947 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000948 PositionalVals[ValNo].second);
949 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000950 --NumPositionalRequired; // We fulfilled our duty...
951 }
952
953 // If we _can_ give this option more arguments, do so now, as long as we
954 // do not give it values that others need. 'Done' controls whether the
955 // option even _WANTS_ any more.
956 //
Misha Brukman069e6b52003-07-10 16:49:51 +0000957 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner5df56c42002-07-22 02:07:59 +0000958 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000959 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000960 case cl::Optional:
961 Done = true; // Optional arguments want _at most_ one value
962 // FALL THROUGH
963 case cl::ZeroOrMore: // Zero or more will take all they can get...
964 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +0000965 ProvidePositionalOption(PositionalOpts[i],
966 PositionalVals[ValNo].first,
967 PositionalVals[ValNo].second);
968 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000969 break;
970 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000971 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner5df56c42002-07-22 02:07:59 +0000972 "positional argument processing!");
973 }
974 }
Chris Lattnere81c4092001-10-27 05:54:17 +0000975 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000976 } else {
977 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
978 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +0000979 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000980 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000981 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000982 PositionalVals[ValNo].first,
983 PositionalVals[ValNo].second);
984 ValNo++;
985 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000986
987 // Handle the case where there is just one positional option, and it's
988 // optional. In this case, we want to give JUST THE FIRST option to the
989 // positional option and keep the rest for the consume after. The above
990 // loop would have assigned no values to positional options in this case.
991 //
Reid Spencer2027a6f2004-08-13 19:47:30 +0000992 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000993 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000994 PositionalVals[ValNo].first,
995 PositionalVals[ValNo].second);
996 ValNo++;
997 }
Misha Brukman10468d82005-04-21 22:55:34 +0000998
Chris Lattner5df56c42002-07-22 02:07:59 +0000999 // Handle over all of the rest of the arguments to the
1000 // cl::ConsumeAfter command line option...
1001 for (; ValNo != PositionalVals.size(); ++ValNo)
1002 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001003 PositionalVals[ValNo].first,
1004 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001005 }
1006
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001007 // Loop over args and make sure all required args are specified!
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001008 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanc18333a2003-07-10 17:05:26 +00001009 E = Opts.end(); I != E; ++I) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001010 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001011 case Required:
1012 case OneOrMore:
Misha Brukman069e6b52003-07-10 16:49:51 +00001013 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001014 I->second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001015 ErrorParsing = true;
1016 }
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001017 // Fall through
1018 default:
1019 break;
1020 }
1021 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001022
Rafael Espindolacf14a382010-11-19 21:14:29 +00001023 // Now that we know if -debug is specified, we can use it.
1024 // Note that if ReadResponseFiles == true, this must be done before the
1025 // memory allocated for the expanded command line is free()d below.
1026 DEBUG(dbgs() << "Args: ";
1027 for (int i = 0; i < argc; ++i)
1028 dbgs() << argv[i] << ' ';
1029 dbgs() << '\n';
1030 );
1031
Chris Lattner5df56c42002-07-22 02:07:59 +00001032 // Free all of the memory allocated to the map. Command line options may only
1033 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001034 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001035 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001036 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001037
1038 // If we had an error processing our arguments, don't let the program execute
1039 if (ErrorParsing) exit(1);
1040}
1041
1042//===----------------------------------------------------------------------===//
1043// Option Base class implementation
1044//
Chris Lattner36a57d32001-07-23 17:17:47 +00001045
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001046bool Option::error(const Twine &Message, StringRef ArgName) {
1047 if (ArgName.data() == 0) ArgName = ArgStr;
1048 if (ArgName.empty())
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001049 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001050 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001051 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001052
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001053 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001054 return true;
1055}
1056
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001057bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001058 StringRef Value, bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001059 if (!MultiArg)
1060 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001061
Misha Brukman069e6b52003-07-10 16:49:51 +00001062 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001063 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001064 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001065 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001066 break;
1067 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001068 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001069 return error("must occur exactly one time!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001070 // Fall through
1071 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001072 case ZeroOrMore:
1073 case ConsumeAfter: break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001074 }
1075
Reid Spencer2027a6f2004-08-13 19:47:30 +00001076 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001077}
1078
Chris Lattner5df56c42002-07-22 02:07:59 +00001079
1080// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1081// has been specified yet.
1082//
1083static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1084 if (O.ValueStr[0] == 0) return DefaultMsg;
1085 return O.ValueStr;
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// cl::alias class implementation
1090//
1091
Chris Lattner36a57d32001-07-23 17:17:47 +00001092// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001093size_t alias::getOptionWidth() const {
Chris Lattner36a57d32001-07-23 17:17:47 +00001094 return std::strlen(ArgStr)+6;
1095}
1096
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001097static void printHelpStr(StringRef HelpStr, size_t Indent,
1098 size_t FirstLineIndentedBy) {
1099 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1100 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1101 while (!Split.second.empty()) {
1102 Split = Split.second.split('\n');
1103 outs().indent(Indent) << Split.first << "\n";
1104 }
1105}
1106
Chris Lattner1b7a5152006-04-28 05:36:25 +00001107// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001108void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001109 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001110 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001111}
1112
Chris Lattner36a57d32001-07-23 17:17:47 +00001113//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001114// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001115//
1116
Chris Lattnerb4101b12002-08-07 18:36:37 +00001117// basic_parser implementation
1118//
1119
1120// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001121size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1122 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001123 if (const char *ValName = getValueName())
1124 Len += std::strlen(getValueStr(O, ValName))+3;
1125
1126 return Len + 6;
1127}
1128
Misha Brukman10468d82005-04-21 22:55:34 +00001129// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001130// to-be-maintained width is specified.
1131//
1132void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001133 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001134 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001135
1136 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001137 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001138
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001139 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001140}
1141
Andrew Trick12004012011-04-05 18:54:36 +00001142void basic_parser_impl::printOptionName(const Option &O,
1143 size_t GlobalWidth) const {
1144 outs() << " -" << O.ArgStr;
1145 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1146}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001147
1148
Chris Lattner5df56c42002-07-22 02:07:59 +00001149// parser<bool> implementation
1150//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001151bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001152 StringRef Arg, bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001153 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001154 Arg == "1") {
1155 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001156 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001157 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001158
Chris Lattneraecd74d2009-09-19 18:55:05 +00001159 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1160 Value = false;
1161 return false;
1162 }
1163 return O.error("'" + Arg +
1164 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001165}
1166
Dale Johannesen82810c82007-05-22 17:14:46 +00001167// parser<boolOrDefault> implementation
1168//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001169bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001170 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001171 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1172 Arg == "1") {
1173 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001174 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001175 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001176 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1177 Value = BOU_FALSE;
1178 return false;
1179 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001180
Chris Lattneraecd74d2009-09-19 18:55:05 +00001181 return O.error("'" + Arg +
1182 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001183}
1184
Chris Lattner5df56c42002-07-22 02:07:59 +00001185// parser<int> implementation
1186//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001187bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001188 StringRef Arg, int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001189 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001190 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001191 return false;
1192}
1193
Chris Lattner719c7152003-06-28 15:47:20 +00001194// parser<unsigned> implementation
1195//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001196bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001197 StringRef Arg, unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001198
1199 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001200 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001201 return false;
1202}
1203
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001204// parser<unsigned long long> implementation
1205//
1206bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1207 StringRef Arg, unsigned long long &Value){
1208
1209 if (Arg.getAsInteger(0, Value))
1210 return O.error("'" + Arg + "' value invalid for uint argument!");
1211 return false;
1212}
1213
Chris Lattnerb4101b12002-08-07 18:36:37 +00001214// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001215//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001216static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001217 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1218 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001219 char *End;
1220 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001221 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001222 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001223 return false;
1224}
1225
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001226bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001227 StringRef Arg, double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001228 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001229}
1230
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001231bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001232 StringRef Arg, float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001233 double dVal;
1234 if (parseDouble(O, Arg, dVal))
1235 return true;
1236 Val = (float)dVal;
1237 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001238}
1239
1240
Chris Lattner5df56c42002-07-22 02:07:59 +00001241
1242// generic_parser_base implementation
1243//
1244
Chris Lattner494c0b02002-07-23 17:15:12 +00001245// findOption - Return the option number corresponding to the specified
1246// argument string. If the option is not found, getNumOptions() is returned.
1247//
1248unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001249 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001250
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001251 for (unsigned i = 0; i != e; ++i) {
1252 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001253 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001254 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001255 return e;
1256}
1257
1258
Chris Lattner5df56c42002-07-22 02:07:59 +00001259// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001260size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001261 if (O.hasArgStr()) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001262 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001263 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001264 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001265 return Size;
1266 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001267 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001268 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001269 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001270 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001271 }
1272}
1273
Misha Brukman10468d82005-04-21 22:55:34 +00001274// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001275// to-be-maintained width is specified.
1276//
1277void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001278 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001279 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001280 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001281 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001282
Chris Lattner5df56c42002-07-22 02:07:59 +00001283 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001284 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001285 outs() << " =" << getOption(i);
1286 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001287 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001288 } else {
1289 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001290 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001291 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001292 const char *Option = getOption(i);
1293 outs() << " -" << Option;
1294 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001295 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001296 }
1297}
1298
Andrew Trick12004012011-04-05 18:54:36 +00001299static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1300
1301// printGenericOptionDiff - Print the value of this option and it's default.
1302//
1303// "Generic" options have each value mapped to a name.
1304void generic_parser_base::
1305printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1306 const GenericOptionValue &Default,
1307 size_t GlobalWidth) const {
1308 outs() << " -" << O.ArgStr;
1309 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1310
1311 unsigned NumOpts = getNumOptions();
1312 for (unsigned i = 0; i != NumOpts; ++i) {
1313 if (Value.compare(getOptionValue(i)))
1314 continue;
1315
1316 outs() << "= " << getOption(i);
1317 size_t L = std::strlen(getOption(i));
1318 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1319 outs().indent(NumSpaces) << " (default: ";
1320 for (unsigned j = 0; j != NumOpts; ++j) {
1321 if (Default.compare(getOptionValue(j)))
1322 continue;
1323 outs() << getOption(j);
1324 break;
1325 }
1326 outs() << ")\n";
1327 return;
1328 }
1329 outs() << "= *unknown option value*\n";
1330}
1331
1332// printOptionDiff - Specializations for printing basic value types.
1333//
1334#define PRINT_OPT_DIFF(T) \
1335 void parser<T>:: \
1336 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1337 size_t GlobalWidth) const { \
1338 printOptionName(O, GlobalWidth); \
1339 std::string Str; \
1340 { \
1341 raw_string_ostream SS(Str); \
1342 SS << V; \
1343 } \
1344 outs() << "= " << Str; \
1345 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1346 outs().indent(NumSpaces) << " (default: "; \
1347 if (D.hasValue()) \
1348 outs() << D.getValue(); \
1349 else \
1350 outs() << "*no default*"; \
1351 outs() << ")\n"; \
1352 } \
1353
Frits van Bommel87e33672011-04-06 12:29:56 +00001354PRINT_OPT_DIFF(bool)
1355PRINT_OPT_DIFF(boolOrDefault)
1356PRINT_OPT_DIFF(int)
1357PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001358PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001359PRINT_OPT_DIFF(double)
1360PRINT_OPT_DIFF(float)
1361PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001362
1363void parser<std::string>::
1364printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1365 size_t GlobalWidth) const {
1366 printOptionName(O, GlobalWidth);
1367 outs() << "= " << V;
1368 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1369 outs().indent(NumSpaces) << " (default: ";
1370 if (D.hasValue())
1371 outs() << D.getValue();
1372 else
1373 outs() << "*no default*";
1374 outs() << ")\n";
1375}
1376
1377// Print a placeholder for options that don't yet support printOptionDiff().
1378void basic_parser_impl::
1379printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1380 printOptionName(O, GlobalWidth);
1381 outs() << "= *cannot print option value*\n";
1382}
Chris Lattner36a57d32001-07-23 17:17:47 +00001383
1384//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001385// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001386//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001387
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001388static int OptNameCompare(const void *LHS, const void *RHS) {
1389 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001390
Duncan Sands79d793e2012-03-12 10:51:06 +00001391 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001392}
1393
Andrew Trick12004012011-04-05 18:54:36 +00001394// Copy Options into a vector so we can sort them as we like.
1395static void
1396sortOpts(StringMap<Option*> &OptMap,
1397 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1398 bool ShowHidden) {
1399 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1400
1401 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1402 I != E; ++I) {
1403 // Ignore really-hidden options.
1404 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1405 continue;
1406
1407 // Unless showhidden is set, ignore hidden flags.
1408 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1409 continue;
1410
1411 // If we've already seen this option, don't add it to the list again.
1412 if (!OptionSet.insert(I->second))
1413 continue;
1414
1415 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1416 I->second));
1417 }
1418
1419 // Sort the options list alphabetically.
1420 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1421}
1422
Chris Lattner36a57d32001-07-23 17:17:47 +00001423namespace {
1424
Chris Lattner5df56c42002-07-22 02:07:59 +00001425class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001426protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001427 const bool ShowHidden;
Andrew Trick0537a982013-05-06 21:56:23 +00001428 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1429 // Print the options. Opts is assumed to be alphabetically sorted.
1430 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1431 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1432 Opts[i].second->printOptionInfo(MaxArgLen);
1433 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001434
Chris Lattner5df56c42002-07-22 02:07:59 +00001435public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001436 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001437 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001438
Andrew Trick0537a982013-05-06 21:56:23 +00001439 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001440 void operator=(bool Value) {
1441 if (Value == false) return;
1442
Chris Lattner5247f602007-04-06 21:06:55 +00001443 // Get all the options.
Chris Lattner131dca92009-09-20 06:18:38 +00001444 SmallVector<Option*, 4> PositionalOpts;
1445 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001446 StringMap<Option*> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001447 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001448
Andrew Trick0537a982013-05-06 21:56:23 +00001449 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001450 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001451
1452 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001453 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001454
Chris Lattner471ba482009-08-23 08:43:55 +00001455 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001456
Chris Lattner8111c592006-10-04 21:52:35 +00001457 // Print out the positional options.
Chris Lattner5df56c42002-07-22 02:07:59 +00001458 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001459 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001460 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1461 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001462
Evan Cheng86cb3182008-05-05 18:30:58 +00001463 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001464 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001465 outs() << " --" << PositionalOpts[i]->ArgStr;
1466 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001467 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001468
1469 // Print the consume after option info if it exists...
Chris Lattner471ba482009-08-23 08:43:55 +00001470 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001471
Chris Lattner471ba482009-08-23 08:43:55 +00001472 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001473
1474 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001475 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001476 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001477 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001478
Chris Lattner471ba482009-08-23 08:43:55 +00001479 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001480 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001481
Chris Lattner37bcd992004-11-19 17:08:15 +00001482 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001483 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001484 E = MoreHelp->end();
1485 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001486 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001487 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001488
Reid Spencer5e554702004-11-16 06:11:52 +00001489 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001490 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001491 }
1492};
Andrew Trick0537a982013-05-06 21:56:23 +00001493
1494class CategorizedHelpPrinter : public HelpPrinter {
1495public:
1496 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1497
1498 // Helper function for printOptions().
1499 // It shall return true if A's name should be lexographically
1500 // ordered before B's name. It returns false otherwise.
1501 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001502 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001503 }
1504
1505 // Make sure we inherit our base class's operator=()
1506 using HelpPrinter::operator= ;
1507
1508protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001509 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001510 std::vector<OptionCategory *> SortedCategories;
1511 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1512
Alp Tokercb402912014-01-24 17:20:08 +00001513 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001514 // sorting.
1515 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1516 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001517 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001518 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001519 }
Andrew Trick0537a982013-05-06 21:56:23 +00001520
1521 // Sort the different option categories alphabetically.
1522 assert(SortedCategories.size() > 0 && "No option categories registered!");
1523 std::sort(SortedCategories.begin(), SortedCategories.end(),
1524 OptionCategoryCompare);
1525
1526 // Create map to empty vectors.
1527 for (std::vector<OptionCategory *>::const_iterator
1528 I = SortedCategories.begin(),
1529 E = SortedCategories.end();
1530 I != E; ++I)
1531 CategorizedOptions[*I] = std::vector<Option *>();
1532
1533 // Walk through pre-sorted options and assign into categories.
1534 // Because the options are already alphabetically sorted the
1535 // options within categories will also be alphabetically sorted.
1536 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1537 Option *Opt = Opts[I].second;
1538 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1539 "Option has an unregistered category");
1540 CategorizedOptions[Opt->Category].push_back(Opt);
1541 }
1542
1543 // Now do printing.
1544 for (std::vector<OptionCategory *>::const_iterator
1545 Category = SortedCategories.begin(),
1546 E = SortedCategories.end();
1547 Category != E; ++Category) {
1548 // Hide empty categories for -help, but show for -help-hidden.
1549 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1550 if (!ShowHidden && IsEmptyCategory)
1551 continue;
1552
1553 // Print category information.
1554 outs() << "\n";
1555 outs() << (*Category)->getName() << ":\n";
1556
1557 // Check if description is set.
1558 if ((*Category)->getDescription() != 0)
1559 outs() << (*Category)->getDescription() << "\n\n";
1560 else
1561 outs() << "\n";
1562
1563 // When using -help-hidden explicitly state if the category has no
1564 // options associated with it.
1565 if (IsEmptyCategory) {
1566 outs() << " This option category has no options.\n";
1567 continue;
1568 }
1569 // Loop over the options in the category and print.
1570 for (std::vector<Option *>::const_iterator
1571 Opt = CategorizedOptions[*Category].begin(),
1572 E = CategorizedOptions[*Category].end();
1573 Opt != E; ++Opt)
1574 (*Opt)->printOptionInfo(MaxArgLen);
1575 }
1576 }
1577};
1578
1579// This wraps the Uncategorizing and Categorizing printers and decides
1580// at run time which should be invoked.
1581class HelpPrinterWrapper {
1582private:
1583 HelpPrinter &UncategorizedPrinter;
1584 CategorizedHelpPrinter &CategorizedPrinter;
1585
1586public:
1587 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1588 CategorizedHelpPrinter &CategorizedPrinter) :
1589 UncategorizedPrinter(UncategorizedPrinter),
1590 CategorizedPrinter(CategorizedPrinter) { }
1591
1592 // Invoke the printer.
1593 void operator=(bool Value);
1594};
1595
Chris Lattneradb19d62006-10-12 22:09:17 +00001596} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001597
Andrew Trick0537a982013-05-06 21:56:23 +00001598// Declare the four HelpPrinter instances that are used to print out help, or
1599// help-hidden as an uncategorized list or in categories.
1600static HelpPrinter UncategorizedNormalPrinter(false);
1601static HelpPrinter UncategorizedHiddenPrinter(true);
1602static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1603static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1604
1605
1606// Declare HelpPrinter wrappers that will decide whether or not to invoke
1607// a categorizing help printer
1608static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1609 CategorizedNormalPrinter);
1610static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1611 CategorizedHiddenPrinter);
1612
1613// Define uncategorized help printers.
1614// -help-list is hidden by default because if Option categories are being used
1615// then -help behaves the same as -help-list.
1616static cl::opt<HelpPrinter, true, parser<bool> >
1617HLOp("help-list",
1618 cl::desc("Display list of available options (-help-list-hidden for more)"),
1619 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001620
Chris Lattneradb19d62006-10-12 22:09:17 +00001621static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trick0537a982013-05-06 21:56:23 +00001622HLHOp("help-list-hidden",
1623 cl::desc("Display list of all available options"),
1624 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1625
1626// Define uncategorized/categorized help printers. These printers change their
1627// behaviour at runtime depending on whether one or more Option categories have
1628// been declared.
1629static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands142b9ed2010-02-18 14:08:13 +00001630HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trick0537a982013-05-06 21:56:23 +00001631 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001632
Andrew Trick0537a982013-05-06 21:56:23 +00001633static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001634HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trick0537a982013-05-06 21:56:23 +00001635 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1636
1637
Chris Lattner36a57d32001-07-23 17:17:47 +00001638
Andrew Trick12004012011-04-05 18:54:36 +00001639static cl::opt<bool>
1640PrintOptions("print-options",
1641 cl::desc("Print non-default options after command line parsing"),
1642 cl::Hidden, cl::init(false));
1643
1644static cl::opt<bool>
1645PrintAllOptions("print-all-options",
1646 cl::desc("Print all option values after command line parsing"),
1647 cl::Hidden, cl::init(false));
1648
Andrew Trick0537a982013-05-06 21:56:23 +00001649void HelpPrinterWrapper::operator=(bool Value) {
1650 if (Value == false)
1651 return;
1652
1653 // Decide which printer to invoke. If more than one option category is
1654 // registered then it is useful to show the categorized help instead of
1655 // uncategorized help.
1656 if (RegisteredOptionCategories->size() > 1) {
1657 // unhide -help-list option so user can have uncategorized output if they
1658 // want it.
1659 HLOp.setHiddenFlag(NotHidden);
1660
1661 CategorizedPrinter = true; // Invoke categorized printer
1662 }
1663 else
1664 UncategorizedPrinter = true; // Invoke uncategorized printer
1665}
1666
Andrew Trick12004012011-04-05 18:54:36 +00001667// Print the value of each option.
1668void cl::PrintOptionValues() {
1669 if (!PrintOptions && !PrintAllOptions) return;
1670
1671 // Get all the options.
1672 SmallVector<Option*, 4> PositionalOpts;
1673 SmallVector<Option*, 4> SinkOpts;
1674 StringMap<Option*> OptMap;
1675 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1676
1677 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1678 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1679
1680 // Compute the maximum argument length...
1681 size_t MaxArgLen = 0;
1682 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1683 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1684
1685 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1686 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1687}
1688
Chris Lattneradb19d62006-10-12 22:09:17 +00001689static void (*OverrideVersionPrinter)() = 0;
Reid Spencerb3171672006-06-05 16:22:56 +00001690
Chandler Carruthea7e5522011-07-22 07:50:40 +00001691static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1692
Chris Lattneradb19d62006-10-12 22:09:17 +00001693namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001694class VersionPrinter {
1695public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001696 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001697 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001698 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001699 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001700#ifdef LLVM_VERSION_INFO
Chris Lattner131dca92009-09-20 06:18:38 +00001701 OS << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001702#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001703 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001704#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001705 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001706#else
Chris Lattner131dca92009-09-20 06:18:38 +00001707 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001708#endif
1709#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001710 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001711#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001712 std::string CPU = sys::getHostCPUName();
Benjamin Kramer713fd352009-11-17 17:57:04 +00001713 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001714 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001715#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001716 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001717#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001718 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001719 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001720 }
1721 void operator=(bool OptionWasSpecified) {
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001722 if (!OptionWasSpecified) return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001723
Chandler Carruthea7e5522011-07-22 07:50:40 +00001724 if (OverrideVersionPrinter != 0) {
1725 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001726 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001727 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001728 print();
1729
1730 // Iterate over any registered extra printers and call them to add further
1731 // information.
1732 if (ExtraVersionPrinters != 0) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001733 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001734 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1735 E = ExtraVersionPrinters->end();
1736 I != E; ++I)
1737 (*I)();
1738 }
1739
Justin Bogner02b95842014-02-28 19:08:01 +00001740 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001741 }
1742};
Chris Lattneradb19d62006-10-12 22:09:17 +00001743} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001744
1745
Reid Spencerff6cc122004-08-04 00:36:06 +00001746// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001747static VersionPrinter VersionPrinterInstance;
1748
1749static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001750VersOp("version", cl::desc("Display the version of this program"),
Reid Spencerff6cc122004-08-04 00:36:06 +00001751 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1752
Reid Spencer5e554702004-11-16 06:11:52 +00001753// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001754void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1755 // This looks weird, but it actually prints the help message. The Printers are
1756 // types of HelpPrinter and the help gets printed when its operator= is
1757 // invoked. That's because the "normal" usages of the help printer is to be
1758 // assigned true/false depending on whether -help or -help-hidden was given or
1759 // not. Since we're circumventing that we have to make it look like -help or
1760 // -help-hidden were given, so we assign true.
1761
1762 if (!Hidden && !Categorized)
1763 UncategorizedNormalPrinter = true;
1764 else if (!Hidden && Categorized)
1765 CategorizedNormalPrinter = true;
1766 else if (Hidden && !Categorized)
1767 UncategorizedHiddenPrinter = true;
1768 else
1769 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001770}
Reid Spencerb3171672006-06-05 16:22:56 +00001771
Devang Patel9eb2caae2007-02-01 01:43:37 +00001772/// Utility function for printing version number.
1773void cl::PrintVersionMessage() {
1774 VersionPrinterInstance.print();
1775}
1776
Reid Spencerb3171672006-06-05 16:22:56 +00001777void cl::SetVersionPrinter(void (*func)()) {
1778 OverrideVersionPrinter = func;
1779}
Chandler Carruthea7e5522011-07-22 07:50:40 +00001780
1781void cl::AddExtraVersionPrinter(void (*func)()) {
1782 if (ExtraVersionPrinters == 0)
1783 ExtraVersionPrinters = new std::vector<void (*)()>;
1784
1785 ExtraVersionPrinters->push_back(func);
1786}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001787
1788void cl::getRegisteredOptions(StringMap<Option*> &Map)
1789{
1790 // Get all the options.
1791 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1792 SmallVector<Option*, 4> SinkOpts; //NOT USED
1793 assert(Map.size() == 0 && "StringMap must be empty");
1794 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1795 return;
1796}