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