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 // Out of line virtual function to provide home for the class. 00611 void Option::anchor() { 00612 } 00613 00614 bool Option::error(std::string Message, const char *ArgName) { 00615 if (ArgName == 0) ArgName = ArgStr; 00616 if (ArgName[0] == 0) 00617 std::cerr << HelpStr; // Be nice for positional arguments 00618 else 00619 std::cerr << ProgramName << ": for the -" << ArgName; 00620 std::cerr << " option: " << Message << "\n"; 00621 return true; 00622 } 00623 00624 bool Option::addOccurrence(unsigned pos, const char *ArgName, 00625 const std::string &Value) { 00626 NumOccurrences++; // Increment the number of times we have been seen 00627 00628 switch (getNumOccurrencesFlag()) { 00629 case Optional: 00630 if (NumOccurrences > 1) 00631 return error(": may only occur zero or one times!", ArgName); 00632 break; 00633 case Required: 00634 if (NumOccurrences > 1) 00635 return error(": must occur exactly one time!", ArgName); 00636 // Fall through 00637 case OneOrMore: 00638 case ZeroOrMore: 00639 case ConsumeAfter: break; 00640 default: return error(": bad num occurrences flag value!"); 00641 } 00642 00643 return handleOccurrence(pos, ArgName, Value); 00644 } 00645 00646 // addArgument - Tell the system that this Option subclass will handle all 00647 // occurrences of -ArgStr on the command line. 00648 // 00649 void Option::addArgument(const char *ArgStr) { 00650 if (ArgStr[0]) 00651 AddArgument(ArgStr, this); 00652 00653 if (getFormattingFlag() == Positional) 00654 getPositionalOpts().push_back(this); 00655 else if (getNumOccurrencesFlag() == ConsumeAfter) { 00656 if (!getPositionalOpts().empty() && 00657 getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter) 00658 error("Cannot specify more than one option with cl::ConsumeAfter!"); 00659 getPositionalOpts().insert(getPositionalOpts().begin(), this); 00660 } 00661 } 00662 00663 void Option::removeArgument(const char *ArgStr) { 00664 if (ArgStr[0]) 00665 RemoveArgument(ArgStr, this); 00666 00667 if (getFormattingFlag() == Positional) { 00668 std::vector<Option*>::iterator I = 00669 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this); 00670 assert(I != getPositionalOpts().end() && "Arg not registered!"); 00671 getPositionalOpts().erase(I); 00672 } else if (getNumOccurrencesFlag() == ConsumeAfter) { 00673 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this && 00674 "Arg not registered correctly!"); 00675 getPositionalOpts().erase(getPositionalOpts().begin()); 00676 } 00677 } 00678 00679 00680 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 00681 // has been specified yet. 00682 // 00683 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 00684 if (O.ValueStr[0] == 0) return DefaultMsg; 00685 return O.ValueStr; 00686 } 00687 00688 //===----------------------------------------------------------------------===// 00689 // cl::alias class implementation 00690 // 00691 00692 // Return the width of the option tag for printing... 00693 unsigned alias::getOptionWidth() const { 00694 return std::strlen(ArgStr)+6; 00695 } 00696 00697 // Print out the option for the alias. 00698 void alias::printOptionInfo(unsigned GlobalWidth) const { 00699 unsigned L = std::strlen(ArgStr); 00700 std::cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - " 00701 << HelpStr << "\n"; 00702 } 00703 00704 00705 00706 //===----------------------------------------------------------------------===// 00707 // Parser Implementation code... 00708 // 00709 00710 // basic_parser implementation 00711 // 00712 00713 // Return the width of the option tag for printing... 00714 unsigned basic_parser_impl::getOptionWidth(const Option &O) const { 00715 unsigned Len = std::strlen(O.ArgStr); 00716 if (const char *ValName = getValueName()) 00717 Len += std::strlen(getValueStr(O, ValName))+3; 00718 00719 return Len + 6; 00720 } 00721 00722 // printOptionInfo - Print out information about this option. The 00723 // to-be-maintained width is specified. 00724 // 00725 void basic_parser_impl::printOptionInfo(const Option &O, 00726 unsigned GlobalWidth) const { 00727 std::cout << " -" << O.ArgStr; 00728 00729 if (const char *ValName = getValueName()) 00730 std::cout << "=<" << getValueStr(O, ValName) << ">"; 00731 00732 std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - " 00733 << O.HelpStr << "\n"; 00734 } 00735 00736 00737 00738 00739 // parser<bool> implementation 00740 // 00741 bool parser<bool>::parse(Option &O, const char *ArgName, 00742 const std::string &Arg, bool &Value) { 00743 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 00744 Arg == "1") { 00745 Value = true; 00746 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 00747 Value = false; 00748 } else { 00749 return O.error(": '" + Arg + 00750 "' is invalid value for boolean argument! Try 0 or 1"); 00751 } 00752 return false; 00753 } 00754 00755 // parser<int> implementation 00756 // 00757 bool parser<int>::parse(Option &O, const char *ArgName, 00758 const std::string &Arg, int &Value) { 00759 char *End; 00760 Value = (int)strtol(Arg.c_str(), &End, 0); 00761 if (*End != 0) 00762 return O.error(": '" + Arg + "' value invalid for integer argument!"); 00763 return false; 00764 } 00765 00766 // parser<unsigned> implementation 00767 // 00768 bool parser<unsigned>::parse(Option &O, const char *ArgName, 00769 const std::string &Arg, unsigned &Value) { 00770 char *End; 00771 errno = 0; 00772 unsigned long V = strtoul(Arg.c_str(), &End, 0); 00773 Value = (unsigned)V; 00774 if (((V == ULONG_MAX) && (errno == ERANGE)) 00775 || (*End != 0) 00776 || (Value != V)) 00777 return O.error(": '" + Arg + "' value invalid for uint argument!"); 00778 return false; 00779 } 00780 00781 // parser<double>/parser<float> implementation 00782 // 00783 static bool parseDouble(Option &O, const std::string &Arg, double &Value) { 00784 const char *ArgStart = Arg.c_str(); 00785 char *End; 00786 Value = strtod(ArgStart, &End); 00787 if (*End != 0) 00788 return O.error(": '" +Arg+ "' value invalid for floating point argument!"); 00789 return false; 00790 } 00791 00792 bool parser<double>::parse(Option &O, const char *AN, 00793 const std::string &Arg, double &Val) { 00794 return parseDouble(O, Arg, Val); 00795 } 00796 00797 bool parser<float>::parse(Option &O, const char *AN, 00798 const std::string &Arg, float &Val) { 00799 double dVal; 00800 if (parseDouble(O, Arg, dVal)) 00801 return true; 00802 Val = (float)dVal; 00803 return false; 00804 } 00805 00806 00807 00808 // generic_parser_base implementation 00809 // 00810 00811 // findOption - Return the option number corresponding to the specified 00812 // argument string. If the option is not found, getNumOptions() is returned. 00813 // 00814 unsigned generic_parser_base::findOption(const char *Name) { 00815 unsigned i = 0, e = getNumOptions(); 00816 std::string N(Name); 00817 00818 while (i != e) 00819 if (getOption(i) == N) 00820 return i; 00821 else 00822 ++i; 00823 return e; 00824 } 00825 00826 00827 // Return the width of the option tag for printing... 00828 unsigned generic_parser_base::getOptionWidth(const Option &O) const { 00829 if (O.hasArgStr()) { 00830 unsigned Size = std::strlen(O.ArgStr)+6; 00831 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 00832 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8); 00833 return Size; 00834 } else { 00835 unsigned BaseSize = 0; 00836 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 00837 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8); 00838 return BaseSize; 00839 } 00840 } 00841 00842 // printOptionInfo - Print out information about this option. The 00843 // to-be-maintained width is specified. 00844 // 00845 void generic_parser_base::printOptionInfo(const Option &O, 00846 unsigned GlobalWidth) const { 00847 if (O.hasArgStr()) { 00848 unsigned L = std::strlen(O.ArgStr); 00849 std::cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ') 00850 << " - " << O.HelpStr << "\n"; 00851 00852 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 00853 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8; 00854 std::cout << " =" << getOption(i) << std::string(NumSpaces, ' ') 00855 << " - " << getDescription(i) << "\n"; 00856 } 00857 } else { 00858 if (O.HelpStr[0]) 00859 std::cout << " " << O.HelpStr << "\n"; 00860 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 00861 unsigned L = std::strlen(getOption(i)); 00862 std::cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ') 00863 << " - " << getDescription(i) << "\n"; 00864 } 00865 } 00866 } 00867 00868 00869 //===----------------------------------------------------------------------===// 00870 // --help and --help-hidden option implementation 00871 // 00872 00873 namespace { 00874 00875 class HelpPrinter { 00876 unsigned MaxArgLen; 00877 const Option *EmptyArg; 00878 const bool ShowHidden; 00879 00880 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists. 00881 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) { 00882 return OptPair.second->getOptionHiddenFlag() >= Hidden; 00883 } 00884 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) { 00885 return OptPair.second->getOptionHiddenFlag() == ReallyHidden; 00886 } 00887 00888 public: 00889 HelpPrinter(bool showHidden) : ShowHidden(showHidden) { 00890 EmptyArg = 0; 00891 } 00892 00893 void operator=(bool Value) { 00894 if (Value == false) return; 00895 00896 // Copy Options into a vector so we can sort them as we like... 00897 std::vector<std::pair<std::string, Option*> > Options; 00898 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options)); 00899 00900 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden 00901 Options.erase(std::remove_if(Options.begin(), Options.end(), 00902 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)), 00903 Options.end()); 00904 00905 // Eliminate duplicate entries in table (from enum flags options, f.e.) 00906 { // Give OptionSet a scope 00907 std::set<Option*> OptionSet; 00908 for (unsigned i = 0; i != Options.size(); ++i) 00909 if (OptionSet.count(Options[i].second) == 0) 00910 OptionSet.insert(Options[i].second); // Add new entry to set 00911 else 00912 Options.erase(Options.begin()+i--); // Erase duplicate 00913 } 00914 00915 if (ProgramOverview) 00916 std::cout << "OVERVIEW:" << ProgramOverview << "\n"; 00917 00918 std::cout << "USAGE: " << ProgramName << " [options]"; 00919 00920 // Print out the positional options... 00921 std::vector<Option*> &PosOpts = getPositionalOpts(); 00922 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 00923 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 00924 CAOpt = PosOpts[0]; 00925 00926 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) { 00927 if (PosOpts[i]->ArgStr[0]) 00928 std::cout << " --" << PosOpts[i]->ArgStr; 00929 std::cout << " " << PosOpts[i]->HelpStr; 00930 } 00931 00932 // Print the consume after option info if it exists... 00933 if (CAOpt) std::cout << " " << CAOpt->HelpStr; 00934 00935 std::cout << "\n\n"; 00936 00937 // Compute the maximum argument length... 00938 MaxArgLen = 0; 00939 for (unsigned i = 0, e = Options.size(); i != e; ++i) 00940 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth()); 00941 00942 std::cout << "OPTIONS:\n"; 00943 for (unsigned i = 0, e = Options.size(); i != e; ++i) 00944 Options[i].second->printOptionInfo(MaxArgLen); 00945 00946 // Print any extra help the user has declared. 00947 for (std::vector<const char *>::iterator I = MoreHelp().begin(), 00948 E = MoreHelp().end(); I != E; ++I) 00949 std::cout << *I; 00950 MoreHelp().clear(); 00951 00952 // Halt the program since help information was printed 00953 getOpts().clear(); // Don't bother making option dtors remove from map. 00954 exit(1); 00955 } 00956 }; 00957 00958 // Define the two HelpPrinter instances that are used to print out help, or 00959 // help-hidden... 00960 // 00961 HelpPrinter NormalPrinter(false); 00962 HelpPrinter HiddenPrinter(true); 00963 00964 cl::opt<HelpPrinter, true, parser<bool> > 00965 HOp("help", cl::desc("Display available options (--help-hidden for more)"), 00966 cl::location(NormalPrinter), cl::ValueDisallowed); 00967 00968 cl::opt<HelpPrinter, true, parser<bool> > 00969 HHOp("help-hidden", cl::desc("Display all available options"), 00970 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); 00971 00972 void (*OverrideVersionPrinter)() = 0; 00973 00974 class VersionPrinter { 00975 public: 00976 void operator=(bool OptionWasSpecified) { 00977 if (OptionWasSpecified) { 00978 if (OverrideVersionPrinter == 0) { 00979 std::cout << "Low Level Virtual Machine (http://llvm.org/):\n"; 00980 std::cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 00981 #ifdef LLVM_VERSION_INFO 00982 std::cout << LLVM_VERSION_INFO; 00983 #endif 00984 std::cout << "\n "; 00985 #ifndef __OPTIMIZE__ 00986 std::cout << "DEBUG build"; 00987 #else 00988 std::cout << "Optimized build"; 00989 #endif 00990 #ifndef NDEBUG 00991 std::cout << " with assertions"; 00992 #endif 00993 std::cout << ".\n"; 00994 getOpts().clear(); // Don't bother making option dtors remove from map. 00995 exit(1); 00996 } else { 00997 (*OverrideVersionPrinter)(); 00998 exit(1); 00999 } 01000 } 01001 } 01002 }; 01003 01004 01005 // Define the --version option that prints out the LLVM version for the tool 01006 VersionPrinter VersionPrinterInstance; 01007 cl::opt<VersionPrinter, true, parser<bool> > 01008 VersOp("version", cl::desc("Display the version of this program"), 01009 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 01010 01011 01012 } // End anonymous namespace 01013 01014 // Utility function for printing the help message. 01015 void cl::PrintHelpMessage() { 01016 // This looks weird, but it actually prints the help message. The 01017 // NormalPrinter variable is a HelpPrinter and the help gets printed when 01018 // its operator= is invoked. That's because the "normal" usages of the 01019 // help printer is to be assigned true/false depending on whether the 01020 // --help option was given or not. Since we're circumventing that we have 01021 // to make it look like --help was given, so we assign true. 01022 NormalPrinter = true; 01023 } 01024 01025 void cl::SetVersionPrinter(void (*func)()) { 01026 OverrideVersionPrinter = func; 01027 }