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/Config/config.h" 20 #include "llvm/Support/CommandLine.h" 21 #include "llvm/Support/ManagedStatic.h" 22 #include "llvm/Support/Streams.h" 23 #include "llvm/System/Path.h" 24 #include <algorithm> 25 #include <functional> 26 #include <map> 27 #include <ostream> 28 #include <set> 29 #include <cstdlib> 30 #include <cerrno> 31 #include <cstring> 32 #include <climits> 33 using namespace llvm; 34 using namespace cl; 35 36 //===----------------------------------------------------------------------===// 37 // Template instantiations and anchors. 38 // 39 TEMPLATE_INSTANTIATION(class basic_parser<bool>); 40 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 41 TEMPLATE_INSTANTIATION(class basic_parser<int>); 42 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 43 TEMPLATE_INSTANTIATION(class basic_parser<double>); 44 TEMPLATE_INSTANTIATION(class basic_parser<float>); 45 TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 46 47 TEMPLATE_INSTANTIATION(class opt<unsigned>); 48 TEMPLATE_INSTANTIATION(class opt<int>); 49 TEMPLATE_INSTANTIATION(class opt<std::string>); 50 TEMPLATE_INSTANTIATION(class opt<bool>); 51 52 void Option::anchor() {} 53 void basic_parser_impl::anchor() {} 54 void parser<bool>::anchor() {} 55 void parser<boolOrDefault>::anchor() {} 56 void parser<int>::anchor() {} 57 void parser<unsigned>::anchor() {} 58 void parser<double>::anchor() {} 59 void parser<float>::anchor() {} 60 void parser<std::string>::anchor() {} 61 62 //===----------------------------------------------------------------------===// 63 64 // Globals for name and overview of program. Program name is not a string to 65 // avoid static ctor/dtor issues. 66 static char ProgramName[80] = "<premain>"; 67 static const char *ProgramOverview = 0; 68 69 // This collects additional help to be printed. 70 static ManagedStatic<std::vector<const char*> > MoreHelp; 71 72 extrahelp::extrahelp(const char *Help) 73 : morehelp(Help) { 74 MoreHelp->push_back(Help); 75 } 76 77 static bool OptionListChanged = false; 78 79 // MarkOptionsChanged - Internal helper function. 80 void cl::MarkOptionsChanged() { 81 OptionListChanged = true; 82 } 83 84 /// RegisteredOptionList - This is the list of the command line options that 85 /// have statically constructed themselves. 86 static Option *RegisteredOptionList = 0; 87 88 void Option::addArgument() { 89 assert(NextRegistered == 0 && "argument multiply registered!"); 90 91 NextRegistered = RegisteredOptionList; 92 RegisteredOptionList = this; 93 MarkOptionsChanged(); 94 } 95 96 97 //===----------------------------------------------------------------------===// 98 // Basic, shared command line option processing machinery. 99 // 100 101 /// GetOptionInfo - Scan the list of registered options, turning them into data 102 /// structures that are easier to handle. 103 static void GetOptionInfo(std::vector<Option*> &PositionalOpts, 104 std::map<std::string, Option*> &OptionsMap) { 105 std::vector<const char*> OptionNames; 106 Option *CAOpt = 0; // The ConsumeAfter option if it exists. 107 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 108 // If this option wants to handle multiple option names, get the full set. 109 // This handles enum options like "-O1 -O2" etc. 110 O->getExtraOptionNames(OptionNames); 111 if (O->ArgStr[0]) 112 OptionNames.push_back(O->ArgStr); 113 114 // Handle named options. 115 for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) { 116 // Add argument to the argument map! 117 if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i], 118 O)).second) { 119 cerr << ProgramName << ": CommandLine Error: Argument '" 120 << OptionNames[0] << "' defined more than once!\n"; 121 } 122 } 123 124 OptionNames.clear(); 125 126 // Remember information about positional options. 127 if (O->getFormattingFlag() == cl::Positional) 128 PositionalOpts.push_back(O); 129 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 130 if (CAOpt) 131 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 132 CAOpt = O; 133 } 134 } 135 136 if (CAOpt) 137 PositionalOpts.push_back(CAOpt); 138 139 // Make sure that they are in order of registration not backwards. 140 std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 141 } 142 143 144 /// LookupOption - Lookup the option specified by the specified option on the 145 /// command line. If there is a value specified (after an equal sign) return 146 /// that as well. 147 static Option *LookupOption(const char *&Arg, const char *&Value, 148 std::map<std::string, Option*> &OptionsMap) { 149 while (*Arg == '-') ++Arg; // Eat leading dashes 150 151 const char *ArgEnd = Arg; 152 while (*ArgEnd && *ArgEnd != '=') 153 ++ArgEnd; // Scan till end of argument name. 154 155 if (*ArgEnd == '=') // If we have an equals sign... 156 Value = ArgEnd+1; // Get the value, not the equals 157 158 159 if (*Arg == 0) return 0; 160 161 // Look up the option. 162 std::map<std::string, Option*>::iterator I = 163 OptionsMap.find(std::string(Arg, ArgEnd)); 164 return I != OptionsMap.end() ? I->second : 0; 165 } 166 167 static inline bool ProvideOption(Option *Handler, const char *ArgName, 168 const char *Value, int argc, char **argv, 169 int &i) { 170 // Enforce value requirements 171 switch (Handler->getValueExpectedFlag()) { 172 case ValueRequired: 173 if (Value == 0) { // No value specified? 174 if (i+1 < argc) { // Steal the next argument, like for '-o filename' 175 Value = argv[++i]; 176 } else { 177 return Handler->error(" requires a value!"); 178 } 179 } 180 break; 181 case ValueDisallowed: 182 if (Value) 183 return Handler->error(" does not allow a value! '" + 184 std::string(Value) + "' specified."); 185 break; 186 case ValueOptional: 187 break; 188 default: 189 cerr << ProgramName 190 << ": Bad ValueMask flag! CommandLine usage error:" 191 << Handler->getValueExpectedFlag() << "\n"; 192 abort(); 193 break; 194 } 195 196 // Run the handler now! 197 return Handler->addOccurrence(i, ArgName, Value ? Value : ""); 198 } 199 200 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg, 201 int i) { 202 int Dummy = i; 203 return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy); 204 } 205 206 207 // Option predicates... 208 static inline bool isGrouping(const Option *O) { 209 return O->getFormattingFlag() == cl::Grouping; 210 } 211 static inline bool isPrefixedOrGrouping(const Option *O) { 212 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 213 } 214 215 // getOptionPred - Check to see if there are any options that satisfy the 216 // specified predicate with names that are the prefixes in Name. This is 217 // checked by progressively stripping characters off of the name, checking to 218 // see if there options that satisfy the predicate. If we find one, return it, 219 // otherwise return null. 220 // 221 static Option *getOptionPred(std::string Name, unsigned &Length, 222 bool (*Pred)(const Option*), 223 std::map<std::string, Option*> &OptionsMap) { 224 225 std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name); 226 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 227 Length = Name.length(); 228 return OMI->second; 229 } 230 231 if (Name.size() == 1) return 0; 232 do { 233 Name.erase(Name.end()-1, Name.end()); // Chop off the last character... 234 OMI = OptionsMap.find(Name); 235 236 // Loop while we haven't found an option and Name still has at least two 237 // characters in it (so that the next iteration will not be the empty 238 // string... 239 } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1); 240 241 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 242 Length = Name.length(); 243 return OMI->second; // Found one! 244 } 245 return 0; // No option found! 246 } 247 248 static bool RequiresValue(const Option *O) { 249 return O->getNumOccurrencesFlag() == cl::Required || 250 O->getNumOccurrencesFlag() == cl::OneOrMore; 251 } 252 253 static bool EatsUnboundedNumberOfValues(const Option *O) { 254 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 255 O->getNumOccurrencesFlag() == cl::OneOrMore; 256 } 257 258 /// ParseCStringVector - Break INPUT up wherever one or more 259 /// whitespace characters are found, and store the resulting tokens in 260 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated 261 /// using strdup (), so it is the caller's responsibility to free () 262 /// them later. 263 /// 264 static void ParseCStringVector(std::vector<char *> &output, 265 const char *input) { 266 // Characters which will be treated as token separators: 267 static const char *delims = " \v\f\t\r\n"; 268 269 std::string work (input); 270 // Skip past any delims at head of input string. 271 size_t pos = work.find_first_not_of (delims); 272 // If the string consists entirely of delims, then exit early. 273 if (pos == std::string::npos) return; 274 // Otherwise, jump forward to beginning of first word. 275 work = work.substr (pos); 276 // Find position of first delimiter. 277 pos = work.find_first_of (delims); 278 279 while (!work.empty() && pos != std::string::npos) { 280 // Everything from 0 to POS is the next word to copy. 281 output.push_back (strdup (work.substr (0,pos).c_str ())); 282 // Is there another word in the string? 283 size_t nextpos = work.find_first_not_of (delims, pos + 1); 284 if (nextpos != std::string::npos) { 285 // Yes? Then remove delims from beginning ... 286 work = work.substr (work.find_first_not_of (delims, pos + 1)); 287 // and find the end of the word. 288 pos = work.find_first_of (delims); 289 } else { 290 // No? (Remainder of string is delims.) End the loop. 291 work = ""; 292 pos = std::string::npos; 293 } 294 } 295 296 // If `input' ended with non-delim char, then we'll get here with 297 // the last word of `input' in `work'; copy it now. 298 if (!work.empty ()) { 299 output.push_back (strdup (work.c_str ())); 300 } 301 } 302 303 /// ParseEnvironmentOptions - An alternative entry point to the 304 /// CommandLine library, which allows you to read the program's name 305 /// from the caller (as PROGNAME) and its command-line arguments from 306 /// an environment variable (whose name is given in ENVVAR). 307 /// 308 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 309 const char *Overview) { 310 // Check args. 311 assert(progName && "Program name not specified"); 312 assert(envVar && "Environment variable name missing"); 313 314 // Get the environment variable they want us to parse options out of. 315 const char *envValue = getenv(envVar); 316 if (!envValue) 317 return; 318 319 // Get program's "name", which we wouldn't know without the caller 320 // telling us. 321 std::vector<char*> newArgv; 322 newArgv.push_back(strdup(progName)); 323 324 // Parse the value of the environment variable into a "command line" 325 // and hand it off to ParseCommandLineOptions(). 326 ParseCStringVector(newArgv, envValue); 327 int newArgc = newArgv.size(); 328 ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 329 330 // Free all the strdup()ed strings. 331 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 332 i != e; ++i) 333 free (*i); 334 } 335 336 void cl::ParseCommandLineOptions(int argc, char **argv, 337 const char *Overview) { 338 // Process all registered options. 339 std::vector<Option*> PositionalOpts; 340 std::map<std::string, Option*> Opts; 341 GetOptionInfo(PositionalOpts, Opts); 342 343 assert((!Opts.empty() || !PositionalOpts.empty()) && 344 "No options specified!"); 345 sys::Path progname(argv[0]); 346 347 // Copy the program name into ProgName, making sure not to overflow it. 348 std::string ProgName = sys::Path(argv[0]).getLast(); 349 if (ProgName.size() > 79) ProgName.resize(79); 350 strcpy(ProgramName, ProgName.c_str()); 351 352 ProgramOverview = Overview; 353 bool ErrorParsing = false; 354 355 // Check out the positional arguments to collect information about them. 356 unsigned NumPositionalRequired = 0; 357 358 // Determine whether or not there are an unlimited number of positionals 359 bool HasUnlimitedPositionals = false; 360 361 Option *ConsumeAfterOpt = 0; 362 if (!PositionalOpts.empty()) { 363 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 364 assert(PositionalOpts.size() > 1 && 365 "Cannot specify cl::ConsumeAfter without a positional argument!"); 366 ConsumeAfterOpt = PositionalOpts[0]; 367 } 368 369 // Calculate how many positional values are _required_. 370 bool UnboundedFound = false; 371 for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 372 i != e; ++i) { 373 Option *Opt = PositionalOpts[i]; 374 if (RequiresValue(Opt)) 375 ++NumPositionalRequired; 376 else if (ConsumeAfterOpt) { 377 // ConsumeAfter cannot be combined with "optional" positional options 378 // unless there is only one positional argument... 379 if (PositionalOpts.size() > 2) 380 ErrorParsing |= 381 Opt->error(" error - this positional option will never be matched, " 382 "because it does not Require a value, and a " 383 "cl::ConsumeAfter option is active!"); 384 } else if (UnboundedFound && !Opt->ArgStr[0]) { 385 // This option does not "require" a value... Make sure this option is 386 // not specified after an option that eats all extra arguments, or this 387 // one will never get any! 388 // 389 ErrorParsing |= Opt->error(" error - option can never match, because " 390 "another positional argument will match an " 391 "unbounded number of values, and this option" 392 " does not require a value!"); 393 } 394 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 395 } 396 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 397 } 398 399 // PositionalVals - A vector of "positional" arguments we accumulate into 400 // the process at the end... 401 // 402 std::vector<std::pair<std::string,unsigned> > PositionalVals; 403 404 // If the program has named positional arguments, and the name has been run 405 // across, keep track of which positional argument was named. Otherwise put 406 // the positional args into the PositionalVals list... 407 Option *ActivePositionalArg = 0; 408 409 // Loop over all of the arguments... processing them. 410 bool DashDashFound = false; // Have we read '--'? 411 for (int i = 1; i < argc; ++i) { 412 Option *Handler = 0; 413 const char *Value = 0; 414 const char *ArgName = ""; 415 416 // If the option list changed, this means that some command line 417 // option has just been registered or deregistered. This can occur in 418 // response to things like -load, etc. If this happens, rescan the options. 419 if (OptionListChanged) { 420 PositionalOpts.clear(); 421 Opts.clear(); 422 GetOptionInfo(PositionalOpts, Opts); 423 OptionListChanged = false; 424 } 425 426 // Check to see if this is a positional argument. This argument is 427 // considered to be positional if it doesn't start with '-', if it is "-" 428 // itself, or if we have seen "--" already. 429 // 430 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 431 // Positional argument! 432 if (ActivePositionalArg) { 433 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 434 continue; // We are done! 435 } else if (!PositionalOpts.empty()) { 436 PositionalVals.push_back(std::make_pair(argv[i],i)); 437 438 // All of the positional arguments have been fulfulled, give the rest to 439 // the consume after option... if it's specified... 440 // 441 if (PositionalVals.size() >= NumPositionalRequired && 442 ConsumeAfterOpt != 0) { 443 for (++i; i < argc; ++i) 444 PositionalVals.push_back(std::make_pair(argv[i],i)); 445 break; // Handle outside of the argument processing loop... 446 } 447 448 // Delay processing positional arguments until the end... 449 continue; 450 } 451 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 452 !DashDashFound) { 453 DashDashFound = true; // This is the mythical "--"? 454 continue; // Don't try to process it as an argument itself. 455 } else if (ActivePositionalArg && 456 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 457 // If there is a positional argument eating options, check to see if this 458 // option is another positional argument. If so, treat it as an argument, 459 // otherwise feed it to the eating positional. 460 ArgName = argv[i]+1; 461 Handler = LookupOption(ArgName, Value, Opts); 462 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 463 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 464 continue; // We are done! 465 } 466 467 } else { // We start with a '-', must be an argument... 468 ArgName = argv[i]+1; 469 Handler = LookupOption(ArgName, Value, Opts); 470 471 // Check to see if this "option" is really a prefixed or grouped argument. 472 if (Handler == 0) { 473 std::string RealName(ArgName); 474 if (RealName.size() > 1) { 475 unsigned Length = 0; 476 Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping, 477 Opts); 478 479 // If the option is a prefixed option, then the value is simply the 480 // rest of the name... so fall through to later processing, by 481 // setting up the argument name flags and value fields. 482 // 483 if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) { 484 Value = ArgName+Length; 485 assert(Opts.find(std::string(ArgName, Value)) != Opts.end() && 486 Opts.find(std::string(ArgName, Value))->second == PGOpt); 487 Handler = PGOpt; 488 } else if (PGOpt) { 489 // This must be a grouped option... handle them now. 490 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 491 492 do { 493 // Move current arg name out of RealName into RealArgName... 494 std::string RealArgName(RealName.begin(), 495 RealName.begin() + Length); 496 RealName.erase(RealName.begin(), RealName.begin() + Length); 497 498 // Because ValueRequired is an invalid flag for grouped arguments, 499 // we don't need to pass argc/argv in... 500 // 501 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 502 "Option can not be cl::Grouping AND cl::ValueRequired!"); 503 int Dummy; 504 ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), 505 0, 0, 0, Dummy); 506 507 // Get the next grouping option... 508 PGOpt = getOptionPred(RealName, Length, isGrouping, Opts); 509 } while (PGOpt && Length != RealName.size()); 510 511 Handler = PGOpt; // Ate all of the options. 512 } 513 } 514 } 515 } 516 517 if (Handler == 0) { 518 cerr << ProgramName << ": Unknown command line argument '" 519 << argv[i] << "'. Try: '" << argv[0] << " --help'\n"; 520 ErrorParsing = true; 521 continue; 522 } 523 524 // Check to see if this option accepts a comma separated list of values. If 525 // it does, we have to split up the value into multiple values... 526 if (Value && Handler->getMiscFlags() & CommaSeparated) { 527 std::string Val(Value); 528 std::string::size_type Pos = Val.find(','); 529 530 while (Pos != std::string::npos) { 531 // Process the portion before the comma... 532 ErrorParsing |= ProvideOption(Handler, ArgName, 533 std::string(Val.begin(), 534 Val.begin()+Pos).c_str(), 535 argc, argv, i); 536 // Erase the portion before the comma, AND the comma... 537 Val.erase(Val.begin(), Val.begin()+Pos+1); 538 Value += Pos+1; // Increment the original value pointer as well... 539 540 // Check for another comma... 541 Pos = Val.find(','); 542 } 543 } 544 545 // If this is a named positional argument, just remember that it is the 546 // active one... 547 if (Handler->getFormattingFlag() == cl::Positional) 548 ActivePositionalArg = Handler; 549 else 550 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 551 } 552 553 // Check and handle positional arguments now... 554 if (NumPositionalRequired > PositionalVals.size()) { 555 cerr << ProgramName 556 << ": Not enough positional command line arguments specified!\n" 557 << "Must specify at least " << NumPositionalRequired 558 << " positional arguments: See: " << argv[0] << " --help\n"; 559 560 ErrorParsing = true; 561 } else if (!HasUnlimitedPositionals 562 && PositionalVals.size() > PositionalOpts.size()) { 563 cerr << ProgramName 564 << ": Too many positional arguments specified!\n" 565 << "Can specify at most " << PositionalOpts.size() 566 << " positional arguments: See: " << argv[0] << " --help\n"; 567 ErrorParsing = true; 568 569 } else if (ConsumeAfterOpt == 0) { 570 // Positional args have already been handled if ConsumeAfter is specified... 571 unsigned ValNo = 0, NumVals = PositionalVals.size(); 572 for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) { 573 if (RequiresValue(PositionalOpts[i])) { 574 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 575 PositionalVals[ValNo].second); 576 ValNo++; 577 --NumPositionalRequired; // We fulfilled our duty... 578 } 579 580 // If we _can_ give this option more arguments, do so now, as long as we 581 // do not give it values that others need. 'Done' controls whether the 582 // option even _WANTS_ any more. 583 // 584 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 585 while (NumVals-ValNo > NumPositionalRequired && !Done) { 586 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 587 case cl::Optional: 588 Done = true; // Optional arguments want _at most_ one value 589 // FALL THROUGH 590 case cl::ZeroOrMore: // Zero or more will take all they can get... 591 case cl::OneOrMore: // One or more will take all they can get... 592 ProvidePositionalOption(PositionalOpts[i], 593 PositionalVals[ValNo].first, 594 PositionalVals[ValNo].second); 595 ValNo++; 596 break; 597 default: 598 assert(0 && "Internal error, unexpected NumOccurrences flag in " 599 "positional argument processing!"); 600 } 601 } 602 } 603 } else { 604 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 605 unsigned ValNo = 0; 606 for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j) 607 if (RequiresValue(PositionalOpts[j])) { 608 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 609 PositionalVals[ValNo].first, 610 PositionalVals[ValNo].second); 611 ValNo++; 612 } 613 614 // Handle the case where there is just one positional option, and it's 615 // optional. In this case, we want to give JUST THE FIRST option to the 616 // positional option and keep the rest for the consume after. The above 617 // loop would have assigned no values to positional options in this case. 618 // 619 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 620 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 621 PositionalVals[ValNo].first, 622 PositionalVals[ValNo].second); 623 ValNo++; 624 } 625 626 // Handle over all of the rest of the arguments to the 627 // cl::ConsumeAfter command line option... 628 for (; ValNo != PositionalVals.size(); ++ValNo) 629 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 630 PositionalVals[ValNo].first, 631 PositionalVals[ValNo].second); 632 } 633 634 // Loop over args and make sure all required args are specified! 635 for (std::map<std::string, Option*>::iterator I = Opts.begin(), 636 E = Opts.end(); I != E; ++I) { 637 switch (I->second->getNumOccurrencesFlag()) { 638 case Required: 639 case OneOrMore: 640 if (I->second->getNumOccurrences() == 0) { 641 I->second->error(" must be specified at least once!"); 642 ErrorParsing = true; 643 } 644 // Fall through 645 default: 646 break; 647 } 648 } 649 650 // Free all of the memory allocated to the map. Command line options may only 651 // be processed once! 652 Opts.clear(); 653 PositionalOpts.clear(); 654 MoreHelp->clear(); 655 656 // If we had an error processing our arguments, don't let the program execute 657 if (ErrorParsing) exit(1); 658 } 659 660 //===----------------------------------------------------------------------===// 661 // Option Base class implementation 662 // 663 664 bool Option::error(std::string Message, const char *ArgName) { 665 if (ArgName == 0) ArgName = ArgStr; 666 if (ArgName[0] == 0) 667 cerr << HelpStr; // Be nice for positional arguments 668 else 669 cerr << ProgramName << ": for the -" << ArgName; 670 671 cerr << " option: " << Message << "\n"; 672 return true; 673 } 674 675 bool Option::addOccurrence(unsigned pos, const char *ArgName, 676 const std::string &Value) { 677 NumOccurrences++; // Increment the number of times we have been seen 678 679 switch (getNumOccurrencesFlag()) { 680 case Optional: 681 if (NumOccurrences > 1) 682 return error(": may only occur zero or one times!", ArgName); 683 break; 684 case Required: 685 if (NumOccurrences > 1) 686 return error(": must occur exactly one time!", ArgName); 687 // Fall through 688 case OneOrMore: 689 case ZeroOrMore: 690 case ConsumeAfter: break; 691 default: return error(": bad num occurrences flag value!"); 692 } 693 694 return handleOccurrence(pos, ArgName, Value); 695 } 696 697 698 // getValueStr - Get the value description string, using "DefaultMsg" if nothing 699 // has been specified yet. 700 // 701 static const char *getValueStr(const Option &O, const char *DefaultMsg) { 702 if (O.ValueStr[0] == 0) return DefaultMsg; 703 return O.ValueStr; 704 } 705 706 //===----------------------------------------------------------------------===// 707 // cl::alias class implementation 708 // 709 710 // Return the width of the option tag for printing... 711 unsigned alias::getOptionWidth() const { 712 return std::strlen(ArgStr)+6; 713 } 714 715 // Print out the option for the alias. 716 void alias::printOptionInfo(unsigned GlobalWidth) const { 717 unsigned L = std::strlen(ArgStr); 718 cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - " 719 << HelpStr << "\n"; 720 } 721 722 723 724 //===----------------------------------------------------------------------===// 725 // Parser Implementation code... 726 // 727 728 // basic_parser implementation 729 // 730 731 // Return the width of the option tag for printing... 732 unsigned basic_parser_impl::getOptionWidth(const Option &O) const { 733 unsigned Len = std::strlen(O.ArgStr); 734 if (const char *ValName = getValueName()) 735 Len += std::strlen(getValueStr(O, ValName))+3; 736 737 return Len + 6; 738 } 739 740 // printOptionInfo - Print out information about this option. The 741 // to-be-maintained width is specified. 742 // 743 void basic_parser_impl::printOptionInfo(const Option &O, 744 unsigned GlobalWidth) const { 745 cout << " -" << O.ArgStr; 746 747 if (const char *ValName = getValueName()) 748 cout << "=<" << getValueStr(O, ValName) << ">"; 749 750 cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - " 751 << O.HelpStr << "\n"; 752 } 753 754 755 756 757 // parser<bool> implementation 758 // 759 bool parser<bool>::parse(Option &O, const char *ArgName, 760 const std::string &Arg, bool &Value) { 761 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 762 Arg == "1") { 763 Value = true; 764 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 765 Value = false; 766 } else { 767 return O.error(": '" + Arg + 768 "' is invalid value for boolean argument! Try 0 or 1"); 769 } 770 return false; 771 } 772 773 // parser<boolOrDefault> implementation 774 // 775 bool parser<boolOrDefault>::parse(Option &O, const char *ArgName, 776 const std::string &Arg, boolOrDefault &Value) { 777 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 778 Arg == "1") { 779 Value = BOU_TRUE; 780 } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 781 Value = BOU_FALSE; 782 } else { 783 return O.error(": '" + Arg + 784 "' is invalid value for boolean argument! Try 0 or 1"); 785 } 786 return false; 787 } 788 789 // parser<int> implementation 790 // 791 bool parser<int>::parse(Option &O, const char *ArgName, 792 const std::string &Arg, int &Value) { 793 char *End; 794 Value = (int)strtol(Arg.c_str(), &End, 0); 795 if (*End != 0) 796 return O.error(": '" + Arg + "' value invalid for integer argument!"); 797 return false; 798 } 799 800 // parser<unsigned> implementation 801 // 802 bool parser<unsigned>::parse(Option &O, const char *ArgName, 803 const std::string &Arg, unsigned &Value) { 804 char *End; 805 errno = 0; 806 unsigned long V = strtoul(Arg.c_str(), &End, 0); 807 Value = (unsigned)V; 808 if (((V == ULONG_MAX) && (errno == ERANGE)) 809 || (*End != 0) 810 || (Value != V)) 811 return O.error(": '" + Arg + "' value invalid for uint argument!"); 812 return false; 813 } 814 815 // parser<double>/parser<float> implementation 816 // 817 static bool parseDouble(Option &O, const std::string &Arg, double &Value) { 818 const char *ArgStart = Arg.c_str(); 819 char *End; 820 Value = strtod(ArgStart, &End); 821 if (*End != 0) 822 return O.error(": '" +Arg+ "' value invalid for floating point argument!"); 823 return false; 824 } 825 826 bool parser<double>::parse(Option &O, const char *AN, 827 const std::string &Arg, double &Val) { 828 return parseDouble(O, Arg, Val); 829 } 830 831 bool parser<float>::parse(Option &O, const char *AN, 832 const std::string &Arg, float &Val) { 833 double dVal; 834 if (parseDouble(O, Arg, dVal)) 835 return true; 836 Val = (float)dVal; 837 return false; 838 } 839 840 841 842 // generic_parser_base implementation 843 // 844 845 // findOption - Return the option number corresponding to the specified 846 // argument string. If the option is not found, getNumOptions() is returned. 847 // 848 unsigned generic_parser_base::findOption(const char *Name) { 849 unsigned i = 0, e = getNumOptions(); 850 std::string N(Name); 851 852 while (i != e) 853 if (getOption(i) == N) 854 return i; 855 else 856 ++i; 857 return e; 858 } 859 860 861 // Return the width of the option tag for printing... 862 unsigned generic_parser_base::getOptionWidth(const Option &O) const { 863 if (O.hasArgStr()) { 864 unsigned Size = std::strlen(O.ArgStr)+6; 865 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 866 Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8); 867 return Size; 868 } else { 869 unsigned BaseSize = 0; 870 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 871 BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8); 872 return BaseSize; 873 } 874 } 875 876 // printOptionInfo - Print out information about this option. The 877 // to-be-maintained width is specified. 878 // 879 void generic_parser_base::printOptionInfo(const Option &O, 880 unsigned GlobalWidth) const { 881 if (O.hasArgStr()) { 882 unsigned L = std::strlen(O.ArgStr); 883 cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ') 884 << " - " << O.HelpStr << "\n"; 885 886 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 887 unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8; 888 cout << " =" << getOption(i) << std::string(NumSpaces, ' ') 889 << " - " << getDescription(i) << "\n"; 890 } 891 } else { 892 if (O.HelpStr[0]) 893 cout << " " << O.HelpStr << "\n"; 894 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 895 unsigned L = std::strlen(getOption(i)); 896 cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ') 897 << " - " << getDescription(i) << "\n"; 898 } 899 } 900 } 901 902 903 //===----------------------------------------------------------------------===// 904 // --help and --help-hidden option implementation 905 // 906 907 namespace { 908 909 class HelpPrinter { 910 unsigned MaxArgLen; 911 const Option *EmptyArg; 912 const bool ShowHidden; 913 914 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists. 915 inline static bool isHidden(std::pair<std::string, Option *> &OptPair) { 916 return OptPair.second->getOptionHiddenFlag() >= Hidden; 917 } 918 inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) { 919 return OptPair.second->getOptionHiddenFlag() == ReallyHidden; 920 } 921 922 public: 923 HelpPrinter(bool showHidden) : ShowHidden(showHidden) { 924 EmptyArg = 0; 925 } 926 927 void operator=(bool Value) { 928 if (Value == false) return; 929 930 // Get all the options. 931 std::vector<Option*> PositionalOpts; 932 std::map<std::string, Option*> OptMap; 933 GetOptionInfo(PositionalOpts, OptMap); 934 935 // Copy Options into a vector so we can sort them as we like... 936 std::vector<std::pair<std::string, Option*> > Opts; 937 copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts)); 938 939 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden 940 Opts.erase(std::remove_if(Opts.begin(), Opts.end(), 941 std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)), 942 Opts.end()); 943 944 // Eliminate duplicate entries in table (from enum flags options, f.e.) 945 { // Give OptionSet a scope 946 std::set<Option*> OptionSet; 947 for (unsigned i = 0; i != Opts.size(); ++i) 948 if (OptionSet.count(Opts[i].second) == 0) 949 OptionSet.insert(Opts[i].second); // Add new entry to set 950 else 951 Opts.erase(Opts.begin()+i--); // Erase duplicate 952 } 953 954 if (ProgramOverview) 955 cout << "OVERVIEW: " << ProgramOverview << "\n"; 956 957 cout << "USAGE: " << ProgramName << " [options]"; 958 959 // Print out the positional options. 960 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 961 if (!PositionalOpts.empty() && 962 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 963 CAOpt = PositionalOpts[0]; 964 965 for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 966 if (PositionalOpts[i]->ArgStr[0]) 967 cout << " --" << PositionalOpts[i]->ArgStr; 968 cout << " " << PositionalOpts[i]->HelpStr; 969 } 970 971 // Print the consume after option info if it exists... 972 if (CAOpt) cout << " " << CAOpt->HelpStr; 973 974 cout << "\n\n"; 975 976 // Compute the maximum argument length... 977 MaxArgLen = 0; 978 for (unsigned i = 0, e = Opts.size(); i != e; ++i) 979 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 980 981 cout << "OPTIONS:\n"; 982 for (unsigned i = 0, e = Opts.size(); i != e; ++i) 983 Opts[i].second->printOptionInfo(MaxArgLen); 984 985 // Print any extra help the user has declared. 986 for (std::vector<const char *>::iterator I = MoreHelp->begin(), 987 E = MoreHelp->end(); I != E; ++I) 988 cout << *I; 989 MoreHelp->clear(); 990 991 // Halt the program since help information was printed 992 exit(1); 993 } 994 }; 995 } // End anonymous namespace 996 997 // Define the two HelpPrinter instances that are used to print out help, or 998 // help-hidden... 999 // 1000 static HelpPrinter NormalPrinter(false); 1001 static HelpPrinter HiddenPrinter(true); 1002 1003 static cl::opt<HelpPrinter, true, parser<bool> > 1004 HOp("help", cl::desc("Display available options (--help-hidden for more)"), 1005 cl::location(NormalPrinter), cl::ValueDisallowed); 1006 1007 static cl::opt<HelpPrinter, true, parser<bool> > 1008 HHOp("help-hidden", cl::desc("Display all available options"), 1009 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1010 1011 static void (*OverrideVersionPrinter)() = 0; 1012 1013 namespace { 1014 class VersionPrinter { 1015 public: 1016 void print() { 1017 cout << "Low Level Virtual Machine (http://llvm.org/):\n"; 1018 cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1019 #ifdef LLVM_VERSION_INFO 1020 cout << LLVM_VERSION_INFO; 1021 #endif 1022 cout << "\n "; 1023 #ifndef __OPTIMIZE__ 1024 cout << "DEBUG build"; 1025 #else 1026 cout << "Optimized build"; 1027 #endif 1028 #ifndef NDEBUG 1029 cout << " with assertions"; 1030 #endif 1031 cout << ".\n"; 1032 } 1033 void operator=(bool OptionWasSpecified) { 1034 if (OptionWasSpecified) { 1035 if (OverrideVersionPrinter == 0) { 1036 print(); 1037 exit(1); 1038 } else { 1039 (*OverrideVersionPrinter)(); 1040 exit(1); 1041 } 1042 } 1043 } 1044 }; 1045 } // End anonymous namespace 1046 1047 1048 // Define the --version option that prints out the LLVM version for the tool 1049 static VersionPrinter VersionPrinterInstance; 1050 1051 static cl::opt<VersionPrinter, true, parser<bool> > 1052 VersOp("version", cl::desc("Display the version of this program"), 1053 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1054 1055 // Utility function for printing the help message. 1056 void cl::PrintHelpMessage() { 1057 // This looks weird, but it actually prints the help message. The 1058 // NormalPrinter variable is a HelpPrinter and the help gets printed when 1059 // its operator= is invoked. That's because the "normal" usages of the 1060 // help printer is to be assigned true/false depending on whether the 1061 // --help option was given or not. Since we're circumventing that we have 1062 // to make it look like --help was given, so we assign true. 1063 NormalPrinter = true; 1064 } 1065 1066 /// Utility function for printing version number. 1067 void cl::PrintVersionMessage() { 1068 VersionPrinterInstance.print(); 1069 } 1070 1071 void cl::SetVersionPrinter(void (*func)()) { 1072 OverrideVersionPrinter = func; 1073 } 1074