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