1193323Sed//===-- CommandLine.cpp - Command line parser implementation --------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This class implements a command line argument processor that is useful when 11193323Sed// creating a tool. It provides a simple, minimalistic interface that is easily 12193323Sed// extensible and supports nonlocal (library) command line options. 13193323Sed// 14193323Sed// Note that rather than trying to figure out what this code does, you could try 15193323Sed// reading the library documentation located in docs/CommandLine.html 16193323Sed// 17193323Sed//===----------------------------------------------------------------------===// 18193323Sed 19193323Sed#include "llvm/Support/CommandLine.h" 20280031Sdim#include "llvm-c/Support.h" 21261991Sdim#include "llvm/ADT/ArrayRef.h" 22288943Sdim#include "llvm/ADT/STLExtras.h" 23198090Srdivacky#include "llvm/ADT/SmallPtrSet.h" 24198090Srdivacky#include "llvm/ADT/SmallString.h" 25198090Srdivacky#include "llvm/ADT/StringMap.h" 26198090Srdivacky#include "llvm/ADT/Twine.h" 27198090Srdivacky#include "llvm/Config/config.h" 28261991Sdim#include "llvm/Support/ConvertUTF.h" 29249423Sdim#include "llvm/Support/Debug.h" 30249423Sdim#include "llvm/Support/ErrorHandling.h" 31249423Sdim#include "llvm/Support/Host.h" 32249423Sdim#include "llvm/Support/ManagedStatic.h" 33249423Sdim#include "llvm/Support/MemoryBuffer.h" 34249423Sdim#include "llvm/Support/Path.h" 35288943Sdim#include "llvm/Support/StringSaver.h" 36249423Sdim#include "llvm/Support/raw_ostream.h" 37193323Sed#include <cstdlib> 38251662Sdim#include <map> 39193323Sedusing namespace llvm; 40193323Sedusing namespace cl; 41193323Sed 42276479Sdim#define DEBUG_TYPE "commandline" 43276479Sdim 44193323Sed//===----------------------------------------------------------------------===// 45193323Sed// Template instantiations and anchors. 46193323Sed// 47280031Sdimnamespace llvm { 48280031Sdimnamespace cl { 49288943Sdimtemplate class basic_parser<bool>; 50288943Sdimtemplate class basic_parser<boolOrDefault>; 51288943Sdimtemplate class basic_parser<int>; 52288943Sdimtemplate class basic_parser<unsigned>; 53288943Sdimtemplate class basic_parser<unsigned long long>; 54288943Sdimtemplate class basic_parser<double>; 55288943Sdimtemplate class basic_parser<float>; 56288943Sdimtemplate class basic_parser<std::string>; 57288943Sdimtemplate class basic_parser<char>; 58193323Sed 59288943Sdimtemplate class opt<unsigned>; 60288943Sdimtemplate class opt<int>; 61288943Sdimtemplate class opt<std::string>; 62288943Sdimtemplate class opt<char>; 63288943Sdimtemplate class opt<bool>; 64280031Sdim} 65280031Sdim} // end namespace llvm::cl 66193323Sed 67261991Sdim// Pin the vtables to this file. 68234353Sdimvoid GenericOptionValue::anchor() {} 69234353Sdimvoid OptionValue<boolOrDefault>::anchor() {} 70234353Sdimvoid OptionValue<std::string>::anchor() {} 71193323Sedvoid Option::anchor() {} 72193323Sedvoid basic_parser_impl::anchor() {} 73193323Sedvoid parser<bool>::anchor() {} 74193323Sedvoid parser<boolOrDefault>::anchor() {} 75193323Sedvoid parser<int>::anchor() {} 76193323Sedvoid parser<unsigned>::anchor() {} 77226633Sdimvoid parser<unsigned long long>::anchor() {} 78193323Sedvoid parser<double>::anchor() {} 79193323Sedvoid parser<float>::anchor() {} 80193323Sedvoid parser<std::string>::anchor() {} 81193323Sedvoid parser<char>::anchor() {} 82193323Sed 83193323Sed//===----------------------------------------------------------------------===// 84193323Sed 85288943Sdimnamespace { 86193323Sed 87288943Sdimclass CommandLineParser { 88288943Sdimpublic: 89288943Sdim // Globals for name and overview of program. Program name is not a string to 90288943Sdim // avoid static ctor/dtor issues. 91288943Sdim std::string ProgramName; 92288943Sdim const char *ProgramOverview; 93193323Sed 94288943Sdim // This collects additional help to be printed. 95288943Sdim std::vector<const char *> MoreHelp; 96193323Sed 97288943Sdim SmallVector<Option *, 4> PositionalOpts; 98288943Sdim SmallVector<Option *, 4> SinkOpts; 99288943Sdim StringMap<Option *> OptionsMap; 100193323Sed 101288943Sdim Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists. 102193323Sed 103288943Sdim // This collects the different option categories that have been registered. 104288943Sdim SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories; 105193323Sed 106288943Sdim CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {} 107193323Sed 108288943Sdim void ParseCommandLineOptions(int argc, const char *const *argv, 109288943Sdim const char *Overview); 110193323Sed 111288943Sdim void addLiteralOption(Option &Opt, const char *Name) { 112288943Sdim if (!Opt.hasArgStr()) { 113288943Sdim if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) { 114288943Sdim errs() << ProgramName << ": CommandLine Error: Option '" << Name 115288943Sdim << "' registered more than once!\n"; 116288943Sdim report_fatal_error("inconsistency in registered CommandLine options"); 117288943Sdim } 118288943Sdim } 119280031Sdim } 120276479Sdim 121288943Sdim void addOption(Option *O) { 122288943Sdim bool HadErrors = false; 123296417Sdim if (O->hasArgStr()) { 124193323Sed // Add argument to the argument map! 125288943Sdim if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) { 126288943Sdim errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr 127288943Sdim << "' registered more than once!\n"; 128276479Sdim HadErrors = true; 129193323Sed } 130193323Sed } 131193323Sed 132193323Sed // Remember information about positional options. 133193323Sed if (O->getFormattingFlag() == cl::Positional) 134193323Sed PositionalOpts.push_back(O); 135193323Sed else if (O->getMiscFlags() & cl::Sink) // Remember sink options 136193323Sed SinkOpts.push_back(O); 137193323Sed else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 138288943Sdim if (ConsumeAfterOpt) { 139193323Sed O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 140276479Sdim HadErrors = true; 141276479Sdim } 142288943Sdim ConsumeAfterOpt = O; 143193323Sed } 144288943Sdim 145288943Sdim // Fail hard if there were errors. These are strictly unrecoverable and 146288943Sdim // indicate serious issues such as conflicting option names or an 147288943Sdim // incorrectly 148288943Sdim // linked LLVM distribution. 149288943Sdim if (HadErrors) 150288943Sdim report_fatal_error("inconsistency in registered CommandLine options"); 151193323Sed } 152193323Sed 153288943Sdim void removeOption(Option *O) { 154296417Sdim SmallVector<StringRef, 16> OptionNames; 155288943Sdim O->getExtraOptionNames(OptionNames); 156296417Sdim if (O->hasArgStr()) 157288943Sdim OptionNames.push_back(O->ArgStr); 158288943Sdim for (auto Name : OptionNames) 159296417Sdim OptionsMap.erase(Name); 160193323Sed 161288943Sdim if (O->getFormattingFlag() == cl::Positional) 162288943Sdim for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end(); 163288943Sdim ++Opt) { 164288943Sdim if (*Opt == O) { 165288943Sdim PositionalOpts.erase(Opt); 166288943Sdim break; 167288943Sdim } 168288943Sdim } 169288943Sdim else if (O->getMiscFlags() & cl::Sink) 170288943Sdim for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) { 171288943Sdim if (*Opt == O) { 172288943Sdim SinkOpts.erase(Opt); 173288943Sdim break; 174288943Sdim } 175288943Sdim } 176288943Sdim else if (O == ConsumeAfterOpt) 177288943Sdim ConsumeAfterOpt = nullptr; 178288943Sdim } 179276479Sdim 180288943Sdim bool hasOptions() { 181288943Sdim return (!OptionsMap.empty() || !PositionalOpts.empty() || 182288943Sdim nullptr != ConsumeAfterOpt); 183288943Sdim } 184288943Sdim 185296417Sdim void updateArgStr(Option *O, StringRef NewName) { 186288943Sdim if (!OptionsMap.insert(std::make_pair(NewName, O)).second) { 187288943Sdim errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr 188288943Sdim << "' registered more than once!\n"; 189288943Sdim report_fatal_error("inconsistency in registered CommandLine options"); 190288943Sdim } 191296417Sdim OptionsMap.erase(O->ArgStr); 192288943Sdim } 193288943Sdim 194288943Sdim void printOptionValues(); 195288943Sdim 196288943Sdim void registerCategory(OptionCategory *cat) { 197288943Sdim assert(std::count_if(RegisteredOptionCategories.begin(), 198288943Sdim RegisteredOptionCategories.end(), 199288943Sdim [cat](const OptionCategory *Category) { 200288943Sdim return cat->getName() == Category->getName(); 201288943Sdim }) == 0 && 202288943Sdim "Duplicate option categories"); 203288943Sdim 204288943Sdim RegisteredOptionCategories.insert(cat); 205288943Sdim } 206288943Sdim 207288943Sdimprivate: 208288943Sdim Option *LookupOption(StringRef &Arg, StringRef &Value); 209288943Sdim}; 210288943Sdim 211288943Sdim} // namespace 212288943Sdim 213288943Sdimstatic ManagedStatic<CommandLineParser> GlobalParser; 214288943Sdim 215288943Sdimvoid cl::AddLiteralOption(Option &O, const char *Name) { 216288943Sdim GlobalParser->addLiteralOption(O, Name); 217193323Sed} 218193323Sed 219288943Sdimextrahelp::extrahelp(const char *Help) : morehelp(Help) { 220288943Sdim GlobalParser->MoreHelp.push_back(Help); 221288943Sdim} 222288943Sdim 223288943Sdimvoid Option::addArgument() { 224288943Sdim GlobalParser->addOption(this); 225288943Sdim FullyInitialized = true; 226288943Sdim} 227288943Sdim 228288943Sdimvoid Option::removeArgument() { GlobalParser->removeOption(this); } 229288943Sdim 230296417Sdimvoid Option::setArgStr(StringRef S) { 231288943Sdim if (FullyInitialized) 232288943Sdim GlobalParser->updateArgStr(this, S); 233288943Sdim ArgStr = S; 234288943Sdim} 235288943Sdim 236288943Sdim// Initialise the general option category. 237288943SdimOptionCategory llvm::cl::GeneralCategory("General options"); 238288943Sdim 239288943Sdimvoid OptionCategory::registerCategory() { 240288943Sdim GlobalParser->registerCategory(this); 241288943Sdim} 242288943Sdim 243288943Sdim//===----------------------------------------------------------------------===// 244288943Sdim// Basic, shared command line option processing machinery. 245288943Sdim// 246288943Sdim 247193323Sed/// LookupOption - Lookup the option specified by the specified option on the 248193323Sed/// command line. If there is a value specified (after an equal sign) return 249198090Srdivacky/// that as well. This assumes that leading dashes have already been stripped. 250288943SdimOption *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) { 251198090Srdivacky // Reject all dashes. 252280031Sdim if (Arg.empty()) 253280031Sdim return nullptr; 254199989Srdivacky 255198090Srdivacky size_t EqualPos = Arg.find('='); 256199989Srdivacky 257198090Srdivacky // If we have an equals sign, remember the value. 258198090Srdivacky if (EqualPos == StringRef::npos) { 259198090Srdivacky // Look up the option. 260280031Sdim StringMap<Option *>::const_iterator I = OptionsMap.find(Arg); 261276479Sdim return I != OptionsMap.end() ? I->second : nullptr; 262198090Srdivacky } 263193323Sed 264198090Srdivacky // If the argument before the = is a valid option name, we match. If not, 265198090Srdivacky // return Arg unmolested. 266280031Sdim StringMap<Option *>::const_iterator I = 267280031Sdim OptionsMap.find(Arg.substr(0, EqualPos)); 268280031Sdim if (I == OptionsMap.end()) 269280031Sdim return nullptr; 270199989Srdivacky 271280031Sdim Value = Arg.substr(EqualPos + 1); 272198090Srdivacky Arg = Arg.substr(0, EqualPos); 273198090Srdivacky return I->second; 274198090Srdivacky} 275193323Sed 276218893Sdim/// LookupNearestOption - Lookup the closest match to the option specified by 277218893Sdim/// the specified option on the command line. If there is a value specified 278218893Sdim/// (after an equal sign) return that as well. This assumes that leading dashes 279218893Sdim/// have already been stripped. 280218893Sdimstatic Option *LookupNearestOption(StringRef Arg, 281280031Sdim const StringMap<Option *> &OptionsMap, 282221345Sdim std::string &NearestString) { 283218893Sdim // Reject all dashes. 284280031Sdim if (Arg.empty()) 285280031Sdim return nullptr; 286218893Sdim 287218893Sdim // Split on any equal sign. 288221345Sdim std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 289280031Sdim StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 290221345Sdim StringRef &RHS = SplitArg.second; 291218893Sdim 292218893Sdim // Find the closest match. 293276479Sdim Option *Best = nullptr; 294218893Sdim unsigned BestDistance = 0; 295280031Sdim for (StringMap<Option *>::const_iterator it = OptionsMap.begin(), 296280031Sdim ie = OptionsMap.end(); 297280031Sdim it != ie; ++it) { 298218893Sdim Option *O = it->second; 299296417Sdim SmallVector<StringRef, 16> OptionNames; 300218893Sdim O->getExtraOptionNames(OptionNames); 301296417Sdim if (O->hasArgStr()) 302218893Sdim OptionNames.push_back(O->ArgStr); 303218893Sdim 304221345Sdim bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 305221345Sdim StringRef Flag = PermitValue ? LHS : Arg; 306296417Sdim for (auto Name : OptionNames) { 307218893Sdim unsigned Distance = StringRef(Name).edit_distance( 308280031Sdim Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 309218893Sdim if (!Best || Distance < BestDistance) { 310218893Sdim Best = O; 311218893Sdim BestDistance = Distance; 312239462Sdim if (RHS.empty() || !PermitValue) 313296417Sdim NearestString = Name; 314239462Sdim else 315296417Sdim NearestString = (Twine(Name) + "=" + RHS).str(); 316218893Sdim } 317218893Sdim } 318218893Sdim } 319218893Sdim 320218893Sdim return Best; 321218893Sdim} 322218893Sdim 323276479Sdim/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() 324276479Sdim/// that does special handling of cl::CommaSeparated options. 325276479Sdimstatic bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, 326276479Sdim StringRef ArgName, StringRef Value, 327276479Sdim bool MultiArg = false) { 328199989Srdivacky // Check to see if this option accepts a comma separated list of values. If 329199989Srdivacky // it does, we have to split up the value into multiple values. 330199989Srdivacky if (Handler->getMiscFlags() & CommaSeparated) { 331199989Srdivacky StringRef Val(Value); 332199989Srdivacky StringRef::size_type Pos = Val.find(','); 333193323Sed 334199989Srdivacky while (Pos != StringRef::npos) { 335199989Srdivacky // Process the portion before the comma. 336199989Srdivacky if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 337199989Srdivacky return true; 338199989Srdivacky // Erase the portion before the comma, AND the comma. 339280031Sdim Val = Val.substr(Pos + 1); 340280031Sdim Value.substr(Pos + 1); // Increment the original value pointer as well. 341199989Srdivacky // Check for another comma. 342199989Srdivacky Pos = Val.find(','); 343199989Srdivacky } 344193323Sed 345199989Srdivacky Value = Val; 346199989Srdivacky } 347199989Srdivacky 348296417Sdim return Handler->addOccurrence(pos, ArgName, Value, MultiArg); 349199989Srdivacky} 350199989Srdivacky 351198090Srdivacky/// ProvideOption - For Value, this differentiates between an empty value ("") 352198090Srdivacky/// and a null value (StringRef()). The later is accepted for arguments that 353198090Srdivacky/// don't allow a value (-foo) the former is rejected (-foo=). 354198090Srdivackystatic inline bool ProvideOption(Option *Handler, StringRef ArgName, 355234353Sdim StringRef Value, int argc, 356234353Sdim const char *const *argv, int &i) { 357193323Sed // Is this a multi-argument option? 358193323Sed unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 359193323Sed 360193323Sed // Enforce value requirements 361193323Sed switch (Handler->getValueExpectedFlag()) { 362193323Sed case ValueRequired: 363276479Sdim if (!Value.data()) { // No value specified? 364280031Sdim if (i + 1 >= argc) 365198090Srdivacky return Handler->error("requires a value!"); 366198090Srdivacky // Steal the next argument, like for '-o filename' 367280031Sdim assert(argv && "null check"); 368198090Srdivacky Value = argv[++i]; 369193323Sed } 370193323Sed break; 371193323Sed case ValueDisallowed: 372193323Sed if (NumAdditionalVals > 0) 373198090Srdivacky return Handler->error("multi-valued option specified" 374198090Srdivacky " with ValueDisallowed modifier!"); 375193323Sed 376198090Srdivacky if (Value.data()) 377280031Sdim return Handler->error("does not allow a value! '" + Twine(Value) + 378280031Sdim "' specified."); 379193323Sed break; 380193323Sed case ValueOptional: 381193323Sed break; 382193323Sed } 383193323Sed 384193323Sed // If this isn't a multi-arg option, just run the handler. 385198090Srdivacky if (NumAdditionalVals == 0) 386276479Sdim return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value); 387198090Srdivacky 388193323Sed // If it is, run the handle several times. 389198090Srdivacky bool MultiArg = false; 390193323Sed 391198090Srdivacky if (Value.data()) { 392276479Sdim if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 393198090Srdivacky return true; 394198090Srdivacky --NumAdditionalVals; 395198090Srdivacky MultiArg = true; 396198090Srdivacky } 397193323Sed 398198090Srdivacky while (NumAdditionalVals > 0) { 399280031Sdim if (i + 1 >= argc) 400198090Srdivacky return Handler->error("not enough values!"); 401280031Sdim assert(argv && "null check"); 402198090Srdivacky Value = argv[++i]; 403199989Srdivacky 404276479Sdim if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg)) 405198090Srdivacky return true; 406198090Srdivacky MultiArg = true; 407198090Srdivacky --NumAdditionalVals; 408193323Sed } 409198090Srdivacky return false; 410193323Sed} 411193323Sed 412198090Srdivackystatic bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 413193323Sed int Dummy = i; 414276479Sdim return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy); 415193323Sed} 416193323Sed 417193323Sed// Option predicates... 418193323Sedstatic inline bool isGrouping(const Option *O) { 419193323Sed return O->getFormattingFlag() == cl::Grouping; 420193323Sed} 421193323Sedstatic inline bool isPrefixedOrGrouping(const Option *O) { 422193323Sed return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 423193323Sed} 424193323Sed 425193323Sed// getOptionPred - Check to see if there are any options that satisfy the 426193323Sed// specified predicate with names that are the prefixes in Name. This is 427193323Sed// checked by progressively stripping characters off of the name, checking to 428193323Sed// see if there options that satisfy the predicate. If we find one, return it, 429193323Sed// otherwise return null. 430193323Sed// 431198090Srdivackystatic Option *getOptionPred(StringRef Name, size_t &Length, 432280031Sdim bool (*Pred)(const Option *), 433280031Sdim const StringMap<Option *> &OptionsMap) { 434193323Sed 435280031Sdim StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name); 436193323Sed 437198090Srdivacky // Loop while we haven't found an option and Name still has at least two 438198090Srdivacky // characters in it (so that the next iteration will not be the empty 439198090Srdivacky // string. 440198090Srdivacky while (OMI == OptionsMap.end() && Name.size() > 1) { 441280031Sdim Name = Name.substr(0, Name.size() - 1); // Chop off the last character. 442193323Sed OMI = OptionsMap.find(Name); 443198090Srdivacky } 444193323Sed 445193323Sed if (OMI != OptionsMap.end() && Pred(OMI->second)) { 446198090Srdivacky Length = Name.size(); 447280031Sdim return OMI->second; // Found one! 448193323Sed } 449280031Sdim return nullptr; // No option found! 450193323Sed} 451193323Sed 452198090Srdivacky/// HandlePrefixedOrGroupedOption - The specified argument string (which started 453198090Srdivacky/// with at least one '-') does not fully match an available option. Check to 454198090Srdivacky/// see if this is a prefix or grouped option. If so, split arg into output an 455198090Srdivacky/// Arg/Value pair and return the Option to parse it with. 456280031Sdimstatic Option * 457280031SdimHandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 458280031Sdim bool &ErrorParsing, 459280031Sdim const StringMap<Option *> &OptionsMap) { 460280031Sdim if (Arg.size() == 1) 461280031Sdim return nullptr; 462198090Srdivacky 463198090Srdivacky // Do the lookup! 464198090Srdivacky size_t Length = 0; 465198090Srdivacky Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 466280031Sdim if (!PGOpt) 467280031Sdim return nullptr; 468199989Srdivacky 469198090Srdivacky // If the option is a prefixed option, then the value is simply the 470198090Srdivacky // rest of the name... so fall through to later processing, by 471198090Srdivacky // setting up the argument name flags and value fields. 472198090Srdivacky if (PGOpt->getFormattingFlag() == cl::Prefix) { 473198090Srdivacky Value = Arg.substr(Length); 474198090Srdivacky Arg = Arg.substr(0, Length); 475198090Srdivacky assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 476198090Srdivacky return PGOpt; 477198090Srdivacky } 478199989Srdivacky 479198090Srdivacky // This must be a grouped option... handle them now. Grouping options can't 480198090Srdivacky // have values. 481198090Srdivacky assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 482199989Srdivacky 483198090Srdivacky do { 484198090Srdivacky // Move current arg name out of Arg into OneArgName. 485198090Srdivacky StringRef OneArgName = Arg.substr(0, Length); 486198090Srdivacky Arg = Arg.substr(Length); 487199989Srdivacky 488198090Srdivacky // Because ValueRequired is an invalid flag for grouped arguments, 489198090Srdivacky // we don't need to pass argc/argv in. 490198090Srdivacky assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 491198090Srdivacky "Option can not be cl::Grouping AND cl::ValueRequired!"); 492202375Srdivacky int Dummy = 0; 493280031Sdim ErrorParsing |= 494280031Sdim ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy); 495199989Srdivacky 496198090Srdivacky // Get the next grouping option. 497198090Srdivacky PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 498198090Srdivacky } while (PGOpt && Length != Arg.size()); 499199989Srdivacky 500198090Srdivacky // Return the last option with Arg cut down to just the last one. 501198090Srdivacky return PGOpt; 502198090Srdivacky} 503198090Srdivacky 504193323Sedstatic bool RequiresValue(const Option *O) { 505193323Sed return O->getNumOccurrencesFlag() == cl::Required || 506193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 507193323Sed} 508193323Sed 509193323Sedstatic bool EatsUnboundedNumberOfValues(const Option *O) { 510193323Sed return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 511193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 512193323Sed} 513193323Sed 514280031Sdimstatic bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); } 515261991Sdim 516280031Sdimstatic bool isQuote(char C) { return C == '\"' || C == '\''; } 517261991Sdim 518280031Sdimstatic bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); } 519261991Sdim 520261991Sdimvoid cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver, 521280031Sdim SmallVectorImpl<const char *> &NewArgv, 522280031Sdim bool MarkEOLs) { 523261991Sdim SmallString<128> Token; 524261991Sdim for (size_t I = 0, E = Src.size(); I != E; ++I) { 525261991Sdim // Consume runs of whitespace. 526261991Sdim if (Token.empty()) { 527280031Sdim while (I != E && isWhitespace(Src[I])) { 528280031Sdim // Mark the end of lines in response files 529280031Sdim if (MarkEOLs && Src[I] == '\n') 530280031Sdim NewArgv.push_back(nullptr); 531261991Sdim ++I; 532280031Sdim } 533280031Sdim if (I == E) 534280031Sdim break; 535261991Sdim } 536261991Sdim 537261991Sdim // Backslashes can escape backslashes, spaces, and other quotes. Otherwise 538261991Sdim // they are literal. This makes it much easier to read Windows file paths. 539261991Sdim if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) { 540280031Sdim ++I; // Skip the escape. 541261991Sdim Token.push_back(Src[I]); 542261991Sdim continue; 543261991Sdim } 544261991Sdim 545261991Sdim // Consume a quoted string. 546261991Sdim if (isQuote(Src[I])) { 547261991Sdim char Quote = Src[I++]; 548261991Sdim while (I != E && Src[I] != Quote) { 549261991Sdim // Backslashes are literal, unless they escape a special character. 550261991Sdim if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1])) 551261991Sdim ++I; 552261991Sdim Token.push_back(Src[I]); 553261991Sdim ++I; 554261991Sdim } 555280031Sdim if (I == E) 556280031Sdim break; 557261991Sdim continue; 558261991Sdim } 559261991Sdim 560261991Sdim // End the token if this is whitespace. 561261991Sdim if (isWhitespace(Src[I])) { 562261991Sdim if (!Token.empty()) 563288943Sdim NewArgv.push_back(Saver.save(Token.c_str())); 564261991Sdim Token.clear(); 565261991Sdim continue; 566261991Sdim } 567261991Sdim 568261991Sdim // This is a normal character. Append it. 569261991Sdim Token.push_back(Src[I]); 570261991Sdim } 571261991Sdim 572261991Sdim // Append the last token after hitting EOF with no whitespace. 573261991Sdim if (!Token.empty()) 574288943Sdim NewArgv.push_back(Saver.save(Token.c_str())); 575280031Sdim // Mark the end of response files 576280031Sdim if (MarkEOLs) 577280031Sdim NewArgv.push_back(nullptr); 578261991Sdim} 579261991Sdim 580261991Sdim/// Backslashes are interpreted in a rather complicated way in the Windows-style 581261991Sdim/// command line, because backslashes are used both to separate path and to 582261991Sdim/// escape double quote. This method consumes runs of backslashes as well as the 583261991Sdim/// following double quote if it's escaped. 584193323Sed/// 585261991Sdim/// * If an even number of backslashes is followed by a double quote, one 586261991Sdim/// backslash is output for every pair of backslashes, and the last double 587261991Sdim/// quote remains unconsumed. The double quote will later be interpreted as 588261991Sdim/// the start or end of a quoted string in the main loop outside of this 589261991Sdim/// function. 590261991Sdim/// 591261991Sdim/// * If an odd number of backslashes is followed by a double quote, one 592261991Sdim/// backslash is output for every pair of backslashes, and a double quote is 593261991Sdim/// output for the last pair of backslash-double quote. The double quote is 594261991Sdim/// consumed in this case. 595261991Sdim/// 596261991Sdim/// * Otherwise, backslashes are interpreted literally. 597261991Sdimstatic size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) { 598261991Sdim size_t E = Src.size(); 599261991Sdim int BackslashCount = 0; 600261991Sdim // Skip the backslashes. 601261991Sdim do { 602261991Sdim ++I; 603261991Sdim ++BackslashCount; 604261991Sdim } while (I != E && Src[I] == '\\'); 605193323Sed 606261991Sdim bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); 607261991Sdim if (FollowedByDoubleQuote) { 608261991Sdim Token.append(BackslashCount / 2, '\\'); 609261991Sdim if (BackslashCount % 2 == 0) 610261991Sdim return I - 1; 611261991Sdim Token.push_back('"'); 612261991Sdim return I; 613261991Sdim } 614261991Sdim Token.append(BackslashCount, '\\'); 615261991Sdim return I - 1; 616261991Sdim} 617261991Sdim 618261991Sdimvoid cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver, 619280031Sdim SmallVectorImpl<const char *> &NewArgv, 620280031Sdim bool MarkEOLs) { 621261991Sdim SmallString<128> Token; 622261991Sdim 623261991Sdim // This is a small state machine to consume characters until it reaches the 624261991Sdim // end of the source string. 625261991Sdim enum { INIT, UNQUOTED, QUOTED } State = INIT; 626261991Sdim for (size_t I = 0, E = Src.size(); I != E; ++I) { 627261991Sdim // INIT state indicates that the current input index is at the start of 628261991Sdim // the string or between tokens. 629261991Sdim if (State == INIT) { 630280031Sdim if (isWhitespace(Src[I])) { 631280031Sdim // Mark the end of lines in response files 632280031Sdim if (MarkEOLs && Src[I] == '\n') 633280031Sdim NewArgv.push_back(nullptr); 634261991Sdim continue; 635280031Sdim } 636261991Sdim if (Src[I] == '"') { 637261991Sdim State = QUOTED; 638261991Sdim continue; 639261991Sdim } 640261991Sdim if (Src[I] == '\\') { 641261991Sdim I = parseBackslash(Src, I, Token); 642261991Sdim State = UNQUOTED; 643261991Sdim continue; 644261991Sdim } 645261991Sdim Token.push_back(Src[I]); 646261991Sdim State = UNQUOTED; 647198090Srdivacky continue; 648193323Sed } 649199989Srdivacky 650261991Sdim // UNQUOTED state means that it's reading a token not quoted by double 651261991Sdim // quotes. 652261991Sdim if (State == UNQUOTED) { 653261991Sdim // Whitespace means the end of the token. 654261991Sdim if (isWhitespace(Src[I])) { 655288943Sdim NewArgv.push_back(Saver.save(Token.c_str())); 656261991Sdim Token.clear(); 657261991Sdim State = INIT; 658280031Sdim // Mark the end of lines in response files 659280031Sdim if (MarkEOLs && Src[I] == '\n') 660280031Sdim NewArgv.push_back(nullptr); 661261991Sdim continue; 662261991Sdim } 663261991Sdim if (Src[I] == '"') { 664261991Sdim State = QUOTED; 665261991Sdim continue; 666261991Sdim } 667261991Sdim if (Src[I] == '\\') { 668261991Sdim I = parseBackslash(Src, I, Token); 669261991Sdim continue; 670261991Sdim } 671261991Sdim Token.push_back(Src[I]); 672261991Sdim continue; 673261991Sdim } 674199989Srdivacky 675261991Sdim // QUOTED state means that it's reading a token quoted by double quotes. 676261991Sdim if (State == QUOTED) { 677261991Sdim if (Src[I] == '"') { 678261991Sdim State = UNQUOTED; 679261991Sdim continue; 680261991Sdim } 681261991Sdim if (Src[I] == '\\') { 682261991Sdim I = parseBackslash(Src, I, Token); 683261991Sdim continue; 684261991Sdim } 685261991Sdim Token.push_back(Src[I]); 686261991Sdim } 687261991Sdim } 688261991Sdim // Append the last token after hitting EOF with no whitespace. 689261991Sdim if (!Token.empty()) 690288943Sdim NewArgv.push_back(Saver.save(Token.c_str())); 691280031Sdim // Mark the end of response files 692280031Sdim if (MarkEOLs) 693280031Sdim NewArgv.push_back(nullptr); 694261991Sdim} 695199989Srdivacky 696288943Sdim// It is called byte order marker but the UTF-8 BOM is actually not affected 697288943Sdim// by the host system's endianness. 698288943Sdimstatic bool hasUTF8ByteOrderMark(ArrayRef<char> S) { 699288943Sdim return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf'); 700288943Sdim} 701288943Sdim 702261991Sdimstatic bool ExpandResponseFile(const char *FName, StringSaver &Saver, 703261991Sdim TokenizerCallback Tokenizer, 704280031Sdim SmallVectorImpl<const char *> &NewArgv, 705280031Sdim bool MarkEOLs = false) { 706276479Sdim ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr = 707276479Sdim MemoryBuffer::getFile(FName); 708276479Sdim if (!MemBufOrErr) 709261991Sdim return false; 710280031Sdim MemoryBuffer &MemBuf = *MemBufOrErr.get(); 711280031Sdim StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize()); 712261991Sdim 713261991Sdim // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 714280031Sdim ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd()); 715261991Sdim std::string UTF8Buf; 716261991Sdim if (hasUTF16ByteOrderMark(BufRef)) { 717261991Sdim if (!convertUTF16ToUTF8String(BufRef, UTF8Buf)) 718261991Sdim return false; 719261991Sdim Str = StringRef(UTF8Buf); 720193323Sed } 721288943Sdim // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove 722288943Sdim // these bytes before parsing. 723288943Sdim // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark 724288943Sdim else if (hasUTF8ByteOrderMark(BufRef)) 725288943Sdim Str = StringRef(BufRef.data() + 3, BufRef.size() - 3); 726261991Sdim 727261991Sdim // Tokenize the contents into NewArgv. 728280031Sdim Tokenizer(Str, Saver, NewArgv, MarkEOLs); 729261991Sdim 730261991Sdim return true; 731193323Sed} 732193323Sed 733261991Sdim/// \brief Expand response files on a command line recursively using the given 734261991Sdim/// StringSaver and tokenization strategy. 735261991Sdimbool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 736280031Sdim SmallVectorImpl<const char *> &Argv, 737280031Sdim bool MarkEOLs) { 738261991Sdim unsigned RspFiles = 0; 739276479Sdim bool AllExpanded = true; 740261991Sdim 741261991Sdim // Don't cache Argv.size() because it can change. 742280031Sdim for (unsigned I = 0; I != Argv.size();) { 743261991Sdim const char *Arg = Argv[I]; 744280031Sdim // Check if it is an EOL marker 745280031Sdim if (Arg == nullptr) { 746280031Sdim ++I; 747280031Sdim continue; 748280031Sdim } 749261991Sdim if (Arg[0] != '@') { 750261991Sdim ++I; 751261991Sdim continue; 752261991Sdim } 753261991Sdim 754261991Sdim // If we have too many response files, leave some unexpanded. This avoids 755261991Sdim // crashing on self-referential response files. 756261991Sdim if (RspFiles++ > 20) 757261991Sdim return false; 758261991Sdim 759261991Sdim // Replace this response file argument with the tokenization of its 760261991Sdim // contents. Nested response files are expanded in subsequent iterations. 761261991Sdim // FIXME: If a nested response file uses a relative path, is it relative to 762261991Sdim // the cwd of the process or the response file? 763261991Sdim SmallVector<const char *, 0> ExpandedArgv; 764280031Sdim if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv, 765280031Sdim MarkEOLs)) { 766276479Sdim // We couldn't read this file, so we leave it in the argument stream and 767276479Sdim // move on. 768261991Sdim AllExpanded = false; 769276479Sdim ++I; 770261991Sdim continue; 771261991Sdim } 772261991Sdim Argv.erase(Argv.begin() + I); 773261991Sdim Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 774261991Sdim } 775261991Sdim return AllExpanded; 776261991Sdim} 777261991Sdim 778193323Sed/// ParseEnvironmentOptions - An alternative entry point to the 779193323Sed/// CommandLine library, which allows you to read the program's name 780193323Sed/// from the caller (as PROGNAME) and its command-line arguments from 781193323Sed/// an environment variable (whose name is given in ENVVAR). 782193323Sed/// 783193323Sedvoid cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 784243830Sdim const char *Overview) { 785193323Sed // Check args. 786193323Sed assert(progName && "Program name not specified"); 787193323Sed assert(envVar && "Environment variable name missing"); 788193323Sed 789193323Sed // Get the environment variable they want us to parse options out of. 790193323Sed const char *envValue = getenv(envVar); 791193323Sed if (!envValue) 792193323Sed return; 793193323Sed 794193323Sed // Get program's "name", which we wouldn't know without the caller 795193323Sed // telling us. 796261991Sdim SmallVector<const char *, 20> newArgv; 797288943Sdim BumpPtrAllocator A; 798296417Sdim StringSaver Saver(A); 799288943Sdim newArgv.push_back(Saver.save(progName)); 800193323Sed 801193323Sed // Parse the value of the environment variable into a "command line" 802193323Sed // and hand it off to ParseCommandLineOptions(). 803261991Sdim TokenizeGNUCommandLine(envValue, Saver, newArgv); 804193323Sed int newArgc = static_cast<int>(newArgv.size()); 805243830Sdim ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 806193323Sed} 807193323Sed 808280031Sdimvoid cl::ParseCommandLineOptions(int argc, const char *const *argv, 809243830Sdim const char *Overview) { 810288943Sdim GlobalParser->ParseCommandLineOptions(argc, argv, Overview); 811288943Sdim} 812193323Sed 813288943Sdimvoid CommandLineParser::ParseCommandLineOptions(int argc, 814288943Sdim const char *const *argv, 815288943Sdim const char *Overview) { 816288943Sdim assert(hasOptions() && "No options specified!"); 817193323Sed 818193323Sed // Expand response files. 819288943Sdim SmallVector<const char *, 20> newArgv(argv, argv + argc); 820288943Sdim BumpPtrAllocator A; 821296417Sdim StringSaver Saver(A); 822261991Sdim ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv); 823243830Sdim argv = &newArgv[0]; 824243830Sdim argc = static_cast<int>(newArgv.size()); 825193323Sed 826193323Sed // Copy the program name into ProgName, making sure not to overflow it. 827288943Sdim ProgramName = sys::path::filename(argv[0]); 828193323Sed 829193323Sed ProgramOverview = Overview; 830193323Sed bool ErrorParsing = false; 831193323Sed 832193323Sed // Check out the positional arguments to collect information about them. 833193323Sed unsigned NumPositionalRequired = 0; 834193323Sed 835193323Sed // Determine whether or not there are an unlimited number of positionals 836193323Sed bool HasUnlimitedPositionals = false; 837193323Sed 838288943Sdim if (ConsumeAfterOpt) { 839288943Sdim assert(PositionalOpts.size() > 0 && 840288943Sdim "Cannot specify cl::ConsumeAfter without a positional argument!"); 841288943Sdim } 842193323Sed if (!PositionalOpts.empty()) { 843193323Sed 844193323Sed // Calculate how many positional values are _required_. 845193323Sed bool UnboundedFound = false; 846288943Sdim for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 847193323Sed Option *Opt = PositionalOpts[i]; 848193323Sed if (RequiresValue(Opt)) 849193323Sed ++NumPositionalRequired; 850193323Sed else if (ConsumeAfterOpt) { 851193323Sed // ConsumeAfter cannot be combined with "optional" positional options 852193323Sed // unless there is only one positional argument... 853288943Sdim if (PositionalOpts.size() > 1) 854280031Sdim ErrorParsing |= Opt->error( 855280031Sdim "error - this positional option will never be matched, " 856280031Sdim "because it does not Require a value, and a " 857280031Sdim "cl::ConsumeAfter option is active!"); 858296417Sdim } else if (UnboundedFound && !Opt->hasArgStr()) { 859193323Sed // This option does not "require" a value... Make sure this option is 860193323Sed // not specified after an option that eats all extra arguments, or this 861193323Sed // one will never get any! 862193323Sed // 863198090Srdivacky ErrorParsing |= Opt->error("error - option can never match, because " 864193323Sed "another positional argument will match an " 865193323Sed "unbounded number of values, and this option" 866193323Sed " does not require a value!"); 867288943Sdim errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr 868288943Sdim << "' is all messed up!\n"; 869288943Sdim errs() << PositionalOpts.size(); 870193323Sed } 871193323Sed UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 872193323Sed } 873193323Sed HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 874193323Sed } 875193323Sed 876193323Sed // PositionalVals - A vector of "positional" arguments we accumulate into 877198090Srdivacky // the process at the end. 878193323Sed // 879280031Sdim SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals; 880193323Sed 881193323Sed // If the program has named positional arguments, and the name has been run 882193323Sed // across, keep track of which positional argument was named. Otherwise put 883193323Sed // the positional args into the PositionalVals list... 884276479Sdim Option *ActivePositionalArg = nullptr; 885193323Sed 886193323Sed // Loop over all of the arguments... processing them. 887280031Sdim bool DashDashFound = false; // Have we read '--'? 888193323Sed for (int i = 1; i < argc; ++i) { 889276479Sdim Option *Handler = nullptr; 890276479Sdim Option *NearestHandler = nullptr; 891221345Sdim std::string NearestHandlerString; 892198090Srdivacky StringRef Value; 893198090Srdivacky StringRef ArgName = ""; 894193323Sed 895193323Sed // Check to see if this is a positional argument. This argument is 896193323Sed // considered to be positional if it doesn't start with '-', if it is "-" 897193323Sed // itself, or if we have seen "--" already. 898193323Sed // 899193323Sed if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 900193323Sed // Positional argument! 901193323Sed if (ActivePositionalArg) { 902193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 903280031Sdim continue; // We are done! 904198090Srdivacky } 905199989Srdivacky 906198090Srdivacky if (!PositionalOpts.empty()) { 907280031Sdim PositionalVals.push_back(std::make_pair(argv[i], i)); 908193323Sed 909193323Sed // All of the positional arguments have been fulfulled, give the rest to 910193323Sed // the consume after option... if it's specified... 911193323Sed // 912276479Sdim if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) { 913193323Sed for (++i; i < argc; ++i) 914280031Sdim PositionalVals.push_back(std::make_pair(argv[i], i)); 915280031Sdim break; // Handle outside of the argument processing loop... 916193323Sed } 917193323Sed 918193323Sed // Delay processing positional arguments until the end... 919193323Sed continue; 920193323Sed } 921193323Sed } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 922193323Sed !DashDashFound) { 923280031Sdim DashDashFound = true; // This is the mythical "--"? 924280031Sdim continue; // Don't try to process it as an argument itself. 925193323Sed } else if (ActivePositionalArg && 926193323Sed (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 927193323Sed // If there is a positional argument eating options, check to see if this 928193323Sed // option is another positional argument. If so, treat it as an argument, 929193323Sed // otherwise feed it to the eating positional. 930280031Sdim ArgName = argv[i] + 1; 931198090Srdivacky // Eat leading dashes. 932198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 933198090Srdivacky ArgName = ArgName.substr(1); 934199989Srdivacky 935288943Sdim Handler = LookupOption(ArgName, Value); 936193323Sed if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 937193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 938280031Sdim continue; // We are done! 939193323Sed } 940193323Sed 941280031Sdim } else { // We start with a '-', must be an argument. 942280031Sdim ArgName = argv[i] + 1; 943198090Srdivacky // Eat leading dashes. 944198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 945198090Srdivacky ArgName = ArgName.substr(1); 946199989Srdivacky 947288943Sdim Handler = LookupOption(ArgName, Value); 948193323Sed 949193323Sed // Check to see if this "option" is really a prefixed or grouped argument. 950276479Sdim if (!Handler) 951288943Sdim Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, 952288943Sdim OptionsMap); 953218893Sdim 954218893Sdim // Otherwise, look for the closest available option to report to the user 955218893Sdim // in the upcoming error. 956276479Sdim if (!Handler && SinkOpts.empty()) 957280031Sdim NearestHandler = 958288943Sdim LookupNearestOption(ArgName, OptionsMap, NearestHandlerString); 959193323Sed } 960193323Sed 961276479Sdim if (!Handler) { 962193323Sed if (SinkOpts.empty()) { 963280031Sdim errs() << ProgramName << ": Unknown command line argument '" << argv[i] 964280031Sdim << "'. Try: '" << argv[0] << " -help'\n"; 965218893Sdim 966218893Sdim if (NearestHandler) { 967218893Sdim // If we know a near match, report it as well. 968280031Sdim errs() << ProgramName << ": Did you mean '-" << NearestHandlerString 969280031Sdim << "'?\n"; 970218893Sdim } 971218893Sdim 972193323Sed ErrorParsing = true; 973193323Sed } else { 974280031Sdim for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(), 975280031Sdim E = SinkOpts.end(); 976280031Sdim I != E; ++I) 977193323Sed (*I)->addOccurrence(i, "", argv[i]); 978193323Sed } 979193323Sed continue; 980193323Sed } 981193323Sed 982193323Sed // If this is a named positional argument, just remember that it is the 983193323Sed // active one... 984193323Sed if (Handler->getFormattingFlag() == cl::Positional) 985193323Sed ActivePositionalArg = Handler; 986193323Sed else 987193323Sed ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 988193323Sed } 989193323Sed 990193323Sed // Check and handle positional arguments now... 991193323Sed if (NumPositionalRequired > PositionalVals.size()) { 992198090Srdivacky errs() << ProgramName 993280031Sdim << ": Not enough positional command line arguments specified!\n" 994280031Sdim << "Must specify at least " << NumPositionalRequired 995280031Sdim << " positional arguments: See: " << argv[0] << " -help\n"; 996193323Sed 997193323Sed ErrorParsing = true; 998206083Srdivacky } else if (!HasUnlimitedPositionals && 999206083Srdivacky PositionalVals.size() > PositionalOpts.size()) { 1000280031Sdim errs() << ProgramName << ": Too many positional arguments specified!\n" 1001280031Sdim << "Can specify at most " << PositionalOpts.size() 1002280031Sdim << " positional arguments: See: " << argv[0] << " -help\n"; 1003193323Sed ErrorParsing = true; 1004193323Sed 1005276479Sdim } else if (!ConsumeAfterOpt) { 1006198090Srdivacky // Positional args have already been handled if ConsumeAfter is specified. 1007193323Sed unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 1008193323Sed for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 1009193323Sed if (RequiresValue(PositionalOpts[i])) { 1010193323Sed ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 1011193323Sed PositionalVals[ValNo].second); 1012193323Sed ValNo++; 1013280031Sdim --NumPositionalRequired; // We fulfilled our duty... 1014193323Sed } 1015193323Sed 1016193323Sed // If we _can_ give this option more arguments, do so now, as long as we 1017193323Sed // do not give it values that others need. 'Done' controls whether the 1018193323Sed // option even _WANTS_ any more. 1019193323Sed // 1020193323Sed bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 1021280031Sdim while (NumVals - ValNo > NumPositionalRequired && !Done) { 1022193323Sed switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 1023193323Sed case cl::Optional: 1024280031Sdim Done = true; // Optional arguments want _at most_ one value 1025280031Sdim // FALL THROUGH 1026280031Sdim case cl::ZeroOrMore: // Zero or more will take all they can get... 1027280031Sdim case cl::OneOrMore: // One or more will take all they can get... 1028193323Sed ProvidePositionalOption(PositionalOpts[i], 1029193323Sed PositionalVals[ValNo].first, 1030193323Sed PositionalVals[ValNo].second); 1031193323Sed ValNo++; 1032193323Sed break; 1033193323Sed default: 1034198090Srdivacky llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 1035280031Sdim "positional argument processing!"); 1036193323Sed } 1037193323Sed } 1038193323Sed } 1039193323Sed } else { 1040193323Sed assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 1041193323Sed unsigned ValNo = 0; 1042193323Sed for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 1043193323Sed if (RequiresValue(PositionalOpts[j])) { 1044193323Sed ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 1045193323Sed PositionalVals[ValNo].first, 1046193323Sed PositionalVals[ValNo].second); 1047193323Sed ValNo++; 1048193323Sed } 1049193323Sed 1050193323Sed // Handle the case where there is just one positional option, and it's 1051193323Sed // optional. In this case, we want to give JUST THE FIRST option to the 1052193323Sed // positional option and keep the rest for the consume after. The above 1053193323Sed // loop would have assigned no values to positional options in this case. 1054193323Sed // 1055288943Sdim if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) { 1056288943Sdim ErrorParsing |= ProvidePositionalOption(PositionalOpts[0], 1057193323Sed PositionalVals[ValNo].first, 1058193323Sed PositionalVals[ValNo].second); 1059193323Sed ValNo++; 1060193323Sed } 1061193323Sed 1062193323Sed // Handle over all of the rest of the arguments to the 1063193323Sed // cl::ConsumeAfter command line option... 1064193323Sed for (; ValNo != PositionalVals.size(); ++ValNo) 1065280031Sdim ErrorParsing |= 1066280031Sdim ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, 1067280031Sdim PositionalVals[ValNo].second); 1068193323Sed } 1069193323Sed 1070193323Sed // Loop over args and make sure all required args are specified! 1071288943Sdim for (const auto &Opt : OptionsMap) { 1072276479Sdim switch (Opt.second->getNumOccurrencesFlag()) { 1073193323Sed case Required: 1074193323Sed case OneOrMore: 1075276479Sdim if (Opt.second->getNumOccurrences() == 0) { 1076276479Sdim Opt.second->error("must be specified at least once!"); 1077193323Sed ErrorParsing = true; 1078193323Sed } 1079280031Sdim // Fall through 1080193323Sed default: 1081193323Sed break; 1082193323Sed } 1083193323Sed } 1084193323Sed 1085218893Sdim // Now that we know if -debug is specified, we can use it. 1086218893Sdim // Note that if ReadResponseFiles == true, this must be done before the 1087218893Sdim // memory allocated for the expanded command line is free()d below. 1088218893Sdim DEBUG(dbgs() << "Args: "; 1089280031Sdim for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; 1090280031Sdim dbgs() << '\n';); 1091218893Sdim 1092193323Sed // Free all of the memory allocated to the map. Command line options may only 1093193323Sed // be processed once! 1094288943Sdim MoreHelp.clear(); 1095193323Sed 1096193323Sed // If we had an error processing our arguments, don't let the program execute 1097280031Sdim if (ErrorParsing) 1098280031Sdim exit(1); 1099193323Sed} 1100193323Sed 1101193323Sed//===----------------------------------------------------------------------===// 1102193323Sed// Option Base class implementation 1103193323Sed// 1104193323Sed 1105198090Srdivackybool Option::error(const Twine &Message, StringRef ArgName) { 1106280031Sdim if (!ArgName.data()) 1107280031Sdim ArgName = ArgStr; 1108198090Srdivacky if (ArgName.empty()) 1109280031Sdim errs() << HelpStr; // Be nice for positional arguments 1110193323Sed else 1111288943Sdim errs() << GlobalParser->ProgramName << ": for the -" << ArgName; 1112193323Sed 1113198090Srdivacky errs() << " option: " << Message << "\n"; 1114193323Sed return true; 1115193323Sed} 1116193323Sed 1117280031Sdimbool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, 1118280031Sdim bool MultiArg) { 1119193323Sed if (!MultiArg) 1120280031Sdim NumOccurrences++; // Increment the number of times we have been seen 1121193323Sed 1122193323Sed switch (getNumOccurrencesFlag()) { 1123193323Sed case Optional: 1124193323Sed if (NumOccurrences > 1) 1125198090Srdivacky return error("may only occur zero or one times!", ArgName); 1126193323Sed break; 1127193323Sed case Required: 1128193323Sed if (NumOccurrences > 1) 1129198090Srdivacky return error("must occur exactly one time!", ArgName); 1130280031Sdim // Fall through 1131193323Sed case OneOrMore: 1132193323Sed case ZeroOrMore: 1133280031Sdim case ConsumeAfter: 1134280031Sdim break; 1135193323Sed } 1136193323Sed 1137193323Sed return handleOccurrence(pos, ArgName, Value); 1138193323Sed} 1139193323Sed 1140193323Sed// getValueStr - Get the value description string, using "DefaultMsg" if nothing 1141193323Sed// has been specified yet. 1142193323Sed// 1143296417Sdimstatic StringRef getValueStr(const Option &O, StringRef DefaultMsg) { 1144296417Sdim if (O.ValueStr.empty()) 1145280031Sdim return DefaultMsg; 1146193323Sed return O.ValueStr; 1147193323Sed} 1148193323Sed 1149193323Sed//===----------------------------------------------------------------------===// 1150193323Sed// cl::alias class implementation 1151193323Sed// 1152193323Sed 1153193323Sed// Return the width of the option tag for printing... 1154296417Sdimsize_t alias::getOptionWidth() const { return ArgStr.size() + 6; } 1155193323Sed 1156261991Sdimstatic void printHelpStr(StringRef HelpStr, size_t Indent, 1157261991Sdim size_t FirstLineIndentedBy) { 1158261991Sdim std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1159261991Sdim outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n"; 1160261991Sdim while (!Split.second.empty()) { 1161261991Sdim Split = Split.second.split('\n'); 1162261991Sdim outs().indent(Indent) << Split.first << "\n"; 1163261991Sdim } 1164261991Sdim} 1165261991Sdim 1166193323Sed// Print out the option for the alias. 1167193323Sedvoid alias::printOptionInfo(size_t GlobalWidth) const { 1168224145Sdim outs() << " -" << ArgStr; 1169296417Sdim printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6); 1170193323Sed} 1171193323Sed 1172193323Sed//===----------------------------------------------------------------------===// 1173193323Sed// Parser Implementation code... 1174193323Sed// 1175193323Sed 1176193323Sed// basic_parser implementation 1177193323Sed// 1178193323Sed 1179193323Sed// Return the width of the option tag for printing... 1180193323Sedsize_t basic_parser_impl::getOptionWidth(const Option &O) const { 1181296417Sdim size_t Len = O.ArgStr.size(); 1182193323Sed if (const char *ValName = getValueName()) 1183296417Sdim Len += getValueStr(O, ValName).size() + 3; 1184193323Sed 1185193323Sed return Len + 6; 1186193323Sed} 1187193323Sed 1188193323Sed// printOptionInfo - Print out information about this option. The 1189193323Sed// to-be-maintained width is specified. 1190193323Sed// 1191193323Sedvoid basic_parser_impl::printOptionInfo(const Option &O, 1192193323Sed size_t GlobalWidth) const { 1193198090Srdivacky outs() << " -" << O.ArgStr; 1194193323Sed 1195193323Sed if (const char *ValName = getValueName()) 1196198090Srdivacky outs() << "=<" << getValueStr(O, ValName) << '>'; 1197193323Sed 1198261991Sdim printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1199193323Sed} 1200193323Sed 1201221345Sdimvoid basic_parser_impl::printOptionName(const Option &O, 1202221345Sdim size_t GlobalWidth) const { 1203221345Sdim outs() << " -" << O.ArgStr; 1204296417Sdim outs().indent(GlobalWidth - O.ArgStr.size()); 1205221345Sdim} 1206193323Sed 1207193323Sed// parser<bool> implementation 1208193323Sed// 1209280031Sdimbool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, 1210280031Sdim bool &Value) { 1211193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1212193323Sed Arg == "1") { 1213193323Sed Value = true; 1214198090Srdivacky return false; 1215198090Srdivacky } 1216199989Srdivacky 1217198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1218193323Sed Value = false; 1219198090Srdivacky return false; 1220193323Sed } 1221198090Srdivacky return O.error("'" + Arg + 1222198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 1223193323Sed} 1224193323Sed 1225193323Sed// parser<boolOrDefault> implementation 1226193323Sed// 1227280031Sdimbool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, 1228280031Sdim boolOrDefault &Value) { 1229193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1230193323Sed Arg == "1") { 1231193323Sed Value = BOU_TRUE; 1232198090Srdivacky return false; 1233198090Srdivacky } 1234198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1235193323Sed Value = BOU_FALSE; 1236198090Srdivacky return false; 1237193323Sed } 1238199989Srdivacky 1239198090Srdivacky return O.error("'" + Arg + 1240198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 1241193323Sed} 1242193323Sed 1243193323Sed// parser<int> implementation 1244193323Sed// 1245280031Sdimbool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, 1246280031Sdim int &Value) { 1247198090Srdivacky if (Arg.getAsInteger(0, Value)) 1248198090Srdivacky return O.error("'" + Arg + "' value invalid for integer argument!"); 1249193323Sed return false; 1250193323Sed} 1251193323Sed 1252193323Sed// parser<unsigned> implementation 1253193323Sed// 1254280031Sdimbool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, 1255280031Sdim unsigned &Value) { 1256198090Srdivacky 1257198090Srdivacky if (Arg.getAsInteger(0, Value)) 1258198090Srdivacky return O.error("'" + Arg + "' value invalid for uint argument!"); 1259193323Sed return false; 1260193323Sed} 1261193323Sed 1262226633Sdim// parser<unsigned long long> implementation 1263226633Sdim// 1264226633Sdimbool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1265280031Sdim StringRef Arg, 1266280031Sdim unsigned long long &Value) { 1267226633Sdim 1268226633Sdim if (Arg.getAsInteger(0, Value)) 1269226633Sdim return O.error("'" + Arg + "' value invalid for uint argument!"); 1270226633Sdim return false; 1271226633Sdim} 1272226633Sdim 1273193323Sed// parser<double>/parser<float> implementation 1274193323Sed// 1275198090Srdivackystatic bool parseDouble(Option &O, StringRef Arg, double &Value) { 1276198090Srdivacky SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1277198090Srdivacky const char *ArgStart = TmpStr.c_str(); 1278193323Sed char *End; 1279193323Sed Value = strtod(ArgStart, &End); 1280193323Sed if (*End != 0) 1281198090Srdivacky return O.error("'" + Arg + "' value invalid for floating point argument!"); 1282193323Sed return false; 1283193323Sed} 1284193323Sed 1285280031Sdimbool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, 1286280031Sdim double &Val) { 1287193323Sed return parseDouble(O, Arg, Val); 1288193323Sed} 1289193323Sed 1290280031Sdimbool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, 1291280031Sdim float &Val) { 1292193323Sed double dVal; 1293193323Sed if (parseDouble(O, Arg, dVal)) 1294193323Sed return true; 1295193323Sed Val = (float)dVal; 1296193323Sed return false; 1297193323Sed} 1298193323Sed 1299193323Sed// generic_parser_base implementation 1300193323Sed// 1301193323Sed 1302193323Sed// findOption - Return the option number corresponding to the specified 1303193323Sed// argument string. If the option is not found, getNumOptions() is returned. 1304193323Sed// 1305193323Sedunsigned generic_parser_base::findOption(const char *Name) { 1306198090Srdivacky unsigned e = getNumOptions(); 1307193323Sed 1308198090Srdivacky for (unsigned i = 0; i != e; ++i) { 1309198090Srdivacky if (strcmp(getOption(i), Name) == 0) 1310193323Sed return i; 1311198090Srdivacky } 1312193323Sed return e; 1313193323Sed} 1314193323Sed 1315193323Sed// Return the width of the option tag for printing... 1316193323Sedsize_t generic_parser_base::getOptionWidth(const Option &O) const { 1317193323Sed if (O.hasArgStr()) { 1318296417Sdim size_t Size = O.ArgStr.size() + 6; 1319193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1320280031Sdim Size = std::max(Size, std::strlen(getOption(i)) + 8); 1321193323Sed return Size; 1322193323Sed } else { 1323193323Sed size_t BaseSize = 0; 1324193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1325280031Sdim BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8); 1326193323Sed return BaseSize; 1327193323Sed } 1328193323Sed} 1329193323Sed 1330193323Sed// printOptionInfo - Print out information about this option. The 1331193323Sed// to-be-maintained width is specified. 1332193323Sed// 1333193323Sedvoid generic_parser_base::printOptionInfo(const Option &O, 1334193323Sed size_t GlobalWidth) const { 1335193323Sed if (O.hasArgStr()) { 1336198090Srdivacky outs() << " -" << O.ArgStr; 1337296417Sdim printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6); 1338193323Sed 1339193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1340280031Sdim size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8; 1341198090Srdivacky outs() << " =" << getOption(i); 1342198090Srdivacky outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1343193323Sed } 1344193323Sed } else { 1345296417Sdim if (!O.HelpStr.empty()) 1346198090Srdivacky outs() << " " << O.HelpStr << '\n'; 1347193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1348261991Sdim const char *Option = getOption(i); 1349261991Sdim outs() << " -" << Option; 1350261991Sdim printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8); 1351193323Sed } 1352193323Sed } 1353193323Sed} 1354193323Sed 1355221345Sdimstatic const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1356193323Sed 1357221345Sdim// printGenericOptionDiff - Print the value of this option and it's default. 1358221345Sdim// 1359221345Sdim// "Generic" options have each value mapped to a name. 1360280031Sdimvoid generic_parser_base::printGenericOptionDiff( 1361280031Sdim const Option &O, const GenericOptionValue &Value, 1362280031Sdim const GenericOptionValue &Default, size_t GlobalWidth) const { 1363221345Sdim outs() << " -" << O.ArgStr; 1364296417Sdim outs().indent(GlobalWidth - O.ArgStr.size()); 1365221345Sdim 1366221345Sdim unsigned NumOpts = getNumOptions(); 1367221345Sdim for (unsigned i = 0; i != NumOpts; ++i) { 1368221345Sdim if (Value.compare(getOptionValue(i))) 1369221345Sdim continue; 1370221345Sdim 1371221345Sdim outs() << "= " << getOption(i); 1372221345Sdim size_t L = std::strlen(getOption(i)); 1373221345Sdim size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1374221345Sdim outs().indent(NumSpaces) << " (default: "; 1375221345Sdim for (unsigned j = 0; j != NumOpts; ++j) { 1376221345Sdim if (Default.compare(getOptionValue(j))) 1377221345Sdim continue; 1378221345Sdim outs() << getOption(j); 1379221345Sdim break; 1380221345Sdim } 1381221345Sdim outs() << ")\n"; 1382221345Sdim return; 1383221345Sdim } 1384221345Sdim outs() << "= *unknown option value*\n"; 1385221345Sdim} 1386221345Sdim 1387221345Sdim// printOptionDiff - Specializations for printing basic value types. 1388221345Sdim// 1389280031Sdim#define PRINT_OPT_DIFF(T) \ 1390280031Sdim void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1391280031Sdim size_t GlobalWidth) const { \ 1392280031Sdim printOptionName(O, GlobalWidth); \ 1393280031Sdim std::string Str; \ 1394280031Sdim { \ 1395280031Sdim raw_string_ostream SS(Str); \ 1396280031Sdim SS << V; \ 1397280031Sdim } \ 1398280031Sdim outs() << "= " << Str; \ 1399280031Sdim size_t NumSpaces = \ 1400280031Sdim MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \ 1401280031Sdim outs().indent(NumSpaces) << " (default: "; \ 1402280031Sdim if (D.hasValue()) \ 1403280031Sdim outs() << D.getValue(); \ 1404280031Sdim else \ 1405280031Sdim outs() << "*no default*"; \ 1406280031Sdim outs() << ")\n"; \ 1407280031Sdim } 1408221345Sdim 1409221345SdimPRINT_OPT_DIFF(bool) 1410221345SdimPRINT_OPT_DIFF(boolOrDefault) 1411221345SdimPRINT_OPT_DIFF(int) 1412221345SdimPRINT_OPT_DIFF(unsigned) 1413226633SdimPRINT_OPT_DIFF(unsigned long long) 1414221345SdimPRINT_OPT_DIFF(double) 1415221345SdimPRINT_OPT_DIFF(float) 1416221345SdimPRINT_OPT_DIFF(char) 1417221345Sdim 1418280031Sdimvoid parser<std::string>::printOptionDiff(const Option &O, StringRef V, 1419280031Sdim OptionValue<std::string> D, 1420280031Sdim size_t GlobalWidth) const { 1421221345Sdim printOptionName(O, GlobalWidth); 1422221345Sdim outs() << "= " << V; 1423221345Sdim size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1424221345Sdim outs().indent(NumSpaces) << " (default: "; 1425221345Sdim if (D.hasValue()) 1426221345Sdim outs() << D.getValue(); 1427221345Sdim else 1428221345Sdim outs() << "*no default*"; 1429221345Sdim outs() << ")\n"; 1430221345Sdim} 1431221345Sdim 1432221345Sdim// Print a placeholder for options that don't yet support printOptionDiff(). 1433280031Sdimvoid basic_parser_impl::printOptionNoValue(const Option &O, 1434280031Sdim size_t GlobalWidth) const { 1435221345Sdim printOptionName(O, GlobalWidth); 1436221345Sdim outs() << "= *cannot print option value*\n"; 1437221345Sdim} 1438221345Sdim 1439193323Sed//===----------------------------------------------------------------------===// 1440204642Srdivacky// -help and -help-hidden option implementation 1441193323Sed// 1442193323Sed 1443288943Sdimstatic int OptNameCompare(const std::pair<const char *, Option *> *LHS, 1444288943Sdim const std::pair<const char *, Option *> *RHS) { 1445288943Sdim return strcmp(LHS->first, RHS->first); 1446198090Srdivacky} 1447198090Srdivacky 1448221345Sdim// Copy Options into a vector so we can sort them as we like. 1449280031Sdimstatic void sortOpts(StringMap<Option *> &OptMap, 1450280031Sdim SmallVectorImpl<std::pair<const char *, Option *>> &Opts, 1451280031Sdim bool ShowHidden) { 1452280031Sdim SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection. 1453221345Sdim 1454280031Sdim for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end(); 1455221345Sdim I != E; ++I) { 1456221345Sdim // Ignore really-hidden options. 1457221345Sdim if (I->second->getOptionHiddenFlag() == ReallyHidden) 1458221345Sdim continue; 1459221345Sdim 1460221345Sdim // Unless showhidden is set, ignore hidden flags. 1461221345Sdim if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1462221345Sdim continue; 1463221345Sdim 1464221345Sdim // If we've already seen this option, don't add it to the list again. 1465280031Sdim if (!OptionSet.insert(I->second).second) 1466221345Sdim continue; 1467221345Sdim 1468280031Sdim Opts.push_back( 1469280031Sdim std::pair<const char *, Option *>(I->getKey().data(), I->second)); 1470221345Sdim } 1471221345Sdim 1472221345Sdim // Sort the options list alphabetically. 1473288943Sdim array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare); 1474221345Sdim} 1475221345Sdim 1476193323Sednamespace { 1477193323Sed 1478193323Sedclass HelpPrinter { 1479251662Sdimprotected: 1480193323Sed const bool ShowHidden; 1481280031Sdim typedef SmallVector<std::pair<const char *, Option *>, 128> 1482280031Sdim StrOptionPairVector; 1483251662Sdim // Print the options. Opts is assumed to be alphabetically sorted. 1484251662Sdim virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1485251662Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1486251662Sdim Opts[i].second->printOptionInfo(MaxArgLen); 1487251662Sdim } 1488193323Sed 1489193323Sedpublic: 1490249423Sdim explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1491251662Sdim virtual ~HelpPrinter() {} 1492193323Sed 1493251662Sdim // Invoke the printer. 1494193323Sed void operator=(bool Value) { 1495288943Sdim if (!Value) 1496280031Sdim return; 1497193323Sed 1498251662Sdim StrOptionPairVector Opts; 1499288943Sdim sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden); 1500193323Sed 1501288943Sdim if (GlobalParser->ProgramOverview) 1502288943Sdim outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n"; 1503193323Sed 1504288943Sdim outs() << "USAGE: " << GlobalParser->ProgramName << " [options]"; 1505193323Sed 1506288943Sdim for (auto Opt : GlobalParser->PositionalOpts) { 1507296417Sdim if (Opt->hasArgStr()) 1508288943Sdim outs() << " --" << Opt->ArgStr; 1509288943Sdim outs() << " " << Opt->HelpStr; 1510193323Sed } 1511193323Sed 1512193323Sed // Print the consume after option info if it exists... 1513288943Sdim if (GlobalParser->ConsumeAfterOpt) 1514288943Sdim outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr; 1515193323Sed 1516198090Srdivacky outs() << "\n\n"; 1517193323Sed 1518193323Sed // Compute the maximum argument length... 1519249423Sdim size_t MaxArgLen = 0; 1520193323Sed for (size_t i = 0, e = Opts.size(); i != e; ++i) 1521193323Sed MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1522193323Sed 1523198090Srdivacky outs() << "OPTIONS:\n"; 1524251662Sdim printOptions(Opts, MaxArgLen); 1525193323Sed 1526193323Sed // Print any extra help the user has declared. 1527288943Sdim for (auto I : GlobalParser->MoreHelp) 1528288943Sdim outs() << I; 1529288943Sdim GlobalParser->MoreHelp.clear(); 1530193323Sed 1531193323Sed // Halt the program since help information was printed 1532276479Sdim exit(0); 1533193323Sed } 1534193323Sed}; 1535251662Sdim 1536251662Sdimclass CategorizedHelpPrinter : public HelpPrinter { 1537251662Sdimpublic: 1538251662Sdim explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1539251662Sdim 1540251662Sdim // Helper function for printOptions(). 1541288943Sdim // It shall return a negative value if A's name should be lexicographically 1542288943Sdim // ordered before B's name. It returns a value greater equal zero otherwise. 1543288943Sdim static int OptionCategoryCompare(OptionCategory *const *A, 1544288943Sdim OptionCategory *const *B) { 1545288943Sdim return strcmp((*A)->getName(), (*B)->getName()); 1546251662Sdim } 1547251662Sdim 1548251662Sdim // Make sure we inherit our base class's operator=() 1549280031Sdim using HelpPrinter::operator=; 1550251662Sdim 1551251662Sdimprotected: 1552276479Sdim void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override { 1553251662Sdim std::vector<OptionCategory *> SortedCategories; 1554280031Sdim std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions; 1555251662Sdim 1556276479Sdim // Collect registered option categories into vector in preparation for 1557251662Sdim // sorting. 1558288943Sdim for (auto I = GlobalParser->RegisteredOptionCategories.begin(), 1559288943Sdim E = GlobalParser->RegisteredOptionCategories.end(); 1560276479Sdim I != E; ++I) { 1561251662Sdim SortedCategories.push_back(*I); 1562276479Sdim } 1563251662Sdim 1564251662Sdim // Sort the different option categories alphabetically. 1565251662Sdim assert(SortedCategories.size() > 0 && "No option categories registered!"); 1566288943Sdim array_pod_sort(SortedCategories.begin(), SortedCategories.end(), 1567288943Sdim OptionCategoryCompare); 1568251662Sdim 1569251662Sdim // Create map to empty vectors. 1570251662Sdim for (std::vector<OptionCategory *>::const_iterator 1571251662Sdim I = SortedCategories.begin(), 1572251662Sdim E = SortedCategories.end(); 1573251662Sdim I != E; ++I) 1574251662Sdim CategorizedOptions[*I] = std::vector<Option *>(); 1575251662Sdim 1576251662Sdim // Walk through pre-sorted options and assign into categories. 1577251662Sdim // Because the options are already alphabetically sorted the 1578251662Sdim // options within categories will also be alphabetically sorted. 1579251662Sdim for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1580251662Sdim Option *Opt = Opts[I].second; 1581251662Sdim assert(CategorizedOptions.count(Opt->Category) > 0 && 1582251662Sdim "Option has an unregistered category"); 1583251662Sdim CategorizedOptions[Opt->Category].push_back(Opt); 1584251662Sdim } 1585251662Sdim 1586251662Sdim // Now do printing. 1587251662Sdim for (std::vector<OptionCategory *>::const_iterator 1588251662Sdim Category = SortedCategories.begin(), 1589251662Sdim E = SortedCategories.end(); 1590251662Sdim Category != E; ++Category) { 1591251662Sdim // Hide empty categories for -help, but show for -help-hidden. 1592251662Sdim bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1593251662Sdim if (!ShowHidden && IsEmptyCategory) 1594251662Sdim continue; 1595251662Sdim 1596251662Sdim // Print category information. 1597251662Sdim outs() << "\n"; 1598251662Sdim outs() << (*Category)->getName() << ":\n"; 1599251662Sdim 1600251662Sdim // Check if description is set. 1601276479Sdim if ((*Category)->getDescription() != nullptr) 1602251662Sdim outs() << (*Category)->getDescription() << "\n\n"; 1603251662Sdim else 1604251662Sdim outs() << "\n"; 1605251662Sdim 1606251662Sdim // When using -help-hidden explicitly state if the category has no 1607251662Sdim // options associated with it. 1608251662Sdim if (IsEmptyCategory) { 1609251662Sdim outs() << " This option category has no options.\n"; 1610251662Sdim continue; 1611251662Sdim } 1612251662Sdim // Loop over the options in the category and print. 1613251662Sdim for (std::vector<Option *>::const_iterator 1614251662Sdim Opt = CategorizedOptions[*Category].begin(), 1615251662Sdim E = CategorizedOptions[*Category].end(); 1616251662Sdim Opt != E; ++Opt) 1617251662Sdim (*Opt)->printOptionInfo(MaxArgLen); 1618251662Sdim } 1619251662Sdim } 1620251662Sdim}; 1621251662Sdim 1622251662Sdim// This wraps the Uncategorizing and Categorizing printers and decides 1623251662Sdim// at run time which should be invoked. 1624251662Sdimclass HelpPrinterWrapper { 1625251662Sdimprivate: 1626251662Sdim HelpPrinter &UncategorizedPrinter; 1627251662Sdim CategorizedHelpPrinter &CategorizedPrinter; 1628251662Sdim 1629251662Sdimpublic: 1630251662Sdim explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1631280031Sdim CategorizedHelpPrinter &CategorizedPrinter) 1632280031Sdim : UncategorizedPrinter(UncategorizedPrinter), 1633280031Sdim CategorizedPrinter(CategorizedPrinter) {} 1634251662Sdim 1635251662Sdim // Invoke the printer. 1636251662Sdim void operator=(bool Value); 1637251662Sdim}; 1638251662Sdim 1639193323Sed} // End anonymous namespace 1640193323Sed 1641251662Sdim// Declare the four HelpPrinter instances that are used to print out help, or 1642251662Sdim// help-hidden as an uncategorized list or in categories. 1643251662Sdimstatic HelpPrinter UncategorizedNormalPrinter(false); 1644251662Sdimstatic HelpPrinter UncategorizedHiddenPrinter(true); 1645251662Sdimstatic CategorizedHelpPrinter CategorizedNormalPrinter(false); 1646251662Sdimstatic CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1647193323Sed 1648251662Sdim// Declare HelpPrinter wrappers that will decide whether or not to invoke 1649251662Sdim// a categorizing help printer 1650251662Sdimstatic HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1651251662Sdim CategorizedNormalPrinter); 1652251662Sdimstatic HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1653251662Sdim CategorizedHiddenPrinter); 1654251662Sdim 1655288943Sdim// Define a category for generic options that all tools should have. 1656288943Sdimstatic cl::OptionCategory GenericCategory("Generic Options"); 1657288943Sdim 1658251662Sdim// Define uncategorized help printers. 1659251662Sdim// -help-list is hidden by default because if Option categories are being used 1660251662Sdim// then -help behaves the same as -help-list. 1661280031Sdimstatic cl::opt<HelpPrinter, true, parser<bool>> HLOp( 1662280031Sdim "help-list", 1663280031Sdim cl::desc("Display list of available options (-help-list-hidden for more)"), 1664288943Sdim cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed, 1665288943Sdim cl::cat(GenericCategory)); 1666251662Sdim 1667280031Sdimstatic cl::opt<HelpPrinter, true, parser<bool>> 1668280031Sdim HLHOp("help-list-hidden", cl::desc("Display list of all available options"), 1669280031Sdim cl::location(UncategorizedHiddenPrinter), cl::Hidden, 1670288943Sdim cl::ValueDisallowed, cl::cat(GenericCategory)); 1671251662Sdim 1672251662Sdim// Define uncategorized/categorized help printers. These printers change their 1673251662Sdim// behaviour at runtime depending on whether one or more Option categories have 1674251662Sdim// been declared. 1675280031Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool>> 1676280031Sdim HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1677288943Sdim cl::location(WrappedNormalPrinter), cl::ValueDisallowed, 1678288943Sdim cl::cat(GenericCategory)); 1679193323Sed 1680280031Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool>> 1681280031Sdim HHOp("help-hidden", cl::desc("Display all available options"), 1682288943Sdim cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed, 1683288943Sdim cl::cat(GenericCategory)); 1684193323Sed 1685280031Sdimstatic cl::opt<bool> PrintOptions( 1686280031Sdim "print-options", 1687280031Sdim cl::desc("Print non-default options after command line parsing"), 1688288943Sdim cl::Hidden, cl::init(false), cl::cat(GenericCategory)); 1689251662Sdim 1690280031Sdimstatic cl::opt<bool> PrintAllOptions( 1691280031Sdim "print-all-options", 1692280031Sdim cl::desc("Print all option values after command line parsing"), cl::Hidden, 1693288943Sdim cl::init(false), cl::cat(GenericCategory)); 1694251662Sdim 1695251662Sdimvoid HelpPrinterWrapper::operator=(bool Value) { 1696288943Sdim if (!Value) 1697251662Sdim return; 1698251662Sdim 1699251662Sdim // Decide which printer to invoke. If more than one option category is 1700251662Sdim // registered then it is useful to show the categorized help instead of 1701251662Sdim // uncategorized help. 1702288943Sdim if (GlobalParser->RegisteredOptionCategories.size() > 1) { 1703251662Sdim // unhide -help-list option so user can have uncategorized output if they 1704251662Sdim // want it. 1705251662Sdim HLOp.setHiddenFlag(NotHidden); 1706251662Sdim 1707251662Sdim CategorizedPrinter = true; // Invoke categorized printer 1708280031Sdim } else 1709251662Sdim UncategorizedPrinter = true; // Invoke uncategorized printer 1710251662Sdim} 1711251662Sdim 1712221345Sdim// Print the value of each option. 1713288943Sdimvoid cl::PrintOptionValues() { GlobalParser->printOptionValues(); } 1714288943Sdim 1715288943Sdimvoid CommandLineParser::printOptionValues() { 1716280031Sdim if (!PrintOptions && !PrintAllOptions) 1717280031Sdim return; 1718221345Sdim 1719280031Sdim SmallVector<std::pair<const char *, Option *>, 128> Opts; 1720288943Sdim sortOpts(OptionsMap, Opts, /*ShowHidden*/ true); 1721221345Sdim 1722221345Sdim // Compute the maximum argument length... 1723221345Sdim size_t MaxArgLen = 0; 1724221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1725221345Sdim MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1726221345Sdim 1727221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1728221345Sdim Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1729221345Sdim} 1730221345Sdim 1731276479Sdimstatic void (*OverrideVersionPrinter)() = nullptr; 1732193323Sed 1733280031Sdimstatic std::vector<void (*)()> *ExtraVersionPrinters = nullptr; 1734198090Srdivacky 1735193323Sednamespace { 1736193323Sedclass VersionPrinter { 1737193323Sedpublic: 1738193323Sed void print() { 1739198090Srdivacky raw_ostream &OS = outs(); 1740234353Sdim OS << "LLVM (http://llvm.org/):\n" 1741198090Srdivacky << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1742193323Sed#ifdef LLVM_VERSION_INFO 1743276479Sdim OS << " " << LLVM_VERSION_INFO; 1744193323Sed#endif 1745198090Srdivacky OS << "\n "; 1746193323Sed#ifndef __OPTIMIZE__ 1747198090Srdivacky OS << "DEBUG build"; 1748193323Sed#else 1749198090Srdivacky OS << "Optimized build"; 1750193323Sed#endif 1751193323Sed#ifndef NDEBUG 1752198090Srdivacky OS << " with assertions"; 1753193323Sed#endif 1754199481Srdivacky std::string CPU = sys::getHostCPUName(); 1755280031Sdim if (CPU == "generic") 1756280031Sdim CPU = "(unknown)"; 1757198090Srdivacky OS << ".\n" 1758226633Sdim#if (ENABLE_TIMESTAMPS == 1) 1759198090Srdivacky << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1760208599Srdivacky#endif 1761234353Sdim << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1762226633Sdim << " Host CPU: " << CPU << '\n'; 1763193323Sed } 1764193323Sed void operator=(bool OptionWasSpecified) { 1765280031Sdim if (!OptionWasSpecified) 1766280031Sdim return; 1767199989Srdivacky 1768276479Sdim if (OverrideVersionPrinter != nullptr) { 1769226633Sdim (*OverrideVersionPrinter)(); 1770276479Sdim exit(0); 1771193323Sed } 1772226633Sdim print(); 1773226633Sdim 1774226633Sdim // Iterate over any registered extra printers and call them to add further 1775226633Sdim // information. 1776276479Sdim if (ExtraVersionPrinters != nullptr) { 1777226633Sdim outs() << '\n'; 1778226633Sdim for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1779226633Sdim E = ExtraVersionPrinters->end(); 1780226633Sdim I != E; ++I) 1781226633Sdim (*I)(); 1782226633Sdim } 1783226633Sdim 1784276479Sdim exit(0); 1785193323Sed } 1786193323Sed}; 1787193323Sed} // End anonymous namespace 1788193323Sed 1789193323Sed// Define the --version option that prints out the LLVM version for the tool 1790193323Sedstatic VersionPrinter VersionPrinterInstance; 1791193323Sed 1792280031Sdimstatic cl::opt<VersionPrinter, true, parser<bool>> 1793280031Sdim VersOp("version", cl::desc("Display the version of this program"), 1794288943Sdim cl::location(VersionPrinterInstance), cl::ValueDisallowed, 1795288943Sdim cl::cat(GenericCategory)); 1796193323Sed 1797193323Sed// Utility function for printing the help message. 1798251662Sdimvoid cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1799251662Sdim // This looks weird, but it actually prints the help message. The Printers are 1800251662Sdim // types of HelpPrinter and the help gets printed when its operator= is 1801251662Sdim // invoked. That's because the "normal" usages of the help printer is to be 1802251662Sdim // assigned true/false depending on whether -help or -help-hidden was given or 1803251662Sdim // not. Since we're circumventing that we have to make it look like -help or 1804251662Sdim // -help-hidden were given, so we assign true. 1805251662Sdim 1806251662Sdim if (!Hidden && !Categorized) 1807251662Sdim UncategorizedNormalPrinter = true; 1808251662Sdim else if (!Hidden && Categorized) 1809251662Sdim CategorizedNormalPrinter = true; 1810251662Sdim else if (Hidden && !Categorized) 1811251662Sdim UncategorizedHiddenPrinter = true; 1812251662Sdim else 1813251662Sdim CategorizedHiddenPrinter = true; 1814193323Sed} 1815193323Sed 1816193323Sed/// Utility function for printing version number. 1817280031Sdimvoid cl::PrintVersionMessage() { VersionPrinterInstance.print(); } 1818193323Sed 1819280031Sdimvoid cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; } 1820226633Sdim 1821226633Sdimvoid cl::AddExtraVersionPrinter(void (*func)()) { 1822276479Sdim if (!ExtraVersionPrinters) 1823226633Sdim ExtraVersionPrinters = new std::vector<void (*)()>; 1824226633Sdim 1825226633Sdim ExtraVersionPrinters->push_back(func); 1826226633Sdim} 1827251662Sdim 1828288943SdimStringMap<Option *> &cl::getRegisteredOptions() { 1829288943Sdim return GlobalParser->OptionsMap; 1830251662Sdim} 1831280031Sdim 1832288943Sdimvoid cl::HideUnrelatedOptions(cl::OptionCategory &Category) { 1833288943Sdim for (auto &I : GlobalParser->OptionsMap) { 1834288943Sdim if (I.second->Category != &Category && 1835288943Sdim I.second->Category != &GenericCategory) 1836288943Sdim I.second->setHiddenFlag(cl::ReallyHidden); 1837288943Sdim } 1838288943Sdim} 1839288943Sdim 1840288943Sdimvoid cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) { 1841288943Sdim auto CategoriesBegin = Categories.begin(); 1842288943Sdim auto CategoriesEnd = Categories.end(); 1843288943Sdim for (auto &I : GlobalParser->OptionsMap) { 1844288943Sdim if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) == 1845288943Sdim CategoriesEnd && 1846288943Sdim I.second->Category != &GenericCategory) 1847288943Sdim I.second->setHiddenFlag(cl::ReallyHidden); 1848288943Sdim } 1849288943Sdim} 1850288943Sdim 1851280031Sdimvoid LLVMParseCommandLineOptions(int argc, const char *const *argv, 1852280031Sdim const char *Overview) { 1853280031Sdim llvm::cl::ParseCommandLineOptions(argc, argv, Overview); 1854280031Sdim} 1855