blob: 9acaa08bbcc7a4572f7b0e7e9a826d71154c7b15 [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000020#include "llvm/ADT/ArrayRef.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000021#include "llvm/ADT/OwningPtr.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/system_error.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000036#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000037#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000038#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chris Lattner3e5d60f2006-08-27 12:45:47 +000042//===----------------------------------------------------------------------===//
43// Template instantiations and anchors.
44//
Douglas Gregor7baad732009-11-25 06:04:18 +000045namespace llvm { namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000046TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000047TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000048TEMPLATE_INSTANTIATION(class basic_parser<int>);
49TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000050TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000051TEMPLATE_INSTANTIATION(class basic_parser<double>);
52TEMPLATE_INSTANTIATION(class basic_parser<float>);
53TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000054TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000055
56TEMPLATE_INSTANTIATION(class opt<unsigned>);
57TEMPLATE_INSTANTIATION(class opt<int>);
58TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000059TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000060TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor7baad732009-11-25 06:04:18 +000061} } // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000062
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000063// Pin the vtables to this file.
64void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000065void OptionValue<boolOrDefault>::anchor() {}
66void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000067void Option::anchor() {}
68void basic_parser_impl::anchor() {}
69void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000070void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000071void parser<int>::anchor() {}
72void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000073void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000074void parser<double>::anchor() {}
75void parser<float>::anchor() {}
76void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000077void parser<char>::anchor() {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000078void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000079
80//===----------------------------------------------------------------------===//
81
Chris Lattner5af1cbc2006-10-13 00:06:24 +000082// Globals for name and overview of program. Program name is not a string to
83// avoid static ctor/dtor issues.
84static char ProgramName[80] = "<premain>";
Reid Spencer9501b9b2004-09-01 04:41:28 +000085static const char *ProgramOverview = 0;
86
Chris Lattner37bcd992004-11-19 17:08:15 +000087// This collects additional help to be printed.
Chris Lattner8111c592006-10-04 21:52:35 +000088static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000089
Chris Lattner8111c592006-10-04 21:52:35 +000090extrahelp::extrahelp(const char *Help)
Chris Lattner37bcd992004-11-19 17:08:15 +000091 : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000092 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000093}
94
Chris Lattneraf039c52007-04-12 00:36:29 +000095static bool OptionListChanged = false;
96
97// MarkOptionsChanged - Internal helper function.
98void cl::MarkOptionsChanged() {
99 OptionListChanged = true;
100}
101
Chris Lattner5247f602007-04-06 21:06:55 +0000102/// RegisteredOptionList - This is the list of the command line options that
103/// have statically constructed themselves.
104static Option *RegisteredOptionList = 0;
105
106void Option::addArgument() {
107 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000108
Chris Lattner5247f602007-04-06 21:06:55 +0000109 NextRegistered = RegisteredOptionList;
110 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000111 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000112}
113
Andrew Trick0537a982013-05-06 21:56:23 +0000114// This collects the different option categories that have been registered.
115typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
116static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
117
118// Initialise the general option category.
119OptionCategory llvm::cl::GeneralCategory("General options");
120
121void OptionCategory::registerCategory()
122{
123 RegisteredOptionCategories->insert(this);
124}
Chris Lattneraf039c52007-04-12 00:36:29 +0000125
Chris Lattner5df56c42002-07-22 02:07:59 +0000126//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000127// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000128//
129
Chris Lattner5247f602007-04-06 21:06:55 +0000130/// GetOptionInfo - Scan the list of registered options, turning them into data
131/// structures that are easier to handle.
Chris Lattner131dca92009-09-20 06:18:38 +0000132static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
133 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000134 StringMap<Option*> &OptionsMap) {
Chris Lattner56efff07f2009-09-20 06:21:43 +0000135 SmallVector<const char*, 16> OptionNames;
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000136 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000137 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
138 // If this option wants to handle multiple option names, get the full set.
139 // This handles enum options like "-O1 -O2" etc.
140 O->getExtraOptionNames(OptionNames);
141 if (O->ArgStr[0])
142 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000143
Chris Lattner5247f602007-04-06 21:06:55 +0000144 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000145 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000146 // Add argument to the argument map!
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000147 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000148 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijmanc9c67152008-05-30 13:26:11 +0000149 << OptionNames[i] << "' defined more than once!\n";
Chris Lattner5247f602007-04-06 21:06:55 +0000150 }
151 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000152
Chris Lattner5247f602007-04-06 21:06:55 +0000153 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000154
Chris Lattner5247f602007-04-06 21:06:55 +0000155 // Remember information about positional options.
156 if (O->getFormattingFlag() == cl::Positional)
157 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000158 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000159 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000160 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000161 if (CAOpt)
Chris Lattner5247f602007-04-06 21:06:55 +0000162 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000163 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000164 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000165 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000166
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000167 if (CAOpt)
168 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000169
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000170 // Make sure that they are in order of registration not backwards.
171 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Chris Lattner1f790af2002-07-29 20:58:42 +0000172}
173
Chris Lattner5247f602007-04-06 21:06:55 +0000174
Chris Lattner2031b022007-04-05 21:58:17 +0000175/// LookupOption - Lookup the option specified by the specified option on the
176/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000177/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000178static Option *LookupOption(StringRef &Arg, StringRef &Value,
179 const StringMap<Option*> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000180 // Reject all dashes.
181 if (Arg.empty()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000182
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000183 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000184
Chris Lattner0a40a972009-09-20 01:53:12 +0000185 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000186 if (EqualPos == StringRef::npos) {
187 // Look up the option.
188 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
189 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000190 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000191
Chris Lattnere7c1e212009-09-20 05:03:30 +0000192 // If the argument before the = is a valid option name, we match. If not,
193 // return Arg unmolested.
194 StringMap<Option*>::const_iterator I =
195 OptionsMap.find(Arg.substr(0, EqualPos));
196 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000197
Chris Lattnere7c1e212009-09-20 05:03:30 +0000198 Value = Arg.substr(EqualPos+1);
199 Arg = Arg.substr(0, EqualPos);
200 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000201}
202
Daniel Dunbarf4132132011-01-18 01:59:24 +0000203/// LookupNearestOption - Lookup the closest match to the option specified by
204/// the specified option on the command line. If there is a value specified
205/// (after an equal sign) return that as well. This assumes that leading dashes
206/// have already been stripped.
207static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000208 const StringMap<Option*> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000209 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000210 // Reject all dashes.
211 if (Arg.empty()) return 0;
212
213 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000214 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
215 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
216 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000217
218 // Find the closest match.
219 Option *Best = 0;
220 unsigned BestDistance = 0;
221 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
222 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000223 Option *O = it->second;
224 SmallVector<const char*, 16> OptionNames;
225 O->getExtraOptionNames(OptionNames);
226 if (O->ArgStr[0])
227 OptionNames.push_back(O->ArgStr);
228
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000229 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
230 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000231 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
232 StringRef Name = OptionNames[i];
233 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000234 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000235 if (!Best || Distance < BestDistance) {
236 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000237 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000238 if (RHS.empty() || !PermitValue)
239 NearestString = OptionNames[i];
240 else
241 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000242 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000243 }
244 }
245
246 return Best;
247}
248
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000249/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
250/// does special handling of cl::CommaSeparated options.
251static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
252 StringRef ArgName,
253 StringRef Value, bool MultiArg = false)
254{
255 // Check to see if this option accepts a comma separated list of values. If
256 // it does, we have to split up the value into multiple values.
257 if (Handler->getMiscFlags() & CommaSeparated) {
258 StringRef Val(Value);
259 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000260
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000261 while (Pos != StringRef::npos) {
262 // Process the portion before the comma.
263 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
264 return true;
265 // Erase the portion before the comma, AND the comma.
266 Val = Val.substr(Pos+1);
267 Value.substr(Pos+1); // Increment the original value pointer as well.
268 // Check for another comma.
269 Pos = Val.find(',');
270 }
271
272 Value = Val;
273 }
274
275 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
276 return true;
277
278 return false;
279}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000280
Chris Lattner40fef802009-09-20 01:49:31 +0000281/// ProvideOption - For Value, this differentiates between an empty value ("")
282/// and a null value (StringRef()). The later is accepted for arguments that
283/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000284static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000285 StringRef Value, int argc,
286 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000287 // Is this a multi-argument option?
288 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
289
Chris Lattnere81c4092001-10-27 05:54:17 +0000290 // Enforce value requirements
291 switch (Handler->getValueExpectedFlag()) {
292 case ValueRequired:
Chris Lattner40fef802009-09-20 01:49:31 +0000293 if (Value.data() == 0) { // No value specified?
Chris Lattnerca2552d2009-09-20 00:07:40 +0000294 if (i+1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000295 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000296 // Steal the next argument, like for '-o filename'
297 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000298 }
299 break;
300 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000301 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000302 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000303 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000304
Chris Lattner40fef802009-09-20 01:49:31 +0000305 if (Value.data())
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000306 return Handler->error("does not allow a value! '" +
Chris Lattneraecd74d2009-09-19 18:55:05 +0000307 Twine(Value) + "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000308 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000309 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000310 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000311 }
312
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000313 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000314 if (NumAdditionalVals == 0)
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000315 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000316
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000317 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000318 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000319
Chris Lattner40fef802009-09-20 01:49:31 +0000320 if (Value.data()) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000321 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000322 return true;
323 --NumAdditionalVals;
324 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000325 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000326
327 while (NumAdditionalVals > 0) {
Chris Lattneraecd74d2009-09-19 18:55:05 +0000328 if (i+1 >= argc)
329 return Handler->error("not enough values!");
330 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000331
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000332 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000333 return true;
334 MultiArg = true;
335 --NumAdditionalVals;
336 }
337 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000338}
339
Chris Lattnerca2552d2009-09-20 00:07:40 +0000340static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000341 int Dummy = i;
Chris Lattner40fef802009-09-20 01:49:31 +0000342 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000343}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000344
Chris Lattner5df56c42002-07-22 02:07:59 +0000345
346// Option predicates...
347static inline bool isGrouping(const Option *O) {
348 return O->getFormattingFlag() == cl::Grouping;
349}
350static inline bool isPrefixedOrGrouping(const Option *O) {
351 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
352}
353
354// getOptionPred - Check to see if there are any options that satisfy the
355// specified predicate with names that are the prefixes in Name. This is
356// checked by progressively stripping characters off of the name, checking to
357// see if there options that satisfy the predicate. If we find one, return it,
358// otherwise return null.
359//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000360static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner5247f602007-04-06 21:06:55 +0000361 bool (*Pred)(const Option*),
Chris Lattnere7c1e212009-09-20 05:03:30 +0000362 const StringMap<Option*> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000363
Chris Lattnere7c1e212009-09-20 05:03:30 +0000364 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000365
Chris Lattnere7c1e212009-09-20 05:03:30 +0000366 // Loop while we haven't found an option and Name still has at least two
367 // characters in it (so that the next iteration will not be the empty
368 // string.
369 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000370 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000371 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000372 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000373
Chris Lattner5247f602007-04-06 21:06:55 +0000374 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000375 Length = Name.size();
Chris Lattner5247f602007-04-06 21:06:55 +0000376 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000377 }
378 return 0; // No option found!
379}
380
Chris Lattnere7c1e212009-09-20 05:03:30 +0000381/// HandlePrefixedOrGroupedOption - The specified argument string (which started
382/// with at least one '-') does not fully match an available option. Check to
383/// see if this is a prefix or grouped option. If so, split arg into output an
384/// Arg/Value pair and return the Option to parse it with.
385static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
386 bool &ErrorParsing,
387 const StringMap<Option*> &OptionsMap) {
388 if (Arg.size() == 1) return 0;
389
390 // Do the lookup!
391 size_t Length = 0;
392 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
393 if (PGOpt == 0) return 0;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000394
Chris Lattnere7c1e212009-09-20 05:03:30 +0000395 // If the option is a prefixed option, then the value is simply the
396 // rest of the name... so fall through to later processing, by
397 // setting up the argument name flags and value fields.
398 if (PGOpt->getFormattingFlag() == cl::Prefix) {
399 Value = Arg.substr(Length);
400 Arg = Arg.substr(0, Length);
401 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
402 return PGOpt;
403 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000404
Chris Lattnere7c1e212009-09-20 05:03:30 +0000405 // This must be a grouped option... handle them now. Grouping options can't
406 // have values.
407 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000408
Chris Lattnere7c1e212009-09-20 05:03:30 +0000409 do {
410 // Move current arg name out of Arg into OneArgName.
411 StringRef OneArgName = Arg.substr(0, Length);
412 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000413
Chris Lattnere7c1e212009-09-20 05:03:30 +0000414 // Because ValueRequired is an invalid flag for grouped arguments,
415 // we don't need to pass argc/argv in.
416 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
417 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000418 int Dummy = 0;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000419 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
420 StringRef(), 0, 0, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000421
Chris Lattnere7c1e212009-09-20 05:03:30 +0000422 // Get the next grouping option.
423 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
424 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000425
Chris Lattnere7c1e212009-09-20 05:03:30 +0000426 // Return the last option with Arg cut down to just the last one.
427 return PGOpt;
428}
429
430
431
Chris Lattner5df56c42002-07-22 02:07:59 +0000432static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000433 return O->getNumOccurrencesFlag() == cl::Required ||
434 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000435}
436
437static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000438 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
439 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000440}
Chris Lattnere81c4092001-10-27 05:54:17 +0000441
Reid Klecknera73c7782013-07-18 16:52:05 +0000442static bool isWhitespace(char C) {
443 return strchr(" \t\n\r\f\v", C);
444}
Brian Gaeke497216d2003-08-15 21:05:57 +0000445
Reid Klecknera73c7782013-07-18 16:52:05 +0000446static bool isQuote(char C) {
447 return C == '\"' || C == '\'';
448}
449
450static bool isGNUSpecial(char C) {
451 return strchr("\\\"\' ", C);
452}
453
454void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
455 SmallVectorImpl<const char *> &NewArgv) {
456 SmallString<128> Token;
457 for (size_t I = 0, E = Src.size(); I != E; ++I) {
458 // Consume runs of whitespace.
459 if (Token.empty()) {
460 while (I != E && isWhitespace(Src[I]))
461 ++I;
462 if (I == E) break;
463 }
464
465 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
466 // they are literal. This makes it much easier to read Windows file paths.
467 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
468 ++I; // Skip the escape.
469 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000470 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000471 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000472
Reid Klecknera73c7782013-07-18 16:52:05 +0000473 // Consume a quoted string.
474 if (isQuote(Src[I])) {
475 char Quote = Src[I++];
476 while (I != E && Src[I] != Quote) {
477 // Backslashes are literal, unless they escape a special character.
478 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
479 ++I;
480 Token.push_back(Src[I]);
481 ++I;
482 }
483 if (I == E) break;
484 continue;
485 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000486
Reid Klecknera73c7782013-07-18 16:52:05 +0000487 // End the token if this is whitespace.
488 if (isWhitespace(Src[I])) {
489 if (!Token.empty())
490 NewArgv.push_back(Saver.SaveString(Token.c_str()));
491 Token.clear();
492 continue;
493 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000494
Reid Klecknera73c7782013-07-18 16:52:05 +0000495 // This is a normal character. Append it.
496 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000497 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000498
499 // Append the last token after hitting EOF with no whitespace.
500 if (!Token.empty())
501 NewArgv.push_back(Saver.SaveString(Token.c_str()));
502}
503
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000504/// Backslashes are interpreted in a rather complicated way in the Windows-style
505/// command line, because backslashes are used both to separate path and to
506/// escape double quote. This method consumes runs of backslashes as well as the
507/// following double quote if it's escaped.
508///
509/// * If an even number of backslashes is followed by a double quote, one
510/// backslash is output for every pair of backslashes, and the last double
511/// quote remains unconsumed. The double quote will later be interpreted as
512/// the start or end of a quoted string in the main loop outside of this
513/// function.
514///
515/// * If an odd number of backslashes is followed by a double quote, one
516/// backslash is output for every pair of backslashes, and a double quote is
517/// output for the last pair of backslash-double quote. The double quote is
518/// consumed in this case.
519///
520/// * Otherwise, backslashes are interpreted literally.
521static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
522 size_t E = Src.size();
523 int BackslashCount = 0;
524 // Skip the backslashes.
525 do {
526 ++I;
527 ++BackslashCount;
528 } while (I != E && Src[I] == '\\');
529
530 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
531 if (FollowedByDoubleQuote) {
532 Token.append(BackslashCount / 2, '\\');
533 if (BackslashCount % 2 == 0)
534 return I - 1;
535 Token.push_back('"');
536 return I;
537 }
538 Token.append(BackslashCount, '\\');
539 return I - 1;
540}
541
Reid Klecknera73c7782013-07-18 16:52:05 +0000542void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
543 SmallVectorImpl<const char *> &NewArgv) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000544 SmallString<128> Token;
545
546 // This is a small state machine to consume characters until it reaches the
547 // end of the source string.
548 enum { INIT, UNQUOTED, QUOTED } State = INIT;
549 for (size_t I = 0, E = Src.size(); I != E; ++I) {
550 // INIT state indicates that the current input index is at the start of
551 // the string or between tokens.
552 if (State == INIT) {
553 if (isWhitespace(Src[I]))
554 continue;
555 if (Src[I] == '"') {
556 State = QUOTED;
557 continue;
558 }
559 if (Src[I] == '\\') {
560 I = parseBackslash(Src, I, Token);
561 State = UNQUOTED;
562 continue;
563 }
564 Token.push_back(Src[I]);
565 State = UNQUOTED;
566 continue;
567 }
568
569 // UNQUOTED state means that it's reading a token not quoted by double
570 // quotes.
571 if (State == UNQUOTED) {
572 // Whitespace means the end of the token.
573 if (isWhitespace(Src[I])) {
574 NewArgv.push_back(Saver.SaveString(Token.c_str()));
575 Token.clear();
576 State = INIT;
577 continue;
578 }
579 if (Src[I] == '"') {
580 State = QUOTED;
581 continue;
582 }
583 if (Src[I] == '\\') {
584 I = parseBackslash(Src, I, Token);
585 continue;
586 }
587 Token.push_back(Src[I]);
588 continue;
589 }
590
591 // QUOTED state means that it's reading a token quoted by double quotes.
592 if (State == QUOTED) {
593 if (Src[I] == '"') {
594 State = UNQUOTED;
595 continue;
596 }
597 if (Src[I] == '\\') {
598 I = parseBackslash(Src, I, Token);
599 continue;
600 }
601 Token.push_back(Src[I]);
602 }
603 }
604 // Append the last token after hitting EOF with no whitespace.
605 if (!Token.empty())
606 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000607}
608
609static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
610 TokenizerCallback Tokenizer,
611 SmallVectorImpl<const char *> &NewArgv) {
612 OwningPtr<MemoryBuffer> MemBuf;
613 if (MemoryBuffer::getFile(FName, MemBuf))
614 return false;
615 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
616
617 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
618 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
619 std::string UTF8Buf;
620 if (hasUTF16ByteOrderMark(BufRef)) {
621 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
622 return false;
623 Str = StringRef(UTF8Buf);
624 }
625
626 // Tokenize the contents into NewArgv.
627 Tokenizer(Str, Saver, NewArgv);
628
629 return true;
630}
631
632/// \brief Expand response files on a command line recursively using the given
633/// StringSaver and tokenization strategy.
634bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
635 SmallVectorImpl<const char *> &Argv) {
636 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000637 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000638
639 // Don't cache Argv.size() because it can change.
640 for (unsigned I = 0; I != Argv.size(); ) {
641 const char *Arg = Argv[I];
642 if (Arg[0] != '@') {
643 ++I;
644 continue;
645 }
646
647 // If we have too many response files, leave some unexpanded. This avoids
648 // crashing on self-referential response files.
649 if (RspFiles++ > 20)
650 return false;
651
652 // Replace this response file argument with the tokenization of its
653 // contents. Nested response files are expanded in subsequent iterations.
654 // FIXME: If a nested response file uses a relative path, is it relative to
655 // the cwd of the process or the response file?
656 SmallVector<const char *, 0> ExpandedArgv;
657 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
658 AllExpanded = false;
659 continue;
660 }
661 Argv.erase(Argv.begin() + I);
662 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
663 }
664 return AllExpanded;
665}
666
667namespace {
668 class StrDupSaver : public StringSaver {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000669 std::vector<char*> Dups;
670 public:
671 ~StrDupSaver() {
672 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
673 I != E; ++I) {
674 char *Dup = *I;
675 free(Dup);
676 }
677 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000678 const char *SaveString(const char *Str) LLVM_OVERRIDE {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000679 char *Dup = strdup(Str);
680 Dups.push_back(Dup);
681 return Dup;
Reid Klecknera73c7782013-07-18 16:52:05 +0000682 }
683 };
Brian Gaekeca782d92003-08-14 22:00:59 +0000684}
685
686/// ParseEnvironmentOptions - An alternative entry point to the
687/// CommandLine library, which allows you to read the program's name
688/// from the caller (as PROGNAME) and its command-line arguments from
689/// an environment variable (whose name is given in ENVVAR).
690///
Chris Lattnera60f3552004-05-06 22:04:31 +0000691void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000692 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000693 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000694 assert(progName && "Program name not specified");
695 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000696
Brian Gaeke497216d2003-08-15 21:05:57 +0000697 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000698 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000699 if (!envValue)
700 return;
701
Brian Gaekeca782d92003-08-14 22:00:59 +0000702 // Get program's "name", which we wouldn't know without the caller
703 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000704 SmallVector<const char *, 20> newArgv;
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000705 StrDupSaver Saver;
706 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000707
708 // Parse the value of the environment variable into a "command line"
709 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000710 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000711 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000712 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000713}
714
David Blaikie0210e972012-02-07 19:36:01 +0000715void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000716 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000717 // Process all registered options.
Chris Lattner131dca92009-09-20 06:18:38 +0000718 SmallVector<Option*, 4> PositionalOpts;
719 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000720 StringMap<Option*> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000721 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000722
Chris Lattner5247f602007-04-06 21:06:55 +0000723 assert((!Opts.empty() || !PositionalOpts.empty()) &&
724 "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000725
726 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000727 SmallVector<const char *, 20> newArgv;
728 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000729 newArgv.push_back(argv[i]);
Reid Klecknera73c7782013-07-18 16:52:05 +0000730 StrDupSaver Saver;
731 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000732 argv = &newArgv[0];
733 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000734
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000735 // Copy the program name into ProgName, making sure not to overflow it.
Michael J. Spencer762a55b2010-12-18 00:19:10 +0000736 std::string ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000737 size_t Len = std::min(ProgName.size(), size_t(79));
738 memcpy(ProgramName, ProgName.data(), Len);
739 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000740
Chris Lattner36a57d32001-07-23 17:17:47 +0000741 ProgramOverview = Overview;
742 bool ErrorParsing = false;
743
Chris Lattner5df56c42002-07-22 02:07:59 +0000744 // Check out the positional arguments to collect information about them.
745 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000746
Chris Lattnerd380d842005-08-08 17:25:38 +0000747 // Determine whether or not there are an unlimited number of positionals
748 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000749
Chris Lattner5df56c42002-07-22 02:07:59 +0000750 Option *ConsumeAfterOpt = 0;
751 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000752 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000753 assert(PositionalOpts.size() > 1 &&
754 "Cannot specify cl::ConsumeAfter without a positional argument!");
755 ConsumeAfterOpt = PositionalOpts[0];
756 }
757
758 // Calculate how many positional values are _required_.
759 bool UnboundedFound = false;
Evan Cheng86cb3182008-05-05 18:30:58 +0000760 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000761 i != e; ++i) {
762 Option *Opt = PositionalOpts[i];
763 if (RequiresValue(Opt))
764 ++NumPositionalRequired;
765 else if (ConsumeAfterOpt) {
766 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000767 // unless there is only one positional argument...
768 if (PositionalOpts.size() > 2)
769 ErrorParsing |=
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000770 Opt->error("error - this positional option will never be matched, "
Chris Lattnerd49ea882002-07-22 02:21:57 +0000771 "because it does not Require a value, and a "
772 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000773 } else if (UnboundedFound && !Opt->ArgStr[0]) {
774 // This option does not "require" a value... Make sure this option is
775 // not specified after an option that eats all extra arguments, or this
776 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000777 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000778 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000779 "another positional argument will match an "
780 "unbounded number of values, and this option"
781 " does not require a value!");
782 }
783 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
784 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000785 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000786 }
787
Reid Spencer2027a6f2004-08-13 19:47:30 +0000788 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000789 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000790 //
Chris Lattnerca2552d2009-09-20 00:07:40 +0000791 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000792
Chris Lattner2da046f2003-07-30 17:34:02 +0000793 // If the program has named positional arguments, and the name has been run
794 // across, keep track of which positional argument was named. Otherwise put
795 // the positional args into the PositionalVals list...
796 Option *ActivePositionalArg = 0;
797
Chris Lattner36a57d32001-07-23 17:17:47 +0000798 // Loop over all of the arguments... processing them.
Chris Lattner5df56c42002-07-22 02:07:59 +0000799 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000800 for (int i = 1; i < argc; ++i) {
801 Option *Handler = 0;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000802 Option *NearestHandler = 0;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000803 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000804 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000805 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000806
Chris Lattneraf039c52007-04-12 00:36:29 +0000807 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000808 // option has just been registered or deregistered. This can occur in
809 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000810 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000811 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000812 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000813 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000814 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000815 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000816 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000817
Chris Lattner5df56c42002-07-22 02:07:59 +0000818 // Check to see if this is a positional argument. This argument is
819 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000820 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000821 //
822 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
823 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000824 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000825 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner2da046f2003-07-30 17:34:02 +0000826 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000827 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000828
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000829 if (!PositionalOpts.empty()) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000830 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000831
832 // All of the positional arguments have been fulfulled, give the rest to
833 // the consume after option... if it's specified...
834 //
Misha Brukman10468d82005-04-21 22:55:34 +0000835 if (PositionalVals.size() >= NumPositionalRequired &&
Chris Lattner5df56c42002-07-22 02:07:59 +0000836 ConsumeAfterOpt != 0) {
837 for (++i; i < argc; ++i)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000838 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000839 break; // Handle outside of the argument processing loop...
840 }
841
842 // Delay processing positional arguments until the end...
843 continue;
844 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000845 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
846 !DashDashFound) {
847 DashDashFound = true; // This is the mythical "--"?
848 continue; // Don't try to process it as an argument itself.
849 } else if (ActivePositionalArg &&
850 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
851 // If there is a positional argument eating options, check to see if this
852 // option is another positional argument. If so, treat it as an argument,
853 // otherwise feed it to the eating positional.
Chris Lattner36a57d32001-07-23 17:17:47 +0000854 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000855 // Eat leading dashes.
856 while (!ArgName.empty() && ArgName[0] == '-')
857 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000858
Chris Lattner5247f602007-04-06 21:06:55 +0000859 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000860 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000861 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnera60f3552004-05-06 22:04:31 +0000862 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000863 }
864
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000865 } else { // We start with a '-', must be an argument.
Chris Lattnera60f3552004-05-06 22:04:31 +0000866 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000867 // Eat leading dashes.
868 while (!ArgName.empty() && ArgName[0] == '-')
869 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000870
Chris Lattner5247f602007-04-06 21:06:55 +0000871 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000872
Chris Lattnera60f3552004-05-06 22:04:31 +0000873 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000874 if (Handler == 0)
875 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
876 ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000877
878 // Otherwise, look for the closest available option to report to the user
879 // in the upcoming error.
880 if (Handler == 0 && SinkOpts.empty())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000881 NearestHandler = LookupNearestOption(ArgName, Opts,
882 NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000883 }
884
885 if (Handler == 0) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000886 if (SinkOpts.empty()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000887 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands142b9ed2010-02-18 14:08:13 +0000888 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000889
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000890 if (NearestHandler) {
891 // If we know a near match, report it as well.
892 errs() << ProgramName << ": Did you mean '-"
893 << NearestHandlerString << "'?\n";
894 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000895
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000896 ErrorParsing = true;
897 } else {
Chris Lattner131dca92009-09-20 06:18:38 +0000898 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000899 E = SinkOpts.end(); I != E ; ++I)
900 (*I)->addOccurrence(i, "", argv[i]);
901 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000902 continue;
903 }
904
Chris Lattner2da046f2003-07-30 17:34:02 +0000905 // If this is a named positional argument, just remember that it is the
906 // active one...
907 if (Handler->getFormattingFlag() == cl::Positional)
908 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000909 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000910 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000911 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000912
Chris Lattner5df56c42002-07-22 02:07:59 +0000913 // Check and handle positional arguments now...
914 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000915 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000916 << ": Not enough positional command line arguments specified!\n"
917 << "Must specify at least " << NumPositionalRequired
Duncan Sands142b9ed2010-02-18 14:08:13 +0000918 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000919
Chris Lattner5df56c42002-07-22 02:07:59 +0000920 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000921 } else if (!HasUnlimitedPositionals &&
922 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000923 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000924 << ": Too many positional arguments specified!\n"
925 << "Can specify at most " << PositionalOpts.size()
Duncan Sands142b9ed2010-02-18 14:08:13 +0000926 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +0000927 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +0000928
929 } else if (ConsumeAfterOpt == 0) {
Chris Lattnere7c1e212009-09-20 05:03:30 +0000930 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +0000931 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
932 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000933 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +0000934 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000935 PositionalVals[ValNo].second);
936 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000937 --NumPositionalRequired; // We fulfilled our duty...
938 }
939
940 // If we _can_ give this option more arguments, do so now, as long as we
941 // do not give it values that others need. 'Done' controls whether the
942 // option even _WANTS_ any more.
943 //
Misha Brukman069e6b52003-07-10 16:49:51 +0000944 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner5df56c42002-07-22 02:07:59 +0000945 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000946 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000947 case cl::Optional:
948 Done = true; // Optional arguments want _at most_ one value
949 // FALL THROUGH
950 case cl::ZeroOrMore: // Zero or more will take all they can get...
951 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +0000952 ProvidePositionalOption(PositionalOpts[i],
953 PositionalVals[ValNo].first,
954 PositionalVals[ValNo].second);
955 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000956 break;
957 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000958 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner5df56c42002-07-22 02:07:59 +0000959 "positional argument processing!");
960 }
961 }
Chris Lattnere81c4092001-10-27 05:54:17 +0000962 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000963 } else {
964 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
965 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +0000966 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000967 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000968 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000969 PositionalVals[ValNo].first,
970 PositionalVals[ValNo].second);
971 ValNo++;
972 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000973
974 // Handle the case where there is just one positional option, and it's
975 // optional. In this case, we want to give JUST THE FIRST option to the
976 // positional option and keep the rest for the consume after. The above
977 // loop would have assigned no values to positional options in this case.
978 //
Reid Spencer2027a6f2004-08-13 19:47:30 +0000979 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000980 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000981 PositionalVals[ValNo].first,
982 PositionalVals[ValNo].second);
983 ValNo++;
984 }
Misha Brukman10468d82005-04-21 22:55:34 +0000985
Chris Lattner5df56c42002-07-22 02:07:59 +0000986 // Handle over all of the rest of the arguments to the
987 // cl::ConsumeAfter command line option...
988 for (; ValNo != PositionalVals.size(); ++ValNo)
989 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000990 PositionalVals[ValNo].first,
991 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +0000992 }
993
Chris Lattner4fdde2c2001-07-23 23:02:45 +0000994 // Loop over args and make sure all required args are specified!
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000995 for (StringMap<Option*>::iterator I = Opts.begin(),
Misha Brukmanc18333a2003-07-10 17:05:26 +0000996 E = Opts.end(); I != E; ++I) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000997 switch (I->second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +0000998 case Required:
999 case OneOrMore:
Misha Brukman069e6b52003-07-10 16:49:51 +00001000 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001001 I->second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001002 ErrorParsing = true;
1003 }
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001004 // Fall through
1005 default:
1006 break;
1007 }
1008 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001009
Rafael Espindolacf14a382010-11-19 21:14:29 +00001010 // Now that we know if -debug is specified, we can use it.
1011 // Note that if ReadResponseFiles == true, this must be done before the
1012 // memory allocated for the expanded command line is free()d below.
1013 DEBUG(dbgs() << "Args: ";
1014 for (int i = 0; i < argc; ++i)
1015 dbgs() << argv[i] << ' ';
1016 dbgs() << '\n';
1017 );
1018
Chris Lattner5df56c42002-07-22 02:07:59 +00001019 // Free all of the memory allocated to the map. Command line options may only
1020 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001021 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001022 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001023 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001024
1025 // If we had an error processing our arguments, don't let the program execute
1026 if (ErrorParsing) exit(1);
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// Option Base class implementation
1031//
Chris Lattner36a57d32001-07-23 17:17:47 +00001032
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001033bool Option::error(const Twine &Message, StringRef ArgName) {
1034 if (ArgName.data() == 0) ArgName = ArgStr;
1035 if (ArgName.empty())
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001036 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001037 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001038 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001039
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001040 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001041 return true;
1042}
1043
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001044bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001045 StringRef Value, bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001046 if (!MultiArg)
1047 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001048
Misha Brukman069e6b52003-07-10 16:49:51 +00001049 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001050 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001051 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001052 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001053 break;
1054 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001055 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001056 return error("must occur exactly one time!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001057 // Fall through
1058 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001059 case ZeroOrMore:
1060 case ConsumeAfter: break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001061 }
1062
Reid Spencer2027a6f2004-08-13 19:47:30 +00001063 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001064}
1065
Chris Lattner5df56c42002-07-22 02:07:59 +00001066
1067// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1068// has been specified yet.
1069//
1070static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1071 if (O.ValueStr[0] == 0) return DefaultMsg;
1072 return O.ValueStr;
1073}
1074
1075//===----------------------------------------------------------------------===//
1076// cl::alias class implementation
1077//
1078
Chris Lattner36a57d32001-07-23 17:17:47 +00001079// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001080size_t alias::getOptionWidth() const {
Chris Lattner36a57d32001-07-23 17:17:47 +00001081 return std::strlen(ArgStr)+6;
1082}
1083
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001084static void printHelpStr(StringRef HelpStr, size_t Indent,
1085 size_t FirstLineIndentedBy) {
1086 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1087 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1088 while (!Split.second.empty()) {
1089 Split = Split.second.split('\n');
1090 outs().indent(Indent) << Split.first << "\n";
1091 }
1092}
1093
Chris Lattner1b7a5152006-04-28 05:36:25 +00001094// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001095void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001096 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001097 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001098}
1099
Chris Lattner36a57d32001-07-23 17:17:47 +00001100//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001101// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001102//
1103
Chris Lattnerb4101b12002-08-07 18:36:37 +00001104// basic_parser implementation
1105//
1106
1107// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001108size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1109 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001110 if (const char *ValName = getValueName())
1111 Len += std::strlen(getValueStr(O, ValName))+3;
1112
1113 return Len + 6;
1114}
1115
Misha Brukman10468d82005-04-21 22:55:34 +00001116// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001117// to-be-maintained width is specified.
1118//
1119void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001120 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001121 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001122
1123 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001124 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001125
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001126 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001127}
1128
Andrew Trick12004012011-04-05 18:54:36 +00001129void basic_parser_impl::printOptionName(const Option &O,
1130 size_t GlobalWidth) const {
1131 outs() << " -" << O.ArgStr;
1132 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1133}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001134
1135
Chris Lattner5df56c42002-07-22 02:07:59 +00001136// parser<bool> implementation
1137//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001138bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001139 StringRef Arg, bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001140 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001141 Arg == "1") {
1142 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001143 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001144 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001145
Chris Lattneraecd74d2009-09-19 18:55:05 +00001146 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1147 Value = false;
1148 return false;
1149 }
1150 return O.error("'" + Arg +
1151 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001152}
1153
Dale Johannesen82810c82007-05-22 17:14:46 +00001154// parser<boolOrDefault> implementation
1155//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001156bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001157 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001158 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1159 Arg == "1") {
1160 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001161 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001162 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001163 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1164 Value = BOU_FALSE;
1165 return false;
1166 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001167
Chris Lattneraecd74d2009-09-19 18:55:05 +00001168 return O.error("'" + Arg +
1169 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001170}
1171
Chris Lattner5df56c42002-07-22 02:07:59 +00001172// parser<int> implementation
1173//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001174bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001175 StringRef Arg, int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001176 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001177 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001178 return false;
1179}
1180
Chris Lattner719c7152003-06-28 15:47:20 +00001181// parser<unsigned> implementation
1182//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001183bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001184 StringRef Arg, unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001185
1186 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001187 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001188 return false;
1189}
1190
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001191// parser<unsigned long long> implementation
1192//
1193bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1194 StringRef Arg, unsigned long long &Value){
1195
1196 if (Arg.getAsInteger(0, Value))
1197 return O.error("'" + Arg + "' value invalid for uint argument!");
1198 return false;
1199}
1200
Chris Lattnerb4101b12002-08-07 18:36:37 +00001201// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001202//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001203static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001204 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1205 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001206 char *End;
1207 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001208 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001209 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001210 return false;
1211}
1212
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001213bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001214 StringRef Arg, double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001215 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001216}
1217
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001218bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001219 StringRef Arg, float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001220 double dVal;
1221 if (parseDouble(O, Arg, dVal))
1222 return true;
1223 Val = (float)dVal;
1224 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001225}
1226
1227
Chris Lattner5df56c42002-07-22 02:07:59 +00001228
1229// generic_parser_base implementation
1230//
1231
Chris Lattner494c0b02002-07-23 17:15:12 +00001232// findOption - Return the option number corresponding to the specified
1233// argument string. If the option is not found, getNumOptions() is returned.
1234//
1235unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001236 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001237
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001238 for (unsigned i = 0; i != e; ++i) {
1239 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001240 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001241 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001242 return e;
1243}
1244
1245
Chris Lattner5df56c42002-07-22 02:07:59 +00001246// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001247size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001248 if (O.hasArgStr()) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001249 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001250 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001251 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001252 return Size;
1253 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001254 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001255 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001256 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001257 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001258 }
1259}
1260
Misha Brukman10468d82005-04-21 22:55:34 +00001261// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001262// to-be-maintained width is specified.
1263//
1264void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001265 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001266 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001267 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001268 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001269
Chris Lattner5df56c42002-07-22 02:07:59 +00001270 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001271 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001272 outs() << " =" << getOption(i);
1273 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001274 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001275 } else {
1276 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001277 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001278 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001279 const char *Option = getOption(i);
1280 outs() << " -" << Option;
1281 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001282 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001283 }
1284}
1285
Andrew Trick12004012011-04-05 18:54:36 +00001286static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1287
1288// printGenericOptionDiff - Print the value of this option and it's default.
1289//
1290// "Generic" options have each value mapped to a name.
1291void generic_parser_base::
1292printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1293 const GenericOptionValue &Default,
1294 size_t GlobalWidth) const {
1295 outs() << " -" << O.ArgStr;
1296 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1297
1298 unsigned NumOpts = getNumOptions();
1299 for (unsigned i = 0; i != NumOpts; ++i) {
1300 if (Value.compare(getOptionValue(i)))
1301 continue;
1302
1303 outs() << "= " << getOption(i);
1304 size_t L = std::strlen(getOption(i));
1305 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1306 outs().indent(NumSpaces) << " (default: ";
1307 for (unsigned j = 0; j != NumOpts; ++j) {
1308 if (Default.compare(getOptionValue(j)))
1309 continue;
1310 outs() << getOption(j);
1311 break;
1312 }
1313 outs() << ")\n";
1314 return;
1315 }
1316 outs() << "= *unknown option value*\n";
1317}
1318
1319// printOptionDiff - Specializations for printing basic value types.
1320//
1321#define PRINT_OPT_DIFF(T) \
1322 void parser<T>:: \
1323 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1324 size_t GlobalWidth) const { \
1325 printOptionName(O, GlobalWidth); \
1326 std::string Str; \
1327 { \
1328 raw_string_ostream SS(Str); \
1329 SS << V; \
1330 } \
1331 outs() << "= " << Str; \
1332 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1333 outs().indent(NumSpaces) << " (default: "; \
1334 if (D.hasValue()) \
1335 outs() << D.getValue(); \
1336 else \
1337 outs() << "*no default*"; \
1338 outs() << ")\n"; \
1339 } \
1340
Frits van Bommel87e33672011-04-06 12:29:56 +00001341PRINT_OPT_DIFF(bool)
1342PRINT_OPT_DIFF(boolOrDefault)
1343PRINT_OPT_DIFF(int)
1344PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001345PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001346PRINT_OPT_DIFF(double)
1347PRINT_OPT_DIFF(float)
1348PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001349
1350void parser<std::string>::
1351printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1352 size_t GlobalWidth) const {
1353 printOptionName(O, GlobalWidth);
1354 outs() << "= " << V;
1355 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1356 outs().indent(NumSpaces) << " (default: ";
1357 if (D.hasValue())
1358 outs() << D.getValue();
1359 else
1360 outs() << "*no default*";
1361 outs() << ")\n";
1362}
1363
1364// Print a placeholder for options that don't yet support printOptionDiff().
1365void basic_parser_impl::
1366printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1367 printOptionName(O, GlobalWidth);
1368 outs() << "= *cannot print option value*\n";
1369}
Chris Lattner36a57d32001-07-23 17:17:47 +00001370
1371//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001372// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001373//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001374
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001375static int OptNameCompare(const void *LHS, const void *RHS) {
1376 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001377
Duncan Sands79d793e2012-03-12 10:51:06 +00001378 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001379}
1380
Andrew Trick12004012011-04-05 18:54:36 +00001381// Copy Options into a vector so we can sort them as we like.
1382static void
1383sortOpts(StringMap<Option*> &OptMap,
1384 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1385 bool ShowHidden) {
1386 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1387
1388 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1389 I != E; ++I) {
1390 // Ignore really-hidden options.
1391 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1392 continue;
1393
1394 // Unless showhidden is set, ignore hidden flags.
1395 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1396 continue;
1397
1398 // If we've already seen this option, don't add it to the list again.
1399 if (!OptionSet.insert(I->second))
1400 continue;
1401
1402 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1403 I->second));
1404 }
1405
1406 // Sort the options list alphabetically.
1407 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1408}
1409
Chris Lattner36a57d32001-07-23 17:17:47 +00001410namespace {
1411
Chris Lattner5df56c42002-07-22 02:07:59 +00001412class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001413protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001414 const bool ShowHidden;
Andrew Trick0537a982013-05-06 21:56:23 +00001415 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1416 // Print the options. Opts is assumed to be alphabetically sorted.
1417 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1418 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1419 Opts[i].second->printOptionInfo(MaxArgLen);
1420 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001421
Chris Lattner5df56c42002-07-22 02:07:59 +00001422public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001423 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001424 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001425
Andrew Trick0537a982013-05-06 21:56:23 +00001426 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001427 void operator=(bool Value) {
1428 if (Value == false) return;
1429
Chris Lattner5247f602007-04-06 21:06:55 +00001430 // Get all the options.
Chris Lattner131dca92009-09-20 06:18:38 +00001431 SmallVector<Option*, 4> PositionalOpts;
1432 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001433 StringMap<Option*> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001434 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001435
Andrew Trick0537a982013-05-06 21:56:23 +00001436 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001437 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001438
1439 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001440 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001441
Chris Lattner471ba482009-08-23 08:43:55 +00001442 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001443
Chris Lattner8111c592006-10-04 21:52:35 +00001444 // Print out the positional options.
Chris Lattner5df56c42002-07-22 02:07:59 +00001445 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001446 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001447 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1448 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001449
Evan Cheng86cb3182008-05-05 18:30:58 +00001450 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001451 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001452 outs() << " --" << PositionalOpts[i]->ArgStr;
1453 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001454 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001455
1456 // Print the consume after option info if it exists...
Chris Lattner471ba482009-08-23 08:43:55 +00001457 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001458
Chris Lattner471ba482009-08-23 08:43:55 +00001459 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001460
1461 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001462 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001463 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001464 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001465
Chris Lattner471ba482009-08-23 08:43:55 +00001466 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001467 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001468
Chris Lattner37bcd992004-11-19 17:08:15 +00001469 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001470 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001471 E = MoreHelp->end();
1472 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001473 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001474 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001475
Reid Spencer5e554702004-11-16 06:11:52 +00001476 // Halt the program since help information was printed
Chris Lattner5df56c42002-07-22 02:07:59 +00001477 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001478 }
1479};
Andrew Trick0537a982013-05-06 21:56:23 +00001480
1481class CategorizedHelpPrinter : public HelpPrinter {
1482public:
1483 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1484
1485 // Helper function for printOptions().
1486 // It shall return true if A's name should be lexographically
1487 // ordered before B's name. It returns false otherwise.
1488 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1489 int Length = strcmp(A->getName(), B->getName());
1490 assert(Length != 0 && "Duplicate option categories");
1491 return Length < 0;
1492 }
1493
1494 // Make sure we inherit our base class's operator=()
1495 using HelpPrinter::operator= ;
1496
1497protected:
1498 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1499 std::vector<OptionCategory *> SortedCategories;
1500 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1501
1502 // Collect registered option categories into vector in preperation for
1503 // sorting.
1504 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1505 E = RegisteredOptionCategories->end();
1506 I != E; ++I)
1507 SortedCategories.push_back(*I);
1508
1509 // Sort the different option categories alphabetically.
1510 assert(SortedCategories.size() > 0 && "No option categories registered!");
1511 std::sort(SortedCategories.begin(), SortedCategories.end(),
1512 OptionCategoryCompare);
1513
1514 // Create map to empty vectors.
1515 for (std::vector<OptionCategory *>::const_iterator
1516 I = SortedCategories.begin(),
1517 E = SortedCategories.end();
1518 I != E; ++I)
1519 CategorizedOptions[*I] = std::vector<Option *>();
1520
1521 // Walk through pre-sorted options and assign into categories.
1522 // Because the options are already alphabetically sorted the
1523 // options within categories will also be alphabetically sorted.
1524 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1525 Option *Opt = Opts[I].second;
1526 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1527 "Option has an unregistered category");
1528 CategorizedOptions[Opt->Category].push_back(Opt);
1529 }
1530
1531 // Now do printing.
1532 for (std::vector<OptionCategory *>::const_iterator
1533 Category = SortedCategories.begin(),
1534 E = SortedCategories.end();
1535 Category != E; ++Category) {
1536 // Hide empty categories for -help, but show for -help-hidden.
1537 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1538 if (!ShowHidden && IsEmptyCategory)
1539 continue;
1540
1541 // Print category information.
1542 outs() << "\n";
1543 outs() << (*Category)->getName() << ":\n";
1544
1545 // Check if description is set.
1546 if ((*Category)->getDescription() != 0)
1547 outs() << (*Category)->getDescription() << "\n\n";
1548 else
1549 outs() << "\n";
1550
1551 // When using -help-hidden explicitly state if the category has no
1552 // options associated with it.
1553 if (IsEmptyCategory) {
1554 outs() << " This option category has no options.\n";
1555 continue;
1556 }
1557 // Loop over the options in the category and print.
1558 for (std::vector<Option *>::const_iterator
1559 Opt = CategorizedOptions[*Category].begin(),
1560 E = CategorizedOptions[*Category].end();
1561 Opt != E; ++Opt)
1562 (*Opt)->printOptionInfo(MaxArgLen);
1563 }
1564 }
1565};
1566
1567// This wraps the Uncategorizing and Categorizing printers and decides
1568// at run time which should be invoked.
1569class HelpPrinterWrapper {
1570private:
1571 HelpPrinter &UncategorizedPrinter;
1572 CategorizedHelpPrinter &CategorizedPrinter;
1573
1574public:
1575 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1576 CategorizedHelpPrinter &CategorizedPrinter) :
1577 UncategorizedPrinter(UncategorizedPrinter),
1578 CategorizedPrinter(CategorizedPrinter) { }
1579
1580 // Invoke the printer.
1581 void operator=(bool Value);
1582};
1583
Chris Lattneradb19d62006-10-12 22:09:17 +00001584} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001585
Andrew Trick0537a982013-05-06 21:56:23 +00001586// Declare the four HelpPrinter instances that are used to print out help, or
1587// help-hidden as an uncategorized list or in categories.
1588static HelpPrinter UncategorizedNormalPrinter(false);
1589static HelpPrinter UncategorizedHiddenPrinter(true);
1590static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1591static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1592
1593
1594// Declare HelpPrinter wrappers that will decide whether or not to invoke
1595// a categorizing help printer
1596static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1597 CategorizedNormalPrinter);
1598static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1599 CategorizedHiddenPrinter);
1600
1601// Define uncategorized help printers.
1602// -help-list is hidden by default because if Option categories are being used
1603// then -help behaves the same as -help-list.
1604static cl::opt<HelpPrinter, true, parser<bool> >
1605HLOp("help-list",
1606 cl::desc("Display list of available options (-help-list-hidden for more)"),
1607 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001608
Chris Lattneradb19d62006-10-12 22:09:17 +00001609static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trick0537a982013-05-06 21:56:23 +00001610HLHOp("help-list-hidden",
1611 cl::desc("Display list of all available options"),
1612 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1613
1614// Define uncategorized/categorized help printers. These printers change their
1615// behaviour at runtime depending on whether one or more Option categories have
1616// been declared.
1617static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands142b9ed2010-02-18 14:08:13 +00001618HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trick0537a982013-05-06 21:56:23 +00001619 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001620
Andrew Trick0537a982013-05-06 21:56:23 +00001621static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001622HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trick0537a982013-05-06 21:56:23 +00001623 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1624
1625
Chris Lattner36a57d32001-07-23 17:17:47 +00001626
Andrew Trick12004012011-04-05 18:54:36 +00001627static cl::opt<bool>
1628PrintOptions("print-options",
1629 cl::desc("Print non-default options after command line parsing"),
1630 cl::Hidden, cl::init(false));
1631
1632static cl::opt<bool>
1633PrintAllOptions("print-all-options",
1634 cl::desc("Print all option values after command line parsing"),
1635 cl::Hidden, cl::init(false));
1636
Andrew Trick0537a982013-05-06 21:56:23 +00001637void HelpPrinterWrapper::operator=(bool Value) {
1638 if (Value == false)
1639 return;
1640
1641 // Decide which printer to invoke. If more than one option category is
1642 // registered then it is useful to show the categorized help instead of
1643 // uncategorized help.
1644 if (RegisteredOptionCategories->size() > 1) {
1645 // unhide -help-list option so user can have uncategorized output if they
1646 // want it.
1647 HLOp.setHiddenFlag(NotHidden);
1648
1649 CategorizedPrinter = true; // Invoke categorized printer
1650 }
1651 else
1652 UncategorizedPrinter = true; // Invoke uncategorized printer
1653}
1654
Andrew Trick12004012011-04-05 18:54:36 +00001655// Print the value of each option.
1656void cl::PrintOptionValues() {
1657 if (!PrintOptions && !PrintAllOptions) return;
1658
1659 // Get all the options.
1660 SmallVector<Option*, 4> PositionalOpts;
1661 SmallVector<Option*, 4> SinkOpts;
1662 StringMap<Option*> OptMap;
1663 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1664
1665 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1666 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1667
1668 // Compute the maximum argument length...
1669 size_t MaxArgLen = 0;
1670 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1671 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1672
1673 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1674 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1675}
1676
Chris Lattneradb19d62006-10-12 22:09:17 +00001677static void (*OverrideVersionPrinter)() = 0;
Reid Spencerb3171672006-06-05 16:22:56 +00001678
Chandler Carruthea7e5522011-07-22 07:50:40 +00001679static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1680
Chris Lattneradb19d62006-10-12 22:09:17 +00001681namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001682class VersionPrinter {
1683public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001684 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001685 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001686 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001687 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001688#ifdef LLVM_VERSION_INFO
Chris Lattner131dca92009-09-20 06:18:38 +00001689 OS << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001690#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001691 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001692#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001693 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001694#else
Chris Lattner131dca92009-09-20 06:18:38 +00001695 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001696#endif
1697#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001698 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001699#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001700 std::string CPU = sys::getHostCPUName();
Benjamin Kramer713fd352009-11-17 17:57:04 +00001701 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001702 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001703#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001704 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001705#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001706 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001707 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001708 }
1709 void operator=(bool OptionWasSpecified) {
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001710 if (!OptionWasSpecified) return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001711
Chandler Carruthea7e5522011-07-22 07:50:40 +00001712 if (OverrideVersionPrinter != 0) {
1713 (*OverrideVersionPrinter)();
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001714 exit(1);
Reid Spencerb3171672006-06-05 16:22:56 +00001715 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001716 print();
1717
1718 // Iterate over any registered extra printers and call them to add further
1719 // information.
1720 if (ExtraVersionPrinters != 0) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001721 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001722 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1723 E = ExtraVersionPrinters->end();
1724 I != E; ++I)
1725 (*I)();
1726 }
1727
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001728 exit(1);
Reid Spencerb3171672006-06-05 16:22:56 +00001729 }
1730};
Chris Lattneradb19d62006-10-12 22:09:17 +00001731} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001732
1733
Reid Spencerff6cc122004-08-04 00:36:06 +00001734// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001735static VersionPrinter VersionPrinterInstance;
1736
1737static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001738VersOp("version", cl::desc("Display the version of this program"),
Reid Spencerff6cc122004-08-04 00:36:06 +00001739 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1740
Reid Spencer5e554702004-11-16 06:11:52 +00001741// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001742void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1743 // This looks weird, but it actually prints the help message. The Printers are
1744 // types of HelpPrinter and the help gets printed when its operator= is
1745 // invoked. That's because the "normal" usages of the help printer is to be
1746 // assigned true/false depending on whether -help or -help-hidden was given or
1747 // not. Since we're circumventing that we have to make it look like -help or
1748 // -help-hidden were given, so we assign true.
1749
1750 if (!Hidden && !Categorized)
1751 UncategorizedNormalPrinter = true;
1752 else if (!Hidden && Categorized)
1753 CategorizedNormalPrinter = true;
1754 else if (Hidden && !Categorized)
1755 UncategorizedHiddenPrinter = true;
1756 else
1757 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001758}
Reid Spencerb3171672006-06-05 16:22:56 +00001759
Devang Patel9eb2caae2007-02-01 01:43:37 +00001760/// Utility function for printing version number.
1761void cl::PrintVersionMessage() {
1762 VersionPrinterInstance.print();
1763}
1764
Reid Spencerb3171672006-06-05 16:22:56 +00001765void cl::SetVersionPrinter(void (*func)()) {
1766 OverrideVersionPrinter = func;
1767}
Chandler Carruthea7e5522011-07-22 07:50:40 +00001768
1769void cl::AddExtraVersionPrinter(void (*func)()) {
1770 if (ExtraVersionPrinters == 0)
1771 ExtraVersionPrinters = new std::vector<void (*)()>;
1772
1773 ExtraVersionPrinters->push_back(func);
1774}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001775
1776void cl::getRegisteredOptions(StringMap<Option*> &Map)
1777{
1778 // Get all the options.
1779 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1780 SmallVector<Option*, 4> SinkOpts; //NOT USED
1781 assert(Map.size() == 0 && "StringMap must be empty");
1782 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1783 return;
1784}