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