Provide option to enable eating of all arguments following a specific one
[oota-llvm.git] / support / lib / Support / CommandLine.cpp
1 //===-- 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 //
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
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/STLExtras.h"
14 #include <vector>
15 #include <algorithm>
16 #include <map>
17 #include <set>
18 using 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 //
23 static map<string, Option*> &getOpts() {
24   static map<string,Option*> CommandLineOptions;
25   return CommandLineOptions;
26 }
27
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";
32   } else {
33     getOpts()[ArgName] = Opt;  // Add argument to the argument map!
34   }
35 }
36
37 static const char *ProgramName = 0;
38 static const char *ProgramOverview = 0;
39
40 static 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
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;
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?
81       map<string, Option*>::iterator I = getOpts().find("");
82       Handler = I != getOpts().end() ? I->second : 0;
83       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;
89       while (*ArgNameEnd && *ArgNameEnd != '=' &&
90              *ArgNameEnd != '/') ++ArgNameEnd; // Scan till end
91       // TODO: Remove '/' case.  Implement single letter args properly!
92
93       Value = ArgNameEnd;
94       if (*Value)           // If we have an equals sign...
95         ++Value;            // Advance to value...
96
97       if (*ArgName != 0) {
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;
102       }
103     }
104
105     if (Handler == 0) {
106       cerr << "Unknown command line argument '" << argv[i] << "'.  Try: "
107            << argv[0] << " --help'\n";
108       ErrorParsing = true;
109       continue;
110     }
111
112     ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
113
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);
118     }
119   }
120
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()) {
125     case Required:
126     case OneOrMore:
127       if (I->second->getNumOccurances() == 0) {
128         I->second->error(" must be specified at least once!");
129         ErrorParsing = true;
130       }
131       // Fall through
132     default:
133       break;
134     }
135   }
136
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 //
148 Option::Option(const char *argStr, const char *helpStr, int flags)
149   : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
150   AddArgument(ArgStr, this);
151 }
152
153 bool 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
159 bool Option::addOccurance(const char *ArgName, const string &Value) {
160   NumOccurances++;   // Increment the number of times we have been seen
161
162   switch (getNumOccurancesFlag()) {
163   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:
172   case ZeroOrMore:
173   case ConsumeAfter: break;
174   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...
181 unsigned Option::getOptionWidth() const {
182   return std::strlen(ArgStr)+6;
183 }
184
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, ' ') << " - "
189        << HelpStr << endl;
190 }
191
192
193 //===----------------------------------------------------------------------===//
194 // Boolean/flag command line option implementation
195 //
196
197 bool 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 {
204     return error(": '" + Arg +
205                  "' is invalid value for boolean argument! Try 0 or 1");
206   }
207
208   return false;
209 }
210
211 //===----------------------------------------------------------------------===//
212 // Integer valued command line option implementation
213 //
214 bool 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 //
226 bool String::handleOccurance(const char *ArgName, const string &Arg) {
227   *this = Arg;
228   return false;
229 }
230
231 //===----------------------------------------------------------------------===//
232 // StringList valued command line option implementation
233 //
234 bool StringList::handleOccurance(const char *ArgName, const string &Arg) {
235   push_back(Arg);
236   return false;
237 }
238
239 //===----------------------------------------------------------------------===//
240 // Enum valued command line option implementation
241 //
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)));
248   }
249 }
250
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);
255 }
256
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;
260   return "";
261 }
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;
265   return "";
266 }
267
268
269
270 bool 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...
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);
285   return BaseSize;
286 }
287
288 // printOptionInfo - Print out information about this option.  The 
289 // to-be-maintained width is specified.
290 //
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;
297
298     if (i == 0) cerr << " (default)";
299     cerr << endl;
300   }
301 }
302
303 //===----------------------------------------------------------------------===//
304 // Enum flags command line option implementation
305 //
306
307 bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
308   return EnumValueBase::handleOccurance("", ArgName);
309 }
310
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);
315   return BaseSize;
316 }
317
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)";
324     cerr << endl;
325   }
326 }
327
328
329 //===----------------------------------------------------------------------===//
330 // Enum list command line option implementation
331 //
332
333 bool 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...
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);
348   return BaseSize;
349 }
350
351
352 // printOptionInfo - Print out information about this option.  The 
353 // to-be-maintained width is specified.
354 //
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;
360   }
361 }
362
363
364 //===----------------------------------------------------------------------===//
365 // Help option... always automatically provided.
366 //
367 namespace {
368
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;
372 }
373 inline bool isReallyHidden(pair<string, Option *> &OptPair) {
374   return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
375 }
376
377 class 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
431 public:
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
438 Help HelpOp("help", "display available options"
439             " (--help-hidden for more)", false);
440 Help HelpHiddenOpt("help-hidden", "display all available options", true);
441
442 } // End anonymous namespace