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