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