1 //===-- CommandLine.cpp - Command line parser implementation --------------===// 2 // 3 // This class implements a command line argument processor that is useful when 4 // creating a tool. It provides a simple, minimalistic interface that is easily 5 // extensible and supports nonlocal (library) command line options. 6 // 7 // Note that rather than trying to figure out what this code does, you could try 8 // reading the library documentation located in docs/CommandLine.html 9 // 10 //===----------------------------------------------------------------------===// 11 12 #include "Support/CommandLine.h" 13 #include <algorithm> 14 #include <map> 15 #include <set> 16 #include <iostream> 17 18 using namespace cl; 19 20 //===----------------------------------------------------------------------===// 21 // Basic, shared command line option processing machinery... 22 // 23 24 // Return the global command line option vector. Making it a function scoped 25 // static ensures that it will be initialized correctly before its first use. 26 // 27 static std::map<std::string, Option*> *CommandLineOptions = 0; 28 static std::map<std::string, Option*> &getOpts() { 29 if (CommandLineOptions == 0) 30 CommandLineOptions = new std::map<std::string,Option*>(); 31 return *CommandLineOptions; 32 } 33 34 static Option *getOption(const std::string &Str) { 35 if (CommandLineOptions == 0) return 0; 36 std::map<std::string,Option*>::iterator I = CommandLineOptions->find(Str); 37 return I != CommandLineOptions->end() ? I->second : 0; 38 } 39 40 static std::vector<Option*> &getPositionalOpts() { 41 static std::vector<Option*> Positional; 42 return Positional; 43 } 44 45 static void AddArgument(const char *ArgName, Option *Opt) { 46 if (getOption(ArgName)) { 47 std::cerr << "CommandLine Error: Argument '" << ArgName 48 << "' defined more than once!\n"; 49 } else { 50 // Add argument to the argument map! 51 getOpts()[ArgName] = Opt; 52 } 53 } 54 55 // RemoveArgument - It's possible that the argument is no longer in the map if 56 // options have already been processed and the map has been deleted! 57 // 58 static void RemoveArgument(const char *ArgName, Option *Opt) { 59 if (CommandLineOptions == 0) return; 60 assert(getOption(ArgName) == Opt && "Arg not in map!"); 61 CommandLineOptions->erase(ArgName); 62 if (CommandLineOptions->empty()) { 63 delete CommandLineOptions; 64 CommandLineOptions = 0; 65 } 66 } 67 68 static const char *ProgramName = 0; 69 static const char *ProgramOverview = 0; 70 71 static inline bool ProvideOption(Option *Handler, const char *ArgName, 72 const char *Value, int argc, char **argv, 73 int &i) { 74 // Enforce value requirements 75 switch (Handler->getValueExpectedFlag()) { 76 case ValueRequired: 77 if (Value == 0 || *Value == 0) { // No value specified? 78 if (i+1 < argc) { // Steal the next argument, like for '-o filename' 79 Value = argv[++i]; 80 } else { 81 return Handler->error(" requires a value!"); 82 } 83 } 84 break; 85 case ValueDisallowed: 86 if (*Value != 0) 87 return Handler->error(" does not allow a value! '" + 88 std::string(Value) + "' specified."); 89 break; 90 case ValueOptional: break; 91 default: std::cerr << "Bad ValueMask flag! CommandLine usage error:" 92 << Handler->getValueExpectedFlag() << "\n"; abort(); 93 } 94 95 // Run the handler now! 96 return Handler->addOccurrence(ArgName, Value); 97 } 98 99 static bool ProvidePositionalOption(Option *Handler, std::string &Arg) { 100 int Dummy; 101 return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy); 102 } 103 104 105 // Option predicates... 106 static inline bool isGrouping(const Option *O) { 107 return O->getFormattingFlag() == cl::Grouping; 108 } 109 static inline bool isPrefixedOrGrouping(const Option *O) { 110 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 111 } 112 113 // getOptionPred - Check to see if there are any options that satisfy the 114 // specified predicate with names that are the prefixes in Name. This is 115 // checked by progressively stripping characters off of the name, checking to 116 // see if there options that satisfy the predicate. If we find one, return it, 117 // otherwise return null. 118 // 119 static Option *getOptionPred(std::string Name, unsigned &Length, 120 bool (*Pred)(const Option*)) { 121 122 Option *Op = getOption(Name); 123 if (Op && Pred(Op)) { 124 Length = Name.length(); 125 return Op; 126 } 127 128 if (Name.size() == 1) return 0; 129 do { 130 Name.erase(Name.end()-1, Name.end()); // Chop off the last character... 131 Op = getOption(Name); 132 133 // Loop while we haven't found an option and Name still has at least two 134 // characters in it (so that the next iteration will not be the empty 135 // string... 136 } while ((Op == 0 || !Pred(Op)) && Name.size() > 1); 137 138 if (Op && Pred(Op)) { 139 Length = Name.length(); 140 return Op; // Found one! 141 } 142 return 0; // No option found! 143 } 144 145 static bool RequiresValue(const Option *O) { 146 return O->getNumOccurrencesFlag() == cl::Required || 147 O->getNumOccurrencesFlag() == cl::OneOrMore; 148 } 149 150 static bool EatsUnboundedNumberOfValues(const Option *O) { 151 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 152 O->getNumOccurrencesFlag() == cl::OneOrMore; 153 } 154 155 void cl::ParseCommandLineOptions(int &argc, char **argv, 156 const char *Overview) { 157 assert((!getOpts().empty() || !getPositionalOpts().empty()) && 158 "No options specified, or ParseCommandLineOptions called more" 159 " than once!"); 160 ProgramName = argv[0]; // Save this away safe and snug 161 ProgramOverview = Overview; 162 bool ErrorParsing = false; 163 164 std::map<std::string, Option*> &Opts = getOpts(); 165 std::vector<Option*> &PositionalOpts = getPositionalOpts(); 166 167 // Check out the positional arguments to collect information about them. 168 unsigned NumPositionalRequired = 0; 169 Option *ConsumeAfterOpt = 0; 170 if (!PositionalOpts.empty()) { 171 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 172 assert(PositionalOpts.size() > 1 && 173 "Cannot specify cl::ConsumeAfter without a positional argument!"); 174 ConsumeAfterOpt = PositionalOpts[0]; 175 } 176 177 // Calculate how many positional values are _required_. 178 bool UnboundedFound = false; 179 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 180 i != e; ++i) { 181 Option *Opt = PositionalOpts[i]; 182 if (RequiresValue(Opt)) 183 ++NumPositionalRequired; 184 else if (ConsumeAfterOpt) { 185 // ConsumeAfter cannot be combined with "optional" positional options 186 // unless there is only one positional argument... 187 if (PositionalOpts.size() > 2) 188 ErrorParsing |= 189 Opt->error(" error - this positional option will never be matched, " 190 "because it does not Require a value, and a " 191 "cl::ConsumeAfter option is active!"); 192 } else if (UnboundedFound) { // This option does not "require" a value... 193 // Make sure this option is not specified after an option that eats all 194 // extra arguments, or this one will never get any! 195 // 196 ErrorParsing |= Opt->error(" error - option can never match, because " 197 "another positional argument will match an " 198 "unbounded number of values, and this option" 199 " does not require a value!"); 200 } 201 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 202 } 203 } 204 205 // PositionalVals - A vector of "positional" arguments we accumulate into to 206 // processes at the end... 207 // 208 std::vector<std::string> PositionalVals; 209 210 // Loop over all of the arguments... processing them. 211 bool DashDashFound = false; // Have we read '--'? 212 for (int i = 1; i < argc; ++i) { 213 Option *Handler = 0; 214 const char *Value = ""; 215 const char *ArgName = ""; 216 217 // Check to see if this is a positional argument. This argument is 218 // considered to be positional if it doesn't start with '-', if it is "-" 219 // itself, or if we have see "--" already. 220 // 221 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 222 // Positional argument! 223 if (!PositionalOpts.empty()) { 224 PositionalVals.push_back(argv[i]); 225 226 // All of the positional arguments have been fulfulled, give the rest to 227 // the consume after option... if it's specified... 228 // 229 if (PositionalVals.size() >= NumPositionalRequired && 230 ConsumeAfterOpt != 0) { 231 for (++i; i < argc; ++i) 232 PositionalVals.push_back(argv[i]); 233 break; // Handle outside of the argument processing loop... 234 } 235 236 // Delay processing positional arguments until the end... 237 continue; 238 } 239 } else { // We start with a '-', must be an argument... 240 ArgName = argv[i]+1; 241 while (*ArgName == '-') ++ArgName; // Eat leading dashes 242 243 if (*ArgName == 0 && !DashDashFound) { // Is this the mythical "--"? 244 DashDashFound = true; // Yup, take note of that fact... 245 continue; // Don't try to process it as an argument iself. 246 } 247 248 const char *ArgNameEnd = ArgName; 249 while (*ArgNameEnd && *ArgNameEnd != '=') 250 ++ArgNameEnd; // Scan till end of argument name... 251 252 Value = ArgNameEnd; 253 if (*Value) // If we have an equals sign... 254 ++Value; // Advance to value... 255 256 if (*ArgName != 0) { 257 std::string RealName(ArgName, ArgNameEnd); 258 // Extract arg name part 259 std::map<std::string, Option*>::iterator I = Opts.find(RealName); 260 261 if (I == Opts.end() && !*Value && RealName.size() > 1) { 262 // Check to see if this "option" is really a prefixed or grouped 263 // argument... 264 // 265 unsigned Length = 0; 266 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping); 267 268 // If the option is a prefixed option, then the value is simply the 269 // rest of the name... so fall through to later processing, by 270 // setting up the argument name flags and value fields. 271 // 272 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) { 273 ArgNameEnd = ArgName+Length; 274 Value = ArgNameEnd; 275 I = Opts.find(std::string(ArgName, ArgNameEnd)); 276 assert(I->second == PGOpt); 277 } else if (PGOpt) { 278 // This must be a grouped option... handle all of them now... 279 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 280 281 do { 282 // Move current arg name out of RealName into RealArgName... 283 std::string RealArgName(RealName.begin(),RealName.begin()+Length); 284 RealName.erase(RealName.begin(), RealName.begin()+Length); 285 286 // Because ValueRequired is an invalid flag for grouped arguments, 287 // we don't need to pass argc/argv in... 288 // 289 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 290 "Option can not be cl::Grouping AND cl::ValueRequired!"); 291 int Dummy; 292 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "", 293 0, 0, Dummy); 294 295 // Get the next grouping option... 296 if (!RealName.empty()) 297 PGOpt = getOptionPred(RealName, Length, isGrouping); 298 } while (!RealName.empty() && PGOpt); 299 300 if (RealName.empty()) // Processed all of the options, move on 301 continue; // to the next argv[] value... 302 303 // If RealName is not empty, that means we did not match one of the 304 // options! This is an error. 305 // 306 I = Opts.end(); 307 } 308 } 309 310 Handler = I != Opts.end() ? I->second : 0; 311 } 312 } 313 314 if (Handler == 0) { 315 std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: " 316 << argv[0] << " --help'\n"; 317 ErrorParsing = true; 318 continue; 319 } 320 321 // Check to see if this option accepts a comma separated list of values. If 322 // it does, we have to split up the value into multiple values... 323 if (Handler->getMiscFlags() & CommaSeparated) { 324 std::string Val(Value); 325 std::string::size_type Pos = Val.find(','); 326 327 while (Pos != std::string::npos) { 328 // Process the portion before the comma... 329 ErrorParsing |= ProvideOption(Handler, ArgName, 330 std::string(Val.begin(), 331 Val.begin()+Pos).c_str(), 332 argc, argv, i); 333 // Erase the portion before the comma, AND the comma... 334 Val.erase(Val.begin(), Val.begin()+Pos+1); 335 Value += Pos+1; // Increment the original value pointer as well... 336 337 // Check for another comma... 338 Pos = Val.find(','); 339 } 340 } 341 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 342 } 343 344 // Check and handle positional arguments now... 345 if (NumPositionalRequired > PositionalVals.size()) { 346 std::cerr << "Not enough positional command line arguments specified!\n" 347 << "Must specify at least " << NumPositionalRequired 348 << " positional arguments: See: " << argv[0] << " --help\n"; 349 ErrorParsing = true; 350 351 352 } else if (ConsumeAfterOpt == 0) { 353 // Positional args have already been handled if ConsumeAfter is specified... 354 unsigned ValNo = 0, NumVals = PositionalVals.size(); 355 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) { 356 if (RequiresValue(PositionalOpts[i])) { 357 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]); 358 --NumPositionalRequired; // We fulfilled our duty... 359 } 360 361 // If we _can_ give this option more arguments, do so now, as long as we 362 // do not give it values that others need. 'Done' controls whether the 363 // option even _WANTS_ any more. 364 // 365 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 366 while (NumVals-ValNo > NumPositionalRequired && !Done) { 367 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 368 case cl::Optional: 369 Done = true; // Optional arguments want _at most_ one value 370 // FALL THROUGH 371 case cl::ZeroOrMore: // Zero or more will take all they can get... 372 case cl::OneOrMore: // One or more will take all they can get... 373 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]); 374 break; 375 default: 376 assert(0 && "Internal error, unexpected NumOccurrences flag in " 377 "positional argument processing!"); 378 } 379 } 380 } 381 } else { 382 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 383 unsigned ValNo = 0; 384 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j) 385 if (RequiresValue(PositionalOpts[j])) 386 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 387 PositionalVals[ValNo++]); 388 389 // Handle the case where there is just one positional option, and it's 390 // optional. In this case, we want to give JUST THE FIRST option to the 391 // positional option and keep the rest for the consume after. The above 392 // loop would have assigned no values to positional options in this case. 393 // 394 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) 395 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 396 PositionalVals[ValNo++]); 397 398 // Handle over all of the rest of the arguments to the 399 // cl::ConsumeAfter command line option... 400 for (; ValNo != PositionalVals.size(); ++ValNo) 401 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 402 PositionalVals[ValNo]); 403 } 404 405 // Loop over args and make sure all required args are specified! 406 for (std::map<std::string, Option*>::iterator I = Opts.begin(), 407 E = Opts.end(); I != E; ++I) { 408 switch (I->second->getNumOccurrencesFlag()) { 409 case Required: 410 case OneOrMore: 411 if (I->second->getNumOccurrences() == 0) { 412 I->second->error(" must be specified at least once!"); 413 ErrorParsing = true; 414 } 415 // Fall through 416 default: 417 break; 418 } 419 } 420 421 // Free all of the memory allocated to the map. Command line options may only 422 // be processed once! 423 delete CommandLineOptions; 424 CommandLineOptions = 0; 425 PositionalOpts.clear(); 426 427 // If we had an error processing our arguments, don't let the program execute 428 if (ErrorParsing) exit(1); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Option Base class implementation 433 // 434 435 bool Option::error(std::string Message, const char *ArgName) { 436 if (ArgName == 0) ArgName = ArgStr; 437 if (ArgName[0] == 0) 438 std::cerr << HelpStr; // Be nice for positional arguments 439 else 440 std::cerr << "-" << ArgName; 441 std::cerr << " option" << Message << "\n"; 442 return true; 443 } 444 445 bool Option::addOccurrence(const char *ArgName, const std::string &Value) { 446 NumOccurrences++; // Increment the number of times we have been seen 447 448 switch (getNumOccurrencesFlag()) { 449 case Optional: 450 if (NumOccurrences > 1) 451 return error(": may only occur zero or one times!", ArgName); 452 break; 453 case Required: 454 if (NumOccurrences > 1) 455 return error(": must occur exactly one time!", ArgName); 456 // Fall through 457 case OneOrMore: 458 case ZeroOrMore: 459 case ConsumeAfter: break; 460 default: return error(": bad num occurances flag value!"); 461 } 462 463 return handleOccurrence(ArgName, Value); 464 } 465 466 // addArgument - Tell the system that this Option subclass will handle all 467 // occurances of -ArgStr on the command line. 468 // 469 void Option::addArgument(const char *ArgStr) { 470 if (ArgStr[0]) 471 AddArgument(ArgStr, this); 472 else if (getFormattingFlag() == Positional) 473 getPositionalOpts().push_back(this); 474 else if (getNumOccurrencesFlag() == ConsumeAfter) { 475 assert((getPositionalOpts().empty() || 476 getPositionalOpts().front()->getNumOccurrencesFlag() != ConsumeAfter) 477 && "Cannot specify more than one option with cl::ConsumeAfter " 478 "specified!"); 479 getPositionalOpts().insert(getPositionalOpts().begin(), this); 480 } 481 } 482 483 void Option::removeArgument(const char *ArgStr) { 484 if (ArgStr[0]) { 485 RemoveArgument(ArgStr, this); 486 } else if (getFormattingFlag() == Positional) { 487 std::vector<Option*>::iterator I = 488 std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this); 489 assert(I != getPositionalOpts().end() && "Arg not registered!"); 490 getPositionalOpts().erase(I); 491 } else if (getNumOccurrencesFlag() == ConsumeAfter) { 492 assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this && 493 "Arg not registered correctly!"); 494 getPositionalOpts().erase(getPositionalOpts().begin()); 495 } 496 } 497 498 499 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 500 // has been specified yet. 501 // 502 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 503 if (O.ValueStr[0] == 0) return DefaultMsg; 504 return O.ValueStr; 505 } 506 507 //===----------------------------------------------------------------------===// 508 // cl::alias class implementation 509 // 510 511 // Return the width of the option tag for printing... 512 unsigned alias::getOptionWidth() const { 513 return std::strlen(ArgStr)+6; 514 } 515 516 // Print out the option for the alias... 517 void alias::printOptionInfo(unsigned GlobalWidth) const { 518 unsigned L = std::strlen(ArgStr); 519 std::cerr << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - " 520 << HelpStr << "\n"; 521 } 522 523 524 525 //===----------------------------------------------------------------------===// 526 // Parser Implementation code... 527 // 528 529 // basic_parser implementation 530 // 531 532 // Return the width of the option tag for printing... 533 unsigned basic_parser_impl::getOptionWidth(const Option &O) const { 534 unsigned Len = std::strlen(O.ArgStr); 535 if (const char *ValName = getValueName()) 536 Len += std::strlen(getValueStr(O, ValName))+3; 537 538 return Len + 6; 539 } 540 541 // printOptionInfo - Print out information about this option. The 542 // to-be-maintained width is specified. 543 // 544 void basic_parser_impl::printOptionInfo(const Option &O, 545 unsigned GlobalWidth) const { 546 std::cerr << " -" << O.ArgStr; 547 548 if (const char *ValName = getValueName()) 549 std::cerr << "=<" << getValueStr(O, ValName) << ">"; 550 551 std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - " 552 << O.HelpStr << "\n"; 553 } 554 555 556 557 558 // parser<bool> implementation 559 // 560 bool parser<bool>::parse(Option &O, const char *ArgName, 561 const std::string &Arg, bool &Value) { 562 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 563 Arg == "1") { 564 Value = true; 565 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 566 Value = false; 567 } else { 568 return O.error(": '" + Arg + 569 "' is invalid value for boolean argument! Try 0 or 1"); 570 } 571 return false; 572 } 573 574 // parser<int> implementation 575 // 576 bool parser<int>::parse(Option &O, const char *ArgName, 577 const std::string &Arg, int &Value) { 578 char *End; 579 Value = (int)strtol(Arg.c_str(), &End, 0); 580 if (*End != 0) 581 return O.error(": '" + Arg + "' value invalid for integer argument!"); 582 return false; 583 } 584 585 // parser<unsigned> implementation 586 // 587 bool parser<unsigned>::parse(Option &O, const char *ArgName, 588 const std::string &Arg, unsigned &Value) { 589 char *End; 590 long long int V = strtoll(Arg.c_str(), &End, 0); 591 Value = (unsigned)V; 592 if (*End != 0 || V < 0 || Value != V) 593 return O.error(": '" + Arg + "' value invalid for uint argument!"); 594 return false; 595 } 596 597 // parser<double>/parser<float> implementation 598 // 599 static bool parseDouble(Option &O, const std::string &Arg, double &Value) { 600 const char *ArgStart = Arg.c_str(); 601 char *End; 602 Value = strtod(ArgStart, &End); 603 if (*End != 0) 604 return O.error(": '" +Arg+ "' value invalid for floating point argument!"); 605 return false; 606 } 607 608 bool parser<double>::parse(Option &O, const char *AN, 609 const std::string &Arg, double &Val) { 610 return parseDouble(O, Arg, Val); 611 } 612 613 bool parser<float>::parse(Option &O, const char *AN, 614 const std::string &Arg, float &Val) { 615 double dVal; 616 if (parseDouble(O, Arg, dVal)) 617 return true; 618 Val = (float)dVal; 619 return false; 620 } 621 622 623 624 // generic_parser_base implementation 625 // 626 627 // findOption - Return the option number corresponding to the specified 628 // argument string. If the option is not found, getNumOptions() is returned. 629 // 630 unsigned generic_parser_base::findOption(const char *Name) { 631 unsigned i = 0, e = getNumOptions(); 632 std::string N(Name); 633 634 while (i != e) 635 if (getOption(i) == N) 636 return i; 637 else 638 ++i; 639 return e; 640 } 641 642 643 // Return the width of the option tag for printing... 644 unsigned generic_parser_base::getOptionWidth(const Option &O) const { 645 if (O.hasArgStr()) { 646 unsigned Size = std::strlen(O.ArgStr)+6; 647 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 648 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8); 649 return Size; 650 } else { 651 unsigned BaseSize = 0; 652 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 653 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8); 654 return BaseSize; 655 } 656 } 657 658 // printOptionInfo - Print out information about this option. The 659 // to-be-maintained width is specified. 660 // 661 void generic_parser_base::printOptionInfo(const Option &O, 662 unsigned GlobalWidth) const { 663 if (O.hasArgStr()) { 664 unsigned L = std::strlen(O.ArgStr); 665 std::cerr << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ') 666 << " - " << O.HelpStr << "\n"; 667 668 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 669 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8; 670 std::cerr << " =" << getOption(i) << std::string(NumSpaces, ' ') 671 << " - " << getDescription(i) << "\n"; 672 } 673 } else { 674 if (O.HelpStr[0]) 675 std::cerr << " " << O.HelpStr << "\n"; 676 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 677 unsigned L = std::strlen(getOption(i)); 678 std::cerr << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ') 679 << " - " << getDescription(i) << "\n"; 680 } 681 } 682 } 683 684 685 //===----------------------------------------------------------------------===// 686 // --help and --help-hidden option implementation 687 // 688 namespace { 689 690 class HelpPrinter { 691 unsigned MaxArgLen; 692 const Option *EmptyArg; 693 const bool ShowHidden; 694 695 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists. 696 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) { 697 return OptPair.second->getOptionHiddenFlag() >= Hidden; 698 } 699 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) { 700 return OptPair.second->getOptionHiddenFlag() == ReallyHidden; 701 } 702 703 public: 704 HelpPrinter(bool showHidden) : ShowHidden(showHidden) { 705 EmptyArg = 0; 706 } 707 708 void operator=(bool Value) { 709 if (Value == false) return; 710 711 // Copy Options into a vector so we can sort them as we like... 712 std::vector<std::pair<std::string, Option*> > Options; 713 copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options)); 714 715 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden 716 Options.erase(std::remove_if(Options.begin(), Options.end(), 717 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)), 718 Options.end()); 719 720 // Eliminate duplicate entries in table (from enum flags options, f.e.) 721 { // Give OptionSet a scope 722 std::set<Option*> OptionSet; 723 for (unsigned i = 0; i != Options.size(); ++i) 724 if (OptionSet.count(Options[i].second) == 0) 725 OptionSet.insert(Options[i].second); // Add new entry to set 726 else 727 Options.erase(Options.begin()+i--); // Erase duplicate 728 } 729 730 if (ProgramOverview) 731 std::cerr << "OVERVIEW:" << ProgramOverview << "\n"; 732 733 std::cerr << "USAGE: " << ProgramName << " [options]"; 734 735 // Print out the positional options... 736 std::vector<Option*> &PosOpts = getPositionalOpts(); 737 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 738 if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 739 CAOpt = PosOpts[0]; 740 741 for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) 742 std::cerr << " " << PosOpts[i]->HelpStr; 743 744 // Print the consume after option info if it exists... 745 if (CAOpt) std::cerr << " " << CAOpt->HelpStr; 746 747 std::cerr << "\n\n"; 748 749 // Compute the maximum argument length... 750 MaxArgLen = 0; 751 for (unsigned i = 0, e = Options.size(); i != e; ++i) 752 MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth()); 753 754 std::cerr << "OPTIONS:\n"; 755 for (unsigned i = 0, e = Options.size(); i != e; ++i) 756 Options[i].second->printOptionInfo(MaxArgLen); 757 758 // Halt the program if help information is printed 759 exit(1); 760 } 761 }; 762 763 764 765 // Define the two HelpPrinter instances that are used to print out help, or 766 // help-hidden... 767 // 768 HelpPrinter NormalPrinter(false); 769 HelpPrinter HiddenPrinter(true); 770 771 cl::opt<HelpPrinter, true, parser<bool> > 772 HOp("help", cl::desc("display available options (--help-hidden for more)"), 773 cl::location(NormalPrinter), cl::ValueDisallowed); 774 775 cl::opt<HelpPrinter, true, parser<bool> > 776 HHOp("help-hidden", cl::desc("display all available options"), 777 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); 778 779 } // End anonymous namespace 780