blob: 4c1df5c47dd544f497be52c3f6cc57d898eca9f6 [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000020#include "llvm/ADT/ArrayRef.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000021#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000023#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000024#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000025#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000026#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/Host.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/raw_ostream.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000034#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000035#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000036#include <map>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000037#include <system_error>
Chris Lattnerc9499b62003-12-14 21:35:53 +000038using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000039using namespace cl;
40
Chandler Carruthe96dd892014-04-21 22:55:11 +000041#define DEBUG_TYPE "commandline"
42
Chris Lattner3e5d60f2006-08-27 12:45:47 +000043//===----------------------------------------------------------------------===//
44// Template instantiations and anchors.
45//
Douglas Gregor7baad732009-11-25 06:04:18 +000046namespace llvm { namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000047TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000048TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<int>);
50TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000051TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000052TEMPLATE_INSTANTIATION(class basic_parser<double>);
53TEMPLATE_INSTANTIATION(class basic_parser<float>);
54TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000055TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000056
57TEMPLATE_INSTANTIATION(class opt<unsigned>);
58TEMPLATE_INSTANTIATION(class opt<int>);
59TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000060TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000061TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor7baad732009-11-25 06:04:18 +000062} } // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000063
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000064// Pin the vtables to this file.
65void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000066void OptionValue<boolOrDefault>::anchor() {}
67void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000068void Option::anchor() {}
69void basic_parser_impl::anchor() {}
70void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000071void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000072void parser<int>::anchor() {}
73void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000074void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000075void parser<double>::anchor() {}
76void parser<float>::anchor() {}
77void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000078void parser<char>::anchor() {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000079void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000080
81//===----------------------------------------------------------------------===//
82
Chris Lattner5af1cbc2006-10-13 00:06:24 +000083// Globals for name and overview of program. Program name is not a string to
84// avoid static ctor/dtor issues.
85static char ProgramName[80] = "<premain>";
Craig Topperc10719f2014-04-07 04:17:22 +000086static const char *ProgramOverview = nullptr;
Reid Spencer9501b9b2004-09-01 04:41:28 +000087
Chris Lattner37bcd992004-11-19 17:08:15 +000088// This collects additional help to be printed.
Chris Lattner8111c592006-10-04 21:52:35 +000089static ManagedStatic<std::vector<const char*> > MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000090
Chris Lattner8111c592006-10-04 21:52:35 +000091extrahelp::extrahelp(const char *Help)
Chris Lattner37bcd992004-11-19 17:08:15 +000092 : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000093 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000094}
95
Chris Lattneraf039c52007-04-12 00:36:29 +000096static bool OptionListChanged = false;
97
98// MarkOptionsChanged - Internal helper function.
99void cl::MarkOptionsChanged() {
100 OptionListChanged = true;
101}
102
Chris Lattner5247f602007-04-06 21:06:55 +0000103/// RegisteredOptionList - This is the list of the command line options that
104/// have statically constructed themselves.
Craig Topperc10719f2014-04-07 04:17:22 +0000105static Option *RegisteredOptionList = nullptr;
Chris Lattner5247f602007-04-06 21:06:55 +0000106
107void Option::addArgument() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000108 assert(!NextRegistered && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000109
Chris Lattner5247f602007-04-06 21:06:55 +0000110 NextRegistered = RegisteredOptionList;
111 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000112 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000113}
114
Jordan Rosec25b0c72014-01-29 18:54:17 +0000115void Option::removeArgument() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000116 assert(NextRegistered && "argument never registered");
Jordan Rosec25b0c72014-01-29 18:54:17 +0000117 assert(RegisteredOptionList == this && "argument is not the last registered");
118 RegisteredOptionList = NextRegistered;
119 MarkOptionsChanged();
120}
121
Andrew Trick0537a982013-05-06 21:56:23 +0000122// This collects the different option categories that have been registered.
123typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
124static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
125
126// Initialise the general option category.
127OptionCategory llvm::cl::GeneralCategory("General options");
128
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000129void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000130 assert(std::count_if(RegisteredOptionCategories->begin(),
131 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000132 [this](const OptionCategory *Category) {
133 return getName() == Category->getName();
134 }) == 0 && "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000135
Andrew Trick0537a982013-05-06 21:56:23 +0000136 RegisteredOptionCategories->insert(this);
137}
Chris Lattneraf039c52007-04-12 00:36:29 +0000138
Chris Lattner5df56c42002-07-22 02:07:59 +0000139//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000140// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000141//
142
Chris Lattner5247f602007-04-06 21:06:55 +0000143/// GetOptionInfo - Scan the list of registered options, turning them into data
144/// structures that are easier to handle.
Chris Lattner131dca92009-09-20 06:18:38 +0000145static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
146 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000147 StringMap<Option*> &OptionsMap) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000148 bool HadErrors = false;
Chris Lattner56efff07f2009-09-20 06:21:43 +0000149 SmallVector<const char*, 16> OptionNames;
Craig Topperc10719f2014-04-07 04:17:22 +0000150 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000151 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
152 // If this option wants to handle multiple option names, get the full set.
153 // This handles enum options like "-O1 -O2" etc.
154 O->getExtraOptionNames(OptionNames);
155 if (O->ArgStr[0])
156 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000157
Chris Lattner5247f602007-04-06 21:06:55 +0000158 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000159 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000160 // Add argument to the argument map!
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000161 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000162 errs() << ProgramName << ": CommandLine Error: Option '"
163 << OptionNames[i] << "' registered more than once!\n";
164 HadErrors = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000165 }
166 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000167
Chris Lattner5247f602007-04-06 21:06:55 +0000168 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000169
Chris Lattner5247f602007-04-06 21:06:55 +0000170 // Remember information about positional options.
171 if (O->getFormattingFlag() == cl::Positional)
172 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000173 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000174 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000175 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000176 if (CAOpt) {
Chris Lattner5247f602007-04-06 21:06:55 +0000177 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000178 HadErrors = true;
179 }
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000180 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000181 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000182 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000183
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000184 if (CAOpt)
185 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000186
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000187 // Make sure that they are in order of registration not backwards.
188 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000189
190 // Fail hard if there were errors. These are strictly unrecoverable and
191 // indicate serious issues such as conflicting option names or an incorrectly
192 // linked LLVM distribution.
193 if (HadErrors)
194 report_fatal_error("inconsistency in registered CommandLine options");
Chris Lattner1f790af2002-07-29 20:58:42 +0000195}
196
Chris Lattner5247f602007-04-06 21:06:55 +0000197
Chris Lattner2031b022007-04-05 21:58:17 +0000198/// LookupOption - Lookup the option specified by the specified option on the
199/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000200/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000201static Option *LookupOption(StringRef &Arg, StringRef &Value,
202 const StringMap<Option*> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000203 // Reject all dashes.
Craig Topperc10719f2014-04-07 04:17:22 +0000204 if (Arg.empty()) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000205
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000206 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000207
Chris Lattner0a40a972009-09-20 01:53:12 +0000208 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000209 if (EqualPos == StringRef::npos) {
210 // Look up the option.
211 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000212 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000213 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000214
Chris Lattnere7c1e212009-09-20 05:03:30 +0000215 // If the argument before the = is a valid option name, we match. If not,
216 // return Arg unmolested.
217 StringMap<Option*>::const_iterator I =
218 OptionsMap.find(Arg.substr(0, EqualPos));
Craig Topperc10719f2014-04-07 04:17:22 +0000219 if (I == OptionsMap.end()) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000220
Chris Lattnere7c1e212009-09-20 05:03:30 +0000221 Value = Arg.substr(EqualPos+1);
222 Arg = Arg.substr(0, EqualPos);
223 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000224}
225
Daniel Dunbarf4132132011-01-18 01:59:24 +0000226/// LookupNearestOption - Lookup the closest match to the option specified by
227/// the specified option on the command line. If there is a value specified
228/// (after an equal sign) return that as well. This assumes that leading dashes
229/// have already been stripped.
230static Option *LookupNearestOption(StringRef Arg,
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000231 const StringMap<Option*> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000232 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000233 // Reject all dashes.
Craig Topperc10719f2014-04-07 04:17:22 +0000234 if (Arg.empty()) return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000235
236 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000237 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
238 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
239 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000240
241 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000242 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000243 unsigned BestDistance = 0;
244 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
245 ie = OptionsMap.end(); it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000246 Option *O = it->second;
247 SmallVector<const char*, 16> OptionNames;
248 O->getExtraOptionNames(OptionNames);
249 if (O->ArgStr[0])
250 OptionNames.push_back(O->ArgStr);
251
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000252 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
253 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000254 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
255 StringRef Name = OptionNames[i];
256 unsigned Distance = StringRef(Name).edit_distance(
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000257 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000258 if (!Best || Distance < BestDistance) {
259 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000260 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000261 if (RHS.empty() || !PermitValue)
262 NearestString = OptionNames[i];
263 else
264 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000265 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000266 }
267 }
268
269 return Best;
270}
271
Alp Tokercb402912014-01-24 17:20:08 +0000272/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
273/// that does special handling of cl::CommaSeparated options.
274static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
275 StringRef ArgName, StringRef Value,
276 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000277 // Check to see if this option accepts a comma separated list of values. If
278 // it does, we have to split up the value into multiple values.
279 if (Handler->getMiscFlags() & CommaSeparated) {
280 StringRef Val(Value);
281 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000282
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000283 while (Pos != StringRef::npos) {
284 // Process the portion before the comma.
285 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
286 return true;
287 // Erase the portion before the comma, AND the comma.
288 Val = Val.substr(Pos+1);
289 Value.substr(Pos+1); // Increment the original value pointer as well.
290 // Check for another comma.
291 Pos = Val.find(',');
292 }
293
294 Value = Val;
295 }
296
297 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
298 return true;
299
300 return false;
301}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000302
Chris Lattner40fef802009-09-20 01:49:31 +0000303/// ProvideOption - For Value, this differentiates between an empty value ("")
304/// and a null value (StringRef()). The later is accepted for arguments that
305/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000306static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000307 StringRef Value, int argc,
308 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000309 // Is this a multi-argument option?
310 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
311
Chris Lattnere81c4092001-10-27 05:54:17 +0000312 // Enforce value requirements
313 switch (Handler->getValueExpectedFlag()) {
314 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000315 if (!Value.data()) { // No value specified?
Chris Lattnerca2552d2009-09-20 00:07:40 +0000316 if (i+1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000317 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000318 // Steal the next argument, like for '-o filename'
319 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000320 }
321 break;
322 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000323 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000324 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000325 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000326
Chris Lattner40fef802009-09-20 01:49:31 +0000327 if (Value.data())
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000328 return Handler->error("does not allow a value! '" +
Chris Lattneraecd74d2009-09-19 18:55:05 +0000329 Twine(Value) + "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000330 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000331 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000332 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000333 }
334
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000335 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000336 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000337 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000338
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000339 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000340 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000341
Chris Lattner40fef802009-09-20 01:49:31 +0000342 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000343 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000344 return true;
345 --NumAdditionalVals;
346 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000347 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000348
349 while (NumAdditionalVals > 0) {
Chris Lattneraecd74d2009-09-19 18:55:05 +0000350 if (i+1 >= argc)
351 return Handler->error("not enough values!");
352 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000353
Alp Tokercb402912014-01-24 17:20:08 +0000354 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000355 return true;
356 MultiArg = true;
357 --NumAdditionalVals;
358 }
359 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000360}
361
Chris Lattnerca2552d2009-09-20 00:07:40 +0000362static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000363 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000364 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000365}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000366
Chris Lattner5df56c42002-07-22 02:07:59 +0000367
368// Option predicates...
369static inline bool isGrouping(const Option *O) {
370 return O->getFormattingFlag() == cl::Grouping;
371}
372static inline bool isPrefixedOrGrouping(const Option *O) {
373 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
374}
375
376// getOptionPred - Check to see if there are any options that satisfy the
377// specified predicate with names that are the prefixes in Name. This is
378// checked by progressively stripping characters off of the name, checking to
379// see if there options that satisfy the predicate. If we find one, return it,
380// otherwise return null.
381//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000382static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Lattner5247f602007-04-06 21:06:55 +0000383 bool (*Pred)(const Option*),
Chris Lattnere7c1e212009-09-20 05:03:30 +0000384 const StringMap<Option*> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000385
Chris Lattnere7c1e212009-09-20 05:03:30 +0000386 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000387
Chris Lattnere7c1e212009-09-20 05:03:30 +0000388 // Loop while we haven't found an option and Name still has at least two
389 // characters in it (so that the next iteration will not be the empty
390 // string.
391 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000392 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000393 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000394 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000395
Chris Lattner5247f602007-04-06 21:06:55 +0000396 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000397 Length = Name.size();
Chris Lattner5247f602007-04-06 21:06:55 +0000398 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000399 }
Craig Topperc10719f2014-04-07 04:17:22 +0000400 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000401}
402
Chris Lattnere7c1e212009-09-20 05:03:30 +0000403/// HandlePrefixedOrGroupedOption - The specified argument string (which started
404/// with at least one '-') does not fully match an available option. Check to
405/// see if this is a prefix or grouped option. If so, split arg into output an
406/// Arg/Value pair and return the Option to parse it with.
407static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
408 bool &ErrorParsing,
409 const StringMap<Option*> &OptionsMap) {
Craig Topperc10719f2014-04-07 04:17:22 +0000410 if (Arg.size() == 1) return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000411
412 // Do the lookup!
413 size_t Length = 0;
414 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Craig Topper8d399f82014-04-09 04:20:00 +0000415 if (!PGOpt) return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000416
Chris Lattnere7c1e212009-09-20 05:03:30 +0000417 // If the option is a prefixed option, then the value is simply the
418 // rest of the name... so fall through to later processing, by
419 // setting up the argument name flags and value fields.
420 if (PGOpt->getFormattingFlag() == cl::Prefix) {
421 Value = Arg.substr(Length);
422 Arg = Arg.substr(0, Length);
423 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
424 return PGOpt;
425 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000426
Chris Lattnere7c1e212009-09-20 05:03:30 +0000427 // This must be a grouped option... handle them now. Grouping options can't
428 // have values.
429 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000430
Chris Lattnere7c1e212009-09-20 05:03:30 +0000431 do {
432 // Move current arg name out of Arg into OneArgName.
433 StringRef OneArgName = Arg.substr(0, Length);
434 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000435
Chris Lattnere7c1e212009-09-20 05:03:30 +0000436 // Because ValueRequired is an invalid flag for grouped arguments,
437 // we don't need to pass argc/argv in.
438 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
439 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000440 int Dummy = 0;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000441 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
Craig Topperc10719f2014-04-07 04:17:22 +0000442 StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000443
Chris Lattnere7c1e212009-09-20 05:03:30 +0000444 // Get the next grouping option.
445 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
446 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000447
Chris Lattnere7c1e212009-09-20 05:03:30 +0000448 // Return the last option with Arg cut down to just the last one.
449 return PGOpt;
450}
451
452
453
Chris Lattner5df56c42002-07-22 02:07:59 +0000454static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000455 return O->getNumOccurrencesFlag() == cl::Required ||
456 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000457}
458
459static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000460 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
461 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000462}
Chris Lattnere81c4092001-10-27 05:54:17 +0000463
Reid Klecknera73c7782013-07-18 16:52:05 +0000464static bool isWhitespace(char C) {
465 return strchr(" \t\n\r\f\v", C);
466}
Brian Gaeke497216d2003-08-15 21:05:57 +0000467
Reid Klecknera73c7782013-07-18 16:52:05 +0000468static bool isQuote(char C) {
469 return C == '\"' || C == '\'';
470}
471
472static bool isGNUSpecial(char C) {
473 return strchr("\\\"\' ", C);
474}
475
476void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
477 SmallVectorImpl<const char *> &NewArgv) {
478 SmallString<128> Token;
479 for (size_t I = 0, E = Src.size(); I != E; ++I) {
480 // Consume runs of whitespace.
481 if (Token.empty()) {
482 while (I != E && isWhitespace(Src[I]))
483 ++I;
484 if (I == E) break;
485 }
486
487 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
488 // they are literal. This makes it much easier to read Windows file paths.
489 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
490 ++I; // Skip the escape.
491 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000492 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000493 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000494
Reid Klecknera73c7782013-07-18 16:52:05 +0000495 // Consume a quoted string.
496 if (isQuote(Src[I])) {
497 char Quote = Src[I++];
498 while (I != E && Src[I] != Quote) {
499 // Backslashes are literal, unless they escape a special character.
500 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
501 ++I;
502 Token.push_back(Src[I]);
503 ++I;
504 }
505 if (I == E) break;
506 continue;
507 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000508
Reid Klecknera73c7782013-07-18 16:52:05 +0000509 // End the token if this is whitespace.
510 if (isWhitespace(Src[I])) {
511 if (!Token.empty())
512 NewArgv.push_back(Saver.SaveString(Token.c_str()));
513 Token.clear();
514 continue;
515 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000516
Reid Klecknera73c7782013-07-18 16:52:05 +0000517 // This is a normal character. Append it.
518 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000519 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000520
521 // Append the last token after hitting EOF with no whitespace.
522 if (!Token.empty())
523 NewArgv.push_back(Saver.SaveString(Token.c_str()));
524}
525
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000526/// Backslashes are interpreted in a rather complicated way in the Windows-style
527/// command line, because backslashes are used both to separate path and to
528/// escape double quote. This method consumes runs of backslashes as well as the
529/// following double quote if it's escaped.
530///
531/// * If an even number of backslashes is followed by a double quote, one
532/// backslash is output for every pair of backslashes, and the last double
533/// quote remains unconsumed. The double quote will later be interpreted as
534/// the start or end of a quoted string in the main loop outside of this
535/// function.
536///
537/// * If an odd number of backslashes is followed by a double quote, one
538/// backslash is output for every pair of backslashes, and a double quote is
539/// output for the last pair of backslash-double quote. The double quote is
540/// consumed in this case.
541///
542/// * Otherwise, backslashes are interpreted literally.
543static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
544 size_t E = Src.size();
545 int BackslashCount = 0;
546 // Skip the backslashes.
547 do {
548 ++I;
549 ++BackslashCount;
550 } while (I != E && Src[I] == '\\');
551
552 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
553 if (FollowedByDoubleQuote) {
554 Token.append(BackslashCount / 2, '\\');
555 if (BackslashCount % 2 == 0)
556 return I - 1;
557 Token.push_back('"');
558 return I;
559 }
560 Token.append(BackslashCount, '\\');
561 return I - 1;
562}
563
Reid Klecknera73c7782013-07-18 16:52:05 +0000564void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
565 SmallVectorImpl<const char *> &NewArgv) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000566 SmallString<128> Token;
567
568 // This is a small state machine to consume characters until it reaches the
569 // end of the source string.
570 enum { INIT, UNQUOTED, QUOTED } State = INIT;
571 for (size_t I = 0, E = Src.size(); I != E; ++I) {
572 // INIT state indicates that the current input index is at the start of
573 // the string or between tokens.
574 if (State == INIT) {
575 if (isWhitespace(Src[I]))
576 continue;
577 if (Src[I] == '"') {
578 State = QUOTED;
579 continue;
580 }
581 if (Src[I] == '\\') {
582 I = parseBackslash(Src, I, Token);
583 State = UNQUOTED;
584 continue;
585 }
586 Token.push_back(Src[I]);
587 State = UNQUOTED;
588 continue;
589 }
590
591 // UNQUOTED state means that it's reading a token not quoted by double
592 // quotes.
593 if (State == UNQUOTED) {
594 // Whitespace means the end of the token.
595 if (isWhitespace(Src[I])) {
596 NewArgv.push_back(Saver.SaveString(Token.c_str()));
597 Token.clear();
598 State = INIT;
599 continue;
600 }
601 if (Src[I] == '"') {
602 State = QUOTED;
603 continue;
604 }
605 if (Src[I] == '\\') {
606 I = parseBackslash(Src, I, Token);
607 continue;
608 }
609 Token.push_back(Src[I]);
610 continue;
611 }
612
613 // QUOTED state means that it's reading a token quoted by double quotes.
614 if (State == QUOTED) {
615 if (Src[I] == '"') {
616 State = UNQUOTED;
617 continue;
618 }
619 if (Src[I] == '\\') {
620 I = parseBackslash(Src, I, Token);
621 continue;
622 }
623 Token.push_back(Src[I]);
624 }
625 }
626 // Append the last token after hitting EOF with no whitespace.
627 if (!Token.empty())
628 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000629}
630
631static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
632 TokenizerCallback Tokenizer,
633 SmallVectorImpl<const char *> &NewArgv) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000634 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
635 MemoryBuffer::getFile(FName);
636 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000637 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000638 MemoryBuffer &MemBuf = *MemBufOrErr.get();
639 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000640
641 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000642 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000643 std::string UTF8Buf;
644 if (hasUTF16ByteOrderMark(BufRef)) {
645 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
646 return false;
647 Str = StringRef(UTF8Buf);
648 }
649
650 // Tokenize the contents into NewArgv.
651 Tokenizer(Str, Saver, NewArgv);
652
653 return true;
654}
655
656/// \brief Expand response files on a command line recursively using the given
657/// StringSaver and tokenization strategy.
658bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
659 SmallVectorImpl<const char *> &Argv) {
660 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000661 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000662
663 // Don't cache Argv.size() because it can change.
664 for (unsigned I = 0; I != Argv.size(); ) {
665 const char *Arg = Argv[I];
666 if (Arg[0] != '@') {
667 ++I;
668 continue;
669 }
670
671 // If we have too many response files, leave some unexpanded. This avoids
672 // crashing on self-referential response files.
673 if (RspFiles++ > 20)
674 return false;
675
676 // Replace this response file argument with the tokenization of its
677 // contents. Nested response files are expanded in subsequent iterations.
678 // FIXME: If a nested response file uses a relative path, is it relative to
679 // the cwd of the process or the response file?
680 SmallVector<const char *, 0> ExpandedArgv;
681 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000682 // We couldn't read this file, so we leave it in the argument stream and
683 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000684 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000685 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000686 continue;
687 }
688 Argv.erase(Argv.begin() + I);
689 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
690 }
691 return AllExpanded;
692}
693
694namespace {
695 class StrDupSaver : public StringSaver {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000696 std::vector<char*> Dups;
697 public:
698 ~StrDupSaver() {
699 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
700 I != E; ++I) {
701 char *Dup = *I;
702 free(Dup);
703 }
704 }
Craig Topper73156022014-03-02 09:09:27 +0000705 const char *SaveString(const char *Str) override {
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000706 char *Dup = strdup(Str);
707 Dups.push_back(Dup);
708 return Dup;
Reid Klecknera73c7782013-07-18 16:52:05 +0000709 }
710 };
Brian Gaekeca782d92003-08-14 22:00:59 +0000711}
712
713/// ParseEnvironmentOptions - An alternative entry point to the
714/// CommandLine library, which allows you to read the program's name
715/// from the caller (as PROGNAME) and its command-line arguments from
716/// an environment variable (whose name is given in ENVVAR).
717///
Chris Lattnera60f3552004-05-06 22:04:31 +0000718void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000719 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000720 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000721 assert(progName && "Program name not specified");
722 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000723
Brian Gaeke497216d2003-08-15 21:05:57 +0000724 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000725 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000726 if (!envValue)
727 return;
728
Brian Gaekeca782d92003-08-14 22:00:59 +0000729 // Get program's "name", which we wouldn't know without the caller
730 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000731 SmallVector<const char *, 20> newArgv;
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000732 StrDupSaver Saver;
733 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000734
735 // Parse the value of the environment variable into a "command line"
736 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000737 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000738 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000739 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000740}
741
David Blaikie0210e972012-02-07 19:36:01 +0000742void cl::ParseCommandLineOptions(int argc, const char * const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000743 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000744 // Process all registered options.
Chris Lattner131dca92009-09-20 06:18:38 +0000745 SmallVector<Option*, 4> PositionalOpts;
746 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +0000747 StringMap<Option*> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000748 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000749
Chris Lattner5247f602007-04-06 21:06:55 +0000750 assert((!Opts.empty() || !PositionalOpts.empty()) &&
751 "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000752
753 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000754 SmallVector<const char *, 20> newArgv;
755 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000756 newArgv.push_back(argv[i]);
Reid Klecknera73c7782013-07-18 16:52:05 +0000757 StrDupSaver Saver;
758 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000759 argv = &newArgv[0];
760 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000761
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000762 // Copy the program name into ProgName, making sure not to overflow it.
NAKAMURA Takumic2c66492014-04-23 14:51:23 +0000763 StringRef ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000764 size_t Len = std::min(ProgName.size(), size_t(79));
765 memcpy(ProgramName, ProgName.data(), Len);
766 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000767
Chris Lattner36a57d32001-07-23 17:17:47 +0000768 ProgramOverview = Overview;
769 bool ErrorParsing = false;
770
Chris Lattner5df56c42002-07-22 02:07:59 +0000771 // Check out the positional arguments to collect information about them.
772 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000773
Chris Lattnerd380d842005-08-08 17:25:38 +0000774 // Determine whether or not there are an unlimited number of positionals
775 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000776
Craig Topperc10719f2014-04-07 04:17:22 +0000777 Option *ConsumeAfterOpt = nullptr;
Chris Lattner5df56c42002-07-22 02:07:59 +0000778 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000779 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000780 assert(PositionalOpts.size() > 1 &&
781 "Cannot specify cl::ConsumeAfter without a positional argument!");
782 ConsumeAfterOpt = PositionalOpts[0];
783 }
784
785 // Calculate how many positional values are _required_.
786 bool UnboundedFound = false;
Craig Topper8d399f82014-04-09 04:20:00 +0000787 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000788 i != e; ++i) {
789 Option *Opt = PositionalOpts[i];
790 if (RequiresValue(Opt))
791 ++NumPositionalRequired;
792 else if (ConsumeAfterOpt) {
793 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000794 // unless there is only one positional argument...
795 if (PositionalOpts.size() > 2)
796 ErrorParsing |=
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000797 Opt->error("error - this positional option will never be matched, "
Chris Lattnerd49ea882002-07-22 02:21:57 +0000798 "because it does not Require a value, and a "
799 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000800 } else if (UnboundedFound && !Opt->ArgStr[0]) {
801 // This option does not "require" a value... Make sure this option is
802 // not specified after an option that eats all extra arguments, or this
803 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000804 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000805 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000806 "another positional argument will match an "
807 "unbounded number of values, and this option"
808 " does not require a value!");
809 }
810 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
811 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000812 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000813 }
814
Reid Spencer2027a6f2004-08-13 19:47:30 +0000815 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000816 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000817 //
Chris Lattnerca2552d2009-09-20 00:07:40 +0000818 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000819
Chris Lattner2da046f2003-07-30 17:34:02 +0000820 // If the program has named positional arguments, and the name has been run
821 // across, keep track of which positional argument was named. Otherwise put
822 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000823 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000824
Chris Lattner36a57d32001-07-23 17:17:47 +0000825 // Loop over all of the arguments... processing them.
Chris Lattner5df56c42002-07-22 02:07:59 +0000826 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000827 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000828 Option *Handler = nullptr;
829 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000830 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000831 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000832 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000833
Chris Lattneraf039c52007-04-12 00:36:29 +0000834 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000835 // option has just been registered or deregistered. This can occur in
836 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000837 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000838 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000839 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000840 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000841 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000842 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000843 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000844
Chris Lattner5df56c42002-07-22 02:07:59 +0000845 // Check to see if this is a positional argument. This argument is
846 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000847 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000848 //
849 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
850 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000851 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000852 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattner2da046f2003-07-30 17:34:02 +0000853 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000854 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000855
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000856 if (!PositionalOpts.empty()) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000857 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000858
859 // All of the positional arguments have been fulfulled, give the rest to
860 // the consume after option... if it's specified...
861 //
Craig Topper8d399f82014-04-09 04:20:00 +0000862 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000863 for (++i; i < argc; ++i)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000864 PositionalVals.push_back(std::make_pair(argv[i],i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000865 break; // Handle outside of the argument processing loop...
866 }
867
868 // Delay processing positional arguments until the end...
869 continue;
870 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000871 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
872 !DashDashFound) {
873 DashDashFound = true; // This is the mythical "--"?
874 continue; // Don't try to process it as an argument itself.
875 } else if (ActivePositionalArg &&
876 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
877 // If there is a positional argument eating options, check to see if this
878 // option is another positional argument. If so, treat it as an argument,
879 // otherwise feed it to the eating positional.
Chris Lattner36a57d32001-07-23 17:17:47 +0000880 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000881 // Eat leading dashes.
882 while (!ArgName.empty() && ArgName[0] == '-')
883 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000884
Chris Lattner5247f602007-04-06 21:06:55 +0000885 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000886 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000887 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Lattnera60f3552004-05-06 22:04:31 +0000888 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000889 }
890
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000891 } else { // We start with a '-', must be an argument.
Chris Lattnera60f3552004-05-06 22:04:31 +0000892 ArgName = argv[i]+1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000893 // Eat leading dashes.
894 while (!ArgName.empty() && ArgName[0] == '-')
895 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000896
Chris Lattner5247f602007-04-06 21:06:55 +0000897 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000898
Chris Lattnera60f3552004-05-06 22:04:31 +0000899 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000900 if (!Handler)
Chris Lattnere7c1e212009-09-20 05:03:30 +0000901 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
902 ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000903
904 // Otherwise, look for the closest available option to report to the user
905 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000906 if (!Handler && SinkOpts.empty())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000907 NearestHandler = LookupNearestOption(ArgName, Opts,
908 NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000909 }
910
Craig Topper8d399f82014-04-09 04:20:00 +0000911 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000912 if (SinkOpts.empty()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000913 errs() << ProgramName << ": Unknown command line argument '"
Duncan Sands142b9ed2010-02-18 14:08:13 +0000914 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000915
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000916 if (NearestHandler) {
917 // If we know a near match, report it as well.
918 errs() << ProgramName << ": Did you mean '-"
919 << NearestHandlerString << "'?\n";
920 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000921
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000922 ErrorParsing = true;
923 } else {
Chris Lattner131dca92009-09-20 06:18:38 +0000924 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000925 E = SinkOpts.end(); I != E ; ++I)
926 (*I)->addOccurrence(i, "", argv[i]);
927 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000928 continue;
929 }
930
Chris Lattner2da046f2003-07-30 17:34:02 +0000931 // If this is a named positional argument, just remember that it is the
932 // active one...
933 if (Handler->getFormattingFlag() == cl::Positional)
934 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000935 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000936 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000937 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000938
Chris Lattner5df56c42002-07-22 02:07:59 +0000939 // Check and handle positional arguments now...
940 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000941 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000942 << ": Not enough positional command line arguments specified!\n"
943 << "Must specify at least " << NumPositionalRequired
Duncan Sands142b9ed2010-02-18 14:08:13 +0000944 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000945
Chris Lattner5df56c42002-07-22 02:07:59 +0000946 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000947 } else if (!HasUnlimitedPositionals &&
948 PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000949 errs() << ProgramName
Bill Wendlingf3baad32006-12-07 01:30:32 +0000950 << ": Too many positional arguments specified!\n"
951 << "Can specify at most " << PositionalOpts.size()
Duncan Sands142b9ed2010-02-18 14:08:13 +0000952 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +0000953 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +0000954
Craig Topper8d399f82014-04-09 04:20:00 +0000955 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +0000956 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +0000957 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
958 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000959 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +0000960 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +0000961 PositionalVals[ValNo].second);
962 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000963 --NumPositionalRequired; // We fulfilled our duty...
964 }
965
966 // If we _can_ give this option more arguments, do so now, as long as we
967 // do not give it values that others need. 'Done' controls whether the
968 // option even _WANTS_ any more.
969 //
Misha Brukman069e6b52003-07-10 16:49:51 +0000970 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Lattner5df56c42002-07-22 02:07:59 +0000971 while (NumVals-ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000972 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000973 case cl::Optional:
974 Done = true; // Optional arguments want _at most_ one value
975 // FALL THROUGH
976 case cl::ZeroOrMore: // Zero or more will take all they can get...
977 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +0000978 ProvidePositionalOption(PositionalOpts[i],
979 PositionalVals[ValNo].first,
980 PositionalVals[ValNo].second);
981 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +0000982 break;
983 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +0000984 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Lattner5df56c42002-07-22 02:07:59 +0000985 "positional argument processing!");
986 }
987 }
Chris Lattnere81c4092001-10-27 05:54:17 +0000988 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000989 } else {
990 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
991 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +0000992 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +0000993 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000994 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +0000995 PositionalVals[ValNo].first,
996 PositionalVals[ValNo].second);
997 ValNo++;
998 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +0000999
1000 // Handle the case where there is just one positional option, and it's
1001 // optional. In this case, we want to give JUST THE FIRST option to the
1002 // positional option and keep the rest for the consume after. The above
1003 // loop would have assigned no values to positional options in this case.
1004 //
Reid Spencer2027a6f2004-08-13 19:47:30 +00001005 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001006 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001007 PositionalVals[ValNo].first,
1008 PositionalVals[ValNo].second);
1009 ValNo++;
1010 }
Misha Brukman10468d82005-04-21 22:55:34 +00001011
Chris Lattner5df56c42002-07-22 02:07:59 +00001012 // Handle over all of the rest of the arguments to the
1013 // cl::ConsumeAfter command line option...
1014 for (; ValNo != PositionalVals.size(); ++ValNo)
1015 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001016 PositionalVals[ValNo].first,
1017 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001018 }
1019
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001020 // Loop over args and make sure all required args are specified!
Justin Bogner973b2ff2014-07-14 19:24:13 +00001021 for (const auto &Opt : Opts) {
1022 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001023 case Required:
1024 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001025 if (Opt.second->getNumOccurrences() == 0) {
1026 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001027 ErrorParsing = true;
1028 }
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001029 // Fall through
1030 default:
1031 break;
1032 }
1033 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001034
Rafael Espindolacf14a382010-11-19 21:14:29 +00001035 // Now that we know if -debug is specified, we can use it.
1036 // Note that if ReadResponseFiles == true, this must be done before the
1037 // memory allocated for the expanded command line is free()d below.
1038 DEBUG(dbgs() << "Args: ";
1039 for (int i = 0; i < argc; ++i)
1040 dbgs() << argv[i] << ' ';
1041 dbgs() << '\n';
1042 );
1043
Chris Lattner5df56c42002-07-22 02:07:59 +00001044 // Free all of the memory allocated to the map. Command line options may only
1045 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001046 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001047 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001048 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001049
1050 // If we had an error processing our arguments, don't let the program execute
1051 if (ErrorParsing) exit(1);
1052}
1053
1054//===----------------------------------------------------------------------===//
1055// Option Base class implementation
1056//
Chris Lattner36a57d32001-07-23 17:17:47 +00001057
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001058bool Option::error(const Twine &Message, StringRef ArgName) {
Craig Topper8d399f82014-04-09 04:20:00 +00001059 if (!ArgName.data()) ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001060 if (ArgName.empty())
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001061 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001062 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001063 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001064
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001065 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001066 return true;
1067}
1068
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001069bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001070 StringRef Value, bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001071 if (!MultiArg)
1072 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001073
Misha Brukman069e6b52003-07-10 16:49:51 +00001074 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001075 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001076 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001077 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001078 break;
1079 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001080 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001081 return error("must occur exactly one time!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001082 // Fall through
1083 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001084 case ZeroOrMore:
1085 case ConsumeAfter: break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001086 }
1087
Reid Spencer2027a6f2004-08-13 19:47:30 +00001088 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001089}
1090
Chris Lattner5df56c42002-07-22 02:07:59 +00001091
1092// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1093// has been specified yet.
1094//
1095static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1096 if (O.ValueStr[0] == 0) return DefaultMsg;
1097 return O.ValueStr;
1098}
1099
1100//===----------------------------------------------------------------------===//
1101// cl::alias class implementation
1102//
1103
Chris Lattner36a57d32001-07-23 17:17:47 +00001104// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001105size_t alias::getOptionWidth() const {
Chris Lattner36a57d32001-07-23 17:17:47 +00001106 return std::strlen(ArgStr)+6;
1107}
1108
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001109static void printHelpStr(StringRef HelpStr, size_t Indent,
1110 size_t FirstLineIndentedBy) {
1111 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1112 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1113 while (!Split.second.empty()) {
1114 Split = Split.second.split('\n');
1115 outs().indent(Indent) << Split.first << "\n";
1116 }
1117}
1118
Chris Lattner1b7a5152006-04-28 05:36:25 +00001119// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001120void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001121 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001122 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001123}
1124
Chris Lattner36a57d32001-07-23 17:17:47 +00001125//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001126// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001127//
1128
Chris Lattnerb4101b12002-08-07 18:36:37 +00001129// basic_parser implementation
1130//
1131
1132// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001133size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1134 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001135 if (const char *ValName = getValueName())
1136 Len += std::strlen(getValueStr(O, ValName))+3;
1137
1138 return Len + 6;
1139}
1140
Misha Brukman10468d82005-04-21 22:55:34 +00001141// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001142// to-be-maintained width is specified.
1143//
1144void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001145 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001146 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001147
1148 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001149 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001150
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001151 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001152}
1153
Andrew Trick12004012011-04-05 18:54:36 +00001154void basic_parser_impl::printOptionName(const Option &O,
1155 size_t GlobalWidth) const {
1156 outs() << " -" << O.ArgStr;
1157 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1158}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001159
1160
Chris Lattner5df56c42002-07-22 02:07:59 +00001161// parser<bool> implementation
1162//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001163bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001164 StringRef Arg, bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001165 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001166 Arg == "1") {
1167 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001168 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001169 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001170
Chris Lattneraecd74d2009-09-19 18:55:05 +00001171 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1172 Value = false;
1173 return false;
1174 }
1175 return O.error("'" + Arg +
1176 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001177}
1178
Dale Johannesen82810c82007-05-22 17:14:46 +00001179// parser<boolOrDefault> implementation
1180//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001181bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001182 StringRef Arg, boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001183 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1184 Arg == "1") {
1185 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001186 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001187 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001188 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1189 Value = BOU_FALSE;
1190 return false;
1191 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001192
Chris Lattneraecd74d2009-09-19 18:55:05 +00001193 return O.error("'" + Arg +
1194 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001195}
1196
Chris Lattner5df56c42002-07-22 02:07:59 +00001197// parser<int> implementation
1198//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001199bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001200 StringRef Arg, int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001201 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001202 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001203 return false;
1204}
1205
Chris Lattner719c7152003-06-28 15:47:20 +00001206// parser<unsigned> implementation
1207//
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001208bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001209 StringRef Arg, unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001210
1211 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001212 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001213 return false;
1214}
1215
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001216// parser<unsigned long long> implementation
1217//
1218bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1219 StringRef Arg, unsigned long long &Value){
1220
1221 if (Arg.getAsInteger(0, Value))
1222 return O.error("'" + Arg + "' value invalid for uint argument!");
1223 return false;
1224}
1225
Chris Lattnerb4101b12002-08-07 18:36:37 +00001226// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001227//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001228static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001229 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1230 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001231 char *End;
1232 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001233 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001234 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001235 return false;
1236}
1237
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001238bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001239 StringRef Arg, double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001240 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001241}
1242
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001243bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattneraecd74d2009-09-19 18:55:05 +00001244 StringRef Arg, float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001245 double dVal;
1246 if (parseDouble(O, Arg, dVal))
1247 return true;
1248 Val = (float)dVal;
1249 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001250}
1251
1252
Chris Lattner5df56c42002-07-22 02:07:59 +00001253
1254// generic_parser_base implementation
1255//
1256
Chris Lattner494c0b02002-07-23 17:15:12 +00001257// findOption - Return the option number corresponding to the specified
1258// argument string. If the option is not found, getNumOptions() is returned.
1259//
1260unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001261 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001262
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001263 for (unsigned i = 0; i != e; ++i) {
1264 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001265 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001266 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001267 return e;
1268}
1269
1270
Chris Lattner5df56c42002-07-22 02:07:59 +00001271// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001272size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001273 if (O.hasArgStr()) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001274 size_t Size = std::strlen(O.ArgStr)+6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001275 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001276 Size = std::max(Size, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001277 return Size;
1278 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001279 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001280 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng86cb3182008-05-05 18:30:58 +00001281 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001282 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001283 }
1284}
1285
Misha Brukman10468d82005-04-21 22:55:34 +00001286// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001287// to-be-maintained width is specified.
1288//
1289void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001290 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001291 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001292 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001293 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001294
Chris Lattner5df56c42002-07-22 02:07:59 +00001295 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng86cb3182008-05-05 18:30:58 +00001296 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001297 outs() << " =" << getOption(i);
1298 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001299 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001300 } else {
1301 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001302 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001303 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001304 const char *Option = getOption(i);
1305 outs() << " -" << Option;
1306 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001307 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001308 }
1309}
1310
Andrew Trick12004012011-04-05 18:54:36 +00001311static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1312
1313// printGenericOptionDiff - Print the value of this option and it's default.
1314//
1315// "Generic" options have each value mapped to a name.
1316void generic_parser_base::
1317printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1318 const GenericOptionValue &Default,
1319 size_t GlobalWidth) const {
1320 outs() << " -" << O.ArgStr;
1321 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1322
1323 unsigned NumOpts = getNumOptions();
1324 for (unsigned i = 0; i != NumOpts; ++i) {
1325 if (Value.compare(getOptionValue(i)))
1326 continue;
1327
1328 outs() << "= " << getOption(i);
1329 size_t L = std::strlen(getOption(i));
1330 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1331 outs().indent(NumSpaces) << " (default: ";
1332 for (unsigned j = 0; j != NumOpts; ++j) {
1333 if (Default.compare(getOptionValue(j)))
1334 continue;
1335 outs() << getOption(j);
1336 break;
1337 }
1338 outs() << ")\n";
1339 return;
1340 }
1341 outs() << "= *unknown option value*\n";
1342}
1343
1344// printOptionDiff - Specializations for printing basic value types.
1345//
Alp Tokere69170a2014-06-26 22:52:05 +00001346#define PRINT_OPT_DIFF(T) \
1347 void parser<T>:: \
1348 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1349 size_t GlobalWidth) const { \
1350 printOptionName(O, GlobalWidth); \
1351 std::string Str; \
1352 { \
1353 raw_string_ostream SS(Str); \
1354 SS << V; \
1355 } \
1356 outs() << "= " << Str; \
1357 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1358 outs().indent(NumSpaces) << " (default: "; \
1359 if (D.hasValue()) \
1360 outs() << D.getValue(); \
1361 else \
1362 outs() << "*no default*"; \
1363 outs() << ")\n"; \
1364 } \
Andrew Trick12004012011-04-05 18:54:36 +00001365
Frits van Bommel87e33672011-04-06 12:29:56 +00001366PRINT_OPT_DIFF(bool)
1367PRINT_OPT_DIFF(boolOrDefault)
1368PRINT_OPT_DIFF(int)
1369PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001370PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001371PRINT_OPT_DIFF(double)
1372PRINT_OPT_DIFF(float)
1373PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001374
1375void parser<std::string>::
1376printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1377 size_t GlobalWidth) const {
1378 printOptionName(O, GlobalWidth);
1379 outs() << "= " << V;
1380 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1381 outs().indent(NumSpaces) << " (default: ";
1382 if (D.hasValue())
1383 outs() << D.getValue();
1384 else
1385 outs() << "*no default*";
1386 outs() << ")\n";
1387}
1388
1389// Print a placeholder for options that don't yet support printOptionDiff().
1390void basic_parser_impl::
1391printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1392 printOptionName(O, GlobalWidth);
1393 outs() << "= *cannot print option value*\n";
1394}
Chris Lattner36a57d32001-07-23 17:17:47 +00001395
1396//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001397// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001398//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001399
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001400static int OptNameCompare(const void *LHS, const void *RHS) {
1401 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001402
Duncan Sands79d793e2012-03-12 10:51:06 +00001403 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001404}
1405
Andrew Trick12004012011-04-05 18:54:36 +00001406// Copy Options into a vector so we can sort them as we like.
1407static void
1408sortOpts(StringMap<Option*> &OptMap,
1409 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1410 bool ShowHidden) {
1411 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1412
1413 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1414 I != E; ++I) {
1415 // Ignore really-hidden options.
1416 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1417 continue;
1418
1419 // Unless showhidden is set, ignore hidden flags.
1420 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1421 continue;
1422
1423 // If we've already seen this option, don't add it to the list again.
1424 if (!OptionSet.insert(I->second))
1425 continue;
1426
1427 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1428 I->second));
1429 }
1430
1431 // Sort the options list alphabetically.
1432 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1433}
1434
Chris Lattner36a57d32001-07-23 17:17:47 +00001435namespace {
1436
Chris Lattner5df56c42002-07-22 02:07:59 +00001437class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001438protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001439 const bool ShowHidden;
Andrew Trick0537a982013-05-06 21:56:23 +00001440 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1441 // Print the options. Opts is assumed to be alphabetically sorted.
1442 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1443 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1444 Opts[i].second->printOptionInfo(MaxArgLen);
1445 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001446
Chris Lattner5df56c42002-07-22 02:07:59 +00001447public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001448 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001449 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001450
Andrew Trick0537a982013-05-06 21:56:23 +00001451 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001452 void operator=(bool Value) {
1453 if (Value == false) return;
1454
Chris Lattner5247f602007-04-06 21:06:55 +00001455 // Get all the options.
Chris Lattner131dca92009-09-20 06:18:38 +00001456 SmallVector<Option*, 4> PositionalOpts;
1457 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001458 StringMap<Option*> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001459 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001460
Andrew Trick0537a982013-05-06 21:56:23 +00001461 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001462 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001463
1464 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001465 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001466
Chris Lattner471ba482009-08-23 08:43:55 +00001467 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001468
Chris Lattner8111c592006-10-04 21:52:35 +00001469 // Print out the positional options.
Craig Topperc10719f2014-04-07 04:17:22 +00001470 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001471 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001472 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1473 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001474
Craig Topperc10719f2014-04-07 04:17:22 +00001475 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001476 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001477 outs() << " --" << PositionalOpts[i]->ArgStr;
1478 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001479 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001480
1481 // Print the consume after option info if it exists...
Chris Lattner471ba482009-08-23 08:43:55 +00001482 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001483
Chris Lattner471ba482009-08-23 08:43:55 +00001484 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001485
1486 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001487 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001488 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001489 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001490
Chris Lattner471ba482009-08-23 08:43:55 +00001491 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001492 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001493
Chris Lattner37bcd992004-11-19 17:08:15 +00001494 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001495 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001496 E = MoreHelp->end();
1497 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001498 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001499 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001500
Reid Spencer5e554702004-11-16 06:11:52 +00001501 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001502 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001503 }
1504};
Andrew Trick0537a982013-05-06 21:56:23 +00001505
1506class CategorizedHelpPrinter : public HelpPrinter {
1507public:
1508 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1509
1510 // Helper function for printOptions().
1511 // It shall return true if A's name should be lexographically
1512 // ordered before B's name. It returns false otherwise.
1513 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001514 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001515 }
1516
1517 // Make sure we inherit our base class's operator=()
1518 using HelpPrinter::operator= ;
1519
1520protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001521 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001522 std::vector<OptionCategory *> SortedCategories;
1523 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1524
Alp Tokercb402912014-01-24 17:20:08 +00001525 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001526 // sorting.
1527 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1528 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001529 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001530 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001531 }
Andrew Trick0537a982013-05-06 21:56:23 +00001532
1533 // Sort the different option categories alphabetically.
1534 assert(SortedCategories.size() > 0 && "No option categories registered!");
1535 std::sort(SortedCategories.begin(), SortedCategories.end(),
1536 OptionCategoryCompare);
1537
1538 // Create map to empty vectors.
1539 for (std::vector<OptionCategory *>::const_iterator
1540 I = SortedCategories.begin(),
1541 E = SortedCategories.end();
1542 I != E; ++I)
1543 CategorizedOptions[*I] = std::vector<Option *>();
1544
1545 // Walk through pre-sorted options and assign into categories.
1546 // Because the options are already alphabetically sorted the
1547 // options within categories will also be alphabetically sorted.
1548 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1549 Option *Opt = Opts[I].second;
1550 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1551 "Option has an unregistered category");
1552 CategorizedOptions[Opt->Category].push_back(Opt);
1553 }
1554
1555 // Now do printing.
1556 for (std::vector<OptionCategory *>::const_iterator
1557 Category = SortedCategories.begin(),
1558 E = SortedCategories.end();
1559 Category != E; ++Category) {
1560 // Hide empty categories for -help, but show for -help-hidden.
1561 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1562 if (!ShowHidden && IsEmptyCategory)
1563 continue;
1564
1565 // Print category information.
1566 outs() << "\n";
1567 outs() << (*Category)->getName() << ":\n";
1568
1569 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001570 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001571 outs() << (*Category)->getDescription() << "\n\n";
1572 else
1573 outs() << "\n";
1574
1575 // When using -help-hidden explicitly state if the category has no
1576 // options associated with it.
1577 if (IsEmptyCategory) {
1578 outs() << " This option category has no options.\n";
1579 continue;
1580 }
1581 // Loop over the options in the category and print.
1582 for (std::vector<Option *>::const_iterator
1583 Opt = CategorizedOptions[*Category].begin(),
1584 E = CategorizedOptions[*Category].end();
1585 Opt != E; ++Opt)
1586 (*Opt)->printOptionInfo(MaxArgLen);
1587 }
1588 }
1589};
1590
1591// This wraps the Uncategorizing and Categorizing printers and decides
1592// at run time which should be invoked.
1593class HelpPrinterWrapper {
1594private:
1595 HelpPrinter &UncategorizedPrinter;
1596 CategorizedHelpPrinter &CategorizedPrinter;
1597
1598public:
1599 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1600 CategorizedHelpPrinter &CategorizedPrinter) :
1601 UncategorizedPrinter(UncategorizedPrinter),
1602 CategorizedPrinter(CategorizedPrinter) { }
1603
1604 // Invoke the printer.
1605 void operator=(bool Value);
1606};
1607
Chris Lattneradb19d62006-10-12 22:09:17 +00001608} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001609
Andrew Trick0537a982013-05-06 21:56:23 +00001610// Declare the four HelpPrinter instances that are used to print out help, or
1611// help-hidden as an uncategorized list or in categories.
1612static HelpPrinter UncategorizedNormalPrinter(false);
1613static HelpPrinter UncategorizedHiddenPrinter(true);
1614static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1615static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1616
1617
1618// Declare HelpPrinter wrappers that will decide whether or not to invoke
1619// a categorizing help printer
1620static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1621 CategorizedNormalPrinter);
1622static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1623 CategorizedHiddenPrinter);
1624
1625// Define uncategorized help printers.
1626// -help-list is hidden by default because if Option categories are being used
1627// then -help behaves the same as -help-list.
1628static cl::opt<HelpPrinter, true, parser<bool> >
1629HLOp("help-list",
1630 cl::desc("Display list of available options (-help-list-hidden for more)"),
1631 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001632
Chris Lattneradb19d62006-10-12 22:09:17 +00001633static cl::opt<HelpPrinter, true, parser<bool> >
Andrew Trick0537a982013-05-06 21:56:23 +00001634HLHOp("help-list-hidden",
1635 cl::desc("Display list of all available options"),
1636 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1637
1638// Define uncategorized/categorized help printers. These printers change their
1639// behaviour at runtime depending on whether one or more Option categories have
1640// been declared.
1641static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Duncan Sands142b9ed2010-02-18 14:08:13 +00001642HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Andrew Trick0537a982013-05-06 21:56:23 +00001643 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
Chris Lattner5df56c42002-07-22 02:07:59 +00001644
Andrew Trick0537a982013-05-06 21:56:23 +00001645static cl::opt<HelpPrinterWrapper, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001646HHOp("help-hidden", cl::desc("Display all available options"),
Andrew Trick0537a982013-05-06 21:56:23 +00001647 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1648
1649
Chris Lattner36a57d32001-07-23 17:17:47 +00001650
Andrew Trick12004012011-04-05 18:54:36 +00001651static cl::opt<bool>
1652PrintOptions("print-options",
1653 cl::desc("Print non-default options after command line parsing"),
1654 cl::Hidden, cl::init(false));
1655
1656static cl::opt<bool>
1657PrintAllOptions("print-all-options",
1658 cl::desc("Print all option values after command line parsing"),
1659 cl::Hidden, cl::init(false));
1660
Andrew Trick0537a982013-05-06 21:56:23 +00001661void HelpPrinterWrapper::operator=(bool Value) {
1662 if (Value == false)
1663 return;
1664
1665 // Decide which printer to invoke. If more than one option category is
1666 // registered then it is useful to show the categorized help instead of
1667 // uncategorized help.
1668 if (RegisteredOptionCategories->size() > 1) {
1669 // unhide -help-list option so user can have uncategorized output if they
1670 // want it.
1671 HLOp.setHiddenFlag(NotHidden);
1672
1673 CategorizedPrinter = true; // Invoke categorized printer
1674 }
1675 else
1676 UncategorizedPrinter = true; // Invoke uncategorized printer
1677}
1678
Andrew Trick12004012011-04-05 18:54:36 +00001679// Print the value of each option.
1680void cl::PrintOptionValues() {
1681 if (!PrintOptions && !PrintAllOptions) return;
1682
1683 // Get all the options.
1684 SmallVector<Option*, 4> PositionalOpts;
1685 SmallVector<Option*, 4> SinkOpts;
1686 StringMap<Option*> OptMap;
1687 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1688
1689 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1690 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1691
1692 // Compute the maximum argument length...
1693 size_t MaxArgLen = 0;
1694 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1695 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1696
1697 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1698 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1699}
1700
Craig Topperc10719f2014-04-07 04:17:22 +00001701static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001702
Craig Topperc10719f2014-04-07 04:17:22 +00001703static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001704
Chris Lattneradb19d62006-10-12 22:09:17 +00001705namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001706class VersionPrinter {
1707public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001708 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001709 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001710 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001711 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001712#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001713 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001714#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001715 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001716#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001717 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001718#else
Chris Lattner131dca92009-09-20 06:18:38 +00001719 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001720#endif
1721#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001722 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001723#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001724 std::string CPU = sys::getHostCPUName();
Benjamin Kramer713fd352009-11-17 17:57:04 +00001725 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001726 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001727#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001728 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001729#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001730 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001731 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001732 }
1733 void operator=(bool OptionWasSpecified) {
Chris Lattnerb1f2e102009-09-20 05:48:01 +00001734 if (!OptionWasSpecified) return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001735
Craig Topperc10719f2014-04-07 04:17:22 +00001736 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001737 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001738 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001739 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001740 print();
1741
1742 // Iterate over any registered extra printers and call them to add further
1743 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001744 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001745 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001746 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1747 E = ExtraVersionPrinters->end();
1748 I != E; ++I)
1749 (*I)();
1750 }
1751
Justin Bogner02b95842014-02-28 19:08:01 +00001752 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001753 }
1754};
Chris Lattneradb19d62006-10-12 22:09:17 +00001755} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001756
1757
Reid Spencerff6cc122004-08-04 00:36:06 +00001758// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001759static VersionPrinter VersionPrinterInstance;
1760
1761static cl::opt<VersionPrinter, true, parser<bool> >
Chris Lattner88bb4452005-05-13 19:49:09 +00001762VersOp("version", cl::desc("Display the version of this program"),
Reid Spencerff6cc122004-08-04 00:36:06 +00001763 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1764
Reid Spencer5e554702004-11-16 06:11:52 +00001765// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001766void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1767 // This looks weird, but it actually prints the help message. The Printers are
1768 // types of HelpPrinter and the help gets printed when its operator= is
1769 // invoked. That's because the "normal" usages of the help printer is to be
1770 // assigned true/false depending on whether -help or -help-hidden was given or
1771 // not. Since we're circumventing that we have to make it look like -help or
1772 // -help-hidden were given, so we assign true.
1773
1774 if (!Hidden && !Categorized)
1775 UncategorizedNormalPrinter = true;
1776 else if (!Hidden && Categorized)
1777 CategorizedNormalPrinter = true;
1778 else if (Hidden && !Categorized)
1779 UncategorizedHiddenPrinter = true;
1780 else
1781 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001782}
Reid Spencerb3171672006-06-05 16:22:56 +00001783
Devang Patel9eb2caae2007-02-01 01:43:37 +00001784/// Utility function for printing version number.
1785void cl::PrintVersionMessage() {
1786 VersionPrinterInstance.print();
1787}
1788
Reid Spencerb3171672006-06-05 16:22:56 +00001789void cl::SetVersionPrinter(void (*func)()) {
1790 OverrideVersionPrinter = func;
1791}
Chandler Carruthea7e5522011-07-22 07:50:40 +00001792
1793void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001794 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001795 ExtraVersionPrinters = new std::vector<void (*)()>;
1796
1797 ExtraVersionPrinters->push_back(func);
1798}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001799
1800void cl::getRegisteredOptions(StringMap<Option*> &Map)
1801{
1802 // Get all the options.
1803 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1804 SmallVector<Option*, 4> SinkOpts; //NOT USED
1805 assert(Map.size() == 0 && "StringMap must be empty");
1806 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1807 return;
1808}