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