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