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