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