blob: db2c3f373f1c4408b51b0c60c6ebced2049970fd [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
40void cl::ParseCommandLineOptions(int &argc, char **argv,
41 const char *Overview = 0) {
42 ProgramName = argv[0]; // Save this away safe and snug
43 ProgramOverview = Overview;
44 bool ErrorParsing = false;
45
46 // Loop over all of the arguments... processing them.
47 for (int i = 1; i < argc; ++i) {
48 Option *Handler = 0;
49 const char *Value = "";
50 const char *ArgName = "";
51 if (argv[i][0] != '-') { // Unnamed argument?
52 Handler = getOpts()[""];
53 Value = argv[i];
54 } else { // We start with a - or --, eat dashes
55 ArgName = argv[i]+1;
56 while (*ArgName == '-') ++ArgName; // Eat leading dashes
57
58 const char *ArgNameEnd = ArgName;
59 while (*ArgNameEnd && *ArgNameEnd != '=') ++ArgNameEnd; // Scan till end
60
61 Value = ArgNameEnd;
62 if (*Value) // If we have an equals sign...
63 ++Value; // Advance to value...
64
65 if (*ArgName != 0) {
66 string ArgNameStr(ArgName, ArgNameEnd); // Extract arg name part
67 Handler = getOpts()[ArgNameStr];
68 }
69 }
70
71 if (Handler == 0) {
72 cerr << "Unknown command line argument '" << argv[i] << "'. Try: "
73 << argv[0] << " --help\n'";
74 ErrorParsing = true;
75 continue;
76 }
77
78 // Enforce value requirements
Chris Lattnerdc4693d2001-07-23 23:02:45 +000079 switch (Handler->getValueExpectedFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +000080 case ValueRequired:
81 if (Value == 0 || *Value == 0) { // No value specified?
82 if (i+1 < argc) { // Steal the next argument, like for '-o filename'
83 Value = argv[++i];
84 } else {
85 ErrorParsing = Handler->error(" requires a value!");
86 continue;
87 }
88 }
89 break;
90 case ValueDisallowed:
91 if (*Value != 0) {
92 ErrorParsing = Handler->error(" does not allow a value! '" +
93 string(Value) + "' specified.");
94 continue;
95 }
96 break;
Chris Lattner2233a072001-07-23 23:14:23 +000097 case ValueOptional: break;
98 default: cerr << "Bad ValueMask flag! CommandLine usage error:"
99 << Handler->getValueExpectedFlag() << endl; abort();
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000100 }
101
102 // Run the handler now!
103 ErrorParsing |= Handler->addOccurance(ArgName, Value);
104 }
105
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000106 // Loop over args and make sure all required args are specified!
107 for (map<string, Option*>::iterator I = getOpts().begin(),
108 E = getOpts().end(); I != E; ++I) {
109 switch (I->second->getNumOccurancesFlag()) {
110 case Required:
111 case OneOrMore:
112 if (I->second->getNumOccurances() == 0)
113 I->second->error(" must be specified at least once!");
114 // Fall through
115 default:
116 break;
117 }
118 }
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000119
120 // Free all of the memory allocated to the vector. Command line options may
121 // only be processed once!
122 getOpts().clear();
123
124 // If we had an error processing our arguments, don't let the program execute
125 if (ErrorParsing) exit(1);
126}
127
128//===----------------------------------------------------------------------===//
129// Option Base class implementation
130//
131Option::Option(const char *argStr, const char *helpStr, int flags)
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000132 : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000133 AddArgument(ArgStr, this);
134}
135
136bool Option::error(string Message, const char *ArgName = 0) {
137 if (ArgName == 0) ArgName = ArgStr;
138 cerr << "-" << ArgName << " option" << Message << endl;
139 return true;
140}
141
142bool Option::addOccurance(const char *ArgName, const string &Value) {
143 NumOccurances++; // Increment the number of times we have been seen
144
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000145 switch (getNumOccurancesFlag()) {
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000146 case Optional:
147 if (NumOccurances > 1)
148 return error(": may only occur zero or one times!", ArgName);
149 break;
150 case Required:
151 if (NumOccurances > 1)
152 return error(": must occur exactly one time!", ArgName);
153 // Fall through
154 case OneOrMore:
155 case ZeroOrMore: break;
156 default: return error(": bad num occurances flag value!");
157 }
158
159 return handleOccurance(ArgName, Value);
160}
161
162// Return the width of the option tag for printing...
163unsigned Option::getOptionWidth() const {
164 return std::strlen(ArgStr)+6;
165}
166
167void Option::printOptionInfo(unsigned GlobalWidth) const {
168 unsigned L = std::strlen(ArgStr);
169 if (L == 0) return; // Don't print the empty arg like this!
170 cerr << " -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
171 << HelpStr << endl;
172}
173
174
175//===----------------------------------------------------------------------===//
176// Boolean/flag command line option implementation
177//
178
179bool Flag::handleOccurance(const char *ArgName, const string &Arg) {
180 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
181 Arg == "1") {
182 Value = true;
183 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
184 Value = false;
185 } else {
186 return error(": '" + Arg + "' is invalid value for boolean argument! Try 0 or 1");
187 }
188
189 return false;
190}
191
192//===----------------------------------------------------------------------===//
193// Integer valued command line option implementation
194//
195bool Int::handleOccurance(const char *ArgName, const string &Arg) {
196 const char *ArgStart = Arg.c_str();
197 char *End;
198 Value = (int)strtol(ArgStart, &End, 0);
199 if (*End != 0)
200 return error(": '" + Arg + "' value invalid for integer argument!");
201 return false;
202}
203
204//===----------------------------------------------------------------------===//
205// String valued command line option implementation
206//
207bool String::handleOccurance(const char *ArgName, const string &Arg) {
Chris Lattner1e78f362001-07-23 19:27:24 +0000208 *this = Arg;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000209 return false;
210}
211
212//===----------------------------------------------------------------------===//
213// Enum valued command line option implementation
214//
215void EnumBase::processValues(va_list Vals) {
216 while (const char *EnumName = va_arg(Vals, const char *)) {
217 int EnumVal = va_arg(Vals, int);
218 const char *EnumDesc = va_arg(Vals, const char *);
219 ValueMap.push_back(make_pair(EnumName, // Add value to value map
220 make_pair(EnumVal, EnumDesc)));
221 }
222}
223
224// registerArgs - notify the system about these new arguments
225void EnumBase::registerArgs() {
226 for (unsigned i = 0; i < ValueMap.size(); ++i)
227 AddArgument(ValueMap[i].first, this);
228}
229
230const char *EnumBase::getArgName(int ID) const {
231 for (unsigned i = 0; i < ValueMap.size(); ++i)
232 if (ID == ValueMap[i].second.first) return ValueMap[i].first;
233 return "";
234}
235const char *EnumBase::getArgDescription(int ID) const {
236 for (unsigned i = 0; i < ValueMap.size(); ++i)
237 if (ID == ValueMap[i].second.first) return ValueMap[i].second.second;
238 return "";
239}
240
241
242
243bool EnumValueBase::handleOccurance(const char *ArgName, const string &Arg) {
244 unsigned i;
245 for (i = 0; i < ValueMap.size(); ++i)
246 if (ValueMap[i].first == Arg) break;
247 if (i == ValueMap.size())
248 return error(": unrecognized alternative '"+Arg+"'!");
249 Value = ValueMap[i].second.first;
250 return false;
251}
252
253// Return the width of the option tag for printing...
254unsigned EnumValueBase::getOptionWidth() const {
255 unsigned BaseSize = Option::getOptionWidth();
256 for (unsigned i = 0; i < ValueMap.size(); ++i)
257 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+8);
258 return BaseSize;
259}
260
261// printOptionInfo - Print out information about this option. The
262// to-be-maintained width is specified.
263//
264void EnumValueBase::printOptionInfo(unsigned GlobalWidth) const {
265 Option::printOptionInfo(GlobalWidth);
266 for (unsigned i = 0; i < ValueMap.size(); ++i) {
267 unsigned NumSpaces = GlobalWidth-strlen(ValueMap[i].first)-8;
268 cerr << " =" << ValueMap[i].first << string(NumSpaces, ' ') << " - "
269 << ValueMap[i].second.second;
270
271 if (i == 0) cerr << " (default)";
272 cerr << endl;
273 }
274}
275
276//===----------------------------------------------------------------------===//
277// Enum flags command line option implementation
278//
279
280bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
281 return EnumValueBase::handleOccurance("", ArgName);
282}
283
284unsigned EnumFlagsBase::getOptionWidth() const {
285 unsigned BaseSize = 0;
286 for (unsigned i = 0; i < ValueMap.size(); ++i)
287 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
288 return BaseSize;
289}
290
291void EnumFlagsBase::printOptionInfo(unsigned GlobalWidth) const {
292 for (unsigned i = 0; i < ValueMap.size(); ++i) {
293 unsigned L = std::strlen(ValueMap[i].first);
294 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
295 << ValueMap[i].second.second;
296 if (i == 0) cerr << " (default)";
297 cerr << endl;
298 }
299}
300
301
302//===----------------------------------------------------------------------===//
303// Enum list command line option implementation
304//
305
306bool EnumListBase::handleOccurance(const char *ArgName, const string &Arg) {
307 unsigned i;
308 for (i = 0; i < ValueMap.size(); ++i)
309 if (ValueMap[i].first == string(ArgName)) break;
310 if (i == ValueMap.size())
311 return error(": CommandLine INTERNAL ERROR", ArgName);
312 Values.push_back(ValueMap[i].second.first);
313 return false;
314}
315
316// Return the width of the option tag for printing...
317unsigned EnumListBase::getOptionWidth() const {
318 unsigned BaseSize = 0;
319 for (unsigned i = 0; i < ValueMap.size(); ++i)
320 BaseSize = max(BaseSize, std::strlen(ValueMap[i].first)+6);
321 return BaseSize;
322}
323
324
325// printOptionInfo - Print out information about this option. The
326// to-be-maintained width is specified.
327//
328void EnumListBase::printOptionInfo(unsigned GlobalWidth) const {
329 for (unsigned i = 0; i < ValueMap.size(); ++i) {
330 unsigned L = std::strlen(ValueMap[i].first);
331 cerr << " -" << ValueMap[i].first << string(GlobalWidth-L-6, ' ') << " - "
332 << ValueMap[i].second.second << endl;
333 }
334}
335
336
337//===----------------------------------------------------------------------===//
338// Help option... always automatically provided.
339//
340namespace {
341
342// isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
343inline bool isHidden(pair<string, Option *> &OptPair) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000344 return OptPair.second->getOptionHiddenFlag() >= Hidden;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000345}
346inline bool isReallyHidden(pair<string, Option *> &OptPair) {
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000347 return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000348}
349
350class Help : public Option {
351 unsigned MaxArgLen;
352 const Option *EmptyArg;
353 const bool ShowHidden;
354
355 virtual bool handleOccurance(const char *ArgName, const string &Arg) {
356 // Copy Options into a vector so we can sort them as we like...
357 vector<pair<string, Option*> > Options;
358 copy(getOpts().begin(), getOpts().end(), back_inserter(Options));
359
360 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
361 Options.erase(remove_if(Options.begin(), Options.end(),
362 ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
363 Options.end());
364
365 // Eliminate duplicate entries in table (from enum flags options, f.e.)
366 set<Option*> OptionSet;
367 for (unsigned i = 0; i < Options.size(); )
368 if (OptionSet.count(Options[i].second) == 0)
369 OptionSet.insert(Options[i++].second); // Add to set
370 else
371 Options.erase(Options.begin()+i); // Erase duplicate
372
373
374 if (ProgramOverview)
375 cerr << "OVERVIEW:" << ProgramOverview << endl;
376 // TODO: Sort options by some criteria
377
378 cerr << "USAGE: " << ProgramName << " [options]\n\n";
379 // TODO: print usage nicer
380
381 // Compute the maximum argument length...
382 MaxArgLen = 0;
383 for_each(Options.begin(), Options.end(),
384 bind_obj(this, &Help::getMaxArgLen));
385
386 cerr << "OPTIONS:\n";
387 for_each(Options.begin(), Options.end(),
388 bind_obj(this, &Help::printOption));
389
390 return true; // Displaying help is cause to terminate the program
391 }
392
393 void getMaxArgLen(pair<string, Option *> OptPair) {
394 const Option *Opt = OptPair.second;
395 if (Opt->ArgStr[0] == 0) EmptyArg = Opt; // Capture the empty arg if exists
396 MaxArgLen = max(MaxArgLen, Opt->getOptionWidth());
397 }
398
399 void printOption(pair<string, Option *> OptPair) {
400 const Option *Opt = OptPair.second;
401 Opt->printOptionInfo(MaxArgLen);
402 }
403
404public:
405 inline Help(const char *ArgVal, const char *HelpVal, bool showHidden)
406 : Option(ArgVal, HelpVal, showHidden ? Hidden : 0), ShowHidden(showHidden) {
407 EmptyArg = 0;
408 }
409};
410
411Help HelpOp("help", "display available options"
Chris Lattnerdc4693d2001-07-23 23:02:45 +0000412 " (--help-hidden for more)", false);
Chris Lattnerdbab15a2001-07-23 17:17:47 +0000413Help HelpHiddenOpt("help-hidden", "display all available options", true);
414
415} // End anonymous namespace