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