1 //===-- CommandLine.cpp - Command line parser implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // 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/Support/CommandLine.h" 20 #include "llvm/ADT/OwningPtr.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/Config/config.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/Host.h" 29 #include "llvm/Support/ManagedStatic.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include "llvm/Support/system_error.h" 34 #include <cerrno> 35 #include <cstdlib> 36 #include <map> 37 using namespace llvm; 38 using namespace cl; 39 40 //===----------------------------------------------------------------------===// 41 // Template instantiations and anchors. 42 // 43 namespace llvm { namespace cl { 44 TEMPLATE_INSTANTIATION(class basic_parser<bool>); 45 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 46 TEMPLATE_INSTANTIATION(class basic_parser<int>); 47 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 48 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); 49 TEMPLATE_INSTANTIATION(class basic_parser<double>); 50 TEMPLATE_INSTANTIATION(class basic_parser<float>); 51 TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 52 TEMPLATE_INSTANTIATION(class basic_parser<char>); 53 54 TEMPLATE_INSTANTIATION(class opt<unsigned>); 55 TEMPLATE_INSTANTIATION(class opt<int>); 56 TEMPLATE_INSTANTIATION(class opt<std::string>); 57 TEMPLATE_INSTANTIATION(class opt<char>); 58 TEMPLATE_INSTANTIATION(class opt<bool>); 59 } } // end namespace llvm::cl 60 61 void GenericOptionValue::anchor() {} 62 void OptionValue<boolOrDefault>::anchor() {} 63 void OptionValue<std::string>::anchor() {} 64 void Option::anchor() {} 65 void basic_parser_impl::anchor() {} 66 void parser<bool>::anchor() {} 67 void parser<boolOrDefault>::anchor() {} 68 void parser<int>::anchor() {} 69 void parser<unsigned>::anchor() {} 70 void parser<unsigned long long>::anchor() {} 71 void parser<double>::anchor() {} 72 void parser<float>::anchor() {} 73 void parser<std::string>::anchor() {} 74 void parser<char>::anchor() {} 75 76 //===----------------------------------------------------------------------===// 77 78 // Globals for name and overview of program. Program name is not a string to 79 // avoid static ctor/dtor issues. 80 static char ProgramName[80] = "<premain>"; 81 static const char *ProgramOverview = 0; 82 83 // This collects additional help to be printed. 84 static ManagedStatic<std::vector<const char*> > MoreHelp; 85 86 extrahelp::extrahelp(const char *Help) 87 : morehelp(Help) { 88 MoreHelp->push_back(Help); 89 } 90 91 static bool OptionListChanged = false; 92 93 // MarkOptionsChanged - Internal helper function. 94 void cl::MarkOptionsChanged() { 95 OptionListChanged = true; 96 } 97 98 /// RegisteredOptionList - This is the list of the command line options that 99 /// have statically constructed themselves. 100 static Option *RegisteredOptionList = 0; 101 102 void Option::addArgument() { 103 assert(NextRegistered == 0 && "argument multiply registered!"); 104 105 NextRegistered = RegisteredOptionList; 106 RegisteredOptionList = this; 107 MarkOptionsChanged(); 108 } 109 110 // This collects the different option categories that have been registered. 111 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet; 112 static ManagedStatic<OptionCatSet> RegisteredOptionCategories; 113 114 // Initialise the general option category. 115 OptionCategory llvm::cl::GeneralCategory("General options"); 116 117 void OptionCategory::registerCategory() 118 { 119 RegisteredOptionCategories->insert(this); 120 } 121 122 //===----------------------------------------------------------------------===// 123 // Basic, shared command line option processing machinery. 124 // 125 126 /// GetOptionInfo - Scan the list of registered options, turning them into data 127 /// structures that are easier to handle. 128 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 129 SmallVectorImpl<Option*> &SinkOpts, 130 StringMap<Option*> &OptionsMap) { 131 SmallVector<const char*, 16> OptionNames; 132 Option *CAOpt = 0; // The ConsumeAfter option if it exists. 133 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 134 // If this option wants to handle multiple option names, get the full set. 135 // This handles enum options like "-O1 -O2" etc. 136 O->getExtraOptionNames(OptionNames); 137 if (O->ArgStr[0]) 138 OptionNames.push_back(O->ArgStr); 139 140 // Handle named options. 141 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 142 // Add argument to the argument map! 143 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 144 errs() << ProgramName << ": CommandLine Error: Argument '" 145 << OptionNames[i] << "' defined more than once!\n"; 146 } 147 } 148 149 OptionNames.clear(); 150 151 // Remember information about positional options. 152 if (O->getFormattingFlag() == cl::Positional) 153 PositionalOpts.push_back(O); 154 else if (O->getMiscFlags() & cl::Sink) // Remember sink options 155 SinkOpts.push_back(O); 156 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 157 if (CAOpt) 158 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 159 CAOpt = O; 160 } 161 } 162 163 if (CAOpt) 164 PositionalOpts.push_back(CAOpt); 165 166 // Make sure that they are in order of registration not backwards. 167 std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 168 } 169 170 171 /// LookupOption - Lookup the option specified by the specified option on the 172 /// command line. If there is a value specified (after an equal sign) return 173 /// that as well. This assumes that leading dashes have already been stripped. 174 static Option *LookupOption(StringRef &Arg, StringRef &Value, 175 const StringMap<Option*> &OptionsMap) { 176 // Reject all dashes. 177 if (Arg.empty()) return 0; 178 179 size_t EqualPos = Arg.find('='); 180 181 // If we have an equals sign, remember the value. 182 if (EqualPos == StringRef::npos) { 183 // Look up the option. 184 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 185 return I != OptionsMap.end() ? I->second : 0; 186 } 187 188 // If the argument before the = is a valid option name, we match. If not, 189 // return Arg unmolested. 190 StringMap<Option*>::const_iterator I = 191 OptionsMap.find(Arg.substr(0, EqualPos)); 192 if (I == OptionsMap.end()) return 0; 193 194 Value = Arg.substr(EqualPos+1); 195 Arg = Arg.substr(0, EqualPos); 196 return I->second; 197 } 198 199 /// LookupNearestOption - Lookup the closest match to the option specified by 200 /// the specified option on the command line. If there is a value specified 201 /// (after an equal sign) return that as well. This assumes that leading dashes 202 /// have already been stripped. 203 static Option *LookupNearestOption(StringRef Arg, 204 const StringMap<Option*> &OptionsMap, 205 std::string &NearestString) { 206 // Reject all dashes. 207 if (Arg.empty()) return 0; 208 209 // Split on any equal sign. 210 std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 211 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 212 StringRef &RHS = SplitArg.second; 213 214 // Find the closest match. 215 Option *Best = 0; 216 unsigned BestDistance = 0; 217 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), 218 ie = OptionsMap.end(); it != ie; ++it) { 219 Option *O = it->second; 220 SmallVector<const char*, 16> OptionNames; 221 O->getExtraOptionNames(OptionNames); 222 if (O->ArgStr[0]) 223 OptionNames.push_back(O->ArgStr); 224 225 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 226 StringRef Flag = PermitValue ? LHS : Arg; 227 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 228 StringRef Name = OptionNames[i]; 229 unsigned Distance = StringRef(Name).edit_distance( 230 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 231 if (!Best || Distance < BestDistance) { 232 Best = O; 233 BestDistance = Distance; 234 if (RHS.empty() || !PermitValue) 235 NearestString = OptionNames[i]; 236 else 237 NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 238 } 239 } 240 } 241 242 return Best; 243 } 244 245 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that 246 /// does special handling of cl::CommaSeparated options. 247 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, 248 StringRef ArgName, 249 StringRef Value, bool MultiArg = false) 250 { 251 // Check to see if this option accepts a comma separated list of values. If 252 // it does, we have to split up the value into multiple values. 253 if (Handler->getMiscFlags() & CommaSeparated) { 254 StringRef Val(Value); 255 StringRef::size_type Pos = Val.find(','); 256 257 while (Pos != StringRef::npos) { 258 // Process the portion before the comma. 259 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 260 return true; 261 // Erase the portion before the comma, AND the comma. 262 Val = Val.substr(Pos+1); 263 Value.substr(Pos+1); // Increment the original value pointer as well. 264 // Check for another comma. 265 Pos = Val.find(','); 266 } 267 268 Value = Val; 269 } 270 271 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 272 return true; 273 274 return false; 275 } 276 277 /// ProvideOption - For Value, this differentiates between an empty value ("") 278 /// and a null value (StringRef()). The later is accepted for arguments that 279 /// don't allow a value (-foo) the former is rejected (-foo=). 280 static inline bool ProvideOption(Option *Handler, StringRef ArgName, 281 StringRef Value, int argc, 282 const char *const *argv, int &i) { 283 // Is this a multi-argument option? 284 unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 285 286 // Enforce value requirements 287 switch (Handler->getValueExpectedFlag()) { 288 case ValueRequired: 289 if (Value.data() == 0) { // No value specified? 290 if (i+1 >= argc) 291 return Handler->error("requires a value!"); 292 // Steal the next argument, like for '-o filename' 293 Value = argv[++i]; 294 } 295 break; 296 case ValueDisallowed: 297 if (NumAdditionalVals > 0) 298 return Handler->error("multi-valued option specified" 299 " with ValueDisallowed modifier!"); 300 301 if (Value.data()) 302 return Handler->error("does not allow a value! '" + 303 Twine(Value) + "' specified."); 304 break; 305 case ValueOptional: 306 break; 307 } 308 309 // If this isn't a multi-arg option, just run the handler. 310 if (NumAdditionalVals == 0) 311 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); 312 313 // If it is, run the handle several times. 314 bool MultiArg = false; 315 316 if (Value.data()) { 317 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 318 return true; 319 --NumAdditionalVals; 320 MultiArg = true; 321 } 322 323 while (NumAdditionalVals > 0) { 324 if (i+1 >= argc) 325 return Handler->error("not enough values!"); 326 Value = argv[++i]; 327 328 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 329 return true; 330 MultiArg = true; 331 --NumAdditionalVals; 332 } 333 return false; 334 } 335 336 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 337 int Dummy = i; 338 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 339 } 340 341 342 // Option predicates... 343 static inline bool isGrouping(const Option *O) { 344 return O->getFormattingFlag() == cl::Grouping; 345 } 346 static inline bool isPrefixedOrGrouping(const Option *O) { 347 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 348 } 349 350 // getOptionPred - Check to see if there are any options that satisfy the 351 // specified predicate with names that are the prefixes in Name. This is 352 // checked by progressively stripping characters off of the name, checking to 353 // see if there options that satisfy the predicate. If we find one, return it, 354 // otherwise return null. 355 // 356 static Option *getOptionPred(StringRef Name, size_t &Length, 357 bool (*Pred)(const Option*), 358 const StringMap<Option*> &OptionsMap) { 359 360 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 361 362 // Loop while we haven't found an option and Name still has at least two 363 // characters in it (so that the next iteration will not be the empty 364 // string. 365 while (OMI == OptionsMap.end() && Name.size() > 1) { 366 Name = Name.substr(0, Name.size()-1); // Chop off the last character. 367 OMI = OptionsMap.find(Name); 368 } 369 370 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 371 Length = Name.size(); 372 return OMI->second; // Found one! 373 } 374 return 0; // No option found! 375 } 376 377 /// HandlePrefixedOrGroupedOption - The specified argument string (which started 378 /// with at least one '-') does not fully match an available option. Check to 379 /// see if this is a prefix or grouped option. If so, split arg into output an 380 /// Arg/Value pair and return the Option to parse it with. 381 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 382 bool &ErrorParsing, 383 const StringMap<Option*> &OptionsMap) { 384 if (Arg.size() == 1) return 0; 385 386 // Do the lookup! 387 size_t Length = 0; 388 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 389 if (PGOpt == 0) return 0; 390 391 // If the option is a prefixed option, then the value is simply the 392 // rest of the name... so fall through to later processing, by 393 // setting up the argument name flags and value fields. 394 if (PGOpt->getFormattingFlag() == cl::Prefix) { 395 Value = Arg.substr(Length); 396 Arg = Arg.substr(0, Length); 397 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 398 return PGOpt; 399 } 400 401 // This must be a grouped option... handle them now. Grouping options can't 402 // have values. 403 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 404 405 do { 406 // Move current arg name out of Arg into OneArgName. 407 StringRef OneArgName = Arg.substr(0, Length); 408 Arg = Arg.substr(Length); 409 410 // Because ValueRequired is an invalid flag for grouped arguments, 411 // we don't need to pass argc/argv in. 412 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 413 "Option can not be cl::Grouping AND cl::ValueRequired!"); 414 int Dummy = 0; 415 ErrorParsing |= ProvideOption(PGOpt, OneArgName, 416 StringRef(), 0, 0, Dummy); 417 418 // Get the next grouping option. 419 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 420 } while (PGOpt && Length != Arg.size()); 421 422 // Return the last option with Arg cut down to just the last one. 423 return PGOpt; 424 } 425 426 427 428 static bool RequiresValue(const Option *O) { 429 return O->getNumOccurrencesFlag() == cl::Required || 430 O->getNumOccurrencesFlag() == cl::OneOrMore; 431 } 432 433 static bool EatsUnboundedNumberOfValues(const Option *O) { 434 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 435 O->getNumOccurrencesFlag() == cl::OneOrMore; 436 } 437 438 /// ParseCStringVector - Break INPUT up wherever one or more 439 /// whitespace characters are found, and store the resulting tokens in 440 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated 441 /// using strdup(), so it is the caller's responsibility to free() 442 /// them later. 443 /// 444 static void ParseCStringVector(std::vector<char *> &OutputVector, 445 const char *Input) { 446 // Characters which will be treated as token separators: 447 StringRef Delims = " \v\f\t\r\n"; 448 449 StringRef WorkStr(Input); 450 while (!WorkStr.empty()) { 451 // If the first character is a delimiter, strip them off. 452 if (Delims.find(WorkStr[0]) != StringRef::npos) { 453 size_t Pos = WorkStr.find_first_not_of(Delims); 454 if (Pos == StringRef::npos) Pos = WorkStr.size(); 455 WorkStr = WorkStr.substr(Pos); 456 continue; 457 } 458 459 // Find position of first delimiter. 460 size_t Pos = WorkStr.find_first_of(Delims); 461 if (Pos == StringRef::npos) Pos = WorkStr.size(); 462 463 // Everything from 0 to Pos is the next word to copy. 464 char *NewStr = (char*)malloc(Pos+1); 465 memcpy(NewStr, WorkStr.data(), Pos); 466 NewStr[Pos] = 0; 467 OutputVector.push_back(NewStr); 468 469 WorkStr = WorkStr.substr(Pos); 470 } 471 } 472 473 /// ParseEnvironmentOptions - An alternative entry point to the 474 /// CommandLine library, which allows you to read the program's name 475 /// from the caller (as PROGNAME) and its command-line arguments from 476 /// an environment variable (whose name is given in ENVVAR). 477 /// 478 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 479 const char *Overview) { 480 // Check args. 481 assert(progName && "Program name not specified"); 482 assert(envVar && "Environment variable name missing"); 483 484 // Get the environment variable they want us to parse options out of. 485 const char *envValue = getenv(envVar); 486 if (!envValue) 487 return; 488 489 // Get program's "name", which we wouldn't know without the caller 490 // telling us. 491 std::vector<char*> newArgv; 492 newArgv.push_back(strdup(progName)); 493 494 // Parse the value of the environment variable into a "command line" 495 // and hand it off to ParseCommandLineOptions(). 496 ParseCStringVector(newArgv, envValue); 497 int newArgc = static_cast<int>(newArgv.size()); 498 ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 499 500 // Free all the strdup()ed strings. 501 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 502 i != e; ++i) 503 free(*i); 504 } 505 506 507 /// ExpandResponseFiles - Copy the contents of argv into newArgv, 508 /// substituting the contents of the response files for the arguments 509 /// of type @file. 510 static void ExpandResponseFiles(unsigned argc, const char*const* argv, 511 std::vector<char*>& newArgv) { 512 for (unsigned i = 1; i != argc; ++i) { 513 const char *arg = argv[i]; 514 515 if (arg[0] == '@') { 516 sys::PathWithStatus respFile(++arg); 517 518 // Check that the response file is not empty (mmap'ing empty 519 // files can be problematic). 520 const sys::FileStatus *FileStat = respFile.getFileStatus(); 521 if (FileStat && FileStat->getSize() != 0) { 522 523 // If we could open the file, parse its contents, otherwise 524 // pass the @file option verbatim. 525 526 // TODO: we should also support recursive loading of response files, 527 // since this is how gcc behaves. (From their man page: "The file may 528 // itself contain additional @file options; any such options will be 529 // processed recursively.") 530 531 // Mmap the response file into memory. 532 OwningPtr<MemoryBuffer> respFilePtr; 533 if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) { 534 ParseCStringVector(newArgv, respFilePtr->getBufferStart()); 535 continue; 536 } 537 } 538 } 539 newArgv.push_back(strdup(arg)); 540 } 541 } 542 543 void cl::ParseCommandLineOptions(int argc, const char * const *argv, 544 const char *Overview) { 545 // Process all registered options. 546 SmallVector<Option*, 4> PositionalOpts; 547 SmallVector<Option*, 4> SinkOpts; 548 StringMap<Option*> Opts; 549 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 550 551 assert((!Opts.empty() || !PositionalOpts.empty()) && 552 "No options specified!"); 553 554 // Expand response files. 555 std::vector<char*> newArgv; 556 newArgv.push_back(strdup(argv[0])); 557 ExpandResponseFiles(argc, argv, newArgv); 558 argv = &newArgv[0]; 559 argc = static_cast<int>(newArgv.size()); 560 561 // Copy the program name into ProgName, making sure not to overflow it. 562 std::string ProgName = sys::path::filename(argv[0]); 563 size_t Len = std::min(ProgName.size(), size_t(79)); 564 memcpy(ProgramName, ProgName.data(), Len); 565 ProgramName[Len] = '\0'; 566 567 ProgramOverview = Overview; 568 bool ErrorParsing = false; 569 570 // Check out the positional arguments to collect information about them. 571 unsigned NumPositionalRequired = 0; 572 573 // Determine whether or not there are an unlimited number of positionals 574 bool HasUnlimitedPositionals = false; 575 576 Option *ConsumeAfterOpt = 0; 577 if (!PositionalOpts.empty()) { 578 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 579 assert(PositionalOpts.size() > 1 && 580 "Cannot specify cl::ConsumeAfter without a positional argument!"); 581 ConsumeAfterOpt = PositionalOpts[0]; 582 } 583 584 // Calculate how many positional values are _required_. 585 bool UnboundedFound = false; 586 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 587 i != e; ++i) { 588 Option *Opt = PositionalOpts[i]; 589 if (RequiresValue(Opt)) 590 ++NumPositionalRequired; 591 else if (ConsumeAfterOpt) { 592 // ConsumeAfter cannot be combined with "optional" positional options 593 // unless there is only one positional argument... 594 if (PositionalOpts.size() > 2) 595 ErrorParsing |= 596 Opt->error("error - this positional option will never be matched, " 597 "because it does not Require a value, and a " 598 "cl::ConsumeAfter option is active!"); 599 } else if (UnboundedFound && !Opt->ArgStr[0]) { 600 // This option does not "require" a value... Make sure this option is 601 // not specified after an option that eats all extra arguments, or this 602 // one will never get any! 603 // 604 ErrorParsing |= Opt->error("error - option can never match, because " 605 "another positional argument will match an " 606 "unbounded number of values, and this option" 607 " does not require a value!"); 608 } 609 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 610 } 611 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 612 } 613 614 // PositionalVals - A vector of "positional" arguments we accumulate into 615 // the process at the end. 616 // 617 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 618 619 // If the program has named positional arguments, and the name has been run 620 // across, keep track of which positional argument was named. Otherwise put 621 // the positional args into the PositionalVals list... 622 Option *ActivePositionalArg = 0; 623 624 // Loop over all of the arguments... processing them. 625 bool DashDashFound = false; // Have we read '--'? 626 for (int i = 1; i < argc; ++i) { 627 Option *Handler = 0; 628 Option *NearestHandler = 0; 629 std::string NearestHandlerString; 630 StringRef Value; 631 StringRef ArgName = ""; 632 633 // If the option list changed, this means that some command line 634 // option has just been registered or deregistered. This can occur in 635 // response to things like -load, etc. If this happens, rescan the options. 636 if (OptionListChanged) { 637 PositionalOpts.clear(); 638 SinkOpts.clear(); 639 Opts.clear(); 640 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 641 OptionListChanged = false; 642 } 643 644 // Check to see if this is a positional argument. This argument is 645 // considered to be positional if it doesn't start with '-', if it is "-" 646 // itself, or if we have seen "--" already. 647 // 648 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 649 // Positional argument! 650 if (ActivePositionalArg) { 651 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 652 continue; // We are done! 653 } 654 655 if (!PositionalOpts.empty()) { 656 PositionalVals.push_back(std::make_pair(argv[i],i)); 657 658 // All of the positional arguments have been fulfulled, give the rest to 659 // the consume after option... if it's specified... 660 // 661 if (PositionalVals.size() >= NumPositionalRequired && 662 ConsumeAfterOpt != 0) { 663 for (++i; i < argc; ++i) 664 PositionalVals.push_back(std::make_pair(argv[i],i)); 665 break; // Handle outside of the argument processing loop... 666 } 667 668 // Delay processing positional arguments until the end... 669 continue; 670 } 671 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 672 !DashDashFound) { 673 DashDashFound = true; // This is the mythical "--"? 674 continue; // Don't try to process it as an argument itself. 675 } else if (ActivePositionalArg && 676 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 677 // If there is a positional argument eating options, check to see if this 678 // option is another positional argument. If so, treat it as an argument, 679 // otherwise feed it to the eating positional. 680 ArgName = argv[i]+1; 681 // Eat leading dashes. 682 while (!ArgName.empty() && ArgName[0] == '-') 683 ArgName = ArgName.substr(1); 684 685 Handler = LookupOption(ArgName, Value, Opts); 686 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 687 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 688 continue; // We are done! 689 } 690 691 } else { // We start with a '-', must be an argument. 692 ArgName = argv[i]+1; 693 // Eat leading dashes. 694 while (!ArgName.empty() && ArgName[0] == '-') 695 ArgName = ArgName.substr(1); 696 697 Handler = LookupOption(ArgName, Value, Opts); 698 699 // Check to see if this "option" is really a prefixed or grouped argument. 700 if (Handler == 0) 701 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 702 ErrorParsing, Opts); 703 704 // Otherwise, look for the closest available option to report to the user 705 // in the upcoming error. 706 if (Handler == 0 && SinkOpts.empty()) 707 NearestHandler = LookupNearestOption(ArgName, Opts, 708 NearestHandlerString); 709 } 710 711 if (Handler == 0) { 712 if (SinkOpts.empty()) { 713 errs() << ProgramName << ": Unknown command line argument '" 714 << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 715 716 if (NearestHandler) { 717 // If we know a near match, report it as well. 718 errs() << ProgramName << ": Did you mean '-" 719 << NearestHandlerString << "'?\n"; 720 } 721 722 ErrorParsing = true; 723 } else { 724 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 725 E = SinkOpts.end(); I != E ; ++I) 726 (*I)->addOccurrence(i, "", argv[i]); 727 } 728 continue; 729 } 730 731 // If this is a named positional argument, just remember that it is the 732 // active one... 733 if (Handler->getFormattingFlag() == cl::Positional) 734 ActivePositionalArg = Handler; 735 else 736 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 737 } 738 739 // Check and handle positional arguments now... 740 if (NumPositionalRequired > PositionalVals.size()) { 741 errs() << ProgramName 742 << ": Not enough positional command line arguments specified!\n" 743 << "Must specify at least " << NumPositionalRequired 744 << " positional arguments: See: " << argv[0] << " -help\n"; 745 746 ErrorParsing = true; 747 } else if (!HasUnlimitedPositionals && 748 PositionalVals.size() > PositionalOpts.size()) { 749 errs() << ProgramName 750 << ": Too many positional arguments specified!\n" 751 << "Can specify at most " << PositionalOpts.size() 752 << " positional arguments: See: " << argv[0] << " -help\n"; 753 ErrorParsing = true; 754 755 } else if (ConsumeAfterOpt == 0) { 756 // Positional args have already been handled if ConsumeAfter is specified. 757 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 758 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 759 if (RequiresValue(PositionalOpts[i])) { 760 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 761 PositionalVals[ValNo].second); 762 ValNo++; 763 --NumPositionalRequired; // We fulfilled our duty... 764 } 765 766 // If we _can_ give this option more arguments, do so now, as long as we 767 // do not give it values that others need. 'Done' controls whether the 768 // option even _WANTS_ any more. 769 // 770 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 771 while (NumVals-ValNo > NumPositionalRequired && !Done) { 772 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 773 case cl::Optional: 774 Done = true; // Optional arguments want _at most_ one value 775 // FALL THROUGH 776 case cl::ZeroOrMore: // Zero or more will take all they can get... 777 case cl::OneOrMore: // One or more will take all they can get... 778 ProvidePositionalOption(PositionalOpts[i], 779 PositionalVals[ValNo].first, 780 PositionalVals[ValNo].second); 781 ValNo++; 782 break; 783 default: 784 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 785 "positional argument processing!"); 786 } 787 } 788 } 789 } else { 790 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 791 unsigned ValNo = 0; 792 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 793 if (RequiresValue(PositionalOpts[j])) { 794 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 795 PositionalVals[ValNo].first, 796 PositionalVals[ValNo].second); 797 ValNo++; 798 } 799 800 // Handle the case where there is just one positional option, and it's 801 // optional. In this case, we want to give JUST THE FIRST option to the 802 // positional option and keep the rest for the consume after. The above 803 // loop would have assigned no values to positional options in this case. 804 // 805 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 806 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 807 PositionalVals[ValNo].first, 808 PositionalVals[ValNo].second); 809 ValNo++; 810 } 811 812 // Handle over all of the rest of the arguments to the 813 // cl::ConsumeAfter command line option... 814 for (; ValNo != PositionalVals.size(); ++ValNo) 815 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 816 PositionalVals[ValNo].first, 817 PositionalVals[ValNo].second); 818 } 819 820 // Loop over args and make sure all required args are specified! 821 for (StringMap<Option*>::iterator I = Opts.begin(), 822 E = Opts.end(); I != E; ++I) { 823 switch (I->second->getNumOccurrencesFlag()) { 824 case Required: 825 case OneOrMore: 826 if (I->second->getNumOccurrences() == 0) { 827 I->second->error("must be specified at least once!"); 828 ErrorParsing = true; 829 } 830 // Fall through 831 default: 832 break; 833 } 834 } 835 836 // Now that we know if -debug is specified, we can use it. 837 // Note that if ReadResponseFiles == true, this must be done before the 838 // memory allocated for the expanded command line is free()d below. 839 DEBUG(dbgs() << "Args: "; 840 for (int i = 0; i < argc; ++i) 841 dbgs() << argv[i] << ' '; 842 dbgs() << '\n'; 843 ); 844 845 // Free all of the memory allocated to the map. Command line options may only 846 // be processed once! 847 Opts.clear(); 848 PositionalOpts.clear(); 849 MoreHelp->clear(); 850 851 // Free the memory allocated by ExpandResponseFiles. 852 // Free all the strdup()ed strings. 853 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 854 i != e; ++i) 855 free(*i); 856 857 // If we had an error processing our arguments, don't let the program execute 858 if (ErrorParsing) exit(1); 859 } 860 861 //===----------------------------------------------------------------------===// 862 // Option Base class implementation 863 // 864 865 bool Option::error(const Twine &Message, StringRef ArgName) { 866 if (ArgName.data() == 0) ArgName = ArgStr; 867 if (ArgName.empty()) 868 errs() << HelpStr; // Be nice for positional arguments 869 else 870 errs() << ProgramName << ": for the -" << ArgName; 871 872 errs() << " option: " << Message << "\n"; 873 return true; 874 } 875 876 bool Option::addOccurrence(unsigned pos, StringRef ArgName, 877 StringRef Value, bool MultiArg) { 878 if (!MultiArg) 879 NumOccurrences++; // Increment the number of times we have been seen 880 881 switch (getNumOccurrencesFlag()) { 882 case Optional: 883 if (NumOccurrences > 1) 884 return error("may only occur zero or one times!", ArgName); 885 break; 886 case Required: 887 if (NumOccurrences > 1) 888 return error("must occur exactly one time!", ArgName); 889 // Fall through 890 case OneOrMore: 891 case ZeroOrMore: 892 case ConsumeAfter: break; 893 } 894 895 return handleOccurrence(pos, ArgName, Value); 896 } 897 898 899 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 900 // has been specified yet. 901 // 902 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 903 if (O.ValueStr[0] == 0) return DefaultMsg; 904 return O.ValueStr; 905 } 906 907 //===----------------------------------------------------------------------===// 908 // cl::alias class implementation 909 // 910 911 // Return the width of the option tag for printing... 912 size_t alias::getOptionWidth() const { 913 return std::strlen(ArgStr)+6; 914 } 915 916 static void printHelpStr(StringRef HelpStr, size_t Indent, 917 size_t FirstLineIndentedBy) { 918 std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 919 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n"; 920 while (!Split.second.empty()) { 921 Split = Split.second.split('\n'); 922 outs().indent(Indent) << Split.first << "\n"; 923 } 924 } 925 926 // Print out the option for the alias. 927 void alias::printOptionInfo(size_t GlobalWidth) const { 928 outs() << " -" << ArgStr; 929 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6); 930 } 931 932 //===----------------------------------------------------------------------===// 933 // Parser Implementation code... 934 // 935 936 // basic_parser implementation 937 // 938 939 // Return the width of the option tag for printing... 940 size_t basic_parser_impl::getOptionWidth(const Option &O) const { 941 size_t Len = std::strlen(O.ArgStr); 942 if (const char *ValName = getValueName()) 943 Len += std::strlen(getValueStr(O, ValName))+3; 944 945 return Len + 6; 946 } 947 948 // printOptionInfo - Print out information about this option. The 949 // to-be-maintained width is specified. 950 // 951 void basic_parser_impl::printOptionInfo(const Option &O, 952 size_t GlobalWidth) const { 953 outs() << " -" << O.ArgStr; 954 955 if (const char *ValName = getValueName()) 956 outs() << "=<" << getValueStr(O, ValName) << '>'; 957 958 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 959 } 960 961 void basic_parser_impl::printOptionName(const Option &O, 962 size_t GlobalWidth) const { 963 outs() << " -" << O.ArgStr; 964 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 965 } 966 967 968 // parser<bool> implementation 969 // 970 bool parser<bool>::parse(Option &O, StringRef ArgName, 971 StringRef Arg, bool &Value) { 972 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 973 Arg == "1") { 974 Value = true; 975 return false; 976 } 977 978 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 979 Value = false; 980 return false; 981 } 982 return O.error("'" + Arg + 983 "' is invalid value for boolean argument! Try 0 or 1"); 984 } 985 986 // parser<boolOrDefault> implementation 987 // 988 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 989 StringRef Arg, boolOrDefault &Value) { 990 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 991 Arg == "1") { 992 Value = BOU_TRUE; 993 return false; 994 } 995 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 996 Value = BOU_FALSE; 997 return false; 998 } 999 1000 return O.error("'" + Arg + 1001 "' is invalid value for boolean argument! Try 0 or 1"); 1002 } 1003 1004 // parser<int> implementation 1005 // 1006 bool parser<int>::parse(Option &O, StringRef ArgName, 1007 StringRef Arg, int &Value) { 1008 if (Arg.getAsInteger(0, Value)) 1009 return O.error("'" + Arg + "' value invalid for integer argument!"); 1010 return false; 1011 } 1012 1013 // parser<unsigned> implementation 1014 // 1015 bool parser<unsigned>::parse(Option &O, StringRef ArgName, 1016 StringRef Arg, unsigned &Value) { 1017 1018 if (Arg.getAsInteger(0, Value)) 1019 return O.error("'" + Arg + "' value invalid for uint argument!"); 1020 return false; 1021 } 1022 1023 // parser<unsigned long long> implementation 1024 // 1025 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1026 StringRef Arg, unsigned long long &Value){ 1027 1028 if (Arg.getAsInteger(0, Value)) 1029 return O.error("'" + Arg + "' value invalid for uint argument!"); 1030 return false; 1031 } 1032 1033 // parser<double>/parser<float> implementation 1034 // 1035 static bool parseDouble(Option &O, StringRef Arg, double &Value) { 1036 SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1037 const char *ArgStart = TmpStr.c_str(); 1038 char *End; 1039 Value = strtod(ArgStart, &End); 1040 if (*End != 0) 1041 return O.error("'" + Arg + "' value invalid for floating point argument!"); 1042 return false; 1043 } 1044 1045 bool parser<double>::parse(Option &O, StringRef ArgName, 1046 StringRef Arg, double &Val) { 1047 return parseDouble(O, Arg, Val); 1048 } 1049 1050 bool parser<float>::parse(Option &O, StringRef ArgName, 1051 StringRef Arg, float &Val) { 1052 double dVal; 1053 if (parseDouble(O, Arg, dVal)) 1054 return true; 1055 Val = (float)dVal; 1056 return false; 1057 } 1058 1059 1060 1061 // generic_parser_base implementation 1062 // 1063 1064 // findOption - Return the option number corresponding to the specified 1065 // argument string. If the option is not found, getNumOptions() is returned. 1066 // 1067 unsigned generic_parser_base::findOption(const char *Name) { 1068 unsigned e = getNumOptions(); 1069 1070 for (unsigned i = 0; i != e; ++i) { 1071 if (strcmp(getOption(i), Name) == 0) 1072 return i; 1073 } 1074 return e; 1075 } 1076 1077 1078 // Return the width of the option tag for printing... 1079 size_t generic_parser_base::getOptionWidth(const Option &O) const { 1080 if (O.hasArgStr()) { 1081 size_t Size = std::strlen(O.ArgStr)+6; 1082 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1083 Size = std::max(Size, std::strlen(getOption(i))+8); 1084 return Size; 1085 } else { 1086 size_t BaseSize = 0; 1087 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1088 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1089 return BaseSize; 1090 } 1091 } 1092 1093 // printOptionInfo - Print out information about this option. The 1094 // to-be-maintained width is specified. 1095 // 1096 void generic_parser_base::printOptionInfo(const Option &O, 1097 size_t GlobalWidth) const { 1098 if (O.hasArgStr()) { 1099 outs() << " -" << O.ArgStr; 1100 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6); 1101 1102 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1103 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1104 outs() << " =" << getOption(i); 1105 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1106 } 1107 } else { 1108 if (O.HelpStr[0]) 1109 outs() << " " << O.HelpStr << '\n'; 1110 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1111 const char *Option = getOption(i); 1112 outs() << " -" << Option; 1113 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8); 1114 } 1115 } 1116 } 1117 1118 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1119 1120 // printGenericOptionDiff - Print the value of this option and it's default. 1121 // 1122 // "Generic" options have each value mapped to a name. 1123 void generic_parser_base:: 1124 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value, 1125 const GenericOptionValue &Default, 1126 size_t GlobalWidth) const { 1127 outs() << " -" << O.ArgStr; 1128 outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1129 1130 unsigned NumOpts = getNumOptions(); 1131 for (unsigned i = 0; i != NumOpts; ++i) { 1132 if (Value.compare(getOptionValue(i))) 1133 continue; 1134 1135 outs() << "= " << getOption(i); 1136 size_t L = std::strlen(getOption(i)); 1137 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1138 outs().indent(NumSpaces) << " (default: "; 1139 for (unsigned j = 0; j != NumOpts; ++j) { 1140 if (Default.compare(getOptionValue(j))) 1141 continue; 1142 outs() << getOption(j); 1143 break; 1144 } 1145 outs() << ")\n"; 1146 return; 1147 } 1148 outs() << "= *unknown option value*\n"; 1149 } 1150 1151 // printOptionDiff - Specializations for printing basic value types. 1152 // 1153 #define PRINT_OPT_DIFF(T) \ 1154 void parser<T>:: \ 1155 printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1156 size_t GlobalWidth) const { \ 1157 printOptionName(O, GlobalWidth); \ 1158 std::string Str; \ 1159 { \ 1160 raw_string_ostream SS(Str); \ 1161 SS << V; \ 1162 } \ 1163 outs() << "= " << Str; \ 1164 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\ 1165 outs().indent(NumSpaces) << " (default: "; \ 1166 if (D.hasValue()) \ 1167 outs() << D.getValue(); \ 1168 else \ 1169 outs() << "*no default*"; \ 1170 outs() << ")\n"; \ 1171 } \ 1172 1173 PRINT_OPT_DIFF(bool) 1174 PRINT_OPT_DIFF(boolOrDefault) 1175 PRINT_OPT_DIFF(int) 1176 PRINT_OPT_DIFF(unsigned) 1177 PRINT_OPT_DIFF(unsigned long long) 1178 PRINT_OPT_DIFF(double) 1179 PRINT_OPT_DIFF(float) 1180 PRINT_OPT_DIFF(char) 1181 1182 void parser<std::string>:: 1183 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, 1184 size_t GlobalWidth) const { 1185 printOptionName(O, GlobalWidth); 1186 outs() << "= " << V; 1187 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1188 outs().indent(NumSpaces) << " (default: "; 1189 if (D.hasValue()) 1190 outs() << D.getValue(); 1191 else 1192 outs() << "*no default*"; 1193 outs() << ")\n"; 1194 } 1195 1196 // Print a placeholder for options that don't yet support printOptionDiff(). 1197 void basic_parser_impl:: 1198 printOptionNoValue(const Option &O, size_t GlobalWidth) const { 1199 printOptionName(O, GlobalWidth); 1200 outs() << "= *cannot print option value*\n"; 1201 } 1202 1203 //===----------------------------------------------------------------------===// 1204 // -help and -help-hidden option implementation 1205 // 1206 1207 static int OptNameCompare(const void *LHS, const void *RHS) { 1208 typedef std::pair<const char *, Option*> pair_ty; 1209 1210 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first); 1211 } 1212 1213 // Copy Options into a vector so we can sort them as we like. 1214 static void 1215 sortOpts(StringMap<Option*> &OptMap, 1216 SmallVectorImpl< std::pair<const char *, Option*> > &Opts, 1217 bool ShowHidden) { 1218 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1219 1220 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1221 I != E; ++I) { 1222 // Ignore really-hidden options. 1223 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1224 continue; 1225 1226 // Unless showhidden is set, ignore hidden flags. 1227 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1228 continue; 1229 1230 // If we've already seen this option, don't add it to the list again. 1231 if (!OptionSet.insert(I->second)) 1232 continue; 1233 1234 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1235 I->second)); 1236 } 1237 1238 // Sort the options list alphabetically. 1239 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1240 } 1241 1242 namespace { 1243 1244 class HelpPrinter { 1245 protected: 1246 const bool ShowHidden; 1247 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector; 1248 // Print the options. Opts is assumed to be alphabetically sorted. 1249 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1250 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1251 Opts[i].second->printOptionInfo(MaxArgLen); 1252 } 1253 1254 public: 1255 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1256 virtual ~HelpPrinter() {} 1257 1258 // Invoke the printer. 1259 void operator=(bool Value) { 1260 if (Value == false) return; 1261 1262 // Get all the options. 1263 SmallVector<Option*, 4> PositionalOpts; 1264 SmallVector<Option*, 4> SinkOpts; 1265 StringMap<Option*> OptMap; 1266 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1267 1268 StrOptionPairVector Opts; 1269 sortOpts(OptMap, Opts, ShowHidden); 1270 1271 if (ProgramOverview) 1272 outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1273 1274 outs() << "USAGE: " << ProgramName << " [options]"; 1275 1276 // Print out the positional options. 1277 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1278 if (!PositionalOpts.empty() && 1279 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1280 CAOpt = PositionalOpts[0]; 1281 1282 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1283 if (PositionalOpts[i]->ArgStr[0]) 1284 outs() << " --" << PositionalOpts[i]->ArgStr; 1285 outs() << " " << PositionalOpts[i]->HelpStr; 1286 } 1287 1288 // Print the consume after option info if it exists... 1289 if (CAOpt) outs() << " " << CAOpt->HelpStr; 1290 1291 outs() << "\n\n"; 1292 1293 // Compute the maximum argument length... 1294 size_t MaxArgLen = 0; 1295 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1296 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1297 1298 outs() << "OPTIONS:\n"; 1299 printOptions(Opts, MaxArgLen); 1300 1301 // Print any extra help the user has declared. 1302 for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1303 E = MoreHelp->end(); 1304 I != E; ++I) 1305 outs() << *I; 1306 MoreHelp->clear(); 1307 1308 // Halt the program since help information was printed 1309 exit(1); 1310 } 1311 }; 1312 1313 class CategorizedHelpPrinter : public HelpPrinter { 1314 public: 1315 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1316 1317 // Helper function for printOptions(). 1318 // It shall return true if A's name should be lexographically 1319 // ordered before B's name. It returns false otherwise. 1320 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) { 1321 int Length = strcmp(A->getName(), B->getName()); 1322 assert(Length != 0 && "Duplicate option categories"); 1323 return Length < 0; 1324 } 1325 1326 // Make sure we inherit our base class's operator=() 1327 using HelpPrinter::operator= ; 1328 1329 protected: 1330 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1331 std::vector<OptionCategory *> SortedCategories; 1332 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions; 1333 1334 // Collect registered option categories into vector in preperation for 1335 // sorting. 1336 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(), 1337 E = RegisteredOptionCategories->end(); 1338 I != E; ++I) 1339 SortedCategories.push_back(*I); 1340 1341 // Sort the different option categories alphabetically. 1342 assert(SortedCategories.size() > 0 && "No option categories registered!"); 1343 std::sort(SortedCategories.begin(), SortedCategories.end(), 1344 OptionCategoryCompare); 1345 1346 // Create map to empty vectors. 1347 for (std::vector<OptionCategory *>::const_iterator 1348 I = SortedCategories.begin(), 1349 E = SortedCategories.end(); 1350 I != E; ++I) 1351 CategorizedOptions[*I] = std::vector<Option *>(); 1352 1353 // Walk through pre-sorted options and assign into categories. 1354 // Because the options are already alphabetically sorted the 1355 // options within categories will also be alphabetically sorted. 1356 for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1357 Option *Opt = Opts[I].second; 1358 assert(CategorizedOptions.count(Opt->Category) > 0 && 1359 "Option has an unregistered category"); 1360 CategorizedOptions[Opt->Category].push_back(Opt); 1361 } 1362 1363 // Now do printing. 1364 for (std::vector<OptionCategory *>::const_iterator 1365 Category = SortedCategories.begin(), 1366 E = SortedCategories.end(); 1367 Category != E; ++Category) { 1368 // Hide empty categories for -help, but show for -help-hidden. 1369 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1370 if (!ShowHidden && IsEmptyCategory) 1371 continue; 1372 1373 // Print category information. 1374 outs() << "\n"; 1375 outs() << (*Category)->getName() << ":\n"; 1376 1377 // Check if description is set. 1378 if ((*Category)->getDescription() != 0) 1379 outs() << (*Category)->getDescription() << "\n\n"; 1380 else 1381 outs() << "\n"; 1382 1383 // When using -help-hidden explicitly state if the category has no 1384 // options associated with it. 1385 if (IsEmptyCategory) { 1386 outs() << " This option category has no options.\n"; 1387 continue; 1388 } 1389 // Loop over the options in the category and print. 1390 for (std::vector<Option *>::const_iterator 1391 Opt = CategorizedOptions[*Category].begin(), 1392 E = CategorizedOptions[*Category].end(); 1393 Opt != E; ++Opt) 1394 (*Opt)->printOptionInfo(MaxArgLen); 1395 } 1396 } 1397 }; 1398 1399 // This wraps the Uncategorizing and Categorizing printers and decides 1400 // at run time which should be invoked. 1401 class HelpPrinterWrapper { 1402 private: 1403 HelpPrinter &UncategorizedPrinter; 1404 CategorizedHelpPrinter &CategorizedPrinter; 1405 1406 public: 1407 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1408 CategorizedHelpPrinter &CategorizedPrinter) : 1409 UncategorizedPrinter(UncategorizedPrinter), 1410 CategorizedPrinter(CategorizedPrinter) { } 1411 1412 // Invoke the printer. 1413 void operator=(bool Value); 1414 }; 1415 1416 } // End anonymous namespace 1417 1418 // Declare the four HelpPrinter instances that are used to print out help, or 1419 // help-hidden as an uncategorized list or in categories. 1420 static HelpPrinter UncategorizedNormalPrinter(false); 1421 static HelpPrinter UncategorizedHiddenPrinter(true); 1422 static CategorizedHelpPrinter CategorizedNormalPrinter(false); 1423 static CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1424 1425 1426 // Declare HelpPrinter wrappers that will decide whether or not to invoke 1427 // a categorizing help printer 1428 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1429 CategorizedNormalPrinter); 1430 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1431 CategorizedHiddenPrinter); 1432 1433 // Define uncategorized help printers. 1434 // -help-list is hidden by default because if Option categories are being used 1435 // then -help behaves the same as -help-list. 1436 static cl::opt<HelpPrinter, true, parser<bool> > 1437 HLOp("help-list", 1438 cl::desc("Display list of available options (-help-list-hidden for more)"), 1439 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed); 1440 1441 static cl::opt<HelpPrinter, true, parser<bool> > 1442 HLHOp("help-list-hidden", 1443 cl::desc("Display list of all available options"), 1444 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1445 1446 // Define uncategorized/categorized help printers. These printers change their 1447 // behaviour at runtime depending on whether one or more Option categories have 1448 // been declared. 1449 static cl::opt<HelpPrinterWrapper, true, parser<bool> > 1450 HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1451 cl::location(WrappedNormalPrinter), cl::ValueDisallowed); 1452 1453 static cl::opt<HelpPrinterWrapper, true, parser<bool> > 1454 HHOp("help-hidden", cl::desc("Display all available options"), 1455 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1456 1457 1458 1459 static cl::opt<bool> 1460 PrintOptions("print-options", 1461 cl::desc("Print non-default options after command line parsing"), 1462 cl::Hidden, cl::init(false)); 1463 1464 static cl::opt<bool> 1465 PrintAllOptions("print-all-options", 1466 cl::desc("Print all option values after command line parsing"), 1467 cl::Hidden, cl::init(false)); 1468 1469 void HelpPrinterWrapper::operator=(bool Value) { 1470 if (Value == false) 1471 return; 1472 1473 // Decide which printer to invoke. If more than one option category is 1474 // registered then it is useful to show the categorized help instead of 1475 // uncategorized help. 1476 if (RegisteredOptionCategories->size() > 1) { 1477 // unhide -help-list option so user can have uncategorized output if they 1478 // want it. 1479 HLOp.setHiddenFlag(NotHidden); 1480 1481 CategorizedPrinter = true; // Invoke categorized printer 1482 } 1483 else 1484 UncategorizedPrinter = true; // Invoke uncategorized printer 1485 } 1486 1487 // Print the value of each option. 1488 void cl::PrintOptionValues() { 1489 if (!PrintOptions && !PrintAllOptions) return; 1490 1491 // Get all the options. 1492 SmallVector<Option*, 4> PositionalOpts; 1493 SmallVector<Option*, 4> SinkOpts; 1494 StringMap<Option*> OptMap; 1495 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1496 1497 SmallVector<std::pair<const char *, Option*>, 128> Opts; 1498 sortOpts(OptMap, Opts, /*ShowHidden*/true); 1499 1500 // Compute the maximum argument length... 1501 size_t MaxArgLen = 0; 1502 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1503 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1504 1505 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1506 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1507 } 1508 1509 static void (*OverrideVersionPrinter)() = 0; 1510 1511 static std::vector<void (*)()>* ExtraVersionPrinters = 0; 1512 1513 namespace { 1514 class VersionPrinter { 1515 public: 1516 void print() { 1517 raw_ostream &OS = outs(); 1518 OS << "LLVM (http://llvm.org/):\n" 1519 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1520 #ifdef LLVM_VERSION_INFO 1521 OS << LLVM_VERSION_INFO; 1522 #endif 1523 OS << "\n "; 1524 #ifndef __OPTIMIZE__ 1525 OS << "DEBUG build"; 1526 #else 1527 OS << "Optimized build"; 1528 #endif 1529 #ifndef NDEBUG 1530 OS << " with assertions"; 1531 #endif 1532 std::string CPU = sys::getHostCPUName(); 1533 if (CPU == "generic") CPU = "(unknown)"; 1534 OS << ".\n" 1535 #if (ENABLE_TIMESTAMPS == 1) 1536 << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1537 #endif 1538 << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1539 << " Host CPU: " << CPU << '\n'; 1540 } 1541 void operator=(bool OptionWasSpecified) { 1542 if (!OptionWasSpecified) return; 1543 1544 if (OverrideVersionPrinter != 0) { 1545 (*OverrideVersionPrinter)(); 1546 exit(1); 1547 } 1548 print(); 1549 1550 // Iterate over any registered extra printers and call them to add further 1551 // information. 1552 if (ExtraVersionPrinters != 0) { 1553 outs() << '\n'; 1554 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1555 E = ExtraVersionPrinters->end(); 1556 I != E; ++I) 1557 (*I)(); 1558 } 1559 1560 exit(1); 1561 } 1562 }; 1563 } // End anonymous namespace 1564 1565 1566 // Define the --version option that prints out the LLVM version for the tool 1567 static VersionPrinter VersionPrinterInstance; 1568 1569 static cl::opt<VersionPrinter, true, parser<bool> > 1570 VersOp("version", cl::desc("Display the version of this program"), 1571 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1572 1573 // Utility function for printing the help message. 1574 void cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1575 // This looks weird, but it actually prints the help message. The Printers are 1576 // types of HelpPrinter and the help gets printed when its operator= is 1577 // invoked. That's because the "normal" usages of the help printer is to be 1578 // assigned true/false depending on whether -help or -help-hidden was given or 1579 // not. Since we're circumventing that we have to make it look like -help or 1580 // -help-hidden were given, so we assign true. 1581 1582 if (!Hidden && !Categorized) 1583 UncategorizedNormalPrinter = true; 1584 else if (!Hidden && Categorized) 1585 CategorizedNormalPrinter = true; 1586 else if (Hidden && !Categorized) 1587 UncategorizedHiddenPrinter = true; 1588 else 1589 CategorizedHiddenPrinter = true; 1590 } 1591 1592 /// Utility function for printing version number. 1593 void cl::PrintVersionMessage() { 1594 VersionPrinterInstance.print(); 1595 } 1596 1597 void cl::SetVersionPrinter(void (*func)()) { 1598 OverrideVersionPrinter = func; 1599 } 1600 1601 void cl::AddExtraVersionPrinter(void (*func)()) { 1602 if (ExtraVersionPrinters == 0) 1603 ExtraVersionPrinters = new std::vector<void (*)()>; 1604 1605 ExtraVersionPrinters->push_back(func); 1606 } 1607 1608 void cl::getRegisteredOptions(StringMap<Option*> &Map) 1609 { 1610 // Get all the options. 1611 SmallVector<Option*, 4> PositionalOpts; //NOT USED 1612 SmallVector<Option*, 4> SinkOpts; //NOT USED 1613 assert(Map.size() == 0 && "StringMap must be empty"); 1614 GetOptionInfo(PositionalOpts, SinkOpts, Map); 1615 return; 1616 } 1617