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