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