LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

CommandLine.cpp

Go to the documentation of this file.
00001 //===-- CommandLine.cpp - Command line parser implementation --------------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This class implements a command line argument processor that is useful when
00011 // creating a tool.  It provides a simple, minimalistic interface that is easily
00012 // extensible and supports nonlocal (library) command line options.
00013 //
00014 // Note that rather than trying to figure out what this code does, you could try
00015 // reading the library documentation located in docs/CommandLine.html
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Config/config.h"
00020 #include "llvm/Support/CommandLine.h"
00021 #include <algorithm>
00022 #include <map>
00023 #include <set>
00024 #include <iostream>
00025 #include <cstdlib>
00026 #include <cerrno>
00027 #include <cstring>
00028 using namespace llvm;
00029 
00030 using namespace cl;
00031 
00032 // Globals for name and overview of program
00033 static const char *ProgramName = "<unknown>";
00034 static const char *ProgramOverview = 0;
00035 
00036 // This collects additional help to be printed.
00037 static std::vector<const char*> &MoreHelp() {
00038   static std::vector<const char*> moreHelp;
00039   return moreHelp;
00040 }
00041 
00042 extrahelp::extrahelp(const char* Help)
00043   : morehelp(Help) {
00044   MoreHelp().push_back(Help);
00045 }
00046 
00047 //===----------------------------------------------------------------------===//
00048 // Basic, shared command line option processing machinery...
00049 //
00050 
00051 // Return the global command line option vector.  Making it a function scoped
00052 // static ensures that it will be initialized correctly before its first use.
00053 //
00054 static std::map<std::string, Option*> &getOpts() {
00055   static std::map<std::string, Option*> CommandLineOptions;
00056   return CommandLineOptions;
00057 }
00058 
00059 static Option *getOption(const std::string &Str) {
00060   std::map<std::string,Option*>::iterator I = getOpts().find(Str);
00061   return I != getOpts().end() ? I->second : 0;
00062 }
00063 
00064 static std::vector<Option*> &getPositionalOpts() {
00065   static std::vector<Option*> Positional;
00066   return Positional;
00067 }
00068 
00069 static void AddArgument(const char *ArgName, Option *Opt) {
00070   if (getOption(ArgName)) {
00071     std::cerr << ProgramName << ": CommandLine Error: Argument '" 
00072               << ArgName << "' defined more than once!\n";
00073   } else {
00074     // Add argument to the argument map!
00075     getOpts()[ArgName] = Opt;
00076   }
00077 }
00078 
00079 // RemoveArgument - It's possible that the argument is no longer in the map if
00080 // options have already been processed and the map has been deleted!
00081 // 
00082 static void RemoveArgument(const char *ArgName, Option *Opt) {
00083   if(getOpts().empty()) return;
00084 
00085 #ifndef NDEBUG
00086   // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
00087   // If we pass ArgName directly into getOption here.
00088   std::string Tmp = ArgName;
00089   assert(getOption(Tmp) == Opt && "Arg not in map!");
00090 #endif
00091   getOpts().erase(ArgName);
00092 }
00093 
00094 static inline bool ProvideOption(Option *Handler, const char *ArgName,
00095                                  const char *Value, int argc, char **argv,
00096                                  int &i) {
00097   // Enforce value requirements
00098   switch (Handler->getValueExpectedFlag()) {
00099   case ValueRequired:
00100     if (Value == 0 || *Value == 0) {  // No value specified?
00101       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
00102         Value = argv[++i];
00103       } else {
00104         return Handler->error(" requires a value!");
00105       }
00106     }
00107     break;
00108   case ValueDisallowed:
00109     if (*Value != 0)
00110       return Handler->error(" does not allow a value! '" + 
00111                             std::string(Value) + "' specified.");
00112     break;
00113   case ValueOptional: 
00114     break;
00115   default: 
00116     std::cerr << ProgramName 
00117               << ": Bad ValueMask flag! CommandLine usage error:" 
00118               << Handler->getValueExpectedFlag() << "\n"; 
00119     abort();
00120     break;
00121   }
00122 
00123   // Run the handler now!
00124   return Handler->addOccurrence(i, ArgName, Value);
00125 }
00126 
00127 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg, 
00128                                     int i) {
00129   int Dummy = i;
00130   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
00131 }
00132 
00133 
00134 // Option predicates...
00135 static inline bool isGrouping(const Option *O) {
00136   return O->getFormattingFlag() == cl::Grouping;
00137 }
00138 static inline bool isPrefixedOrGrouping(const Option *O) {
00139   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
00140 }
00141 
00142 // getOptionPred - Check to see if there are any options that satisfy the
00143 // specified predicate with names that are the prefixes in Name.  This is
00144 // checked by progressively stripping characters off of the name, checking to
00145 // see if there options that satisfy the predicate.  If we find one, return it,
00146 // otherwise return null.
00147 //
00148 static Option *getOptionPred(std::string Name, unsigned &Length,
00149                              bool (*Pred)(const Option*)) {
00150   
00151   Option *Op = getOption(Name);
00152   if (Op && Pred(Op)) {
00153     Length = Name.length();
00154     return Op;
00155   }
00156 
00157   if (Name.size() == 1) return 0;
00158   do {
00159     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
00160     Op = getOption(Name);
00161 
00162     // Loop while we haven't found an option and Name still has at least two
00163     // characters in it (so that the next iteration will not be the empty
00164     // string...
00165   } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
00166 
00167   if (Op && Pred(Op)) {
00168     Length = Name.length();
00169     return Op;             // Found one!
00170   }
00171   return 0;                // No option found!
00172 }
00173 
00174 static bool RequiresValue(const Option *O) {
00175   return O->getNumOccurrencesFlag() == cl::Required ||
00176          O->getNumOccurrencesFlag() == cl::OneOrMore;
00177 }
00178 
00179 static bool EatsUnboundedNumberOfValues(const Option *O) {
00180   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
00181          O->getNumOccurrencesFlag() == cl::OneOrMore;
00182 }
00183 
00184 /// ParseCStringVector - Break INPUT up wherever one or more
00185 /// whitespace characters are found, and store the resulting tokens in
00186 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
00187 /// using strdup (), so it is the caller's responsibility to free ()
00188 /// them later.
00189 ///
00190 static void ParseCStringVector (std::vector<char *> &output,
00191                                 const char *input) {
00192   // Characters which will be treated as token separators:
00193   static const char *delims = " \v\f\t\r\n";
00194 
00195   std::string work (input);
00196   // Skip past any delims at head of input string.
00197   size_t pos = work.find_first_not_of (delims);
00198   // If the string consists entirely of delims, then exit early.
00199   if (pos == std::string::npos) return;
00200   // Otherwise, jump forward to beginning of first word.
00201   work = work.substr (pos);
00202   // Find position of first delimiter.
00203   pos = work.find_first_of (delims);
00204 
00205   while (!work.empty() && pos != std::string::npos) {
00206     // Everything from 0 to POS is the next word to copy.
00207     output.push_back (strdup (work.substr (0,pos).c_str ()));
00208     // Is there another word in the string?
00209     size_t nextpos = work.find_first_not_of (delims, pos + 1);
00210     if (nextpos != std::string::npos) {
00211       // Yes? Then remove delims from beginning ...
00212       work = work.substr (work.find_first_not_of (delims, pos + 1));
00213       // and find the end of the word.
00214       pos = work.find_first_of (delims);
00215     } else {
00216       // No? (Remainder of string is delims.) End the loop.
00217       work = "";
00218       pos = std::string::npos;
00219     }
00220   }
00221 
00222   // If `input' ended with non-delim char, then we'll get here with
00223   // the last word of `input' in `work'; copy it now.
00224   if (!work.empty ()) {
00225     output.push_back (strdup (work.c_str ()));
00226   }
00227 }
00228 
00229 /// ParseEnvironmentOptions - An alternative entry point to the
00230 /// CommandLine library, which allows you to read the program's name
00231 /// from the caller (as PROGNAME) and its command-line arguments from
00232 /// an environment variable (whose name is given in ENVVAR).
00233 ///
00234 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
00235                                  const char *Overview) {
00236   // Check args.
00237   assert(progName && "Program name not specified");
00238   assert(envVar && "Environment variable name missing");
00239   
00240   // Get the environment variable they want us to parse options out of.
00241   const char *envValue = getenv (envVar);
00242   if (!envValue)
00243     return;
00244 
00245   // Get program's "name", which we wouldn't know without the caller
00246   // telling us.
00247   std::vector<char *> newArgv;
00248   newArgv.push_back (strdup (progName));
00249 
00250   // Parse the value of the environment variable into a "command line"
00251   // and hand it off to ParseCommandLineOptions().
00252   ParseCStringVector (newArgv, envValue);
00253   int newArgc = newArgv.size ();
00254   ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
00255 
00256   // Free all the strdup()ed strings.
00257   for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
00258        i != e; ++i) {
00259     free (*i);
00260   }
00261 }
00262 
00263 /// LookupOption - Lookup the option specified by the specified option on the
00264 /// command line.  If there is a value specified (after an equal sign) return
00265 /// that as well.
00266 static Option *LookupOption(const char *&Arg, const char *&Value) {
00267   while (*Arg == '-') ++Arg;  // Eat leading dashes
00268   
00269   const char *ArgEnd = Arg;
00270   while (*ArgEnd && *ArgEnd != '=')
00271     ++ArgEnd; // Scan till end of argument name...
00272 
00273   Value = ArgEnd;
00274   if (*Value)           // If we have an equals sign...
00275     ++Value;            // Advance to value...
00276   
00277   if (*Arg == 0) return 0;
00278 
00279   // Look up the option.
00280   std::map<std::string, Option*> &Opts = getOpts();
00281   std::map<std::string, Option*>::iterator I =
00282     Opts.find(std::string(Arg, ArgEnd));
00283   return (I != Opts.end()) ? I->second : 0;
00284 }
00285 
00286 void cl::ParseCommandLineOptions(int &argc, char **argv,
00287                                  const char *Overview) {
00288   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
00289          "No options specified, or ParseCommandLineOptions called more"
00290          " than once!");
00291   ProgramName = argv[0];  // Save this away safe and snug
00292   ProgramOverview = Overview;
00293   bool ErrorParsing = false;
00294 
00295   std::map<std::string, Option*> &Opts = getOpts();
00296   std::vector<Option*> &PositionalOpts = getPositionalOpts();
00297 
00298   // Check out the positional arguments to collect information about them.
00299   unsigned NumPositionalRequired = 0;
00300   Option *ConsumeAfterOpt = 0;
00301   if (!PositionalOpts.empty()) {
00302     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00303       assert(PositionalOpts.size() > 1 &&
00304              "Cannot specify cl::ConsumeAfter without a positional argument!");
00305       ConsumeAfterOpt = PositionalOpts[0];
00306     }
00307 
00308     // Calculate how many positional values are _required_.
00309     bool UnboundedFound = false;
00310     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
00311          i != e; ++i) {
00312       Option *Opt = PositionalOpts[i];
00313       if (RequiresValue(Opt))
00314         ++NumPositionalRequired;
00315       else if (ConsumeAfterOpt) {
00316         // ConsumeAfter cannot be combined with "optional" positional options
00317         // unless there is only one positional argument...
00318         if (PositionalOpts.size() > 2)
00319           ErrorParsing |=
00320             Opt->error(" error - this positional option will never be matched, "
00321                        "because it does not Require a value, and a "
00322                        "cl::ConsumeAfter option is active!");
00323       } else if (UnboundedFound && !Opt->ArgStr[0]) {
00324         // This option does not "require" a value...  Make sure this option is
00325         // not specified after an option that eats all extra arguments, or this
00326         // one will never get any!
00327         //
00328         ErrorParsing |= Opt->error(" error - option can never match, because "
00329                                    "another positional argument will match an "
00330                                    "unbounded number of values, and this option"
00331                                    " does not require a value!");
00332       }
00333       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
00334     }
00335   }
00336 
00337   // PositionalVals - A vector of "positional" arguments we accumulate into
00338   // the process at the end...
00339   //
00340   std::vector<std::pair<std::string,unsigned> > PositionalVals;
00341 
00342   // If the program has named positional arguments, and the name has been run
00343   // across, keep track of which positional argument was named.  Otherwise put
00344   // the positional args into the PositionalVals list...
00345   Option *ActivePositionalArg = 0;
00346 
00347   // Loop over all of the arguments... processing them.
00348   bool DashDashFound = false;  // Have we read '--'?
00349   for (int i = 1; i < argc; ++i) {
00350     Option *Handler = 0;
00351     const char *Value = "";
00352     const char *ArgName = "";
00353 
00354     // Check to see if this is a positional argument.  This argument is
00355     // considered to be positional if it doesn't start with '-', if it is "-"
00356     // itself, or if we have seen "--" already.
00357     //
00358     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
00359       // Positional argument!
00360       if (ActivePositionalArg) {
00361         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00362         continue;  // We are done!
00363       } else if (!PositionalOpts.empty()) {
00364         PositionalVals.push_back(std::make_pair(argv[i],i));
00365 
00366         // All of the positional arguments have been fulfulled, give the rest to
00367         // the consume after option... if it's specified...
00368         //
00369         if (PositionalVals.size() >= NumPositionalRequired && 
00370             ConsumeAfterOpt != 0) {
00371           for (++i; i < argc; ++i)
00372             PositionalVals.push_back(std::make_pair(argv[i],i));
00373           break;   // Handle outside of the argument processing loop...
00374         }
00375 
00376         // Delay processing positional arguments until the end...
00377         continue;
00378       }
00379     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
00380                !DashDashFound) {
00381       DashDashFound = true;  // This is the mythical "--"?
00382       continue;              // Don't try to process it as an argument itself.
00383     } else if (ActivePositionalArg &&
00384                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
00385       // If there is a positional argument eating options, check to see if this
00386       // option is another positional argument.  If so, treat it as an argument,
00387       // otherwise feed it to the eating positional.
00388       ArgName = argv[i]+1;
00389       Handler = LookupOption(ArgName, Value);
00390       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
00391         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00392         continue;  // We are done!
00393       }
00394 
00395     } else {     // We start with a '-', must be an argument...
00396       ArgName = argv[i]+1;
00397       Handler = LookupOption(ArgName, Value);
00398 
00399       // Check to see if this "option" is really a prefixed or grouped argument.
00400       if (Handler == 0) {
00401         std::string RealName(ArgName);
00402         if (RealName.size() > 1) {
00403           unsigned Length = 0;
00404           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
00405   
00406           // If the option is a prefixed option, then the value is simply the
00407           // rest of the name...  so fall through to later processing, by
00408           // setting up the argument name flags and value fields.
00409           //
00410           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
00411             Value = ArgName+Length;
00412             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
00413                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
00414             Handler = PGOpt;
00415           } else if (PGOpt) {
00416             // This must be a grouped option... handle them now.
00417             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
00418             
00419             do {
00420               // Move current arg name out of RealName into RealArgName...
00421               std::string RealArgName(RealName.begin(),
00422                                       RealName.begin() + Length);
00423               RealName.erase(RealName.begin(), RealName.begin() + Length);
00424               
00425               // Because ValueRequired is an invalid flag for grouped arguments,
00426               // we don't need to pass argc/argv in...
00427               //
00428               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
00429                      "Option can not be cl::Grouping AND cl::ValueRequired!");
00430               int Dummy;
00431               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
00432                                             "", 0, 0, Dummy);
00433               
00434               // Get the next grouping option...
00435               PGOpt = getOptionPred(RealName, Length, isGrouping);
00436             } while (PGOpt && Length != RealName.size());
00437             
00438             Handler = PGOpt; // Ate all of the options.
00439           }
00440         }
00441       }
00442     }
00443 
00444     if (Handler == 0) {
00445       std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
00446                 << "'.  Try: '" << argv[0] << " --help'\n";
00447       ErrorParsing = true;
00448       continue;
00449     }
00450 
00451     // Check to see if this option accepts a comma separated list of values.  If
00452     // it does, we have to split up the value into multiple values...
00453     if (Handler->getMiscFlags() & CommaSeparated) {
00454       std::string Val(Value);
00455       std::string::size_type Pos = Val.find(',');
00456 
00457       while (Pos != std::string::npos) {
00458         // Process the portion before the comma...
00459         ErrorParsing |= ProvideOption(Handler, ArgName,
00460                                       std::string(Val.begin(),
00461                                                   Val.begin()+Pos).c_str(),
00462                                       argc, argv, i);
00463         // Erase the portion before the comma, AND the comma...
00464         Val.erase(Val.begin(), Val.begin()+Pos+1);
00465         Value += Pos+1;  // Increment the original value pointer as well...
00466 
00467         // Check for another comma...
00468         Pos = Val.find(',');
00469       }
00470     }
00471 
00472     // If this is a named positional argument, just remember that it is the
00473     // active one...
00474     if (Handler->getFormattingFlag() == cl::Positional)
00475       ActivePositionalArg = Handler;
00476     else 
00477       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
00478   }
00479 
00480   // Check and handle positional arguments now...
00481   if (NumPositionalRequired > PositionalVals.size()) {
00482     std::cerr << ProgramName 
00483               << ": Not enough positional command line arguments specified!\n"
00484               << "Must specify at least " << NumPositionalRequired
00485               << " positional arguments: See: " << argv[0] << " --help\n";
00486     ErrorParsing = true;
00487 
00488 
00489   } else if (ConsumeAfterOpt == 0) {
00490     // Positional args have already been handled if ConsumeAfter is specified...
00491     unsigned ValNo = 0, NumVals = PositionalVals.size();
00492     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
00493       if (RequiresValue(PositionalOpts[i])) {
00494         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 
00495                                 PositionalVals[ValNo].second);
00496         ValNo++;
00497         --NumPositionalRequired;  // We fulfilled our duty...
00498       }
00499 
00500       // If we _can_ give this option more arguments, do so now, as long as we
00501       // do not give it values that others need.  'Done' controls whether the
00502       // option even _WANTS_ any more.
00503       //
00504       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
00505       while (NumVals-ValNo > NumPositionalRequired && !Done) {
00506         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
00507         case cl::Optional:
00508           Done = true;          // Optional arguments want _at most_ one value
00509           // FALL THROUGH
00510         case cl::ZeroOrMore:    // Zero or more will take all they can get...
00511         case cl::OneOrMore:     // One or more will take all they can get...
00512           ProvidePositionalOption(PositionalOpts[i],
00513                                   PositionalVals[ValNo].first,
00514                                   PositionalVals[ValNo].second);
00515           ValNo++;
00516           break;
00517         default:
00518           assert(0 && "Internal error, unexpected NumOccurrences flag in "
00519                  "positional argument processing!");
00520         }
00521       }
00522     }
00523   } else {
00524     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
00525     unsigned ValNo = 0;
00526     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
00527       if (RequiresValue(PositionalOpts[j])) {
00528         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
00529                                                 PositionalVals[ValNo].first,
00530                                                 PositionalVals[ValNo].second);
00531         ValNo++;
00532       }
00533 
00534     // Handle the case where there is just one positional option, and it's
00535     // optional.  In this case, we want to give JUST THE FIRST option to the
00536     // positional option and keep the rest for the consume after.  The above
00537     // loop would have assigned no values to positional options in this case.
00538     //
00539     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
00540       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
00541                                               PositionalVals[ValNo].first,
00542                                               PositionalVals[ValNo].second);
00543       ValNo++;
00544     }
00545     
00546     // Handle over all of the rest of the arguments to the
00547     // cl::ConsumeAfter command line option...
00548     for (; ValNo != PositionalVals.size(); ++ValNo)
00549       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
00550                                               PositionalVals[ValNo].first,
00551                                               PositionalVals[ValNo].second);
00552   }
00553 
00554   // Loop over args and make sure all required args are specified!
00555   for (std::map<std::string, Option*>::iterator I = Opts.begin(), 
00556          E = Opts.end(); I != E; ++I) {
00557     switch (I->second->getNumOccurrencesFlag()) {
00558     case Required:
00559     case OneOrMore:
00560       if (I->second->getNumOccurrences() == 0) {
00561         I->second->error(" must be specified at least once!");
00562         ErrorParsing = true;
00563       }
00564       // Fall through
00565     default:
00566       break;
00567     }
00568   }
00569 
00570   // Free all of the memory allocated to the map.  Command line options may only
00571   // be processed once!
00572   getOpts().clear();
00573   PositionalOpts.clear();
00574   MoreHelp().clear();
00575 
00576   // If we had an error processing our arguments, don't let the program execute
00577   if (ErrorParsing) exit(1);
00578 }
00579 
00580 //===----------------------------------------------------------------------===//
00581 // Option Base class implementation
00582 //
00583 
00584 bool Option::error(std::string Message, const char *ArgName) {
00585   if (ArgName == 0) ArgName = ArgStr;
00586   if (ArgName[0] == 0)
00587     std::cerr << HelpStr;  // Be nice for positional arguments
00588   else
00589     std::cerr << ProgramName << ": for the -" << ArgName;
00590   std::cerr << " option: " << Message << "\n";
00591   return true;
00592 }
00593 
00594 bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
00595   NumOccurrences++;   // Increment the number of times we have been seen
00596 
00597   switch (getNumOccurrencesFlag()) {
00598   case Optional:
00599     if (NumOccurrences > 1)
00600       return error(": may only occur zero or one times!", ArgName);
00601     break;
00602   case Required:
00603     if (NumOccurrences > 1)
00604       return error(": must occur exactly one time!", ArgName);
00605     // Fall through
00606   case OneOrMore:
00607   case ZeroOrMore:
00608   case ConsumeAfter: break;
00609   default: return error(": bad num occurrences flag value!");
00610   }
00611 
00612   return handleOccurrence(pos, ArgName, Value);
00613 }
00614 
00615 // addArgument - Tell the system that this Option subclass will handle all
00616 // occurrences of -ArgStr on the command line.
00617 //
00618 void Option::addArgument(const char *ArgStr) {
00619   if (ArgStr[0])
00620     AddArgument(ArgStr, this);
00621 
00622   if (getFormattingFlag() == Positional)
00623     getPositionalOpts().push_back(this);
00624   else if (getNumOccurrencesFlag() == ConsumeAfter) {
00625     if (!getPositionalOpts().empty() &&
00626         getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
00627       error("Cannot specify more than one option with cl::ConsumeAfter!");
00628     getPositionalOpts().insert(getPositionalOpts().begin(), this);
00629   }
00630 }
00631 
00632 void Option::removeArgument(const char *ArgStr) {
00633   if (ArgStr[0])
00634     RemoveArgument(ArgStr, this);
00635 
00636   if (getFormattingFlag() == Positional) {
00637     std::vector<Option*>::iterator I =
00638       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
00639     assert(I != getPositionalOpts().end() && "Arg not registered!");
00640     getPositionalOpts().erase(I);
00641   } else if (getNumOccurrencesFlag() == ConsumeAfter) {
00642     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
00643            "Arg not registered correctly!");
00644     getPositionalOpts().erase(getPositionalOpts().begin());
00645   }
00646 }
00647 
00648 
00649 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
00650 // has been specified yet.
00651 //
00652 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
00653   if (O.ValueStr[0] == 0) return DefaultMsg;
00654   return O.ValueStr;
00655 }
00656 
00657 //===----------------------------------------------------------------------===//
00658 // cl::alias class implementation
00659 //
00660 
00661 // Return the width of the option tag for printing...
00662 unsigned alias::getOptionWidth() const {
00663   return std::strlen(ArgStr)+6;
00664 }
00665 
00666 // Print out the option for the alias...
00667 void alias::printOptionInfo(unsigned GlobalWidth) const {
00668   unsigned L = std::strlen(ArgStr);
00669   std::cerr << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
00670             << HelpStr << "\n";
00671 }
00672 
00673 
00674 
00675 //===----------------------------------------------------------------------===//
00676 // Parser Implementation code...
00677 //
00678 
00679 // basic_parser implementation
00680 //
00681 
00682 // Return the width of the option tag for printing...
00683 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
00684   unsigned Len = std::strlen(O.ArgStr);
00685   if (const char *ValName = getValueName())
00686     Len += std::strlen(getValueStr(O, ValName))+3;
00687 
00688   return Len + 6;
00689 }
00690 
00691 // printOptionInfo - Print out information about this option.  The 
00692 // to-be-maintained width is specified.
00693 //
00694 void basic_parser_impl::printOptionInfo(const Option &O,
00695                                         unsigned GlobalWidth) const {
00696   std::cerr << "  -" << O.ArgStr;
00697 
00698   if (const char *ValName = getValueName())
00699     std::cerr << "=<" << getValueStr(O, ValName) << ">";
00700 
00701   std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
00702             << O.HelpStr << "\n";
00703 }
00704 
00705 
00706 
00707 
00708 // parser<bool> implementation
00709 //
00710 bool parser<bool>::parse(Option &O, const char *ArgName,
00711                          const std::string &Arg, bool &Value) {
00712   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 
00713       Arg == "1") {
00714     Value = true;
00715   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
00716     Value = false;
00717   } else {
00718     return O.error(": '" + Arg +
00719                    "' is invalid value for boolean argument! Try 0 or 1");
00720   }
00721   return false;
00722 }
00723 
00724 // parser<int> implementation
00725 //
00726 bool parser<int>::parse(Option &O, const char *ArgName,
00727                         const std::string &Arg, int &Value) {
00728   char *End;
00729   Value = (int)strtol(Arg.c_str(), &End, 0);
00730   if (*End != 0) 
00731     return O.error(": '" + Arg + "' value invalid for integer argument!");
00732   return false;
00733 }
00734 
00735 // parser<unsigned> implementation
00736 //
00737 bool parser<unsigned>::parse(Option &O, const char *ArgName,
00738                              const std::string &Arg, unsigned &Value) {
00739   char *End;
00740   errno = 0;
00741   unsigned long V = strtoul(Arg.c_str(), &End, 0);
00742   Value = (unsigned)V;
00743   if (((V == ULONG_MAX) && (errno == ERANGE))
00744       || (*End != 0)
00745       || (Value != V))
00746     return O.error(": '" + Arg + "' value invalid for uint argument!");
00747   return false;
00748 }
00749 
00750 // parser<double>/parser<float> implementation
00751 //
00752 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
00753   const char *ArgStart = Arg.c_str();
00754   char *End;
00755   Value = strtod(ArgStart, &End);
00756   if (*End != 0) 
00757     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
00758   return false;
00759 }
00760 
00761 bool parser<double>::parse(Option &O, const char *AN,
00762                            const std::string &Arg, double &Val) {
00763   return parseDouble(O, Arg, Val);
00764 }
00765 
00766 bool parser<float>::parse(Option &O, const char *AN,
00767                           const std::string &Arg, float &Val) {
00768   double dVal;
00769   if (parseDouble(O, Arg, dVal))
00770     return true;
00771   Val = (float)dVal;
00772   return false;
00773 }
00774 
00775 
00776 
00777 // generic_parser_base implementation
00778 //
00779 
00780 // findOption - Return the option number corresponding to the specified
00781 // argument string.  If the option is not found, getNumOptions() is returned.
00782 //
00783 unsigned generic_parser_base::findOption(const char *Name) {
00784   unsigned i = 0, e = getNumOptions();
00785   std::string N(Name);
00786 
00787   while (i != e)
00788     if (getOption(i) == N)
00789       return i;
00790     else
00791       ++i;
00792   return e;
00793 }
00794 
00795 
00796 // Return the width of the option tag for printing...
00797 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
00798   if (O.hasArgStr()) {
00799     unsigned Size = std::strlen(O.ArgStr)+6;
00800     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00801       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
00802     return Size;
00803   } else {
00804     unsigned BaseSize = 0;
00805     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00806       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
00807     return BaseSize;
00808   }
00809 }
00810 
00811 // printOptionInfo - Print out information about this option.  The 
00812 // to-be-maintained width is specified.
00813 //
00814 void generic_parser_base::printOptionInfo(const Option &O,
00815                                           unsigned GlobalWidth) const {
00816   if (O.hasArgStr()) {
00817     unsigned L = std::strlen(O.ArgStr);
00818     std::cerr << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
00819               << " - " << O.HelpStr << "\n";
00820 
00821     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00822       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
00823       std::cerr << "    =" << getOption(i) << std::string(NumSpaces, ' ')
00824                 << " - " << getDescription(i) << "\n";
00825     }
00826   } else {
00827     if (O.HelpStr[0])
00828       std::cerr << "  " << O.HelpStr << "\n"; 
00829     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00830       unsigned L = std::strlen(getOption(i));
00831       std::cerr << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
00832                 << " - " << getDescription(i) << "\n";
00833     }
00834   }
00835 }
00836 
00837 
00838 //===----------------------------------------------------------------------===//
00839 // --help and --help-hidden option implementation
00840 //
00841 
00842 namespace {
00843 
00844 class HelpPrinter {
00845   unsigned MaxArgLen;
00846   const Option *EmptyArg;
00847   const bool ShowHidden;
00848 
00849   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
00850   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
00851     return OptPair.second->getOptionHiddenFlag() >= Hidden;
00852   }
00853   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
00854     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
00855   }
00856 
00857 public:
00858   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
00859     EmptyArg = 0;
00860   }
00861 
00862   void operator=(bool Value) {
00863     if (Value == false) return;
00864 
00865     // Copy Options into a vector so we can sort them as we like...
00866     std::vector<std::pair<std::string, Option*> > Options;
00867     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
00868 
00869     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
00870     Options.erase(std::remove_if(Options.begin(), Options.end(), 
00871                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
00872                   Options.end());
00873 
00874     // Eliminate duplicate entries in table (from enum flags options, f.e.)
00875     {  // Give OptionSet a scope
00876       std::set<Option*> OptionSet;
00877       for (unsigned i = 0; i != Options.size(); ++i)
00878         if (OptionSet.count(Options[i].second) == 0)
00879           OptionSet.insert(Options[i].second);   // Add new entry to set
00880         else
00881           Options.erase(Options.begin()+i--);    // Erase duplicate
00882     }
00883 
00884     if (ProgramOverview)
00885       std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
00886 
00887     std::cerr << "USAGE: " << ProgramName << " [options]";
00888 
00889     // Print out the positional options...
00890     std::vector<Option*> &PosOpts = getPositionalOpts();
00891     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
00892     if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
00893       CAOpt = PosOpts[0];
00894 
00895     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
00896       if (PosOpts[i]->ArgStr[0])
00897         std::cerr << " --" << PosOpts[i]->ArgStr;
00898       std::cerr << " " << PosOpts[i]->HelpStr;
00899     }
00900 
00901     // Print the consume after option info if it exists...
00902     if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
00903 
00904     std::cerr << "\n\n";
00905 
00906     // Compute the maximum argument length...
00907     MaxArgLen = 0;
00908     for (unsigned i = 0, e = Options.size(); i != e; ++i)
00909       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
00910 
00911     std::cerr << "OPTIONS:\n";
00912     for (unsigned i = 0, e = Options.size(); i != e; ++i)
00913       Options[i].second->printOptionInfo(MaxArgLen);
00914 
00915     // Print any extra help the user has declared.
00916     for (std::vector<const char *>::iterator I = MoreHelp().begin(),
00917           E = MoreHelp().end(); I != E; ++I)
00918       std::cerr << *I;
00919     MoreHelp().clear();
00920 
00921     // Halt the program since help information was printed
00922     exit(1);
00923   }
00924 };
00925 
00926 class VersionPrinter {
00927 public:
00928   void operator=(bool OptionWasSpecified) {
00929     if (OptionWasSpecified) {
00930       std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") " 
00931                 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
00932       exit(1);
00933     }
00934   }
00935 };
00936 
00937 
00938 // Define the two HelpPrinter instances that are used to print out help, or
00939 // help-hidden...
00940 //
00941 HelpPrinter NormalPrinter(false);
00942 HelpPrinter HiddenPrinter(true);
00943 
00944 cl::opt<HelpPrinter, true, parser<bool> > 
00945 HOp("help", cl::desc("display available options (--help-hidden for more)"),
00946     cl::location(NormalPrinter), cl::ValueDisallowed);
00947 
00948 cl::opt<HelpPrinter, true, parser<bool> >
00949 HHOp("help-hidden", cl::desc("display all available options"),
00950      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
00951 
00952 // Define the --version option that prints out the LLVM version for the tool
00953 VersionPrinter VersionPrinterInstance;
00954 cl::opt<VersionPrinter, true, parser<bool> >
00955 VersOp("version", cl::desc("display the version"), 
00956     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
00957 
00958 
00959 } // End anonymous namespace
00960 
00961 // Utility function for printing the help message.
00962 void cl::PrintHelpMessage() {
00963   // This looks weird, but it actually prints the help message. The 
00964   // NormalPrinter variable is a HelpPrinter and the help gets printed when
00965   // its operator= is invoked. That's because the "normal" usages of the
00966   // help printer is to be assigned true/false depending on whether the 
00967   // --help option was given or not. Since we're circumventing that we have
00968   // to make it look like --help was given, so we assign true.
00969   NormalPrinter = true;
00970 }