blob: 84dd26dff92005387f830b73482cedc48989d8d1 [file] [log] [blame]
Chris Lattnerdbab15a2001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
2//
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.
6//
Chris Lattner03fe1bd2001-07-23 23:04:07 +00007// 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
9//
Chris Lattnerdbab15a2001-07-23 17:17:47 +000010//===----------------------------------------------------------------------===//
11
Chris Lattner57dbb3a2001-07-23 17:46:59 +000012#include "llvm/Support/CommandLine.h"
13#include "llvm/Support/STLExtras.h"
Chris Lattnerdbab15a2001-07-23 17:17:47 +000014#include <vector>
15#include <algorithm>
16#include <map>
17#include <set>
18using namespace cl;
19
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.
22//
23static map<string, Option*> &getOpts() {
24 static map<string,Option*> CommandLineOptions;
25 return CommandLineOptions;
26}
27
28static 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";
32 } else {
33 getOpts()[ArgName] = Opt; // Add argument to the argument map!
34 }
35}
36
37static const char *ProgramName = 0;
38static const char *ProgramOverview = 0;
39
Chris Lattnercaccd762001-10-27 05:54:17 +000040static inline bool ProvideOption(Option *Handler, const char *ArgName,
41 const char *Value, int argc, char **argv,
42 int &i) {
43 // Enforce value requirements
44 switch (Handler->getValueExpectedFlag()) {
45 case ValueRequired:
46 if (Value == 0 || *Value == 0) { // No value specified?
47 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
48 Value = argv[++i];
49 } else {
50 return Handler->error(" requires a value!");
51 }
52 }
53 break;
54 case ValueDisallowed:
55 if (*Value != 0)
56 return Handler->error(" does not allow a value! '" +
57 string(Value) + "' specified.");
58 break;
59 case ValueOptional: break;
60 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
61 << Handler->getValueExpectedFlag() << endl; abort();
62 }
63
64 // Run the handler now!
65 return Handler->addOccurance(ArgName, Value);
66}
67
68
Chris Lattnerdbab15a2001-07-23 17:17:47 +000069void 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;
74
75 // Loop over all of the arguments... processing them.
76 for (int i = 1; i < argc; ++i) {
77 Option *Handler = 0;
78 const char *Value = "";
79 const char *ArgName = "";
80 if (argv[i][0] != '-') { // Unnamed argument?
Chris Lattner3805e4c2001-07-25 18:40:49 +000081 map<string, Option*>::iterator I = getOpts().find("");
82 Handler = I != getOpts().end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +000083 Value = argv[i];
84 } else { // We start with a - or --, eat dashes
85 ArgName = argv[i]+1;
86 while (*ArgName == '-') ++ArgName; // Eat leading dashes
87
88 const char *ArgNameEnd = ArgName;
Chris Lattnerf038acb2001-10-24 06:21:56 +000089 while (*ArgNameEnd && *ArgNameEnd != '=' &&
90 *ArgNameEnd != '/') ++ArgNameEnd; // Scan till end
Chris Lattnercaccd762001-10-27 05:54:17 +000091 // TODO: Remove '/' case. Implement single letter args properly!
Chris Lattnerdbab15a2001-07-23 17:17:47 +000092
93 Value = ArgNameEnd;
94 if (*Value) // If we have an equals sign...
95 ++Value; // Advance to value...
96
97 if (*ArgName != 0) {
Chris Lattner3805e4c2001-07-25 18:40:49 +000098 // Extract arg name part
Chris Lattnercaccd762001-10-27 05:54:17 +000099 map<string, Option*>::iterator I =
100 getOpts().find(string(ArgName, ArgNameEnd));
Chris Lattner3805e4c2001-07-25 18:40:49 +0000101 Handler = I != getOpts().end() ? I->second : 0;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000102 }
103 }
104
105 if (Handler == 0) {
106 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
Chris Lattnerf038acb2001-10-24 06:21:56 +0000107 << argv[0] << " --help'\n";
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000108 ErrorParsing = true;
109 continue;
110 }
111
Chris Lattnercaccd762001-10-27 05:54:17 +0000112 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000113
Chris Lattnercaccd762001-10-27 05:54:17 +0000114 // 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);
118 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000119 }
120
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000121 // 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()) {
125 case Required:
126 case OneOrMore:
Chris Lattnerf038acb2001-10-24 06:21:56 +0000127 if (I->second->getNumOccurances() == 0) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000128 I->second->error(" must be specified at least once!");
Chris Lattnerf038acb2001-10-24 06:21:56 +0000129 ErrorParsing = true;
130 }
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000131 // Fall through
132 default:
133 break;
134 }
135 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000136
137 // Free all of the memory allocated to the vector. Command line options may
138 // only be processed once!
139 getOpts().clear();
140
141 // If we had an error processing our arguments, don't let the program execute
142 if (ErrorParsing) exit(1);
143}
144
145//===----------------------------------------------------------------------===//
146// Option Base class implementation
147//
148Option::Option(const char *argStr, const char *helpStr, int flags)
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000149 : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000150 AddArgument(ArgStr, this);
151}
152
153bool Option::error(string Message, const char *ArgName = 0) {
154 if (ArgName == 0) ArgName = ArgStr;
155 cerr << "-" << ArgName << " option" << Message << endl;
156 return true;
157}
158
159bool Option::addOccurance(const char *ArgName, const string &Value) {
160 NumOccurances++; // Increment the number of times we have been seen
161
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000162 switch (getNumOccurancesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000163 case Optional:
164 if (NumOccurances > 1)
165 return error(": may only occur zero or one times!", ArgName);
166 break;
167 case Required:
168 if (NumOccurances > 1)
169 return error(": must occur exactly one time!", ArgName);
170 // Fall through
171 case OneOrMore:
Chris Lattnercaccd762001-10-27 05:54:17 +0000172 case ZeroOrMore:
173 case ConsumeAfter: break;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000174 default: return error(": bad num occurances flag value!");
175 }
176
177 return handleOccurance(ArgName, Value);
178}
179
180// Return the width of the option tag for printing...
181unsigned Option::getOptionWidth() const {
182 return std::strlen(ArgStr)+6;
183}
184
185void 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, ' ') << " - "
189 << HelpStr << endl;
190}
191
192
193//===----------------------------------------------------------------------===//
194// Boolean/flag command line option implementation
195//
196
197bool Flag::handleOccurance(const char *ArgName, const string &Arg) {
198 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
199 Arg == "1") {
200 Value = true;
201 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
202 Value = false;
203 } else {
Chris Lattnerd215fd12001-10-13 06:53:19 +0000204 return error(": '" + Arg +
205 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000206 }
207
208 return false;
209}
210
211//===----------------------------------------------------------------------===//
212// Integer valued command line option implementation
213//
214bool Int::handleOccurance(const char *ArgName, const string &Arg) {
215 const char *ArgStart = Arg.c_str();
216 char *End;
217 Value = (int)strtol(ArgStart, &End, 0);
218 if (*End != 0)
219 return error(": '" + Arg + "' value invalid for integer argument!");
220 return false;
221}
222
223//===----------------------------------------------------------------------===//
224// String valued command line option implementation
225//
226bool String::handleOccurance(const char *ArgName, const string &Arg) {
Chris Lattner1e78f362001-07-23 19:27:24 +0000227 *this = Arg;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000228 return false;
229}
230
231//===----------------------------------------------------------------------===//
Chris Lattnerd215fd12001-10-13 06:53:19 +0000232// StringList valued command line option implementation
233//
234bool StringList::handleOccurance(const char *ArgName, const string &Arg) {
Chris Lattnercaccd762001-10-27 05:54:17 +0000235 push_back(Arg);
Chris Lattnerd215fd12001-10-13 06:53:19 +0000236 return false;
237}
238
239//===----------------------------------------------------------------------===//
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000240// Enum valued command line option implementation
241//
242void 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)));
248 }
249}
250
251// registerArgs - notify the system about these new arguments
252void EnumBase::registerArgs() {
253 for (unsigned i = 0; i < ValueMap.size(); ++i)
254 AddArgument(ValueMap[i].first, this);
255}
256
257const 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;
260 return "";
261}
262const 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;
265 return "";
266}
267
268
269
270bool EnumValueBase::handleOccurance(const char *ArgName, const string &Arg) {
271 unsigned i;
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;
277 return false;
278}
279
280// Return the width of the option tag for printing...
281unsigned 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);
285 return BaseSize;
286}
287
288// printOptionInfo - Print out information about this option. The
289// to-be-maintained width is specified.
290//
291void 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;
297
298 if (i == 0) cerr << " (default)";
299 cerr << endl;
300 }
301}
302
303//===----------------------------------------------------------------------===//
304// Enum flags command line option implementation
305//
306
307bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
308 return EnumValueBase::handleOccurance("", ArgName);
309}
310
311unsigned 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);
315 return BaseSize;
316}
317
318void 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)";
324 cerr << endl;
325 }
326}
327
328
329//===----------------------------------------------------------------------===//
330// Enum list command line option implementation
331//
332
333bool EnumListBase::handleOccurance(const char *ArgName, const string &Arg) {
334 unsigned i;
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);
340 return false;
341}
342
343// Return the width of the option tag for printing...
344unsigned 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);
348 return BaseSize;
349}
350
351
352// printOptionInfo - Print out information about this option. The
353// to-be-maintained width is specified.
354//
355void 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;
360 }
361}
362
363
364//===----------------------------------------------------------------------===//
365// Help option... always automatically provided.
366//
367namespace {
368
369// isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
370inline bool isHidden(pair<string, Option *> &OptPair) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000371 return OptPair.second->getOptionHiddenFlag() >= Hidden;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000372}
373inline bool isReallyHidden(pair<string, Option *> &OptPair) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000374 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000375}
376
377class Help : public Option {
378 unsigned MaxArgLen;
379 const Option *EmptyArg;
380 const bool ShowHidden;
381
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));
386
387 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
388 Options.erase(remove_if(Options.begin(), Options.end(),
389 ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
390 Options.end());
391
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
397 else
398 Options.erase(Options.begin()+i); // Erase duplicate
399
400
401 if (ProgramOverview)
402 cerr << "OVERVIEW:" << ProgramOverview << endl;
403 // TODO: Sort options by some criteria
404
405 cerr << "USAGE: " << ProgramName << " [options]\n\n";
406 // TODO: print usage nicer
407
408 // Compute the maximum argument length...
409 MaxArgLen = 0;
410 for_each(Options.begin(), Options.end(),
411 bind_obj(this, &Help::getMaxArgLen));
412
413 cerr << "OPTIONS:\n";
414 for_each(Options.begin(), Options.end(),
415 bind_obj(this, &Help::printOption));
416
417 return true; // Displaying help is cause to terminate the program
418 }
419
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());
424 }
425
426 void printOption(pair<string, Option *> OptPair) {
427 const Option *Opt = OptPair.second;
428 Opt->printOptionInfo(MaxArgLen);
429 }
430
431public:
432 inline Help(const char *ArgVal, const char *HelpVal, bool showHidden)
433 : Option(ArgVal, HelpVal, showHidden ? Hidden : 0), ShowHidden(showHidden) {
434 EmptyArg = 0;
435 }
436};
437
438Help HelpOp("help", "display available options"
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000439 " (--help-hidden for more)", false);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000440Help HelpHiddenOpt("help-hidden", "display all available options", true);
441
442} // End anonymous namespace