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