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