57620b50d6c6f8a3a8e81c194616a414a923e53c
[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 /// LookupOption - Lookup the option specified by the specified option on the
290 /// command line.  If there is a value specified (after an equal sign) return
291 /// that as well.
292 static Option *LookupOption(const char *&Arg, const char *&Value) {
293   while (*Arg == '-') ++Arg;  // Eat leading dashes
294
295   const char *ArgEnd = Arg;
296   while (*ArgEnd && *ArgEnd != '=')
297     ++ArgEnd; // Scan till end of argument name.
298
299   if (*ArgEnd == '=')  // If we have an equals sign...
300     Value = ArgEnd+1;  // Get the value, not the equals
301
302
303   if (*Arg == 0) return 0;
304
305   // Look up the option.
306   std::map<std::string, Option*> &Opts = getOpts();
307   std::map<std::string, Option*>::iterator I =
308     Opts.find(std::string(Arg, ArgEnd));
309   return (I != Opts.end()) ? I->second : 0;
310 }
311
312 void cl::ParseCommandLineOptions(int &argc, char **argv,
313                                  const char *Overview) {
314   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
315          "No options specified, or ParseCommandLineOptions called more"
316          " than once!");
317   sys::Path progname(argv[0]);
318   ProgramName = sys::Path(argv[0]).getLast();
319   ProgramOverview = Overview;
320   bool ErrorParsing = false;
321
322   std::map<std::string, Option*> &Opts = getOpts();
323   std::vector<Option*> &PositionalOpts = getPositionalOpts();
324
325   // Check out the positional arguments to collect information about them.
326   unsigned NumPositionalRequired = 0;
327   
328   // Determine whether or not there are an unlimited number of positionals
329   bool HasUnlimitedPositionals = false;
330   
331   Option *ConsumeAfterOpt = 0;
332   if (!PositionalOpts.empty()) {
333     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
334       assert(PositionalOpts.size() > 1 &&
335              "Cannot specify cl::ConsumeAfter without a positional argument!");
336       ConsumeAfterOpt = PositionalOpts[0];
337     }
338
339     // Calculate how many positional values are _required_.
340     bool UnboundedFound = false;
341     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
342          i != e; ++i) {
343       Option *Opt = PositionalOpts[i];
344       if (RequiresValue(Opt))
345         ++NumPositionalRequired;
346       else if (ConsumeAfterOpt) {
347         // ConsumeAfter cannot be combined with "optional" positional options
348         // unless there is only one positional argument...
349         if (PositionalOpts.size() > 2)
350           ErrorParsing |=
351             Opt->error(" error - this positional option will never be matched, "
352                        "because it does not Require a value, and a "
353                        "cl::ConsumeAfter option is active!");
354       } else if (UnboundedFound && !Opt->ArgStr[0]) {
355         // This option does not "require" a value...  Make sure this option is
356         // not specified after an option that eats all extra arguments, or this
357         // one will never get any!
358         //
359         ErrorParsing |= Opt->error(" error - option can never match, because "
360                                    "another positional argument will match an "
361                                    "unbounded number of values, and this option"
362                                    " does not require a value!");
363       }
364       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
365     }
366     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
367   }
368
369   // PositionalVals - A vector of "positional" arguments we accumulate into
370   // the process at the end...
371   //
372   std::vector<std::pair<std::string,unsigned> > PositionalVals;
373
374   // If the program has named positional arguments, and the name has been run
375   // across, keep track of which positional argument was named.  Otherwise put
376   // the positional args into the PositionalVals list...
377   Option *ActivePositionalArg = 0;
378
379   // Loop over all of the arguments... processing them.
380   bool DashDashFound = false;  // Have we read '--'?
381   for (int i = 1; i < argc; ++i) {
382     Option *Handler = 0;
383     const char *Value = 0;
384     const char *ArgName = "";
385
386     // Check to see if this is a positional argument.  This argument is
387     // considered to be positional if it doesn't start with '-', if it is "-"
388     // itself, or if we have seen "--" already.
389     //
390     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
391       // Positional argument!
392       if (ActivePositionalArg) {
393         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
394         continue;  // We are done!
395       } else if (!PositionalOpts.empty()) {
396         PositionalVals.push_back(std::make_pair(argv[i],i));
397
398         // All of the positional arguments have been fulfulled, give the rest to
399         // the consume after option... if it's specified...
400         //
401         if (PositionalVals.size() >= NumPositionalRequired &&
402             ConsumeAfterOpt != 0) {
403           for (++i; i < argc; ++i)
404             PositionalVals.push_back(std::make_pair(argv[i],i));
405           break;   // Handle outside of the argument processing loop...
406         }
407
408         // Delay processing positional arguments until the end...
409         continue;
410       }
411     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
412                !DashDashFound) {
413       DashDashFound = true;  // This is the mythical "--"?
414       continue;              // Don't try to process it as an argument itself.
415     } else if (ActivePositionalArg &&
416                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
417       // If there is a positional argument eating options, check to see if this
418       // option is another positional argument.  If so, treat it as an argument,
419       // otherwise feed it to the eating positional.
420       ArgName = argv[i]+1;
421       Handler = LookupOption(ArgName, Value);
422       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
423         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
424         continue;  // We are done!
425       }
426
427     } else {     // We start with a '-', must be an argument...
428       ArgName = argv[i]+1;
429       Handler = LookupOption(ArgName, Value);
430
431       // Check to see if this "option" is really a prefixed or grouped argument.
432       if (Handler == 0) {
433         std::string RealName(ArgName);
434         if (RealName.size() > 1) {
435           unsigned Length = 0;
436           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
437
438           // If the option is a prefixed option, then the value is simply the
439           // rest of the name...  so fall through to later processing, by
440           // setting up the argument name flags and value fields.
441           //
442           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
443             Value = ArgName+Length;
444             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
445                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
446             Handler = PGOpt;
447           } else if (PGOpt) {
448             // This must be a grouped option... handle them now.
449             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
450
451             do {
452               // Move current arg name out of RealName into RealArgName...
453               std::string RealArgName(RealName.begin(),
454                                       RealName.begin() + Length);
455               RealName.erase(RealName.begin(), RealName.begin() + Length);
456
457               // Because ValueRequired is an invalid flag for grouped arguments,
458               // we don't need to pass argc/argv in...
459               //
460               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
461                      "Option can not be cl::Grouping AND cl::ValueRequired!");
462               int Dummy;
463               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
464                                             0, 0, 0, Dummy);
465
466               // Get the next grouping option...
467               PGOpt = getOptionPred(RealName, Length, isGrouping);
468             } while (PGOpt && Length != RealName.size());
469
470             Handler = PGOpt; // Ate all of the options.
471           }
472         }
473       }
474     }
475
476     if (Handler == 0) {
477       std::cerr << ProgramName << ": Unknown command line argument '"
478                   << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
479       ErrorParsing = true;
480       continue;
481     }
482
483     // Check to see if this option accepts a comma separated list of values.  If
484     // it does, we have to split up the value into multiple values...
485     if (Value && Handler->getMiscFlags() & CommaSeparated) {
486       std::string Val(Value);
487       std::string::size_type Pos = Val.find(',');
488
489       while (Pos != std::string::npos) {
490         // Process the portion before the comma...
491         ErrorParsing |= ProvideOption(Handler, ArgName,
492                                       std::string(Val.begin(),
493                                                   Val.begin()+Pos).c_str(),
494                                       argc, argv, i);
495         // Erase the portion before the comma, AND the comma...
496         Val.erase(Val.begin(), Val.begin()+Pos+1);
497         Value += Pos+1;  // Increment the original value pointer as well...
498
499         // Check for another comma...
500         Pos = Val.find(',');
501       }
502     }
503
504     // If this is a named positional argument, just remember that it is the
505     // active one...
506     if (Handler->getFormattingFlag() == cl::Positional)
507       ActivePositionalArg = Handler;
508     else
509       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
510   }
511
512   // Check and handle positional arguments now...
513   if (NumPositionalRequired > PositionalVals.size()) {
514     std::cerr << ProgramName
515               << ": Not enough positional command line arguments specified!\n"
516               << "Must specify at least " << NumPositionalRequired
517               << " positional arguments: See: " << argv[0] << " --help\n";
518     
519     ErrorParsing = true;
520   } else if (!HasUnlimitedPositionals
521              && PositionalVals.size() > PositionalOpts.size()) {
522     std::cerr << ProgramName
523               << ": Too many positional arguments specified!\n"
524               << "Can specify at most " << PositionalOpts.size()
525               << " positional arguments: See: " << argv[0] << " --help\n";
526     ErrorParsing = true;
527
528   } else if (ConsumeAfterOpt == 0) {
529     // Positional args have already been handled if ConsumeAfter is specified...
530     unsigned ValNo = 0, NumVals = PositionalVals.size();
531     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
532       if (RequiresValue(PositionalOpts[i])) {
533         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
534                                 PositionalVals[ValNo].second);
535         ValNo++;
536         --NumPositionalRequired;  // We fulfilled our duty...
537       }
538
539       // If we _can_ give this option more arguments, do so now, as long as we
540       // do not give it values that others need.  'Done' controls whether the
541       // option even _WANTS_ any more.
542       //
543       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
544       while (NumVals-ValNo > NumPositionalRequired && !Done) {
545         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
546         case cl::Optional:
547           Done = true;          // Optional arguments want _at most_ one value
548           // FALL THROUGH
549         case cl::ZeroOrMore:    // Zero or more will take all they can get...
550         case cl::OneOrMore:     // One or more will take all they can get...
551           ProvidePositionalOption(PositionalOpts[i],
552                                   PositionalVals[ValNo].first,
553                                   PositionalVals[ValNo].second);
554           ValNo++;
555           break;
556         default:
557           assert(0 && "Internal error, unexpected NumOccurrences flag in "
558                  "positional argument processing!");
559         }
560       }
561     }
562   } else {
563     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
564     unsigned ValNo = 0;
565     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
566       if (RequiresValue(PositionalOpts[j])) {
567         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
568                                                 PositionalVals[ValNo].first,
569                                                 PositionalVals[ValNo].second);
570         ValNo++;
571       }
572
573     // Handle the case where there is just one positional option, and it's
574     // optional.  In this case, we want to give JUST THE FIRST option to the
575     // positional option and keep the rest for the consume after.  The above
576     // loop would have assigned no values to positional options in this case.
577     //
578     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
579       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
580                                               PositionalVals[ValNo].first,
581                                               PositionalVals[ValNo].second);
582       ValNo++;
583     }
584
585     // Handle over all of the rest of the arguments to the
586     // cl::ConsumeAfter command line option...
587     for (; ValNo != PositionalVals.size(); ++ValNo)
588       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
589                                               PositionalVals[ValNo].first,
590                                               PositionalVals[ValNo].second);
591   }
592
593   // Loop over args and make sure all required args are specified!
594   for (std::map<std::string, Option*>::iterator I = Opts.begin(),
595          E = Opts.end(); I != E; ++I) {
596     switch (I->second->getNumOccurrencesFlag()) {
597     case Required:
598     case OneOrMore:
599       if (I->second->getNumOccurrences() == 0) {
600         I->second->error(" must be specified at least once!");
601         ErrorParsing = true;
602       }
603       // Fall through
604     default:
605       break;
606     }
607   }
608
609   // Free all of the memory allocated to the map.  Command line options may only
610   // be processed once!
611   getOpts().clear();
612   PositionalOpts.clear();
613   MoreHelp().clear();
614
615   // If we had an error processing our arguments, don't let the program execute
616   if (ErrorParsing) exit(1);
617 }
618
619 //===----------------------------------------------------------------------===//
620 // Option Base class implementation
621 //
622
623 bool Option::error(std::string Message, const char *ArgName) {
624   if (ArgName == 0) ArgName = ArgStr;
625   if (ArgName[0] == 0)
626     std::cerr << HelpStr;  // Be nice for positional arguments
627   else
628     std::cerr << ProgramName << ": for the -" << ArgName;
629   
630   std::cerr << " option: " << Message << "\n";
631   return true;
632 }
633
634 bool Option::addOccurrence(unsigned pos, const char *ArgName,
635                            const std::string &Value) {
636   NumOccurrences++;   // Increment the number of times we have been seen
637
638   switch (getNumOccurrencesFlag()) {
639   case Optional:
640     if (NumOccurrences > 1)
641       return error(": may only occur zero or one times!", ArgName);
642     break;
643   case Required:
644     if (NumOccurrences > 1)
645       return error(": must occur exactly one time!", ArgName);
646     // Fall through
647   case OneOrMore:
648   case ZeroOrMore:
649   case ConsumeAfter: break;
650   default: return error(": bad num occurrences flag value!");
651   }
652
653   return handleOccurrence(pos, ArgName, Value);
654 }
655
656 // addArgument - Tell the system that this Option subclass will handle all
657 // occurrences of -ArgStr on the command line.
658 //
659 void Option::addArgument(const char *ArgStr) {
660   if (ArgStr[0])
661     AddArgument(ArgStr, this);
662
663   if (getFormattingFlag() == Positional)
664     getPositionalOpts().push_back(this);
665   else if (getNumOccurrencesFlag() == ConsumeAfter) {
666     if (!getPositionalOpts().empty() &&
667         getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
668       error("Cannot specify more than one option with cl::ConsumeAfter!");
669     getPositionalOpts().insert(getPositionalOpts().begin(), this);
670   }
671 }
672
673 void Option::removeArgument(const char *ArgStr) {
674   if (ArgStr[0])
675     RemoveArgument(ArgStr, this);
676
677   if (getFormattingFlag() == Positional) {
678     std::vector<Option*>::iterator I =
679       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
680     assert(I != getPositionalOpts().end() && "Arg not registered!");
681     getPositionalOpts().erase(I);
682   } else if (getNumOccurrencesFlag() == ConsumeAfter) {
683     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
684            "Arg not registered correctly!");
685     getPositionalOpts().erase(getPositionalOpts().begin());
686   }
687 }
688
689
690 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
691 // has been specified yet.
692 //
693 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
694   if (O.ValueStr[0] == 0) return DefaultMsg;
695   return O.ValueStr;
696 }
697
698 //===----------------------------------------------------------------------===//
699 // cl::alias class implementation
700 //
701
702 // Return the width of the option tag for printing...
703 unsigned alias::getOptionWidth() const {
704   return std::strlen(ArgStr)+6;
705 }
706
707 // Print out the option for the alias.
708 void alias::printOptionInfo(unsigned GlobalWidth) const {
709   unsigned L = std::strlen(ArgStr);
710   std::cout << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
711             << HelpStr << "\n";
712 }
713
714
715
716 //===----------------------------------------------------------------------===//
717 // Parser Implementation code...
718 //
719
720 // basic_parser implementation
721 //
722
723 // Return the width of the option tag for printing...
724 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
725   unsigned Len = std::strlen(O.ArgStr);
726   if (const char *ValName = getValueName())
727     Len += std::strlen(getValueStr(O, ValName))+3;
728
729   return Len + 6;
730 }
731
732 // printOptionInfo - Print out information about this option.  The
733 // to-be-maintained width is specified.
734 //
735 void basic_parser_impl::printOptionInfo(const Option &O,
736                                         unsigned GlobalWidth) const {
737   std::cout << "  -" << O.ArgStr;
738
739   if (const char *ValName = getValueName())
740     std::cout << "=<" << getValueStr(O, ValName) << ">";
741
742   std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
743             << O.HelpStr << "\n";
744 }
745
746
747
748
749 // parser<bool> implementation
750 //
751 bool parser<bool>::parse(Option &O, const char *ArgName,
752                          const std::string &Arg, bool &Value) {
753   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
754       Arg == "1") {
755     Value = true;
756   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
757     Value = false;
758   } else {
759     return O.error(": '" + Arg +
760                    "' is invalid value for boolean argument! Try 0 or 1");
761   }
762   return false;
763 }
764
765 // parser<int> implementation
766 //
767 bool parser<int>::parse(Option &O, const char *ArgName,
768                         const std::string &Arg, int &Value) {
769   char *End;
770   Value = (int)strtol(Arg.c_str(), &End, 0);
771   if (*End != 0)
772     return O.error(": '" + Arg + "' value invalid for integer argument!");
773   return false;
774 }
775
776 // parser<unsigned> implementation
777 //
778 bool parser<unsigned>::parse(Option &O, const char *ArgName,
779                              const std::string &Arg, unsigned &Value) {
780   char *End;
781   errno = 0;
782   unsigned long V = strtoul(Arg.c_str(), &End, 0);
783   Value = (unsigned)V;
784   if (((V == ULONG_MAX) && (errno == ERANGE))
785       || (*End != 0)
786       || (Value != V))
787     return O.error(": '" + Arg + "' value invalid for uint argument!");
788   return false;
789 }
790
791 // parser<double>/parser<float> implementation
792 //
793 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
794   const char *ArgStart = Arg.c_str();
795   char *End;
796   Value = strtod(ArgStart, &End);
797   if (*End != 0)
798     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
799   return false;
800 }
801
802 bool parser<double>::parse(Option &O, const char *AN,
803                            const std::string &Arg, double &Val) {
804   return parseDouble(O, Arg, Val);
805 }
806
807 bool parser<float>::parse(Option &O, const char *AN,
808                           const std::string &Arg, float &Val) {
809   double dVal;
810   if (parseDouble(O, Arg, dVal))
811     return true;
812   Val = (float)dVal;
813   return false;
814 }
815
816
817
818 // generic_parser_base implementation
819 //
820
821 // findOption - Return the option number corresponding to the specified
822 // argument string.  If the option is not found, getNumOptions() is returned.
823 //
824 unsigned generic_parser_base::findOption(const char *Name) {
825   unsigned i = 0, e = getNumOptions();
826   std::string N(Name);
827
828   while (i != e)
829     if (getOption(i) == N)
830       return i;
831     else
832       ++i;
833   return e;
834 }
835
836
837 // Return the width of the option tag for printing...
838 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
839   if (O.hasArgStr()) {
840     unsigned Size = std::strlen(O.ArgStr)+6;
841     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
842       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
843     return Size;
844   } else {
845     unsigned BaseSize = 0;
846     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
847       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
848     return BaseSize;
849   }
850 }
851
852 // printOptionInfo - Print out information about this option.  The
853 // to-be-maintained width is specified.
854 //
855 void generic_parser_base::printOptionInfo(const Option &O,
856                                           unsigned GlobalWidth) const {
857   if (O.hasArgStr()) {
858     unsigned L = std::strlen(O.ArgStr);
859     std::cout << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
860               << " - " << O.HelpStr << "\n";
861
862     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
863       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
864       std::cout << "    =" << getOption(i) << std::string(NumSpaces, ' ')
865                 << " - " << getDescription(i) << "\n";
866     }
867   } else {
868     if (O.HelpStr[0])
869       std::cout << "  " << O.HelpStr << "\n";
870     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
871       unsigned L = std::strlen(getOption(i));
872       std::cout << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
873                 << " - " << getDescription(i) << "\n";
874     }
875   }
876 }
877
878
879 //===----------------------------------------------------------------------===//
880 // --help and --help-hidden option implementation
881 //
882
883 namespace {
884
885 class HelpPrinter {
886   unsigned MaxArgLen;
887   const Option *EmptyArg;
888   const bool ShowHidden;
889
890   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
891   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
892     return OptPair.second->getOptionHiddenFlag() >= Hidden;
893   }
894   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
895     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
896   }
897
898 public:
899   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
900     EmptyArg = 0;
901   }
902
903   void operator=(bool Value) {
904     if (Value == false) return;
905
906     // Copy Options into a vector so we can sort them as we like...
907     std::vector<std::pair<std::string, Option*> > Options;
908     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
909
910     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
911     Options.erase(std::remove_if(Options.begin(), Options.end(),
912                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
913                   Options.end());
914
915     // Eliminate duplicate entries in table (from enum flags options, f.e.)
916     {  // Give OptionSet a scope
917       std::set<Option*> OptionSet;
918       for (unsigned i = 0; i != Options.size(); ++i)
919         if (OptionSet.count(Options[i].second) == 0)
920           OptionSet.insert(Options[i].second);   // Add new entry to set
921         else
922           Options.erase(Options.begin()+i--);    // Erase duplicate
923     }
924
925     if (ProgramOverview)
926       std::cout << "OVERVIEW:" << ProgramOverview << "\n";
927
928     std::cout << "USAGE: " << ProgramName << " [options]";
929
930     // Print out the positional options...
931     std::vector<Option*> &PosOpts = getPositionalOpts();
932     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
933     if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
934       CAOpt = PosOpts[0];
935
936     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
937       if (PosOpts[i]->ArgStr[0])
938         std::cout << " --" << PosOpts[i]->ArgStr;
939       std::cout << " " << PosOpts[i]->HelpStr;
940     }
941
942     // Print the consume after option info if it exists...
943     if (CAOpt) std::cout << " " << CAOpt->HelpStr;
944
945     std::cout << "\n\n";
946
947     // Compute the maximum argument length...
948     MaxArgLen = 0;
949     for (unsigned i = 0, e = Options.size(); i != e; ++i)
950       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
951
952     std::cout << "OPTIONS:\n";
953     for (unsigned i = 0, e = Options.size(); i != e; ++i)
954       Options[i].second->printOptionInfo(MaxArgLen);
955
956     // Print any extra help the user has declared.
957     for (std::vector<const char *>::iterator I = MoreHelp().begin(),
958           E = MoreHelp().end(); I != E; ++I)
959       std::cout << *I;
960     MoreHelp().clear();
961
962     // Halt the program since help information was printed
963     getOpts().clear();  // Don't bother making option dtors remove from map.
964     exit(1);
965   }
966 };
967
968 // Define the two HelpPrinter instances that are used to print out help, or
969 // help-hidden...
970 //
971 HelpPrinter NormalPrinter(false);
972 HelpPrinter HiddenPrinter(true);
973
974 cl::opt<HelpPrinter, true, parser<bool> >
975 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
976     cl::location(NormalPrinter), cl::ValueDisallowed);
977
978 cl::opt<HelpPrinter, true, parser<bool> >
979 HHOp("help-hidden", cl::desc("Display all available options"),
980      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
981
982 void (*OverrideVersionPrinter)() = 0;
983
984 class VersionPrinter {
985 public:
986   void operator=(bool OptionWasSpecified) {
987     if (OptionWasSpecified) {
988       if (OverrideVersionPrinter == 0) {
989         std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
990         std::cout << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
991 #ifdef LLVM_VERSION_INFO
992         std::cout << LLVM_VERSION_INFO;
993 #endif
994         std::cout << "\n  ";
995 #ifndef __OPTIMIZE__
996         std::cout << "DEBUG build";
997 #else
998         std::cout << "Optimized build";
999 #endif
1000 #ifndef NDEBUG
1001         std::cout << " with assertions";
1002 #endif
1003         std::cout << ".\n";
1004         getOpts().clear();  // Don't bother making option dtors remove from map.
1005         exit(1);
1006       } else {
1007         (*OverrideVersionPrinter)();
1008         exit(1);
1009       }
1010     }
1011   }
1012 };
1013
1014
1015 // Define the --version option that prints out the LLVM version for the tool
1016 VersionPrinter VersionPrinterInstance;
1017 cl::opt<VersionPrinter, true, parser<bool> >
1018 VersOp("version", cl::desc("Display the version of this program"),
1019     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1020
1021
1022 } // End anonymous namespace
1023
1024 // Utility function for printing the help message.
1025 void cl::PrintHelpMessage() {
1026   // This looks weird, but it actually prints the help message. The
1027   // NormalPrinter variable is a HelpPrinter and the help gets printed when
1028   // its operator= is invoked. That's because the "normal" usages of the
1029   // help printer is to be assigned true/false depending on whether the
1030   // --help option was given or not. Since we're circumventing that we have
1031   // to make it look like --help was given, so we assign true.
1032   NormalPrinter = true;
1033 }
1034
1035 void cl::SetVersionPrinter(void (*func)()) {
1036   OverrideVersionPrinter = func;
1037 }