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