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