Minor changes to implementation of CommandLine library to let users override
[oota-llvm.git] / 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 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Support/CommandLine.h"
10 #include "llvm/Support/STLExtras.h"
11 #include <vector>
12 #include <algorithm>
13 #include <map>
14 #include <set>
15 using namespace cl;
16
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.
19 //
20 static map<string, Option*> &getOpts() {
21   static map<string,Option*> CommandLineOptions;
22   return CommandLineOptions;
23 }
24
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";
29   } else {
30     getOpts()[ArgName] = Opt;  // Add argument to the argument map!
31   }
32 }
33
34 static const char *ProgramName = 0;
35 static const char *ProgramOverview = 0;
36
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;
42
43   // Loop over all of the arguments... processing them.
44   for (int i = 1; i < argc; ++i) {
45     Option *Handler = 0;
46     const char *Value = "";
47     const char *ArgName = "";
48     if (argv[i][0] != '-') {   // Unnamed argument?
49       Handler = getOpts()[""];
50       Value = argv[i];
51     } else {               // We start with a - or --, eat dashes
52       ArgName = argv[i]+1;
53       while (*ArgName == '-') ++ArgName;  // Eat leading dashes
54
55       const char *ArgNameEnd = ArgName;
56       while (*ArgNameEnd && *ArgNameEnd != '=') ++ArgNameEnd; // Scan till end
57
58       Value = ArgNameEnd;
59       if (*Value)           // If we have an equals sign...
60         ++Value;            // Advance to value...
61
62       if (*ArgName != 0) {
63         string ArgNameStr(ArgName, ArgNameEnd); // Extract arg name part
64         Handler = getOpts()[ArgNameStr];
65       }
66     }
67
68     if (Handler == 0) {
69       cerr << "Unknown command line argument '" << argv[i] << "'.  Try: "
70            << argv[0] << " --help\n'";
71       ErrorParsing = true;
72       continue;
73     }
74
75     // Enforce value requirements
76     switch (Handler->getValueExpectedFlag()) {
77     case ValueRequired:
78       if (Value == 0 || *Value == 0) {  // No value specified?
79         if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
80           Value = argv[++i];
81         } else {
82           ErrorParsing = Handler->error(" requires a value!");
83           continue;
84         }
85       }
86       break;
87     case ValueDisallowed:
88       if (*Value != 0) {
89         ErrorParsing = Handler->error(" does not allow a value! '" + 
90                                       string(Value) + "' specified.");
91         continue;
92       }
93       break;
94     case Optional: break;
95     default: cerr << "Bad ValueMask flag! CommandLine usage error!\n"; abort();
96     }
97
98     // Run the handler now!
99     ErrorParsing |= Handler->addOccurance(ArgName, Value);
100   }
101
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()) {
106     case Required:
107     case OneOrMore:
108       if (I->second->getNumOccurances() == 0)
109         I->second->error(" must be specified at least once!");
110       // Fall through
111     default:
112       break;
113     }
114   }
115
116   // Free all of the memory allocated to the vector.  Command line options may
117   // only be processed once!
118   getOpts().clear();
119
120   // If we had an error processing our arguments, don't let the program execute
121   if (ErrorParsing) exit(1);
122 }
123
124 //===----------------------------------------------------------------------===//
125 // Option Base class implementation
126 //
127 Option::Option(const char *argStr, const char *helpStr, int flags)
128   : NumOccurances(0), Flags(flags), ArgStr(argStr), HelpStr(helpStr) {
129   AddArgument(ArgStr, this);
130 }
131
132 bool Option::error(string Message, const char *ArgName = 0) {
133   if (ArgName == 0) ArgName = ArgStr;
134   cerr << "-" << ArgName << " option" << Message << endl;
135   return true;
136 }
137
138 bool Option::addOccurance(const char *ArgName, const string &Value) {
139   NumOccurances++;   // Increment the number of times we have been seen
140
141   switch (getNumOccurancesFlag()) {
142   case Optional:
143     if (NumOccurances > 1)
144       return error(": may only occur zero or one times!", ArgName);
145     break;
146   case Required:
147     if (NumOccurances > 1)
148       return error(": must occur exactly one time!", ArgName);
149     // Fall through
150   case OneOrMore:
151   case ZeroOrMore: break;
152   default: return error(": bad num occurances flag value!");
153   }
154
155   return handleOccurance(ArgName, Value);
156 }
157
158 // Return the width of the option tag for printing...
159 unsigned Option::getOptionWidth() const {
160   return std::strlen(ArgStr)+6;
161 }
162
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, ' ') << " - "
167        << HelpStr << endl;
168 }
169
170
171 //===----------------------------------------------------------------------===//
172 // Boolean/flag command line option implementation
173 //
174
175 bool Flag::handleOccurance(const char *ArgName, const string &Arg) {
176   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 
177       Arg == "1") {
178     Value = true;
179   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
180     Value = false;
181   } else {
182     return error(": '" + Arg + "' is invalid value for boolean argument! Try 0 or 1");
183   }
184
185   return false;
186 }
187
188 //===----------------------------------------------------------------------===//
189 // Integer valued command line option implementation
190 //
191 bool Int::handleOccurance(const char *ArgName, const string &Arg) {
192   const char *ArgStart = Arg.c_str();
193   char *End;
194   Value = (int)strtol(ArgStart, &End, 0);
195   if (*End != 0) 
196     return error(": '" + Arg + "' value invalid for integer argument!");
197   return false;  
198 }
199
200 //===----------------------------------------------------------------------===//
201 // String valued command line option implementation
202 //
203 bool String::handleOccurance(const char *ArgName, const string &Arg) {
204   *this = Arg;
205   return false;
206 }
207
208 //===----------------------------------------------------------------------===//
209 // Enum valued command line option implementation
210 //
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)));
217   }
218 }
219
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);
224 }
225
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;
229   return "";
230 }
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;
234   return "";
235 }
236
237
238
239 bool EnumValueBase::handleOccurance(const char *ArgName, const string &Arg) {
240   unsigned i;
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;
246   return false;
247 }
248
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);
254   return BaseSize;
255 }
256
257 // printOptionInfo - Print out information about this option.  The 
258 // to-be-maintained width is specified.
259 //
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;
266
267     if (i == 0) cerr << " (default)";
268     cerr << endl;
269   }
270 }
271
272 //===----------------------------------------------------------------------===//
273 // Enum flags command line option implementation
274 //
275
276 bool EnumFlagsBase::handleOccurance(const char *ArgName, const string &Arg) {
277   return EnumValueBase::handleOccurance("", ArgName);
278 }
279
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);
284   return BaseSize;
285 }
286
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)";
293     cerr << endl;
294   }
295 }
296
297
298 //===----------------------------------------------------------------------===//
299 // Enum list command line option implementation
300 //
301
302 bool EnumListBase::handleOccurance(const char *ArgName, const string &Arg) {
303   unsigned i;
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);
309   return false;
310 }
311
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);
317   return BaseSize;
318 }
319
320
321 // printOptionInfo - Print out information about this option.  The 
322 // to-be-maintained width is specified.
323 //
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;
329   }
330 }
331
332
333 //===----------------------------------------------------------------------===//
334 // Help option... always automatically provided.
335 //
336 namespace {
337
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;
341 }
342 inline bool isReallyHidden(pair<string, Option *> &OptPair) {
343   return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
344 }
345
346 class Help : public Option {
347   unsigned MaxArgLen;
348   const Option *EmptyArg;
349   const bool ShowHidden;
350
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));
355
356     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
357     Options.erase(remove_if(Options.begin(), Options.end(), 
358                             ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
359                   Options.end());
360
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
366       else
367         Options.erase(Options.begin()+i);      // Erase duplicate
368
369
370     if (ProgramOverview)
371       cerr << "OVERVIEW:" << ProgramOverview << endl;
372     // TODO: Sort options by some criteria
373
374     cerr << "USAGE: " << ProgramName << " [options]\n\n";
375     // TODO: print usage nicer
376
377     // Compute the maximum argument length...
378     MaxArgLen = 0;
379     for_each(Options.begin(), Options.end(),
380              bind_obj(this, &Help::getMaxArgLen));
381
382     cerr << "OPTIONS:\n";
383     for_each(Options.begin(), Options.end(), 
384              bind_obj(this, &Help::printOption));
385
386     return true;  // Displaying help is cause to terminate the program
387   }
388
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());
393   }
394
395   void printOption(pair<string, Option *> OptPair) {
396     const Option *Opt = OptPair.second;
397     Opt->printOptionInfo(MaxArgLen);
398   }
399
400 public:
401   inline Help(const char *ArgVal, const char *HelpVal, bool showHidden)
402     : Option(ArgVal, HelpVal, showHidden ? Hidden : 0), ShowHidden(showHidden) {
403     EmptyArg = 0;
404   }
405 };
406
407 Help HelpOp("help", "display available options"
408             " (--help-hidden for more)", false);
409 Help HelpHiddenOpt("help-hidden", "display all available options", true);
410
411 } // End anonymous namespace