Fix PR1318 by reacting appropriately to a mutating option list.
[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/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 /// RegisteredOptionList - This is the list of the command line options that
75 /// have statically constructed themselves.
76 static Option *RegisteredOptionList = 0;
77
78 void Option::addArgument() {
79   assert(NextRegistered == 0 && "argument multiply registered!");
80   
81   NextRegistered = RegisteredOptionList;
82   RegisteredOptionList = this;
83 }
84
85 //===----------------------------------------------------------------------===//
86 // Basic, shared command line option processing machinery.
87 //
88
89 /// GetOptionInfo - Scan the list of registered options, turning them into data
90 /// structures that are easier to handle.
91 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
92                           std::map<std::string, Option*> &OptionsMap) {
93   std::vector<const char*> OptionNames;
94   Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
95   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
96     // If this option wants to handle multiple option names, get the full set.
97     // This handles enum options like "-O1 -O2" etc.
98     O->getExtraOptionNames(OptionNames);
99     if (O->ArgStr[0])
100       OptionNames.push_back(O->ArgStr);
101     
102     // Handle named options.
103     for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
104       // Add argument to the argument map!
105       if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
106                                                             O)).second) {
107         cerr << ProgramName << ": CommandLine Error: Argument '"
108              << OptionNames[0] << "' defined more than once!\n";
109       }
110     }
111     
112     OptionNames.clear();
113     
114     // Remember information about positional options.
115     if (O->getFormattingFlag() == cl::Positional)
116       PositionalOpts.push_back(O);
117     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
118       if (CAOpt)
119         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
120       CAOpt = O;
121     }
122   }
123   
124   if (CAOpt)
125     PositionalOpts.push_back(CAOpt);
126   
127   // Make sure that they are in order of registration not backwards.
128   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
129 }
130
131
132 /// LookupOption - Lookup the option specified by the specified option on the
133 /// command line.  If there is a value specified (after an equal sign) return
134 /// that as well.
135 static Option *LookupOption(const char *&Arg, const char *&Value,
136                             std::map<std::string, Option*> &OptionsMap) {
137   while (*Arg == '-') ++Arg;  // Eat leading dashes
138   
139   const char *ArgEnd = Arg;
140   while (*ArgEnd && *ArgEnd != '=')
141     ++ArgEnd; // Scan till end of argument name.
142   
143   if (*ArgEnd == '=')  // If we have an equals sign...
144     Value = ArgEnd+1;  // Get the value, not the equals
145   
146   
147   if (*Arg == 0) return 0;
148   
149   // Look up the option.
150   std::map<std::string, Option*>::iterator I =
151     OptionsMap.find(std::string(Arg, ArgEnd));
152   return I != OptionsMap.end() ? I->second : 0;
153 }
154
155 static inline bool ProvideOption(Option *Handler, const char *ArgName,
156                                  const char *Value, int argc, char **argv,
157                                  int &i) {
158   // Enforce value requirements
159   switch (Handler->getValueExpectedFlag()) {
160   case ValueRequired:
161     if (Value == 0) {       // No value specified?
162       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
163         Value = argv[++i];
164       } else {
165         return Handler->error(" requires a value!");
166       }
167     }
168     break;
169   case ValueDisallowed:
170     if (Value)
171       return Handler->error(" does not allow a value! '" +
172                             std::string(Value) + "' specified.");
173     break;
174   case ValueOptional:
175     break;
176   default:
177     cerr << ProgramName
178          << ": Bad ValueMask flag! CommandLine usage error:"
179          << Handler->getValueExpectedFlag() << "\n";
180     abort();
181     break;
182   }
183
184   // Run the handler now!
185   return Handler->addOccurrence(i, ArgName, Value ? Value : "");
186 }
187
188 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
189                                     int i) {
190   int Dummy = i;
191   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
192 }
193
194
195 // Option predicates...
196 static inline bool isGrouping(const Option *O) {
197   return O->getFormattingFlag() == cl::Grouping;
198 }
199 static inline bool isPrefixedOrGrouping(const Option *O) {
200   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
201 }
202
203 // getOptionPred - Check to see if there are any options that satisfy the
204 // specified predicate with names that are the prefixes in Name.  This is
205 // checked by progressively stripping characters off of the name, checking to
206 // see if there options that satisfy the predicate.  If we find one, return it,
207 // otherwise return null.
208 //
209 static Option *getOptionPred(std::string Name, unsigned &Length,
210                              bool (*Pred)(const Option*),
211                              std::map<std::string, Option*> &OptionsMap) {
212
213   std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
214   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
215     Length = Name.length();
216     return OMI->second;
217   }
218
219   if (Name.size() == 1) return 0;
220   do {
221     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
222     OMI = OptionsMap.find(Name);
223
224     // Loop while we haven't found an option and Name still has at least two
225     // characters in it (so that the next iteration will not be the empty
226     // string...
227   } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
228
229   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
230     Length = Name.length();
231     return OMI->second;    // Found one!
232   }
233   return 0;                // No option found!
234 }
235
236 static bool RequiresValue(const Option *O) {
237   return O->getNumOccurrencesFlag() == cl::Required ||
238          O->getNumOccurrencesFlag() == cl::OneOrMore;
239 }
240
241 static bool EatsUnboundedNumberOfValues(const Option *O) {
242   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
243          O->getNumOccurrencesFlag() == cl::OneOrMore;
244 }
245
246 /// ParseCStringVector - Break INPUT up wherever one or more
247 /// whitespace characters are found, and store the resulting tokens in
248 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
249 /// using strdup (), so it is the caller's responsibility to free ()
250 /// them later.
251 ///
252 static void ParseCStringVector(std::vector<char *> &output,
253                                const char *input) {
254   // Characters which will be treated as token separators:
255   static const char *delims = " \v\f\t\r\n";
256
257   std::string work (input);
258   // Skip past any delims at head of input string.
259   size_t pos = work.find_first_not_of (delims);
260   // If the string consists entirely of delims, then exit early.
261   if (pos == std::string::npos) return;
262   // Otherwise, jump forward to beginning of first word.
263   work = work.substr (pos);
264   // Find position of first delimiter.
265   pos = work.find_first_of (delims);
266
267   while (!work.empty() && pos != std::string::npos) {
268     // Everything from 0 to POS is the next word to copy.
269     output.push_back (strdup (work.substr (0,pos).c_str ()));
270     // Is there another word in the string?
271     size_t nextpos = work.find_first_not_of (delims, pos + 1);
272     if (nextpos != std::string::npos) {
273       // Yes? Then remove delims from beginning ...
274       work = work.substr (work.find_first_not_of (delims, pos + 1));
275       // and find the end of the word.
276       pos = work.find_first_of (delims);
277     } else {
278       // No? (Remainder of string is delims.) End the loop.
279       work = "";
280       pos = std::string::npos;
281     }
282   }
283
284   // If `input' ended with non-delim char, then we'll get here with
285   // the last word of `input' in `work'; copy it now.
286   if (!work.empty ()) {
287     output.push_back (strdup (work.c_str ()));
288   }
289 }
290
291 /// ParseEnvironmentOptions - An alternative entry point to the
292 /// CommandLine library, which allows you to read the program's name
293 /// from the caller (as PROGNAME) and its command-line arguments from
294 /// an environment variable (whose name is given in ENVVAR).
295 ///
296 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
297                                  const char *Overview) {
298   // Check args.
299   assert(progName && "Program name not specified");
300   assert(envVar && "Environment variable name missing");
301
302   // Get the environment variable they want us to parse options out of.
303   const char *envValue = getenv(envVar);
304   if (!envValue)
305     return;
306
307   // Get program's "name", which we wouldn't know without the caller
308   // telling us.
309   std::vector<char*> newArgv;
310   newArgv.push_back(strdup(progName));
311
312   // Parse the value of the environment variable into a "command line"
313   // and hand it off to ParseCommandLineOptions().
314   ParseCStringVector(newArgv, envValue);
315   int newArgc = newArgv.size();
316   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
317
318   // Free all the strdup()ed strings.
319   for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
320        i != e; ++i)
321     free (*i);
322 }
323
324 void cl::ParseCommandLineOptions(int &argc, char **argv,
325                                  const char *Overview) {
326   // Process all registered options.
327   std::vector<Option*> PositionalOpts;
328   std::map<std::string, Option*> Opts;
329   GetOptionInfo(PositionalOpts, Opts);
330   
331   assert((!Opts.empty() || !PositionalOpts.empty()) &&
332          "No options specified!");
333   sys::Path progname(argv[0]);
334
335   // Copy the program name into ProgName, making sure not to overflow it.
336   std::string ProgName = sys::Path(argv[0]).getLast();
337   if (ProgName.size() > 79) ProgName.resize(79);
338   strcpy(ProgramName, ProgName.c_str());
339   
340   ProgramOverview = Overview;
341   bool ErrorParsing = false;
342
343   // Check out the positional arguments to collect information about them.
344   unsigned NumPositionalRequired = 0;
345   
346   // Determine whether or not there are an unlimited number of positionals
347   bool HasUnlimitedPositionals = false;
348   
349   Option *ConsumeAfterOpt = 0;
350   if (!PositionalOpts.empty()) {
351     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
352       assert(PositionalOpts.size() > 1 &&
353              "Cannot specify cl::ConsumeAfter without a positional argument!");
354       ConsumeAfterOpt = PositionalOpts[0];
355     }
356
357     // Calculate how many positional values are _required_.
358     bool UnboundedFound = false;
359     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
360          i != e; ++i) {
361       Option *Opt = PositionalOpts[i];
362       if (RequiresValue(Opt))
363         ++NumPositionalRequired;
364       else if (ConsumeAfterOpt) {
365         // ConsumeAfter cannot be combined with "optional" positional options
366         // unless there is only one positional argument...
367         if (PositionalOpts.size() > 2)
368           ErrorParsing |=
369             Opt->error(" error - this positional option will never be matched, "
370                        "because it does not Require a value, and a "
371                        "cl::ConsumeAfter option is active!");
372       } else if (UnboundedFound && !Opt->ArgStr[0]) {
373         // This option does not "require" a value...  Make sure this option is
374         // not specified after an option that eats all extra arguments, or this
375         // one will never get any!
376         //
377         ErrorParsing |= Opt->error(" error - option can never match, because "
378                                    "another positional argument will match an "
379                                    "unbounded number of values, and this option"
380                                    " does not require a value!");
381       }
382       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
383     }
384     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
385   }
386
387   // PositionalVals - A vector of "positional" arguments we accumulate into
388   // the process at the end...
389   //
390   std::vector<std::pair<std::string,unsigned> > PositionalVals;
391
392   // If the program has named positional arguments, and the name has been run
393   // across, keep track of which positional argument was named.  Otherwise put
394   // the positional args into the PositionalVals list...
395   Option *ActivePositionalArg = 0;
396
397   // Keep track of the option list so far so that we can tell if it is ever
398   // extended.
399   Option *CurOptionList = RegisteredOptionList;
400   
401   // Loop over all of the arguments... processing them.
402   bool DashDashFound = false;  // Have we read '--'?
403   for (int i = 1; i < argc; ++i) {
404     Option *Handler = 0;
405     const char *Value = 0;
406     const char *ArgName = "";
407
408     // If the head of the option list changed, this means that some command line
409     // option has just been registered or deregistered.  This can occur in
410     // response to things like -load, etc.  If this happens, rescan the options.
411     if (CurOptionList != RegisteredOptionList) {
412       PositionalOpts.clear();
413       Opts.clear();
414       GetOptionInfo(PositionalOpts, Opts);
415       CurOptionList = RegisteredOptionList;
416     }
417     
418     // Check to see if this is a positional argument.  This argument is
419     // considered to be positional if it doesn't start with '-', if it is "-"
420     // itself, or if we have seen "--" already.
421     //
422     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
423       // Positional argument!
424       if (ActivePositionalArg) {
425         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
426         continue;  // We are done!
427       } else if (!PositionalOpts.empty()) {
428         PositionalVals.push_back(std::make_pair(argv[i],i));
429
430         // All of the positional arguments have been fulfulled, give the rest to
431         // the consume after option... if it's specified...
432         //
433         if (PositionalVals.size() >= NumPositionalRequired &&
434             ConsumeAfterOpt != 0) {
435           for (++i; i < argc; ++i)
436             PositionalVals.push_back(std::make_pair(argv[i],i));
437           break;   // Handle outside of the argument processing loop...
438         }
439
440         // Delay processing positional arguments until the end...
441         continue;
442       }
443     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
444                !DashDashFound) {
445       DashDashFound = true;  // This is the mythical "--"?
446       continue;              // Don't try to process it as an argument itself.
447     } else if (ActivePositionalArg &&
448                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
449       // If there is a positional argument eating options, check to see if this
450       // option is another positional argument.  If so, treat it as an argument,
451       // otherwise feed it to the eating positional.
452       ArgName = argv[i]+1;
453       Handler = LookupOption(ArgName, Value, Opts);
454       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
455         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
456         continue;  // We are done!
457       }
458
459     } else {     // We start with a '-', must be an argument...
460       ArgName = argv[i]+1;
461       Handler = LookupOption(ArgName, Value, Opts);
462
463       // Check to see if this "option" is really a prefixed or grouped argument.
464       if (Handler == 0) {
465         std::string RealName(ArgName);
466         if (RealName.size() > 1) {
467           unsigned Length = 0;
468           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
469                                         Opts);
470
471           // If the option is a prefixed option, then the value is simply the
472           // rest of the name...  so fall through to later processing, by
473           // setting up the argument name flags and value fields.
474           //
475           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
476             Value = ArgName+Length;
477             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
478                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
479             Handler = PGOpt;
480           } else if (PGOpt) {
481             // This must be a grouped option... handle them now.
482             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
483
484             do {
485               // Move current arg name out of RealName into RealArgName...
486               std::string RealArgName(RealName.begin(),
487                                       RealName.begin() + Length);
488               RealName.erase(RealName.begin(), RealName.begin() + Length);
489
490               // Because ValueRequired is an invalid flag for grouped arguments,
491               // we don't need to pass argc/argv in...
492               //
493               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
494                      "Option can not be cl::Grouping AND cl::ValueRequired!");
495               int Dummy;
496               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
497                                             0, 0, 0, Dummy);
498
499               // Get the next grouping option...
500               PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
501             } while (PGOpt && Length != RealName.size());
502
503             Handler = PGOpt; // Ate all of the options.
504           }
505         }
506       }
507     }
508
509     if (Handler == 0) {
510       cerr << ProgramName << ": Unknown command line argument '"
511            << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
512       ErrorParsing = true;
513       continue;
514     }
515
516     // Check to see if this option accepts a comma separated list of values.  If
517     // it does, we have to split up the value into multiple values...
518     if (Value && Handler->getMiscFlags() & CommaSeparated) {
519       std::string Val(Value);
520       std::string::size_type Pos = Val.find(',');
521
522       while (Pos != std::string::npos) {
523         // Process the portion before the comma...
524         ErrorParsing |= ProvideOption(Handler, ArgName,
525                                       std::string(Val.begin(),
526                                                   Val.begin()+Pos).c_str(),
527                                       argc, argv, i);
528         // Erase the portion before the comma, AND the comma...
529         Val.erase(Val.begin(), Val.begin()+Pos+1);
530         Value += Pos+1;  // Increment the original value pointer as well...
531
532         // Check for another comma...
533         Pos = Val.find(',');
534       }
535     }
536
537     // If this is a named positional argument, just remember that it is the
538     // active one...
539     if (Handler->getFormattingFlag() == cl::Positional)
540       ActivePositionalArg = Handler;
541     else
542       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
543   }
544
545   // Check and handle positional arguments now...
546   if (NumPositionalRequired > PositionalVals.size()) {
547     cerr << ProgramName
548          << ": Not enough positional command line arguments specified!\n"
549          << "Must specify at least " << NumPositionalRequired
550          << " positional arguments: See: " << argv[0] << " --help\n";
551     
552     ErrorParsing = true;
553   } else if (!HasUnlimitedPositionals
554              && PositionalVals.size() > PositionalOpts.size()) {
555     cerr << ProgramName
556          << ": Too many positional arguments specified!\n"
557          << "Can specify at most " << PositionalOpts.size()
558          << " positional arguments: See: " << argv[0] << " --help\n";
559     ErrorParsing = true;
560
561   } else if (ConsumeAfterOpt == 0) {
562     // Positional args have already been handled if ConsumeAfter is specified...
563     unsigned ValNo = 0, NumVals = PositionalVals.size();
564     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
565       if (RequiresValue(PositionalOpts[i])) {
566         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
567                                 PositionalVals[ValNo].second);
568         ValNo++;
569         --NumPositionalRequired;  // We fulfilled our duty...
570       }
571
572       // If we _can_ give this option more arguments, do so now, as long as we
573       // do not give it values that others need.  'Done' controls whether the
574       // option even _WANTS_ any more.
575       //
576       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
577       while (NumVals-ValNo > NumPositionalRequired && !Done) {
578         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
579         case cl::Optional:
580           Done = true;          // Optional arguments want _at most_ one value
581           // FALL THROUGH
582         case cl::ZeroOrMore:    // Zero or more will take all they can get...
583         case cl::OneOrMore:     // One or more will take all they can get...
584           ProvidePositionalOption(PositionalOpts[i],
585                                   PositionalVals[ValNo].first,
586                                   PositionalVals[ValNo].second);
587           ValNo++;
588           break;
589         default:
590           assert(0 && "Internal error, unexpected NumOccurrences flag in "
591                  "positional argument processing!");
592         }
593       }
594     }
595   } else {
596     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
597     unsigned ValNo = 0;
598     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
599       if (RequiresValue(PositionalOpts[j])) {
600         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
601                                                 PositionalVals[ValNo].first,
602                                                 PositionalVals[ValNo].second);
603         ValNo++;
604       }
605
606     // Handle the case where there is just one positional option, and it's
607     // optional.  In this case, we want to give JUST THE FIRST option to the
608     // positional option and keep the rest for the consume after.  The above
609     // loop would have assigned no values to positional options in this case.
610     //
611     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
612       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
613                                               PositionalVals[ValNo].first,
614                                               PositionalVals[ValNo].second);
615       ValNo++;
616     }
617
618     // Handle over all of the rest of the arguments to the
619     // cl::ConsumeAfter command line option...
620     for (; ValNo != PositionalVals.size(); ++ValNo)
621       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
622                                               PositionalVals[ValNo].first,
623                                               PositionalVals[ValNo].second);
624   }
625
626   // Loop over args and make sure all required args are specified!
627   for (std::map<std::string, Option*>::iterator I = Opts.begin(),
628          E = Opts.end(); I != E; ++I) {
629     switch (I->second->getNumOccurrencesFlag()) {
630     case Required:
631     case OneOrMore:
632       if (I->second->getNumOccurrences() == 0) {
633         I->second->error(" must be specified at least once!");
634         ErrorParsing = true;
635       }
636       // Fall through
637     default:
638       break;
639     }
640   }
641
642   // Free all of the memory allocated to the map.  Command line options may only
643   // be processed once!
644   Opts.clear();
645   PositionalOpts.clear();
646   MoreHelp->clear();
647
648   // If we had an error processing our arguments, don't let the program execute
649   if (ErrorParsing) exit(1);
650 }
651
652 //===----------------------------------------------------------------------===//
653 // Option Base class implementation
654 //
655
656 bool Option::error(std::string Message, const char *ArgName) {
657   if (ArgName == 0) ArgName = ArgStr;
658   if (ArgName[0] == 0)
659     cerr << HelpStr;  // Be nice for positional arguments
660   else
661     cerr << ProgramName << ": for the -" << ArgName;
662   
663   cerr << " option: " << Message << "\n";
664   return true;
665 }
666
667 bool Option::addOccurrence(unsigned pos, const char *ArgName,
668                            const std::string &Value) {
669   NumOccurrences++;   // Increment the number of times we have been seen
670
671   switch (getNumOccurrencesFlag()) {
672   case Optional:
673     if (NumOccurrences > 1)
674       return error(": may only occur zero or one times!", ArgName);
675     break;
676   case Required:
677     if (NumOccurrences > 1)
678       return error(": must occur exactly one time!", ArgName);
679     // Fall through
680   case OneOrMore:
681   case ZeroOrMore:
682   case ConsumeAfter: break;
683   default: return error(": bad num occurrences flag value!");
684   }
685
686   return handleOccurrence(pos, ArgName, Value);
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   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   cout << "  -" << O.ArgStr;
738
739   if (const char *ValName = getValueName())
740     cout << "=<" << getValueStr(O, ValName) << ">";
741
742   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     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       cout << "    =" << getOption(i) << std::string(NumSpaces, ' ')
865            << " - " << getDescription(i) << "\n";
866     }
867   } else {
868     if (O.HelpStr[0])
869       cout << "  " << O.HelpStr << "\n";
870     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
871       unsigned L = std::strlen(getOption(i));
872       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     // Get all the options.
907     std::vector<Option*> PositionalOpts;
908     std::map<std::string, Option*> OptMap;
909     GetOptionInfo(PositionalOpts, OptMap);
910     
911     // Copy Options into a vector so we can sort them as we like...
912     std::vector<std::pair<std::string, Option*> > Opts;
913     copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
914
915     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
916     Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
917                           std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
918                Opts.end());
919
920     // Eliminate duplicate entries in table (from enum flags options, f.e.)
921     {  // Give OptionSet a scope
922       std::set<Option*> OptionSet;
923       for (unsigned i = 0; i != Opts.size(); ++i)
924         if (OptionSet.count(Opts[i].second) == 0)
925           OptionSet.insert(Opts[i].second);   // Add new entry to set
926         else
927           Opts.erase(Opts.begin()+i--);    // Erase duplicate
928     }
929
930     if (ProgramOverview)
931       cout << "OVERVIEW:" << ProgramOverview << "\n";
932
933     cout << "USAGE: " << ProgramName << " [options]";
934
935     // Print out the positional options.
936     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
937     if (!PositionalOpts.empty() && 
938         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
939       CAOpt = PositionalOpts[0];
940
941     for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
942       if (PositionalOpts[i]->ArgStr[0])
943         cout << " --" << PositionalOpts[i]->ArgStr;
944       cout << " " << PositionalOpts[i]->HelpStr;
945     }
946
947     // Print the consume after option info if it exists...
948     if (CAOpt) cout << " " << CAOpt->HelpStr;
949
950     cout << "\n\n";
951
952     // Compute the maximum argument length...
953     MaxArgLen = 0;
954     for (unsigned i = 0, e = Opts.size(); i != e; ++i)
955       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
956
957     cout << "OPTIONS:\n";
958     for (unsigned i = 0, e = Opts.size(); i != e; ++i)
959       Opts[i].second->printOptionInfo(MaxArgLen);
960
961     // Print any extra help the user has declared.
962     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
963           E = MoreHelp->end(); I != E; ++I)
964       cout << *I;
965     MoreHelp->clear();
966
967     // Halt the program since help information was printed
968     exit(1);
969   }
970 };
971 } // End anonymous namespace
972
973 // Define the two HelpPrinter instances that are used to print out help, or
974 // help-hidden...
975 //
976 static HelpPrinter NormalPrinter(false);
977 static HelpPrinter HiddenPrinter(true);
978
979 static cl::opt<HelpPrinter, true, parser<bool> >
980 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
981     cl::location(NormalPrinter), cl::ValueDisallowed);
982
983 static cl::opt<HelpPrinter, true, parser<bool> >
984 HHOp("help-hidden", cl::desc("Display all available options"),
985      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
986
987 static void (*OverrideVersionPrinter)() = 0;
988
989 namespace {
990 class VersionPrinter {
991 public:
992   void print() {
993         cout << "Low Level Virtual Machine (http://llvm.org/):\n";
994         cout << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
995 #ifdef LLVM_VERSION_INFO
996         cout << LLVM_VERSION_INFO;
997 #endif
998         cout << "\n  ";
999 #ifndef __OPTIMIZE__
1000         cout << "DEBUG build";
1001 #else
1002         cout << "Optimized build";
1003 #endif
1004 #ifndef NDEBUG
1005         cout << " with assertions";
1006 #endif
1007         cout << ".\n";
1008   }
1009   void operator=(bool OptionWasSpecified) {
1010     if (OptionWasSpecified) {
1011       if (OverrideVersionPrinter == 0) {
1012         print();
1013         exit(1);
1014       } else {
1015         (*OverrideVersionPrinter)();
1016         exit(1);
1017       }
1018     }
1019   }
1020 };
1021 } // End anonymous namespace
1022
1023
1024 // Define the --version option that prints out the LLVM version for the tool
1025 static VersionPrinter VersionPrinterInstance;
1026
1027 static cl::opt<VersionPrinter, true, parser<bool> >
1028 VersOp("version", cl::desc("Display the version of this program"),
1029     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1030
1031 // Utility function for printing the help message.
1032 void cl::PrintHelpMessage() {
1033   // This looks weird, but it actually prints the help message. The
1034   // NormalPrinter variable is a HelpPrinter and the help gets printed when
1035   // its operator= is invoked. That's because the "normal" usages of the
1036   // help printer is to be assigned true/false depending on whether the
1037   // --help option was given or not. Since we're circumventing that we have
1038   // to make it look like --help was given, so we assign true.
1039   NormalPrinter = true;
1040 }
1041
1042 /// Utility function for printing version number.
1043 void cl::PrintVersionMessage() {
1044   VersionPrinterInstance.print();
1045 }
1046
1047 void cl::SetVersionPrinter(void (*func)()) {
1048   OverrideVersionPrinter = func;
1049 }