Changes For Bug 352
[oota-llvm.git] / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements a command line argument processor that is useful when
11 // creating a tool.  It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
13 //
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include <algorithm>
22 #include <map>
23 #include <set>
24 #include <iostream>
25 #include <cstdlib>
26 #include <cerrno>
27 #include <cstring>
28 using namespace llvm;
29
30 using namespace cl;
31
32 // Globals for name and overview of program
33 static const char *ProgramName = "<unknown>";
34 static const char *ProgramOverview = 0;
35
36 //===----------------------------------------------------------------------===//
37 // Basic, shared command line option processing machinery...
38 //
39
40 // Return the global command line option vector.  Making it a function scoped
41 // static ensures that it will be initialized correctly before its first use.
42 //
43 static std::map<std::string, Option*> *CommandLineOptions = 0;
44 static std::map<std::string, Option*> &getOpts() {
45   if (CommandLineOptions == 0)
46     CommandLineOptions = new std::map<std::string,Option*>();
47   return *CommandLineOptions;
48 }
49
50 static Option *getOption(const std::string &Str) {
51   if (CommandLineOptions == 0) return 0;
52   std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str);
53   return I != CommandLineOptions->end() ? I->second : 0;
54 }
55
56 static std::vector<Option*> &getPositionalOpts() {
57   static std::vector<Option*> *Positional = 0;
58   if (!Positional) Positional = new std::vector<Option*>();
59   return *Positional;
60 }
61
62 static void AddArgument(const char *ArgName, Option *Opt) {
63   if (getOption(ArgName)) {
64     std::cerr << ProgramName << ": CommandLine Error: Argument '" 
65               << ArgName << "' defined more than once!\n";
66   } else {
67     // Add argument to the argument map!
68     getOpts()[ArgName] = Opt;
69   }
70 }
71
72 // RemoveArgument - It's possible that the argument is no longer in the map if
73 // options have already been processed and the map has been deleted!
74 // 
75 static void RemoveArgument(const char *ArgName, Option *Opt) {
76   if (CommandLineOptions == 0) return;
77 #ifndef NDEBUG
78   // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
79   // If we pass ArgName directly into getOption here.
80   std::string Tmp = ArgName;
81   assert(getOption(Tmp) == Opt && "Arg not in map!");
82 #endif
83   CommandLineOptions->erase(ArgName);
84   if (CommandLineOptions->empty()) {
85     delete CommandLineOptions;
86     CommandLineOptions = 0;
87   }
88 }
89
90 static inline bool ProvideOption(Option *Handler, const char *ArgName,
91                                  const char *Value, int argc, char **argv,
92                                  int &i) {
93   // Enforce value requirements
94   switch (Handler->getValueExpectedFlag()) {
95   case ValueRequired:
96     if (Value == 0 || *Value == 0) {  // No value specified?
97       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
98         Value = argv[++i];
99       } else {
100         return Handler->error(" requires a value!");
101       }
102     }
103     break;
104   case ValueDisallowed:
105     if (*Value != 0)
106       return Handler->error(" does not allow a value! '" + 
107                             std::string(Value) + "' specified.");
108     break;
109   case ValueOptional: 
110     break;
111   default: 
112     std::cerr << ProgramName 
113               << ": Bad ValueMask flag! CommandLine usage error:" 
114               << Handler->getValueExpectedFlag() << "\n"; 
115     abort();
116     break;
117   }
118
119   // Run the handler now!
120   return Handler->addOccurrence(i, ArgName, Value);
121 }
122
123 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg, 
124                                     int i) {
125   int Dummy = i;
126   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
127 }
128
129
130 // Option predicates...
131 static inline bool isGrouping(const Option *O) {
132   return O->getFormattingFlag() == cl::Grouping;
133 }
134 static inline bool isPrefixedOrGrouping(const Option *O) {
135   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
136 }
137
138 // getOptionPred - Check to see if there are any options that satisfy the
139 // specified predicate with names that are the prefixes in Name.  This is
140 // checked by progressively stripping characters off of the name, checking to
141 // see if there options that satisfy the predicate.  If we find one, return it,
142 // otherwise return null.
143 //
144 static Option *getOptionPred(std::string Name, unsigned &Length,
145                              bool (*Pred)(const Option*)) {
146   
147   Option *Op = getOption(Name);
148   if (Op && Pred(Op)) {
149     Length = Name.length();
150     return Op;
151   }
152
153   if (Name.size() == 1) return 0;
154   do {
155     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
156     Op = getOption(Name);
157
158     // Loop while we haven't found an option and Name still has at least two
159     // characters in it (so that the next iteration will not be the empty
160     // string...
161   } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
162
163   if (Op && Pred(Op)) {
164     Length = Name.length();
165     return Op;             // Found one!
166   }
167   return 0;                // No option found!
168 }
169
170 static bool RequiresValue(const Option *O) {
171   return O->getNumOccurrencesFlag() == cl::Required ||
172          O->getNumOccurrencesFlag() == cl::OneOrMore;
173 }
174
175 static bool EatsUnboundedNumberOfValues(const Option *O) {
176   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
177          O->getNumOccurrencesFlag() == cl::OneOrMore;
178 }
179
180 /// ParseCStringVector - Break INPUT up wherever one or more
181 /// whitespace characters are found, and store the resulting tokens in
182 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
183 /// using strdup (), so it is the caller's responsibility to free ()
184 /// them later.
185 ///
186 static void ParseCStringVector (std::vector<char *> &output,
187                                 const char *input) {
188   // Characters which will be treated as token separators:
189   static const char *delims = " \v\f\t\r\n";
190
191   std::string work (input);
192   // Skip past any delims at head of input string.
193   size_t pos = work.find_first_not_of (delims);
194   // If the string consists entirely of delims, then exit early.
195   if (pos == std::string::npos) return;
196   // Otherwise, jump forward to beginning of first word.
197   work = work.substr (pos);
198   // Find position of first delimiter.
199   pos = work.find_first_of (delims);
200
201   while (!work.empty() && pos != std::string::npos) {
202     // Everything from 0 to POS is the next word to copy.
203     output.push_back (strdup (work.substr (0,pos).c_str ()));
204     // Is there another word in the string?
205     size_t nextpos = work.find_first_not_of (delims, pos + 1);
206     if (nextpos != std::string::npos) {
207       // Yes? Then remove delims from beginning ...
208       work = work.substr (work.find_first_not_of (delims, pos + 1));
209       // and find the end of the word.
210       pos = work.find_first_of (delims);
211     } else {
212       // No? (Remainder of string is delims.) End the loop.
213       work = "";
214       pos = std::string::npos;
215     }
216   }
217
218   // If `input' ended with non-delim char, then we'll get here with
219   // the last word of `input' in `work'; copy it now.
220   if (!work.empty ()) {
221     output.push_back (strdup (work.c_str ()));
222   }
223 }
224
225 /// ParseEnvironmentOptions - An alternative entry point to the
226 /// CommandLine library, which allows you to read the program's name
227 /// from the caller (as PROGNAME) and its command-line arguments from
228 /// an environment variable (whose name is given in ENVVAR).
229 ///
230 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
231                                  const char *Overview) {
232   // Check args.
233   assert(progName && "Program name not specified");
234   assert(envVar && "Environment variable name missing");
235   
236   // Get the environment variable they want us to parse options out of.
237   const char *envValue = getenv (envVar);
238   if (!envValue)
239     return;
240
241   // Get program's "name", which we wouldn't know without the caller
242   // telling us.
243   std::vector<char *> newArgv;
244   newArgv.push_back (strdup (progName));
245
246   // Parse the value of the environment variable into a "command line"
247   // and hand it off to ParseCommandLineOptions().
248   ParseCStringVector (newArgv, envValue);
249   int newArgc = newArgv.size ();
250   ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
251
252   // Free all the strdup()ed strings.
253   for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
254        i != e; ++i) {
255     free (*i);
256   }
257 }
258
259 /// LookupOption - Lookup the option specified by the specified option on the
260 /// command line.  If there is a value specified (after an equal sign) return
261 /// that as well.
262 static Option *LookupOption(const char *&Arg, const char *&Value) {
263   while (*Arg == '-') ++Arg;  // Eat leading dashes
264   
265   const char *ArgEnd = Arg;
266   while (*ArgEnd && *ArgEnd != '=')
267     ++ArgEnd; // Scan till end of argument name...
268
269   Value = ArgEnd;
270   if (*Value)           // If we have an equals sign...
271     ++Value;            // Advance to value...
272   
273   if (*Arg == 0) return 0;
274
275   // Look up the option.
276   std::map<std::string, Option*> &Opts = getOpts();
277   std::map<std::string, Option*>::iterator I =
278     Opts.find(std::string(Arg, ArgEnd));
279   return (I != Opts.end()) ? I->second : 0;
280 }
281
282 void cl::ParseCommandLineOptions(int &argc, char **argv,
283                                  const char *Overview) {
284   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
285          "No options specified, or ParseCommandLineOptions called more"
286          " than once!");
287   ProgramName = argv[0];  // Save this away safe and snug
288   ProgramOverview = Overview;
289   bool ErrorParsing = false;
290
291   std::map<std::string, Option*> &Opts = getOpts();
292   std::vector<Option*> &PositionalOpts = getPositionalOpts();
293
294   // Check out the positional arguments to collect information about them.
295   unsigned NumPositionalRequired = 0;
296   Option *ConsumeAfterOpt = 0;
297   if (!PositionalOpts.empty()) {
298     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
299       assert(PositionalOpts.size() > 1 &&
300              "Cannot specify cl::ConsumeAfter without a positional argument!");
301       ConsumeAfterOpt = PositionalOpts[0];
302     }
303
304     // Calculate how many positional values are _required_.
305     bool UnboundedFound = false;
306     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
307          i != e; ++i) {
308       Option *Opt = PositionalOpts[i];
309       if (RequiresValue(Opt))
310         ++NumPositionalRequired;
311       else if (ConsumeAfterOpt) {
312         // ConsumeAfter cannot be combined with "optional" positional options
313         // unless there is only one positional argument...
314         if (PositionalOpts.size() > 2)
315           ErrorParsing |=
316             Opt->error(" error - this positional option will never be matched, "
317                        "because it does not Require a value, and a "
318                        "cl::ConsumeAfter option is active!");
319       } else if (UnboundedFound && !Opt->ArgStr[0]) {
320         // This option does not "require" a value...  Make sure this option is
321         // not specified after an option that eats all extra arguments, or this
322         // one will never get any!
323         //
324         ErrorParsing |= Opt->error(" error - option can never match, because "
325                                    "another positional argument will match an "
326                                    "unbounded number of values, and this option"
327                                    " does not require a value!");
328       }
329       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
330     }
331   }
332
333   // PositionalVals - A vector of "positional" arguments we accumulate into
334   // the process at the end...
335   //
336   std::vector<std::pair<std::string,unsigned> > PositionalVals;
337
338   // If the program has named positional arguments, and the name has been run
339   // across, keep track of which positional argument was named.  Otherwise put
340   // the positional args into the PositionalVals list...
341   Option *ActivePositionalArg = 0;
342
343   // Loop over all of the arguments... processing them.
344   bool DashDashFound = false;  // Have we read '--'?
345   for (int i = 1; i < argc; ++i) {
346     Option *Handler = 0;
347     const char *Value = "";
348     const char *ArgName = "";
349
350     // Check to see if this is a positional argument.  This argument is
351     // considered to be positional if it doesn't start with '-', if it is "-"
352     // itself, or if we have seen "--" already.
353     //
354     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
355       // Positional argument!
356       if (ActivePositionalArg) {
357         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
358         continue;  // We are done!
359       } else if (!PositionalOpts.empty()) {
360         PositionalVals.push_back(std::make_pair(argv[i],i));
361
362         // All of the positional arguments have been fulfulled, give the rest to
363         // the consume after option... if it's specified...
364         //
365         if (PositionalVals.size() >= NumPositionalRequired && 
366             ConsumeAfterOpt != 0) {
367           for (++i; i < argc; ++i)
368             PositionalVals.push_back(std::make_pair(argv[i],i));
369           break;   // Handle outside of the argument processing loop...
370         }
371
372         // Delay processing positional arguments until the end...
373         continue;
374       }
375     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
376                !DashDashFound) {
377       DashDashFound = true;  // This is the mythical "--"?
378       continue;              // Don't try to process it as an argument itself.
379     } else if (ActivePositionalArg &&
380                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
381       // If there is a positional argument eating options, check to see if this
382       // option is another positional argument.  If so, treat it as an argument,
383       // otherwise feed it to the eating positional.
384       ArgName = argv[i]+1;
385       Handler = LookupOption(ArgName, Value);
386       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
387         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
388         continue;  // We are done!
389       }
390
391     } else {     // We start with a '-', must be an argument...
392       ArgName = argv[i]+1;
393       Handler = LookupOption(ArgName, Value);
394
395       // Check to see if this "option" is really a prefixed or grouped argument.
396       if (Handler == 0 && *Value == 0) {
397         std::string RealName(ArgName);
398         if (RealName.size() > 1) {
399           unsigned Length = 0;
400           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
401   
402           // If the option is a prefixed option, then the value is simply the
403           // rest of the name...  so fall through to later processing, by
404           // setting up the argument name flags and value fields.
405           //
406           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
407             Value = ArgName+Length;
408             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
409                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
410             Handler = PGOpt;
411           } else if (PGOpt) {
412             // This must be a grouped option... handle them now.
413             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
414             
415             do {
416               // Move current arg name out of RealName into RealArgName...
417               std::string RealArgName(RealName.begin(),
418                                       RealName.begin() + Length);
419               RealName.erase(RealName.begin(), RealName.begin() + Length);
420               
421               // Because ValueRequired is an invalid flag for grouped arguments,
422               // we don't need to pass argc/argv in...
423               //
424               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
425                      "Option can not be cl::Grouping AND cl::ValueRequired!");
426               int Dummy;
427               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
428                                             "", 0, 0, Dummy);
429               
430               // Get the next grouping option...
431               PGOpt = getOptionPred(RealName, Length, isGrouping);
432             } while (PGOpt && Length != RealName.size());
433             
434             Handler = PGOpt; // Ate all of the options.
435           }
436         }
437       }
438     }
439
440     if (Handler == 0) {
441       std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
442                 << "'.  Try: '" << argv[0] << " --help'\n";
443       ErrorParsing = true;
444       continue;
445     }
446
447     // Check to see if this option accepts a comma separated list of values.  If
448     // it does, we have to split up the value into multiple values...
449     if (Handler->getMiscFlags() & CommaSeparated) {
450       std::string Val(Value);
451       std::string::size_type Pos = Val.find(',');
452
453       while (Pos != std::string::npos) {
454         // Process the portion before the comma...
455         ErrorParsing |= ProvideOption(Handler, ArgName,
456                                       std::string(Val.begin(),
457                                                   Val.begin()+Pos).c_str(),
458                                       argc, argv, i);
459         // Erase the portion before the comma, AND the comma...
460         Val.erase(Val.begin(), Val.begin()+Pos+1);
461         Value += Pos+1;  // Increment the original value pointer as well...
462
463         // Check for another comma...
464         Pos = Val.find(',');
465       }
466     }
467
468     // If this is a named positional argument, just remember that it is the
469     // active one...
470     if (Handler->getFormattingFlag() == cl::Positional)
471       ActivePositionalArg = Handler;
472     else 
473       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
474   }
475
476   // Check and handle positional arguments now...
477   if (NumPositionalRequired > PositionalVals.size()) {
478     std::cerr << ProgramName 
479               << ": Not enough positional command line arguments specified!\n"
480               << "Must specify at least " << NumPositionalRequired
481               << " positional arguments: See: " << argv[0] << " --help\n";
482     ErrorParsing = true;
483
484
485   } else if (ConsumeAfterOpt == 0) {
486     // Positional args have already been handled if ConsumeAfter is specified...
487     unsigned ValNo = 0, NumVals = PositionalVals.size();
488     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
489       if (RequiresValue(PositionalOpts[i])) {
490         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 
491                                 PositionalVals[ValNo].second);
492         ValNo++;
493         --NumPositionalRequired;  // We fulfilled our duty...
494       }
495
496       // If we _can_ give this option more arguments, do so now, as long as we
497       // do not give it values that others need.  'Done' controls whether the
498       // option even _WANTS_ any more.
499       //
500       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
501       while (NumVals-ValNo > NumPositionalRequired && !Done) {
502         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
503         case cl::Optional:
504           Done = true;          // Optional arguments want _at most_ one value
505           // FALL THROUGH
506         case cl::ZeroOrMore:    // Zero or more will take all they can get...
507         case cl::OneOrMore:     // One or more will take all they can get...
508           ProvidePositionalOption(PositionalOpts[i],
509                                   PositionalVals[ValNo].first,
510                                   PositionalVals[ValNo].second);
511           ValNo++;
512           break;
513         default:
514           assert(0 && "Internal error, unexpected NumOccurrences flag in "
515                  "positional argument processing!");
516         }
517       }
518     }
519   } else {
520     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
521     unsigned ValNo = 0;
522     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
523       if (RequiresValue(PositionalOpts[j])) {
524         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
525                                                 PositionalVals[ValNo].first,
526                                                 PositionalVals[ValNo].second);
527         ValNo++;
528       }
529
530     // Handle the case where there is just one positional option, and it's
531     // optional.  In this case, we want to give JUST THE FIRST option to the
532     // positional option and keep the rest for the consume after.  The above
533     // loop would have assigned no values to positional options in this case.
534     //
535     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
536       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
537                                               PositionalVals[ValNo].first,
538                                               PositionalVals[ValNo].second);
539       ValNo++;
540     }
541     
542     // Handle over all of the rest of the arguments to the
543     // cl::ConsumeAfter command line option...
544     for (; ValNo != PositionalVals.size(); ++ValNo)
545       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
546                                               PositionalVals[ValNo].first,
547                                               PositionalVals[ValNo].second);
548   }
549
550   // Loop over args and make sure all required args are specified!
551   for (std::map<std::string, Option*>::iterator I = Opts.begin(), 
552          E = Opts.end(); I != E; ++I) {
553     switch (I->second->getNumOccurrencesFlag()) {
554     case Required:
555     case OneOrMore:
556       if (I->second->getNumOccurrences() == 0) {
557         I->second->error(" must be specified at least once!");
558         ErrorParsing = true;
559       }
560       // Fall through
561     default:
562       break;
563     }
564   }
565
566   // Free all of the memory allocated to the map.  Command line options may only
567   // be processed once!
568   delete CommandLineOptions;
569   CommandLineOptions = 0;
570   PositionalOpts.clear();
571
572   // If we had an error processing our arguments, don't let the program execute
573   if (ErrorParsing) exit(1);
574 }
575
576 //===----------------------------------------------------------------------===//
577 // Option Base class implementation
578 //
579
580 bool Option::error(std::string Message, const char *ArgName) {
581   if (ArgName == 0) ArgName = ArgStr;
582   if (ArgName[0] == 0)
583     std::cerr << HelpStr;  // Be nice for positional arguments
584   else
585     std::cerr << ProgramName << ": for the -" << ArgName;
586   std::cerr << " option: " << Message << "\n";
587   return true;
588 }
589
590 bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
591   NumOccurrences++;   // Increment the number of times we have been seen
592
593   switch (getNumOccurrencesFlag()) {
594   case Optional:
595     if (NumOccurrences > 1)
596       return error(": may only occur zero or one times!", ArgName);
597     break;
598   case Required:
599     if (NumOccurrences > 1)
600       return error(": must occur exactly one time!", ArgName);
601     // Fall through
602   case OneOrMore:
603   case ZeroOrMore:
604   case ConsumeAfter: break;
605   default: return error(": bad num occurrences flag value!");
606   }
607
608   return handleOccurrence(pos, ArgName, Value);
609 }
610
611 // addArgument - Tell the system that this Option subclass will handle all
612 // occurrences of -ArgStr on the command line.
613 //
614 void Option::addArgument(const char *ArgStr) {
615   if (ArgStr[0])
616     AddArgument(ArgStr, this);
617
618   if (getFormattingFlag() == Positional)
619     getPositionalOpts().push_back(this);
620   else if (getNumOccurrencesFlag() == ConsumeAfter) {
621     if (!getPositionalOpts().empty() &&
622         getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
623       error("Cannot specify more than one option with cl::ConsumeAfter!");
624     getPositionalOpts().insert(getPositionalOpts().begin(), this);
625   }
626 }
627
628 void Option::removeArgument(const char *ArgStr) {
629   if (ArgStr[0])
630     RemoveArgument(ArgStr, this);
631
632   if (getFormattingFlag() == Positional) {
633     std::vector<Option*>::iterator I =
634       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
635     assert(I != getPositionalOpts().end() && "Arg not registered!");
636     getPositionalOpts().erase(I);
637   } else if (getNumOccurrencesFlag() == ConsumeAfter) {
638     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
639            "Arg not registered correctly!");
640     getPositionalOpts().erase(getPositionalOpts().begin());
641   }
642 }
643
644
645 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
646 // has been specified yet.
647 //
648 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
649   if (O.ValueStr[0] == 0) return DefaultMsg;
650   return O.ValueStr;
651 }
652
653 //===----------------------------------------------------------------------===//
654 // cl::alias class implementation
655 //
656
657 // Return the width of the option tag for printing...
658 unsigned alias::getOptionWidth() const {
659   return std::strlen(ArgStr)+6;
660 }
661
662 // Print out the option for the alias...
663 void alias::printOptionInfo(unsigned GlobalWidth) const {
664   unsigned L = std::strlen(ArgStr);
665   std::cerr << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
666             << HelpStr << "\n";
667 }
668
669
670
671 //===----------------------------------------------------------------------===//
672 // Parser Implementation code...
673 //
674
675 // basic_parser implementation
676 //
677
678 // Return the width of the option tag for printing...
679 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
680   unsigned Len = std::strlen(O.ArgStr);
681   if (const char *ValName = getValueName())
682     Len += std::strlen(getValueStr(O, ValName))+3;
683
684   return Len + 6;
685 }
686
687 // printOptionInfo - Print out information about this option.  The 
688 // to-be-maintained width is specified.
689 //
690 void basic_parser_impl::printOptionInfo(const Option &O,
691                                         unsigned GlobalWidth) const {
692   std::cerr << "  -" << O.ArgStr;
693
694   if (const char *ValName = getValueName())
695     std::cerr << "=<" << getValueStr(O, ValName) << ">";
696
697   std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
698             << O.HelpStr << "\n";
699 }
700
701
702
703
704 // parser<bool> implementation
705 //
706 bool parser<bool>::parse(Option &O, const char *ArgName,
707                          const std::string &Arg, bool &Value) {
708   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 
709       Arg == "1") {
710     Value = true;
711   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
712     Value = false;
713   } else {
714     return O.error(": '" + Arg +
715                    "' is invalid value for boolean argument! Try 0 or 1");
716   }
717   return false;
718 }
719
720 // parser<int> implementation
721 //
722 bool parser<int>::parse(Option &O, const char *ArgName,
723                         const std::string &Arg, int &Value) {
724   char *End;
725   Value = (int)strtol(Arg.c_str(), &End, 0);
726   if (*End != 0) 
727     return O.error(": '" + Arg + "' value invalid for integer argument!");
728   return false;
729 }
730
731 // parser<unsigned> implementation
732 //
733 bool parser<unsigned>::parse(Option &O, const char *ArgName,
734                              const std::string &Arg, unsigned &Value) {
735   char *End;
736   errno = 0;
737   unsigned long V = strtoul(Arg.c_str(), &End, 0);
738   Value = (unsigned)V;
739   if (((V == ULONG_MAX) && (errno == ERANGE))
740       || (*End != 0)
741       || (Value != V))
742     return O.error(": '" + Arg + "' value invalid for uint argument!");
743   return false;
744 }
745
746 // parser<double>/parser<float> implementation
747 //
748 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
749   const char *ArgStart = Arg.c_str();
750   char *End;
751   Value = strtod(ArgStart, &End);
752   if (*End != 0) 
753     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
754   return false;
755 }
756
757 bool parser<double>::parse(Option &O, const char *AN,
758                            const std::string &Arg, double &Val) {
759   return parseDouble(O, Arg, Val);
760 }
761
762 bool parser<float>::parse(Option &O, const char *AN,
763                           const std::string &Arg, float &Val) {
764   double dVal;
765   if (parseDouble(O, Arg, dVal))
766     return true;
767   Val = (float)dVal;
768   return false;
769 }
770
771
772
773 // generic_parser_base implementation
774 //
775
776 // findOption - Return the option number corresponding to the specified
777 // argument string.  If the option is not found, getNumOptions() is returned.
778 //
779 unsigned generic_parser_base::findOption(const char *Name) {
780   unsigned i = 0, e = getNumOptions();
781   std::string N(Name);
782
783   while (i != e)
784     if (getOption(i) == N)
785       return i;
786     else
787       ++i;
788   return e;
789 }
790
791
792 // Return the width of the option tag for printing...
793 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
794   if (O.hasArgStr()) {
795     unsigned Size = std::strlen(O.ArgStr)+6;
796     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
797       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
798     return Size;
799   } else {
800     unsigned BaseSize = 0;
801     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
802       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
803     return BaseSize;
804   }
805 }
806
807 // printOptionInfo - Print out information about this option.  The 
808 // to-be-maintained width is specified.
809 //
810 void generic_parser_base::printOptionInfo(const Option &O,
811                                           unsigned GlobalWidth) const {
812   if (O.hasArgStr()) {
813     unsigned L = std::strlen(O.ArgStr);
814     std::cerr << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
815               << " - " << O.HelpStr << "\n";
816
817     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
818       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
819       std::cerr << "    =" << getOption(i) << std::string(NumSpaces, ' ')
820                 << " - " << getDescription(i) << "\n";
821     }
822   } else {
823     if (O.HelpStr[0])
824       std::cerr << "  " << O.HelpStr << "\n"; 
825     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
826       unsigned L = std::strlen(getOption(i));
827       std::cerr << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
828                 << " - " << getDescription(i) << "\n";
829     }
830   }
831 }
832
833
834 //===----------------------------------------------------------------------===//
835 // --help and --help-hidden option implementation
836 //
837 namespace {
838
839 class HelpPrinter {
840   unsigned MaxArgLen;
841   const Option *EmptyArg;
842   const bool ShowHidden;
843
844   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
845   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
846     return OptPair.second->getOptionHiddenFlag() >= Hidden;
847   }
848   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
849     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
850   }
851
852 public:
853   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
854     EmptyArg = 0;
855   }
856
857   void operator=(bool Value) {
858     if (Value == false) return;
859
860     // Copy Options into a vector so we can sort them as we like...
861     std::vector<std::pair<std::string, Option*> > Options;
862     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
863
864     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
865     Options.erase(std::remove_if(Options.begin(), Options.end(), 
866                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
867                   Options.end());
868
869     // Eliminate duplicate entries in table (from enum flags options, f.e.)
870     {  // Give OptionSet a scope
871       std::set<Option*> OptionSet;
872       for (unsigned i = 0; i != Options.size(); ++i)
873         if (OptionSet.count(Options[i].second) == 0)
874           OptionSet.insert(Options[i].second);   // Add new entry to set
875         else
876           Options.erase(Options.begin()+i--);    // Erase duplicate
877     }
878
879     if (ProgramOverview)
880       std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
881
882     std::cerr << "USAGE: " << ProgramName << " [options]";
883
884     // Print out the positional options...
885     std::vector<Option*> &PosOpts = getPositionalOpts();
886     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
887     if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
888       CAOpt = PosOpts[0];
889
890     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
891       if (PosOpts[i]->ArgStr[0])
892         std::cerr << " --" << PosOpts[i]->ArgStr;
893       std::cerr << " " << PosOpts[i]->HelpStr;
894     }
895
896     // Print the consume after option info if it exists...
897     if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
898
899     std::cerr << "\n\n";
900
901     // Compute the maximum argument length...
902     MaxArgLen = 0;
903     for (unsigned i = 0, e = Options.size(); i != e; ++i)
904       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
905
906     std::cerr << "OPTIONS:\n";
907     for (unsigned i = 0, e = Options.size(); i != e; ++i)
908       Options[i].second->printOptionInfo(MaxArgLen);
909
910     // Halt the program if help information is printed
911     exit(1);
912   }
913 };
914
915 class VersionPrinter {
916 public:
917   void operator=(bool OptionWasSpecified) {
918     if (OptionWasSpecified) {
919       std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") " 
920         << PACKAGE_VERSION << " (see http://llvm.org/)\n";
921       exit(1);
922     }
923   }
924 };
925
926
927 // Define the two HelpPrinter instances that are used to print out help, or
928 // help-hidden...
929 //
930 HelpPrinter NormalPrinter(false);
931 HelpPrinter HiddenPrinter(true);
932
933 cl::opt<HelpPrinter, true, parser<bool> > 
934 HOp("help", cl::desc("display available options (--help-hidden for more)"),
935     cl::location(NormalPrinter), cl::ValueDisallowed);
936
937 cl::opt<HelpPrinter, true, parser<bool> >
938 HHOp("help-hidden", cl::desc("display all available options"),
939      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
940
941 // Define the --version option that prints out the LLVM version for the tool
942 VersionPrinter VersionPrinterInstance;
943 cl::opt<VersionPrinter, true, parser<bool> >
944 VersOp("version", cl::desc("display the version"), 
945     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
946
947 } // End anonymous namespace