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 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/CommandLine.h"
10 #include "llvm/Support/STLExtras.h"
17 // Return the global command line option vector. Making it a function scoped
18 // static ensures that it will be initialized before its first use correctly.
20 static map<string, Option*> &getOpts() {
21 static map<string,Option*> CommandLineOptions;
22 return CommandLineOptions;
25 static void AddArgument(const string &ArgName, Option *Opt) {
26 if (getOpts().find(ArgName) != getOpts().end()) {
27 cerr << "CommandLine Error: Argument '" << ArgName
28 << "' specified more than once!\n";
30 getOpts()[ArgName] = Opt; // Add argument to the argument map!
34 static const char *ProgramName = 0;
35 static const char *ProgramOverview = 0;
37 void cl::ParseCommandLineOptions(int &argc, char **argv,
38 const char *Overview = 0) {
39 ProgramName = argv[0]; // Save this away safe and snug
40 ProgramOverview = Overview;
41 bool ErrorParsing = false;
43 // Loop over all of the arguments... processing them.
44 for (int i = 1; i < argc; ++i) {
46 const char *Value = "";
47 const char *ArgName = "";
48 if (argv[i][0] != '-') { // Unnamed argument?
49 Handler = getOpts()[""];
51 } else { // We start with a - or --, eat dashes
53 while (*ArgName == '-') ++ArgName; // Eat leading dashes
55 const char *ArgNameEnd = ArgName;
56 while (*ArgNameEnd && *ArgNameEnd != '=') ++ArgNameEnd; // Scan till end
59 if (*Value) // If we have an equals sign...
60 ++Value; // Advance to value...
63 string ArgNameStr(ArgName, ArgNameEnd); // Extract arg name part
64 Handler = getOpts()[ArgNameStr];
69 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
70 << argv[0] << " --help\n'";
75 // Enforce value requirements
76 switch (Handler->getValueExpectedFlag()) {
78 if (Value == 0 || *Value == 0) { // No value specified?
79 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
82 ErrorParsing = Handler->error(" requires a value!");
89 ErrorParsing = Handler->error(" does not allow a value! '" +
90 string(Value) + "' specified.");
95 default: cerr << "Bad ValueMask flag! CommandLine usage error!\n"; abort();
98 // Run the handler now!
99 ErrorParsing |= Handler->addOccurance(ArgName, Value);
102 // Loop over args and make sure all required args are specified!
103 for (map<string, Option*>::iterator I = getOpts().begin(),
104 E = getOpts().end(); I != E; ++I) {
105 switch (I->second->getNumOccurancesFlag()) {
108 if (I->second->getNumOccurances() == 0)
109 I->second->error(" must be specified at least once!");
116 // Free all of the memory allocated to the vector. Command line options may
117 // only be processed once!
120 // If we had an error processing our arguments, don't let the program execute
121 if (ErrorParsing) exit(1);
124 //===----------------------------------------------------------------------===//
125 // Option Base class implementation
127 Option::Option(const char *argStr, const char *helpStr, int flags)
128 : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
129 AddArgument(ArgStr, this);
132 bool Option::error(string Message, const char *ArgName = 0) {
133 if (ArgName == 0) ArgName = ArgStr;
134 cerr << "-" << ArgName << " option" << Message << endl;
138 bool Option::addOccurance(const char *ArgName, const string &Value) {
139 NumOccurances++; // Increment the number of times we have been seen
141 switch (getNumOccurancesFlag()) {
143 if (NumOccurances > 1)
144 return error(": may only occur zero or one times!", ArgName);
147 if (NumOccurances > 1)
148 return error(": must occur exactly one time!", ArgName);
151 case ZeroOrMore: break;
152 default: return error(": bad num occurances flag value!");
155 return handleOccurance(ArgName, Value);
158 // Return the width of the option tag for printing...
159 unsigned Option::getOptionWidth() const {
160 return std::strlen(ArgStr)+6;
163 void Option::printOptionInfo(unsigned GlobalWidth) const {
164 unsigned L = std::strlen(ArgStr);
165 if (L == 0) return; // Don't print the empty arg like this!
166 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
171 //===----------------------------------------------------------------------===//
172 // Boolean/flag command line option implementation
175 bool Flag::handleOccurance(const char *ArgName, const string &Arg) {
176 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
179 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
182 return error(": '" + Arg + "' is invalid value for boolean argument! Try 0 or 1");
188 //===----------------------------------------------------------------------===//
189 // Integer valued command line option implementation
191 bool Int::handleOccurance(const char *ArgName, const string &Arg) {
192 const char *ArgStart = Arg.c_str();
194 Value = (int)strtol(ArgStart, &End, 0);
196 return error(": '" + Arg + "' value invalid for integer argument!");
200 //===----------------------------------------------------------------------===//
201 // String valued command line option implementation
203 bool String::handleOccurance(const char *ArgName, const string &Arg) {
208 //===----------------------------------------------------------------------===//
209 // Enum valued command line option implementation
211 void EnumBase::processValues(va_list Vals) {
212 while (const char *EnumName = va_arg(Vals, const char *)) {
213 int EnumVal = va_arg(Vals, int);
214 const char *EnumDesc = va_arg(Vals, const char *);
215 ValueMap.push_back(make_pair(EnumName, // Add value to value map
216 make_pair(EnumVal, EnumDesc)));
220 // registerArgs - notify the system about these new arguments
221 void EnumBase::registerArgs() {
222 for (unsigned i = 0; i < ValueMap.size(); ++i)
223 AddArgument(ValueMap[i].first, this);
226 const char *EnumBase::getArgName(int ID) const {
227 for (unsigned i = 0; i < ValueMap.size(); ++i)
228 if (ID == ValueMap[i].second.first) return ValueMap[i].first;
231 const char *EnumBase::getArgDescription(int ID) const {
232 for (unsigned i = 0; i < ValueMap.size(); ++i)
233 if (ID == ValueMap[i].second.first) return ValueMap[i].second.second;
239 bool EnumValueBase::handleOccurance(const char *ArgName, const string &Arg) {
241 for (i = 0; i < ValueMap.size(); ++i)
242 if (ValueMap[i].first == Arg) break;
243 if (i == ValueMap.size())
244 return error(": unrecognized alternative '"+Arg+"'!");
245 Value = ValueMap[i].second.first;
249 // Return the width of the option tag for printing...
250 unsigned EnumValueBase::getOptionWidth() const {
251 unsigned BaseSize = Option::getOptionWidth();
252 for (unsigned i = 0; i < ValueMap.size(); ++i)
253 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+8);
257 // printOptionInfo - Print out information about this option. The
258 // to-be-maintained width is specified.
260 void EnumValueBase::printOptionInfo(unsigned GlobalWidth) const {
261 Option::printOptionInfo(GlobalWidth);
262 for (unsigned i = 0; i < ValueMap.size(); ++i) {
263 unsigned NumSpaces = GlobalWidth-strlen(ValueMap[i].first)-8;
264 cerr << " =" << ValueMap[i].first << string(NumSpaces, ' ') << " - "
265 << ValueMap[i].second.second;
267 if (i == 0) cerr << " (default)";
272 //===----------------------------------------------------------------------===//
273 // Enum flags command line option implementation
276 bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
277 return EnumValueBase::handleOccurance("", ArgName);
280 unsigned EnumFlagsBase::getOptionWidth() const {
281 unsigned BaseSize = 0;
282 for (unsigned i = 0; i < ValueMap.size(); ++i)
283 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
287 void EnumFlagsBase::printOptionInfo(unsigned GlobalWidth) const {
288 for (unsigned i = 0; i < ValueMap.size(); ++i) {
289 unsigned L = std::strlen(ValueMap[i].first);
290 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
291 << ValueMap[i].second.second;
292 if (i == 0) cerr << " (default)";
298 //===----------------------------------------------------------------------===//
299 // Enum list command line option implementation
302 bool EnumListBase::handleOccurance(const char *ArgName, const string &Arg) {
304 for (i = 0; i < ValueMap.size(); ++i)
305 if (ValueMap[i].first == string(ArgName)) break;
306 if (i == ValueMap.size())
307 return error(": CommandLine INTERNAL ERROR", ArgName);
308 Values.push_back(ValueMap[i].second.first);
312 // Return the width of the option tag for printing...
313 unsigned EnumListBase::getOptionWidth() const {
314 unsigned BaseSize = 0;
315 for (unsigned i = 0; i < ValueMap.size(); ++i)
316 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
321 // printOptionInfo - Print out information about this option. The
322 // to-be-maintained width is specified.
324 void EnumListBase::printOptionInfo(unsigned GlobalWidth) const {
325 for (unsigned i = 0; i < ValueMap.size(); ++i) {
326 unsigned L = std::strlen(ValueMap[i].first);
327 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
328 << ValueMap[i].second.second << endl;
333 //===----------------------------------------------------------------------===//
334 // Help option... always automatically provided.
338 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
339 inline bool isHidden(pair<string, Option *> &OptPair) {
340 return OptPair.second->getOptionHiddenFlag() >= Hidden;
342 inline bool isReallyHidden(pair<string, Option *> &OptPair) {
343 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
346 class Help : public Option {
348 const Option *EmptyArg;
349 const bool ShowHidden;
351 virtual bool handleOccurance(const char *ArgName, const string &Arg) {
352 // Copy Options into a vector so we can sort them as we like...
353 vector<pair<string, Option*> > Options;
354 copy(getOpts().begin(), getOpts().end(), back_inserter(Options));
356 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
357 Options.erase(remove_if(Options.begin(), Options.end(),
358 ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
361 // Eliminate duplicate entries in table (from enum flags options, f.e.)
362 set<Option*> OptionSet;
363 for (unsigned i = 0; i < Options.size(); )
364 if (OptionSet.count(Options[i].second) == 0)
365 OptionSet.insert(Options[i++].second); // Add to set
367 Options.erase(Options.begin()+i); // Erase duplicate
371 cerr << "OVERVIEW:" << ProgramOverview << endl;
372 // TODO: Sort options by some criteria
374 cerr << "USAGE: " << ProgramName << " [options]\n\n";
375 // TODO: print usage nicer
377 // Compute the maximum argument length...
379 for_each(Options.begin(), Options.end(),
380 bind_obj(this, &Help::getMaxArgLen));
382 cerr << "OPTIONS:\n";
383 for_each(Options.begin(), Options.end(),
384 bind_obj(this, &Help::printOption));
386 return true; // Displaying help is cause to terminate the program
389 void getMaxArgLen(pair<string, Option *> OptPair) {
390 const Option *Opt = OptPair.second;
391 if (Opt->ArgStr[0] == 0) EmptyArg = Opt; // Capture the empty arg if exists
392 MaxArgLen = max(MaxArgLen, Opt->getOptionWidth());
395 void printOption(pair<string, Option *> OptPair) {
396 const Option *Opt = OptPair.second;
397 Opt->printOptionInfo(MaxArgLen);
401 inline Help(const char *ArgVal, const char *HelpVal, bool showHidden)
402 : Option(ArgVal, HelpVal, showHidden ? Hidden : 0), ShowHidden(showHidden) {
407 Help HelpOp("help", "display available options"
408 " (--help-hidden for more)", false);
409 Help HelpHiddenOpt("help-hidden", "display all available options", true);
411 } // End anonymous namespace