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