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