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