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