1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // This class implements a command line argument processor that is useful when
4 // creating a tool. It provides a simple, minimalistic interface that is easily
5 // extensible and supports nonlocal (library) command line options.
7 // Note that rather than trying to figure out what this code does, you could try
8 // reading the library documentation located in docs/CommandLine.html
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/STLExtras.h"
20 // Return the global command line option vector. Making it a function scoped
21 // static ensures that it will be initialized before its first use correctly.
23 static map<string, Option*> &getOpts() {
24 static map<string,Option*> CommandLineOptions;
25 return CommandLineOptions;
28 static void AddArgument(const string &ArgName, Option *Opt) {
29 if (getOpts().find(ArgName) != getOpts().end()) {
30 cerr << "CommandLine Error: Argument '" << ArgName
31 << "' specified more than once!\n";
33 getOpts()[ArgName] = Opt; // Add argument to the argument map!
37 static const char *ProgramName = 0;
38 static const char *ProgramOverview = 0;
40 static inline bool ProvideOption(Option *Handler, const char *ArgName,
41 const char *Value, int argc, char **argv,
43 // Enforce value requirements
44 switch (Handler->getValueExpectedFlag()) {
46 if (Value == 0 || *Value == 0) { // No value specified?
47 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
50 return Handler->error(" requires a value!");
56 return Handler->error(" does not allow a value! '" +
57 string(Value) + "' specified.");
59 case ValueOptional: break;
60 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
61 << Handler->getValueExpectedFlag() << endl; abort();
64 // Run the handler now!
65 return Handler->addOccurance(ArgName, Value);
69 void cl::ParseCommandLineOptions(int &argc, char **argv,
70 const char *Overview = 0) {
71 ProgramName = argv[0]; // Save this away safe and snug
72 ProgramOverview = Overview;
73 bool ErrorParsing = false;
75 // Loop over all of the arguments... processing them.
76 for (int i = 1; i < argc; ++i) {
78 const char *Value = "";
79 const char *ArgName = "";
80 if (argv[i][0] != '-') { // Unnamed argument?
81 map<string, Option*>::iterator I = getOpts().find("");
82 Handler = I != getOpts().end() ? I->second : 0;
84 } else { // We start with a - or --, eat dashes
86 while (*ArgName == '-') ++ArgName; // Eat leading dashes
88 const char *ArgNameEnd = ArgName;
89 while (*ArgNameEnd && *ArgNameEnd != '=' &&
90 *ArgNameEnd != '/') ++ArgNameEnd; // Scan till end
91 // TODO: Remove '/' case. Implement single letter args properly!
94 if (*Value) // If we have an equals sign...
95 ++Value; // Advance to value...
98 // Extract arg name part
99 map<string, Option*>::iterator I =
100 getOpts().find(string(ArgName, ArgNameEnd));
101 Handler = I != getOpts().end() ? I->second : 0;
106 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
107 << argv[0] << " --help'\n";
112 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
114 // If this option should consume all arguments that come after it...
115 if (Handler->getNumOccurancesFlag() == ConsumeAfter) {
116 for (++i; i < argc; ++i)
117 ErrorParsing |= ProvideOption(Handler, ArgName, argv[i], argc, argv, i);
121 // Loop over args and make sure all required args are specified!
122 for (map<string, Option*>::iterator I = getOpts().begin(),
123 E = getOpts().end(); I != E; ++I) {
124 switch (I->second->getNumOccurancesFlag()) {
127 if (I->second->getNumOccurances() == 0) {
128 I->second->error(" must be specified at least once!");
137 // Free all of the memory allocated to the vector. Command line options may
138 // only be processed once!
141 // If we had an error processing our arguments, don't let the program execute
142 if (ErrorParsing) exit(1);
145 //===----------------------------------------------------------------------===//
146 // Option Base class implementation
148 Option::Option(const char *argStr, const char *helpStr, int flags)
149 : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
150 AddArgument(ArgStr, this);
153 bool Option::error(string Message, const char *ArgName = 0) {
154 if (ArgName == 0) ArgName = ArgStr;
155 cerr << "-" << ArgName << " option" << Message << endl;
159 bool Option::addOccurance(const char *ArgName, const string &Value) {
160 NumOccurances++; // Increment the number of times we have been seen
162 switch (getNumOccurancesFlag()) {
164 if (NumOccurances > 1)
165 return error(": may only occur zero or one times!", ArgName);
168 if (NumOccurances > 1)
169 return error(": must occur exactly one time!", ArgName);
173 case ConsumeAfter: break;
174 default: return error(": bad num occurances flag value!");
177 return handleOccurance(ArgName, Value);
180 // Return the width of the option tag for printing...
181 unsigned Option::getOptionWidth() const {
182 return std::strlen(ArgStr)+6;
185 void Option::printOptionInfo(unsigned GlobalWidth) const {
186 unsigned L = std::strlen(ArgStr);
187 if (L == 0) return; // Don't print the empty arg like this!
188 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
193 //===----------------------------------------------------------------------===//
194 // Boolean/flag command line option implementation
197 bool Flag::handleOccurance(const char *ArgName, const string &Arg) {
198 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
201 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
204 return error(": '" + Arg +
205 "' is invalid value for boolean argument! Try 0 or 1");
211 //===----------------------------------------------------------------------===//
212 // Integer valued command line option implementation
214 bool Int::handleOccurance(const char *ArgName, const string &Arg) {
215 const char *ArgStart = Arg.c_str();
217 Value = (int)strtol(ArgStart, &End, 0);
219 return error(": '" + Arg + "' value invalid for integer argument!");
223 //===----------------------------------------------------------------------===//
224 // String valued command line option implementation
226 bool String::handleOccurance(const char *ArgName, const string &Arg) {
231 //===----------------------------------------------------------------------===//
232 // StringList valued command line option implementation
234 bool StringList::handleOccurance(const char *ArgName, const string &Arg) {
239 //===----------------------------------------------------------------------===//
240 // Enum valued command line option implementation
242 void EnumBase::processValues(va_list Vals) {
243 while (const char *EnumName = va_arg(Vals, const char *)) {
244 int EnumVal = va_arg(Vals, int);
245 const char *EnumDesc = va_arg(Vals, const char *);
246 ValueMap.push_back(make_pair(EnumName, // Add value to value map
247 make_pair(EnumVal, EnumDesc)));
251 // registerArgs - notify the system about these new arguments
252 void EnumBase::registerArgs() {
253 for (unsigned i = 0; i < ValueMap.size(); ++i)
254 AddArgument(ValueMap[i].first, this);
257 const char *EnumBase::getArgName(int ID) const {
258 for (unsigned i = 0; i < ValueMap.size(); ++i)
259 if (ID == ValueMap[i].second.first) return ValueMap[i].first;
262 const char *EnumBase::getArgDescription(int ID) const {
263 for (unsigned i = 0; i < ValueMap.size(); ++i)
264 if (ID == ValueMap[i].second.first) return ValueMap[i].second.second;
270 bool EnumValueBase::handleOccurance(const char *ArgName, const string &Arg) {
272 for (i = 0; i < ValueMap.size(); ++i)
273 if (ValueMap[i].first == Arg) break;
274 if (i == ValueMap.size())
275 return error(": unrecognized alternative '"+Arg+"'!");
276 Value = ValueMap[i].second.first;
280 // Return the width of the option tag for printing...
281 unsigned EnumValueBase::getOptionWidth() const {
282 unsigned BaseSize = Option::getOptionWidth();
283 for (unsigned i = 0; i < ValueMap.size(); ++i)
284 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+8);
288 // printOptionInfo - Print out information about this option. The
289 // to-be-maintained width is specified.
291 void EnumValueBase::printOptionInfo(unsigned GlobalWidth) const {
292 Option::printOptionInfo(GlobalWidth);
293 for (unsigned i = 0; i < ValueMap.size(); ++i) {
294 unsigned NumSpaces = GlobalWidth-strlen(ValueMap[i].first)-8;
295 cerr << " =" << ValueMap[i].first << string(NumSpaces, ' ') << " - "
296 << ValueMap[i].second.second;
298 if (i == 0) cerr << " (default)";
303 //===----------------------------------------------------------------------===//
304 // Enum flags command line option implementation
307 bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
308 return EnumValueBase::handleOccurance("", ArgName);
311 unsigned EnumFlagsBase::getOptionWidth() const {
312 unsigned BaseSize = 0;
313 for (unsigned i = 0; i < ValueMap.size(); ++i)
314 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
318 void EnumFlagsBase::printOptionInfo(unsigned GlobalWidth) const {
319 for (unsigned i = 0; i < ValueMap.size(); ++i) {
320 unsigned L = std::strlen(ValueMap[i].first);
321 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
322 << ValueMap[i].second.second;
323 if (i == 0) cerr << " (default)";
329 //===----------------------------------------------------------------------===//
330 // Enum list command line option implementation
333 bool EnumListBase::handleOccurance(const char *ArgName, const string &Arg) {
335 for (i = 0; i < ValueMap.size(); ++i)
336 if (ValueMap[i].first == string(ArgName)) break;
337 if (i == ValueMap.size())
338 return error(": CommandLine INTERNAL ERROR", ArgName);
339 Values.push_back(ValueMap[i].second.first);
343 // Return the width of the option tag for printing...
344 unsigned EnumListBase::getOptionWidth() const {
345 unsigned BaseSize = 0;
346 for (unsigned i = 0; i < ValueMap.size(); ++i)
347 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
352 // printOptionInfo - Print out information about this option. The
353 // to-be-maintained width is specified.
355 void EnumListBase::printOptionInfo(unsigned GlobalWidth) const {
356 for (unsigned i = 0; i < ValueMap.size(); ++i) {
357 unsigned L = std::strlen(ValueMap[i].first);
358 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
359 << ValueMap[i].second.second << endl;
364 //===----------------------------------------------------------------------===//
365 // Help option... always automatically provided.
369 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
370 inline bool isHidden(pair<string, Option *> &OptPair) {
371 return OptPair.second->getOptionHiddenFlag() >= Hidden;
373 inline bool isReallyHidden(pair<string, Option *> &OptPair) {
374 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
377 class Help : public Option {
379 const Option *EmptyArg;
380 const bool ShowHidden;
382 virtual bool handleOccurance(const char *ArgName, const string &Arg) {
383 // Copy Options into a vector so we can sort them as we like...
384 vector<pair<string, Option*> > Options;
385 copy(getOpts().begin(), getOpts().end(), back_inserter(Options));
387 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
388 Options.erase(remove_if(Options.begin(), Options.end(),
389 ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
392 // Eliminate duplicate entries in table (from enum flags options, f.e.)
393 set<Option*> OptionSet;
394 for (unsigned i = 0; i < Options.size(); )
395 if (OptionSet.count(Options[i].second) == 0)
396 OptionSet.insert(Options[i++].second); // Add to set
398 Options.erase(Options.begin()+i); // Erase duplicate
402 cerr << "OVERVIEW:" << ProgramOverview << endl;
403 // TODO: Sort options by some criteria
405 cerr << "USAGE: " << ProgramName << " [options]\n\n";
406 // TODO: print usage nicer
408 // Compute the maximum argument length...
410 for_each(Options.begin(), Options.end(),
411 bind_obj(this, &Help::getMaxArgLen));
413 cerr << "OPTIONS:\n";
414 for_each(Options.begin(), Options.end(),
415 bind_obj(this, &Help::printOption));
417 return true; // Displaying help is cause to terminate the program
420 void getMaxArgLen(pair<string, Option *> OptPair) {
421 const Option *Opt = OptPair.second;
422 if (Opt->ArgStr[0] == 0) EmptyArg = Opt; // Capture the empty arg if exists
423 MaxArgLen = max(MaxArgLen, Opt->getOptionWidth());
426 void printOption(pair<string, Option *> OptPair) {
427 const Option *Opt = OptPair.second;
428 Opt->printOptionInfo(MaxArgLen);
432 inline Help(const char *ArgVal, const char *HelpVal, bool showHidden)
433 : Option(ArgVal, HelpVal, showHidden ? Hidden : 0), ShowHidden(showHidden) {
438 Help HelpOp("help", "display available options"
439 " (--help-hidden for more)", false);
440 Help HelpHiddenOpt("help-hidden", "display all available options", true);
442 } // End anonymous namespace