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