LLVM API Documentation

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 is distributed under the University of Illinois Open Source
00006 // 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/ADT/OwningPtr.h"
00021 #include "llvm/Support/CommandLine.h"
00022 #include "llvm/Support/MemoryBuffer.h"
00023 #include "llvm/Support/ManagedStatic.h"
00024 #include "llvm/Support/Streams.h"
00025 #include "llvm/System/Path.h"
00026 #include <algorithm>
00027 #include <functional>
00028 #include <map>
00029 #include <ostream>
00030 #include <set>
00031 #include <cstdlib>
00032 #include <cerrno>
00033 #include <cstring>
00034 #include <climits>
00035 using namespace llvm;
00036 using namespace cl;
00037 
00038 //===----------------------------------------------------------------------===//
00039 // Template instantiations and anchors.
00040 //
00041 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
00042 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
00043 TEMPLATE_INSTANTIATION(class basic_parser<int>);
00044 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
00045 TEMPLATE_INSTANTIATION(class basic_parser<double>);
00046 TEMPLATE_INSTANTIATION(class basic_parser<float>);
00047 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
00048 
00049 TEMPLATE_INSTANTIATION(class opt<unsigned>);
00050 TEMPLATE_INSTANTIATION(class opt<int>);
00051 TEMPLATE_INSTANTIATION(class opt<std::string>);
00052 TEMPLATE_INSTANTIATION(class opt<bool>);
00053 
00054 void Option::anchor() {}
00055 void basic_parser_impl::anchor() {}
00056 void parser<bool>::anchor() {}
00057 void parser<boolOrDefault>::anchor() {}
00058 void parser<int>::anchor() {}
00059 void parser<unsigned>::anchor() {}
00060 void parser<double>::anchor() {}
00061 void parser<float>::anchor() {}
00062 void parser<std::string>::anchor() {}
00063 
00064 //===----------------------------------------------------------------------===//
00065 
00066 // Globals for name and overview of program.  Program name is not a string to
00067 // avoid static ctor/dtor issues.
00068 static char ProgramName[80] = "<premain>";
00069 static const char *ProgramOverview = 0;
00070 
00071 // This collects additional help to be printed.
00072 static ManagedStatic<std::vector<const char*> > MoreHelp;
00073 
00074 extrahelp::extrahelp(const char *Help)
00075   : morehelp(Help) {
00076   MoreHelp->push_back(Help);
00077 }
00078 
00079 static bool OptionListChanged = false;
00080 
00081 // MarkOptionsChanged - Internal helper function.
00082 void cl::MarkOptionsChanged() {
00083   OptionListChanged = true;
00084 }
00085 
00086 /// RegisteredOptionList - This is the list of the command line options that
00087 /// have statically constructed themselves.
00088 static Option *RegisteredOptionList = 0;
00089 
00090 void Option::addArgument() {
00091   assert(NextRegistered == 0 && "argument multiply registered!");
00092 
00093   NextRegistered = RegisteredOptionList;
00094   RegisteredOptionList = this;
00095   MarkOptionsChanged();
00096 }
00097 
00098 
00099 //===----------------------------------------------------------------------===//
00100 // Basic, shared command line option processing machinery.
00101 //
00102 
00103 /// GetOptionInfo - Scan the list of registered options, turning them into data
00104 /// structures that are easier to handle.
00105 static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
00106                           std::vector<Option*> &SinkOpts,
00107                           std::map<std::string, Option*> &OptionsMap) {
00108   std::vector<const char*> OptionNames;
00109   Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
00110   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
00111     // If this option wants to handle multiple option names, get the full set.
00112     // This handles enum options like "-O1 -O2" etc.
00113     O->getExtraOptionNames(OptionNames);
00114     if (O->ArgStr[0])
00115       OptionNames.push_back(O->ArgStr);
00116 
00117     // Handle named options.
00118     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
00119       // Add argument to the argument map!
00120       if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
00121                                                             O)).second) {
00122         cerr << ProgramName << ": CommandLine Error: Argument '"
00123              << OptionNames[i] << "' defined more than once!\n";
00124       }
00125     }
00126 
00127     OptionNames.clear();
00128 
00129     // Remember information about positional options.
00130     if (O->getFormattingFlag() == cl::Positional)
00131       PositionalOpts.push_back(O);
00132     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
00133       SinkOpts.push_back(O);
00134     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00135       if (CAOpt)
00136         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
00137       CAOpt = O;
00138     }
00139   }
00140 
00141   if (CAOpt)
00142     PositionalOpts.push_back(CAOpt);
00143 
00144   // Make sure that they are in order of registration not backwards.
00145   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
00146 }
00147 
00148 
00149 /// LookupOption - Lookup the option specified by the specified option on the
00150 /// command line.  If there is a value specified (after an equal sign) return
00151 /// that as well.
00152 static Option *LookupOption(const char *&Arg, const char *&Value,
00153                             std::map<std::string, Option*> &OptionsMap) {
00154   while (*Arg == '-') ++Arg;  // Eat leading dashes
00155 
00156   const char *ArgEnd = Arg;
00157   while (*ArgEnd && *ArgEnd != '=')
00158     ++ArgEnd; // Scan till end of argument name.
00159 
00160   if (*ArgEnd == '=')  // If we have an equals sign...
00161     Value = ArgEnd+1;  // Get the value, not the equals
00162 
00163 
00164   if (*Arg == 0) return 0;
00165 
00166   // Look up the option.
00167   std::map<std::string, Option*>::iterator I =
00168     OptionsMap.find(std::string(Arg, ArgEnd));
00169   return I != OptionsMap.end() ? I->second : 0;
00170 }
00171 
00172 static inline bool ProvideOption(Option *Handler, const char *ArgName,
00173                                  const char *Value, int argc, char **argv,
00174                                  int &i) {
00175   // Is this a multi-argument option?
00176   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
00177 
00178   // Enforce value requirements
00179   switch (Handler->getValueExpectedFlag()) {
00180   case ValueRequired:
00181     if (Value == 0) {       // No value specified?
00182       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
00183         Value = argv[++i];
00184       } else {
00185         return Handler->error(" requires a value!");
00186       }
00187     }
00188     break;
00189   case ValueDisallowed:
00190     if (NumAdditionalVals > 0)
00191       return Handler->error(": multi-valued option specified"
00192       " with ValueDisallowed modifier!");
00193 
00194     if (Value)
00195       return Handler->error(" does not allow a value! '" +
00196                             std::string(Value) + "' specified.");
00197     break;
00198   case ValueOptional:
00199     break;
00200   default:
00201     cerr << ProgramName
00202          << ": Bad ValueMask flag! CommandLine usage error:"
00203          << Handler->getValueExpectedFlag() << "\n";
00204     abort();
00205     break;
00206   }
00207 
00208   // If this isn't a multi-arg option, just run the handler.
00209   if (NumAdditionalVals == 0) {
00210     return Handler->addOccurrence(i, ArgName, Value ? Value : "");
00211   }
00212   // If it is, run the handle several times.
00213   else {
00214     bool MultiArg = false;
00215 
00216     if (Value) {
00217       if (Handler->addOccurrence(i, ArgName, Value, MultiArg))
00218         return true;
00219       --NumAdditionalVals;
00220       MultiArg = true;
00221     }
00222 
00223     while (NumAdditionalVals > 0) {
00224 
00225       if (i+1 < argc) {
00226         Value = argv[++i];
00227       } else {
00228         return Handler->error(": not enough values!");
00229       }
00230       if (Handler->addOccurrence(i, ArgName, Value, MultiArg))
00231         return true;
00232       MultiArg = true;
00233       --NumAdditionalVals;
00234     }
00235     return false;
00236   }
00237 }
00238 
00239 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
00240                                     int i) {
00241   int Dummy = i;
00242   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
00243 }
00244 
00245 
00246 // Option predicates...
00247 static inline bool isGrouping(const Option *O) {
00248   return O->getFormattingFlag() == cl::Grouping;
00249 }
00250 static inline bool isPrefixedOrGrouping(const Option *O) {
00251   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
00252 }
00253 
00254 // getOptionPred - Check to see if there are any options that satisfy the
00255 // specified predicate with names that are the prefixes in Name.  This is
00256 // checked by progressively stripping characters off of the name, checking to
00257 // see if there options that satisfy the predicate.  If we find one, return it,
00258 // otherwise return null.
00259 //
00260 static Option *getOptionPred(std::string Name, size_t &Length,
00261                              bool (*Pred)(const Option*),
00262                              std::map<std::string, Option*> &OptionsMap) {
00263 
00264   std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
00265   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
00266     Length = Name.length();
00267     return OMI->second;
00268   }
00269 
00270   if (Name.size() == 1) return 0;
00271   do {
00272     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
00273     OMI = OptionsMap.find(Name);
00274 
00275     // Loop while we haven't found an option and Name still has at least two
00276     // characters in it (so that the next iteration will not be the empty
00277     // string...
00278   } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
00279 
00280   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
00281     Length = Name.length();
00282     return OMI->second;    // Found one!
00283   }
00284   return 0;                // No option found!
00285 }
00286 
00287 static bool RequiresValue(const Option *O) {
00288   return O->getNumOccurrencesFlag() == cl::Required ||
00289          O->getNumOccurrencesFlag() == cl::OneOrMore;
00290 }
00291 
00292 static bool EatsUnboundedNumberOfValues(const Option *O) {
00293   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
00294          O->getNumOccurrencesFlag() == cl::OneOrMore;
00295 }
00296 
00297 /// ParseCStringVector - Break INPUT up wherever one or more
00298 /// whitespace characters are found, and store the resulting tokens in
00299 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
00300 /// using strdup (), so it is the caller's responsibility to free ()
00301 /// them later.
00302 ///
00303 static void ParseCStringVector(std::vector<char *> &output,
00304                                const char *input) {
00305   // Characters which will be treated as token separators:
00306   static const char *const delims = " \v\f\t\r\n";
00307 
00308   std::string work (input);
00309   // Skip past any delims at head of input string.
00310   size_t pos = work.find_first_not_of (delims);
00311   // If the string consists entirely of delims, then exit early.
00312   if (pos == std::string::npos) return;
00313   // Otherwise, jump forward to beginning of first word.
00314   work = work.substr (pos);
00315   // Find position of first delimiter.
00316   pos = work.find_first_of (delims);
00317 
00318   while (!work.empty() && pos != std::string::npos) {
00319     // Everything from 0 to POS is the next word to copy.
00320     output.push_back (strdup (work.substr (0,pos).c_str ()));
00321     // Is there another word in the string?
00322     size_t nextpos = work.find_first_not_of (delims, pos + 1);
00323     if (nextpos != std::string::npos) {
00324       // Yes? Then remove delims from beginning ...
00325       work = work.substr (work.find_first_not_of (delims, pos + 1));
00326       // and find the end of the word.
00327       pos = work.find_first_of (delims);
00328     } else {
00329       // No? (Remainder of string is delims.) End the loop.
00330       work = "";
00331       pos = std::string::npos;
00332     }
00333   }
00334 
00335   // If `input' ended with non-delim char, then we'll get here with
00336   // the last word of `input' in `work'; copy it now.
00337   if (!work.empty ()) {
00338     output.push_back (strdup (work.c_str ()));
00339   }
00340 }
00341 
00342 /// ParseEnvironmentOptions - An alternative entry point to the
00343 /// CommandLine library, which allows you to read the program's name
00344 /// from the caller (as PROGNAME) and its command-line arguments from
00345 /// an environment variable (whose name is given in ENVVAR).
00346 ///
00347 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
00348                                  const char *Overview, bool ReadResponseFiles) {
00349   // Check args.
00350   assert(progName && "Program name not specified");
00351   assert(envVar && "Environment variable name missing");
00352 
00353   // Get the environment variable they want us to parse options out of.
00354   const char *envValue = getenv(envVar);
00355   if (!envValue)
00356     return;
00357 
00358   // Get program's "name", which we wouldn't know without the caller
00359   // telling us.
00360   std::vector<char*> newArgv;
00361   newArgv.push_back(strdup(progName));
00362 
00363   // Parse the value of the environment variable into a "command line"
00364   // and hand it off to ParseCommandLineOptions().
00365   ParseCStringVector(newArgv, envValue);
00366   int newArgc = static_cast<int>(newArgv.size());
00367   ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
00368 
00369   // Free all the strdup()ed strings.
00370   for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
00371        i != e; ++i)
00372     free (*i);
00373 }
00374 
00375 
00376 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
00377 /// substituting the contents of the response files for the arguments
00378 /// of type @file.
00379 static void ExpandResponseFiles(int argc, char** argv,
00380                                 std::vector<char*>& newArgv) {
00381   for (int i = 1; i != argc; ++i) {
00382     char* arg = argv[i];
00383 
00384     if (arg[0] == '@') {
00385 
00386       sys::PathWithStatus respFile(++arg);
00387 
00388       // Check that the response file is not empty (mmap'ing empty
00389       // files can be problematic).
00390       const sys::FileStatus *FileStat = respFile.getFileStatus();
00391       if (FileStat && FileStat->getSize() != 0) {
00392 
00393         // Mmap the response file into memory.
00394         OwningPtr<MemoryBuffer>
00395           respFilePtr(MemoryBuffer::getFile(respFile.c_str()));
00396 
00397         // If we could open the file, parse its contents, otherwise
00398         // pass the @file option verbatim.
00399 
00400         // TODO: we should also support recursive loading of response files,
00401         // since this is how gcc behaves. (From their man page: "The file may
00402         // itself contain additional @file options; any such options will be
00403         // processed recursively.")
00404 
00405         if (respFilePtr != 0) {
00406           ParseCStringVector(newArgv, respFilePtr->getBufferStart());
00407           continue;
00408         }
00409       }
00410     }
00411     newArgv.push_back(strdup(arg));
00412   }
00413 }
00414 
00415 void cl::ParseCommandLineOptions(int argc, char **argv,
00416                                  const char *Overview, bool ReadResponseFiles) {
00417   // Process all registered options.
00418   std::vector<Option*> PositionalOpts;
00419   std::vector<Option*> SinkOpts;
00420   std::map<std::string, Option*> Opts;
00421   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00422 
00423   assert((!Opts.empty() || !PositionalOpts.empty()) &&
00424          "No options specified!");
00425 
00426   // Expand response files.
00427   std::vector<char*> newArgv;
00428   if (ReadResponseFiles) {
00429     newArgv.push_back(strdup(argv[0]));
00430     ExpandResponseFiles(argc, argv, newArgv);
00431     argv = &newArgv[0];
00432     argc = static_cast<int>(newArgv.size());
00433   }
00434 
00435   // Copy the program name into ProgName, making sure not to overflow it.
00436   std::string ProgName = sys::Path(argv[0]).getLast();
00437   if (ProgName.size() > 79) ProgName.resize(79);
00438   strcpy(ProgramName, ProgName.c_str());
00439 
00440   ProgramOverview = Overview;
00441   bool ErrorParsing = false;
00442 
00443   // Check out the positional arguments to collect information about them.
00444   unsigned NumPositionalRequired = 0;
00445 
00446   // Determine whether or not there are an unlimited number of positionals
00447   bool HasUnlimitedPositionals = false;
00448 
00449   Option *ConsumeAfterOpt = 0;
00450   if (!PositionalOpts.empty()) {
00451     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
00452       assert(PositionalOpts.size() > 1 &&
00453              "Cannot specify cl::ConsumeAfter without a positional argument!");
00454       ConsumeAfterOpt = PositionalOpts[0];
00455     }
00456 
00457     // Calculate how many positional values are _required_.
00458     bool UnboundedFound = false;
00459     for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
00460          i != e; ++i) {
00461       Option *Opt = PositionalOpts[i];
00462       if (RequiresValue(Opt))
00463         ++NumPositionalRequired;
00464       else if (ConsumeAfterOpt) {
00465         // ConsumeAfter cannot be combined with "optional" positional options
00466         // unless there is only one positional argument...
00467         if (PositionalOpts.size() > 2)
00468           ErrorParsing |=
00469             Opt->error(" error - this positional option will never be matched, "
00470                        "because it does not Require a value, and a "
00471                        "cl::ConsumeAfter option is active!");
00472       } else if (UnboundedFound && !Opt->ArgStr[0]) {
00473         // This option does not "require" a value...  Make sure this option is
00474         // not specified after an option that eats all extra arguments, or this
00475         // one will never get any!
00476         //
00477         ErrorParsing |= Opt->error(" error - option can never match, because "
00478                                    "another positional argument will match an "
00479                                    "unbounded number of values, and this option"
00480                                    " does not require a value!");
00481       }
00482       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
00483     }
00484     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
00485   }
00486 
00487   // PositionalVals - A vector of "positional" arguments we accumulate into
00488   // the process at the end...
00489   //
00490   std::vector<std::pair<std::string,unsigned> > PositionalVals;
00491 
00492   // If the program has named positional arguments, and the name has been run
00493   // across, keep track of which positional argument was named.  Otherwise put
00494   // the positional args into the PositionalVals list...
00495   Option *ActivePositionalArg = 0;
00496 
00497   // Loop over all of the arguments... processing them.
00498   bool DashDashFound = false;  // Have we read '--'?
00499   for (int i = 1; i < argc; ++i) {
00500     Option *Handler = 0;
00501     const char *Value = 0;
00502     const char *ArgName = "";
00503 
00504     // If the option list changed, this means that some command line
00505     // option has just been registered or deregistered.  This can occur in
00506     // response to things like -load, etc.  If this happens, rescan the options.
00507     if (OptionListChanged) {
00508       PositionalOpts.clear();
00509       SinkOpts.clear();
00510       Opts.clear();
00511       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
00512       OptionListChanged = false;
00513     }
00514 
00515     // Check to see if this is a positional argument.  This argument is
00516     // considered to be positional if it doesn't start with '-', if it is "-"
00517     // itself, or if we have seen "--" already.
00518     //
00519     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
00520       // Positional argument!
00521       if (ActivePositionalArg) {
00522         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00523         continue;  // We are done!
00524       } else if (!PositionalOpts.empty()) {
00525         PositionalVals.push_back(std::make_pair(argv[i],i));
00526 
00527         // All of the positional arguments have been fulfulled, give the rest to
00528         // the consume after option... if it's specified...
00529         //
00530         if (PositionalVals.size() >= NumPositionalRequired &&
00531             ConsumeAfterOpt != 0) {
00532           for (++i; i < argc; ++i)
00533             PositionalVals.push_back(std::make_pair(argv[i],i));
00534           break;   // Handle outside of the argument processing loop...
00535         }
00536 
00537         // Delay processing positional arguments until the end...
00538         continue;
00539       }
00540     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
00541                !DashDashFound) {
00542       DashDashFound = true;  // This is the mythical "--"?
00543       continue;              // Don't try to process it as an argument itself.
00544     } else if (ActivePositionalArg &&
00545                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
00546       // If there is a positional argument eating options, check to see if this
00547       // option is another positional argument.  If so, treat it as an argument,
00548       // otherwise feed it to the eating positional.
00549       ArgName = argv[i]+1;
00550       Handler = LookupOption(ArgName, Value, Opts);
00551       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
00552         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
00553         continue;  // We are done!
00554       }
00555 
00556     } else {     // We start with a '-', must be an argument...
00557       ArgName = argv[i]+1;
00558       Handler = LookupOption(ArgName, Value, Opts);
00559 
00560       // Check to see if this "option" is really a prefixed or grouped argument.
00561       if (Handler == 0) {
00562         std::string RealName(ArgName);
00563         if (RealName.size() > 1) {
00564           size_t Length = 0;
00565           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
00566                                         Opts);
00567 
00568           // If the option is a prefixed option, then the value is simply the
00569           // rest of the name...  so fall through to later processing, by
00570           // setting up the argument name flags and value fields.
00571           //
00572           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
00573             Value = ArgName+Length;
00574             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
00575                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
00576             Handler = PGOpt;
00577           } else if (PGOpt) {
00578             // This must be a grouped option... handle them now.
00579             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
00580 
00581             do {
00582               // Move current arg name out of RealName into RealArgName...
00583               std::string RealArgName(RealName.begin(),
00584                                       RealName.begin() + Length);
00585               RealName.erase(RealName.begin(), RealName.begin() + Length);
00586 
00587               // Because ValueRequired is an invalid flag for grouped arguments,
00588               // we don't need to pass argc/argv in...
00589               //
00590               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
00591                      "Option can not be cl::Grouping AND cl::ValueRequired!");
00592               int Dummy;
00593               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
00594                                             0, 0, 0, Dummy);
00595 
00596               // Get the next grouping option...
00597               PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
00598             } while (PGOpt && Length != RealName.size());
00599 
00600             Handler = PGOpt; // Ate all of the options.
00601           }
00602         }
00603       }
00604     }
00605 
00606     if (Handler == 0) {
00607       if (SinkOpts.empty()) {
00608         cerr << ProgramName << ": Unknown command line argument '"
00609              << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
00610         ErrorParsing = true;
00611       } else {
00612         for (std::vector<Option*>::iterator I = SinkOpts.begin(),
00613                E = SinkOpts.end(); I != E ; ++I)
00614           (*I)->addOccurrence(i, "", argv[i]);
00615       }
00616       continue;
00617     }
00618 
00619     // Check to see if this option accepts a comma separated list of values.  If
00620     // it does, we have to split up the value into multiple values...
00621     if (Value && Handler->getMiscFlags() & CommaSeparated) {
00622       std::string Val(Value);
00623       std::string::size_type Pos = Val.find(',');
00624 
00625       while (Pos != std::string::npos) {
00626         // Process the portion before the comma...
00627         ErrorParsing |= ProvideOption(Handler, ArgName,
00628                                       std::string(Val.begin(),
00629                                                   Val.begin()+Pos).c_str(),
00630                                       argc, argv, i);
00631         // Erase the portion before the comma, AND the comma...
00632         Val.erase(Val.begin(), Val.begin()+Pos+1);
00633         Value += Pos+1;  // Increment the original value pointer as well...
00634 
00635         // Check for another comma...
00636         Pos = Val.find(',');
00637       }
00638     }
00639 
00640     // If this is a named positional argument, just remember that it is the
00641     // active one...
00642     if (Handler->getFormattingFlag() == cl::Positional)
00643       ActivePositionalArg = Handler;
00644     else
00645       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
00646   }
00647 
00648   // Check and handle positional arguments now...
00649   if (NumPositionalRequired > PositionalVals.size()) {
00650     cerr << ProgramName
00651          << ": Not enough positional command line arguments specified!\n"
00652          << "Must specify at least " << NumPositionalRequired
00653          << " positional arguments: See: " << argv[0] << " --help\n";
00654 
00655     ErrorParsing = true;
00656   } else if (!HasUnlimitedPositionals
00657              && PositionalVals.size() > PositionalOpts.size()) {
00658     cerr << ProgramName
00659          << ": Too many positional arguments specified!\n"
00660          << "Can specify at most " << PositionalOpts.size()
00661          << " positional arguments: See: " << argv[0] << " --help\n";
00662     ErrorParsing = true;
00663 
00664   } else if (ConsumeAfterOpt == 0) {
00665     // Positional args have already been handled if ConsumeAfter is specified...
00666     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
00667     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
00668       if (RequiresValue(PositionalOpts[i])) {
00669         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
00670                                 PositionalVals[ValNo].second);
00671         ValNo++;
00672         --NumPositionalRequired;  // We fulfilled our duty...
00673       }
00674 
00675       // If we _can_ give this option more arguments, do so now, as long as we
00676       // do not give it values that others need.  'Done' controls whether the
00677       // option even _WANTS_ any more.
00678       //
00679       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
00680       while (NumVals-ValNo > NumPositionalRequired && !Done) {
00681         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
00682         case cl::Optional:
00683           Done = true;          // Optional arguments want _at most_ one value
00684           // FALL THROUGH
00685         case cl::ZeroOrMore:    // Zero or more will take all they can get...
00686         case cl::OneOrMore:     // One or more will take all they can get...
00687           ProvidePositionalOption(PositionalOpts[i],
00688                                   PositionalVals[ValNo].first,
00689                                   PositionalVals[ValNo].second);
00690           ValNo++;
00691           break;
00692         default:
00693           assert(0 && "Internal error, unexpected NumOccurrences flag in "
00694                  "positional argument processing!");
00695         }
00696       }
00697     }
00698   } else {
00699     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
00700     unsigned ValNo = 0;
00701     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
00702       if (RequiresValue(PositionalOpts[j])) {
00703         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
00704                                                 PositionalVals[ValNo].first,
00705                                                 PositionalVals[ValNo].second);
00706         ValNo++;
00707       }
00708 
00709     // Handle the case where there is just one positional option, and it's
00710     // optional.  In this case, we want to give JUST THE FIRST option to the
00711     // positional option and keep the rest for the consume after.  The above
00712     // loop would have assigned no values to positional options in this case.
00713     //
00714     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
00715       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
00716                                               PositionalVals[ValNo].first,
00717                                               PositionalVals[ValNo].second);
00718       ValNo++;
00719     }
00720 
00721     // Handle over all of the rest of the arguments to the
00722     // cl::ConsumeAfter command line option...
00723     for (; ValNo != PositionalVals.size(); ++ValNo)
00724       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
00725                                               PositionalVals[ValNo].first,
00726                                               PositionalVals[ValNo].second);
00727   }
00728 
00729   // Loop over args and make sure all required args are specified!
00730   for (std::map<std::string, Option*>::iterator I = Opts.begin(),
00731          E = Opts.end(); I != E; ++I) {
00732     switch (I->second->getNumOccurrencesFlag()) {
00733     case Required:
00734     case OneOrMore:
00735       if (I->second->getNumOccurrences() == 0) {
00736         I->second->error(" must be specified at least once!");
00737         ErrorParsing = true;
00738       }
00739       // Fall through
00740     default:
00741       break;
00742     }
00743   }
00744 
00745   // Free all of the memory allocated to the map.  Command line options may only
00746   // be processed once!
00747   Opts.clear();
00748   PositionalOpts.clear();
00749   MoreHelp->clear();
00750 
00751   // Free the memory allocated by ExpandResponseFiles.
00752   if (ReadResponseFiles) {
00753     // Free all the strdup()ed strings.
00754     for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
00755          i != e; ++i)
00756       free (*i);
00757   }
00758 
00759   // If we had an error processing our arguments, don't let the program execute
00760   if (ErrorParsing) exit(1);
00761 }
00762 
00763 //===----------------------------------------------------------------------===//
00764 // Option Base class implementation
00765 //
00766 
00767 bool Option::error(std::string Message, const char *ArgName) {
00768   if (ArgName == 0) ArgName = ArgStr;
00769   if (ArgName[0] == 0)
00770     cerr << HelpStr;  // Be nice for positional arguments
00771   else
00772     cerr << ProgramName << ": for the -" << ArgName;
00773 
00774   cerr << " option: " << Message << "\n";
00775   return true;
00776 }
00777 
00778 bool Option::addOccurrence(unsigned pos, const char *ArgName,
00779                            const std::string &Value,
00780                            bool MultiArg) {
00781   if (!MultiArg)
00782     NumOccurrences++;   // Increment the number of times we have been seen
00783 
00784   switch (getNumOccurrencesFlag()) {
00785   case Optional:
00786     if (NumOccurrences > 1)
00787       return error(": may only occur zero or one times!", ArgName);
00788     break;
00789   case Required:
00790     if (NumOccurrences > 1)
00791       return error(": must occur exactly one time!", ArgName);
00792     // Fall through
00793   case OneOrMore:
00794   case ZeroOrMore:
00795   case ConsumeAfter: break;
00796   default: return error(": bad num occurrences flag value!");
00797   }
00798 
00799   return handleOccurrence(pos, ArgName, Value);
00800 }
00801 
00802 
00803 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
00804 // has been specified yet.
00805 //
00806 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
00807   if (O.ValueStr[0] == 0) return DefaultMsg;
00808   return O.ValueStr;
00809 }
00810 
00811 //===----------------------------------------------------------------------===//
00812 // cl::alias class implementation
00813 //
00814 
00815 // Return the width of the option tag for printing...
00816 size_t alias::getOptionWidth() const {
00817   return std::strlen(ArgStr)+6;
00818 }
00819 
00820 // Print out the option for the alias.
00821 void alias::printOptionInfo(size_t GlobalWidth) const {
00822   size_t L = std::strlen(ArgStr);
00823   cout << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
00824        << HelpStr << "\n";
00825 }
00826 
00827 
00828 
00829 //===----------------------------------------------------------------------===//
00830 // Parser Implementation code...
00831 //
00832 
00833 // basic_parser implementation
00834 //
00835 
00836 // Return the width of the option tag for printing...
00837 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
00838   size_t Len = std::strlen(O.ArgStr);
00839   if (const char *ValName = getValueName())
00840     Len += std::strlen(getValueStr(O, ValName))+3;
00841 
00842   return Len + 6;
00843 }
00844 
00845 // printOptionInfo - Print out information about this option.  The
00846 // to-be-maintained width is specified.
00847 //
00848 void basic_parser_impl::printOptionInfo(const Option &O,
00849                                         size_t GlobalWidth) const {
00850   cout << "  -" << O.ArgStr;
00851 
00852   if (const char *ValName = getValueName())
00853     cout << "=<" << getValueStr(O, ValName) << ">";
00854 
00855   cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
00856        << O.HelpStr << "\n";
00857 }
00858 
00859 
00860 
00861 
00862 // parser<bool> implementation
00863 //
00864 bool parser<bool>::parse(Option &O, const char *ArgName,
00865                          const std::string &Arg, bool &Value) {
00866   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
00867       Arg == "1") {
00868     Value = true;
00869   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
00870     Value = false;
00871   } else {
00872     return O.error(": '" + Arg +
00873                    "' is invalid value for boolean argument! Try 0 or 1");
00874   }
00875   if (IsInvertable && strncmp(ArgName+1, "no-", 3) == 0)
00876     Value = !Value;
00877   return false;
00878 }
00879 
00880 // parser<boolOrDefault> implementation
00881 //
00882 bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
00883                          const std::string &Arg, boolOrDefault &Value) {
00884   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
00885       Arg == "1") {
00886     Value = BOU_TRUE;
00887   } else if (Arg == "false" || Arg == "FALSE"
00888              || Arg == "False" || Arg == "0") {
00889     Value = BOU_FALSE;
00890   } else {
00891     return O.error(": '" + Arg +
00892                    "' is invalid value for boolean argument! Try 0 or 1");
00893   }
00894   return false;
00895 }
00896 
00897 // parser<int> implementation
00898 //
00899 bool parser<int>::parse(Option &O, const char *ArgName,
00900                         const std::string &Arg, int &Value) {
00901   char *End;
00902   Value = (int)strtol(Arg.c_str(), &End, 0);
00903   if (*End != 0)
00904     return O.error(": '" + Arg + "' value invalid for integer argument!");
00905   return false;
00906 }
00907 
00908 // parser<unsigned> implementation
00909 //
00910 bool parser<unsigned>::parse(Option &O, const char *ArgName,
00911                              const std::string &Arg, unsigned &Value) {
00912   char *End;
00913   errno = 0;
00914   unsigned long V = strtoul(Arg.c_str(), &End, 0);
00915   Value = (unsigned)V;
00916   if (((V == ULONG_MAX) && (errno == ERANGE))
00917       || (*End != 0)
00918       || (Value != V))
00919     return O.error(": '" + Arg + "' value invalid for uint argument!");
00920   return false;
00921 }
00922 
00923 // parser<double>/parser<float> implementation
00924 //
00925 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
00926   const char *ArgStart = Arg.c_str();
00927   char *End;
00928   Value = strtod(ArgStart, &End);
00929   if (*End != 0)
00930     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
00931   return false;
00932 }
00933 
00934 bool parser<double>::parse(Option &O, const char *AN,
00935                            const std::string &Arg, double &Val) {
00936   return parseDouble(O, Arg, Val);
00937 }
00938 
00939 bool parser<float>::parse(Option &O, const char *AN,
00940                           const std::string &Arg, float &Val) {
00941   double dVal;
00942   if (parseDouble(O, Arg, dVal))
00943     return true;
00944   Val = (float)dVal;
00945   return false;
00946 }
00947 
00948 
00949 
00950 // generic_parser_base implementation
00951 //
00952 
00953 // findOption - Return the option number corresponding to the specified
00954 // argument string.  If the option is not found, getNumOptions() is returned.
00955 //
00956 unsigned generic_parser_base::findOption(const char *Name) {
00957   unsigned i = 0, e = getNumOptions();
00958   std::string N(Name);
00959 
00960   while (i != e)
00961     if (getOption(i) == N)
00962       return i;
00963     else
00964       ++i;
00965   return e;
00966 }
00967 
00968 
00969 // Return the width of the option tag for printing...
00970 size_t generic_parser_base::getOptionWidth(const Option &O) const {
00971   if (O.hasArgStr()) {
00972     size_t Size = std::strlen(O.ArgStr)+6;
00973     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00974       Size = std::max(Size, std::strlen(getOption(i))+8);
00975     return Size;
00976   } else {
00977     size_t BaseSize = 0;
00978     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
00979       BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
00980     return BaseSize;
00981   }
00982 }
00983 
00984 // printOptionInfo - Print out information about this option.  The
00985 // to-be-maintained width is specified.
00986 //
00987 void generic_parser_base::printOptionInfo(const Option &O,
00988                                           size_t GlobalWidth) const {
00989   if (O.hasArgStr()) {
00990     size_t L = std::strlen(O.ArgStr);
00991     cout << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
00992          << " - " << O.HelpStr << "\n";
00993 
00994     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
00995       size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
00996       cout << "    =" << getOption(i) << std::string(NumSpaces, ' ')
00997            << " -   " << getDescription(i) << "\n";
00998     }
00999   } else {
01000     if (O.HelpStr[0])
01001       cout << "  " << O.HelpStr << "\n";
01002     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
01003       size_t L = std::strlen(getOption(i));
01004       cout << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
01005            << " - " << getDescription(i) << "\n";
01006     }
01007   }
01008 }
01009 
01010 
01011 //===----------------------------------------------------------------------===//
01012 // --help and --help-hidden option implementation
01013 //
01014 
01015 namespace {
01016 
01017 class HelpPrinter {
01018   size_t MaxArgLen;
01019   const Option *EmptyArg;
01020   const bool ShowHidden;
01021 
01022   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
01023   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
01024     return OptPair.second->getOptionHiddenFlag() >= Hidden;
01025   }
01026   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
01027     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
01028   }
01029 
01030 public:
01031   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
01032     EmptyArg = 0;
01033   }
01034 
01035   void operator=(bool Value) {
01036     if (Value == false) return;
01037 
01038     // Get all the options.
01039     std::vector<Option*> PositionalOpts;
01040     std::vector<Option*> SinkOpts;
01041     std::map<std::string, Option*> OptMap;
01042     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
01043 
01044     // Copy Options into a vector so we can sort them as we like...
01045     std::vector<std::pair<std::string, Option*> > Opts;
01046     copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
01047 
01048     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
01049     Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
01050                           std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
01051                Opts.end());
01052 
01053     // Eliminate duplicate entries in table (from enum flags options, f.e.)
01054     {  // Give OptionSet a scope
01055       std::set<Option*> OptionSet;
01056       for (unsigned i = 0; i != Opts.size(); ++i)
01057         if (OptionSet.count(Opts[i].second) == 0)
01058           OptionSet.insert(Opts[i].second);   // Add new entry to set
01059         else
01060           Opts.erase(Opts.begin()+i--);    // Erase duplicate
01061     }
01062 
01063     if (ProgramOverview)
01064       cout << "OVERVIEW: " << ProgramOverview << "\n";
01065 
01066     cout << "USAGE: " << ProgramName << " [options]";
01067 
01068     // Print out the positional options.
01069     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
01070     if (!PositionalOpts.empty() &&
01071         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
01072       CAOpt = PositionalOpts[0];
01073 
01074     for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
01075       if (PositionalOpts[i]->ArgStr[0])
01076         cout << " --" << PositionalOpts[i]->ArgStr;
01077       cout << " " << PositionalOpts[i]->HelpStr;
01078     }
01079 
01080     // Print the consume after option info if it exists...
01081     if (CAOpt) cout << " " << CAOpt->HelpStr;
01082 
01083     cout << "\n\n";
01084 
01085     // Compute the maximum argument length...
01086     MaxArgLen = 0;
01087     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01088       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
01089 
01090     cout << "OPTIONS:\n";
01091     for (size_t i = 0, e = Opts.size(); i != e; ++i)
01092       Opts[i].second->printOptionInfo(MaxArgLen);
01093 
01094     // Print any extra help the user has declared.
01095     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
01096           E = MoreHelp->end(); I != E; ++I)
01097       cout << *I;
01098     MoreHelp->clear();
01099 
01100     // Halt the program since help information was printed
01101     exit(1);
01102   }
01103 };
01104 } // End anonymous namespace
01105 
01106 // Define the two HelpPrinter instances that are used to print out help, or
01107 // help-hidden...
01108 //
01109 static HelpPrinter NormalPrinter(false);
01110 static HelpPrinter HiddenPrinter(true);
01111 
01112 static cl::opt<HelpPrinter, true, parser<bool> >
01113 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
01114     cl::location(NormalPrinter), cl::ValueDisallowed);
01115 
01116 static cl::opt<HelpPrinter, true, parser<bool> >
01117 HHOp("help-hidden", cl::desc("Display all available options"),
01118      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
01119 
01120 static void (*OverrideVersionPrinter)() = 0;
01121 
01122 namespace {
01123 class VersionPrinter {
01124 public:
01125   void print() {
01126         cout << "Low Level Virtual Machine (http://llvm.org/):\n";
01127         cout << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
01128 #ifdef LLVM_VERSION_INFO
01129         cout << LLVM_VERSION_INFO;
01130 #endif
01131         cout << "\n  ";
01132 #ifndef __OPTIMIZE__
01133         cout << "DEBUG build";
01134 #else
01135         cout << "Optimized build";
01136 #endif
01137 #ifndef NDEBUG
01138         cout << " with assertions";
01139 #endif
01140         cout << ".\n";
01141         cout << "  Built " << __DATE__ << "(" << __TIME__ << ").\n";
01142   }
01143   void operator=(bool OptionWasSpecified) {
01144     if (OptionWasSpecified) {
01145       if (OverrideVersionPrinter == 0) {
01146         print();
01147         exit(1);
01148       } else {
01149         (*OverrideVersionPrinter)();
01150         exit(1);
01151       }
01152     }
01153   }
01154 };
01155 } // End anonymous namespace
01156 
01157 
01158 // Define the --version option that prints out the LLVM version for the tool
01159 static VersionPrinter VersionPrinterInstance;
01160 
01161 static cl::opt<VersionPrinter, true, parser<bool> >
01162 VersOp("version", cl::desc("Display the version of this program"),
01163     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
01164 
01165 // Utility function for printing the help message.
01166 void cl::PrintHelpMessage() {
01167   // This looks weird, but it actually prints the help message. The
01168   // NormalPrinter variable is a HelpPrinter and the help gets printed when
01169   // its operator= is invoked. That's because the "normal" usages of the
01170   // help printer is to be assigned true/false depending on whether the
01171   // --help option was given or not. Since we're circumventing that we have
01172   // to make it look like --help was given, so we assign true.
01173   NormalPrinter = true;
01174 }
01175 
01176 /// Utility function for printing version number.
01177 void cl::PrintVersionMessage() {
01178   VersionPrinterInstance.print();
01179 }
01180 
01181 void cl::SetVersionPrinter(void (*func)()) {
01182   OverrideVersionPrinter = func;
01183 }