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" 20263508Sdim#include "llvm/ADT/ArrayRef.h" 21198090Srdivacky#include "llvm/ADT/OwningPtr.h" 22198090Srdivacky#include "llvm/ADT/SmallPtrSet.h" 23198090Srdivacky#include "llvm/ADT/SmallString.h" 24198090Srdivacky#include "llvm/ADT/StringMap.h" 25198090Srdivacky#include "llvm/ADT/Twine.h" 26198090Srdivacky#include "llvm/Config/config.h" 27263508Sdim#include "llvm/Support/ConvertUTF.h" 28249423Sdim#include "llvm/Support/Debug.h" 29249423Sdim#include "llvm/Support/ErrorHandling.h" 30249423Sdim#include "llvm/Support/Host.h" 31249423Sdim#include "llvm/Support/ManagedStatic.h" 32249423Sdim#include "llvm/Support/MemoryBuffer.h" 33249423Sdim#include "llvm/Support/Path.h" 34249423Sdim#include "llvm/Support/raw_ostream.h" 35249423Sdim#include "llvm/Support/system_error.h" 36198090Srdivacky#include <cerrno> 37193323Sed#include <cstdlib> 38251662Sdim#include <map> 39193323Sedusing namespace llvm; 40193323Sedusing namespace cl; 41193323Sed 42193323Sed//===----------------------------------------------------------------------===// 43193323Sed// Template instantiations and anchors. 44193323Sed// 45199989Srdivackynamespace llvm { namespace cl { 46193323SedTEMPLATE_INSTANTIATION(class basic_parser<bool>); 47193323SedTEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 48193323SedTEMPLATE_INSTANTIATION(class basic_parser<int>); 49193323SedTEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 50226633SdimTEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); 51193323SedTEMPLATE_INSTANTIATION(class basic_parser<double>); 52193323SedTEMPLATE_INSTANTIATION(class basic_parser<float>); 53193323SedTEMPLATE_INSTANTIATION(class basic_parser<std::string>); 54193323SedTEMPLATE_INSTANTIATION(class basic_parser<char>); 55193323Sed 56193323SedTEMPLATE_INSTANTIATION(class opt<unsigned>); 57193323SedTEMPLATE_INSTANTIATION(class opt<int>); 58193323SedTEMPLATE_INSTANTIATION(class opt<std::string>); 59193323SedTEMPLATE_INSTANTIATION(class opt<char>); 60193323SedTEMPLATE_INSTANTIATION(class opt<bool>); 61199989Srdivacky} } // end namespace llvm::cl 62193323Sed 63263508Sdim// Pin the vtables to this file. 64234353Sdimvoid GenericOptionValue::anchor() {} 65234353Sdimvoid OptionValue<boolOrDefault>::anchor() {} 66234353Sdimvoid OptionValue<std::string>::anchor() {} 67193323Sedvoid Option::anchor() {} 68193323Sedvoid basic_parser_impl::anchor() {} 69193323Sedvoid parser<bool>::anchor() {} 70193323Sedvoid parser<boolOrDefault>::anchor() {} 71193323Sedvoid parser<int>::anchor() {} 72193323Sedvoid parser<unsigned>::anchor() {} 73226633Sdimvoid parser<unsigned long long>::anchor() {} 74193323Sedvoid parser<double>::anchor() {} 75193323Sedvoid parser<float>::anchor() {} 76193323Sedvoid parser<std::string>::anchor() {} 77193323Sedvoid parser<char>::anchor() {} 78263508Sdimvoid StringSaver::anchor() {} 79193323Sed 80193323Sed//===----------------------------------------------------------------------===// 81193323Sed 82193323Sed// Globals for name and overview of program. Program name is not a string to 83193323Sed// avoid static ctor/dtor issues. 84193323Sedstatic char ProgramName[80] = "<premain>"; 85193323Sedstatic const char *ProgramOverview = 0; 86193323Sed 87193323Sed// This collects additional help to be printed. 88193323Sedstatic ManagedStatic<std::vector<const char*> > MoreHelp; 89193323Sed 90193323Sedextrahelp::extrahelp(const char *Help) 91193323Sed : morehelp(Help) { 92193323Sed MoreHelp->push_back(Help); 93193323Sed} 94193323Sed 95193323Sedstatic bool OptionListChanged = false; 96193323Sed 97193323Sed// MarkOptionsChanged - Internal helper function. 98193323Sedvoid cl::MarkOptionsChanged() { 99193323Sed OptionListChanged = true; 100193323Sed} 101193323Sed 102193323Sed/// RegisteredOptionList - This is the list of the command line options that 103193323Sed/// have statically constructed themselves. 104193323Sedstatic Option *RegisteredOptionList = 0; 105193323Sed 106193323Sedvoid Option::addArgument() { 107193323Sed assert(NextRegistered == 0 && "argument multiply registered!"); 108193323Sed 109193323Sed NextRegistered = RegisteredOptionList; 110193323Sed RegisteredOptionList = this; 111193323Sed MarkOptionsChanged(); 112193323Sed} 113193323Sed 114251662Sdim// This collects the different option categories that have been registered. 115251662Sdimtypedef SmallPtrSet<OptionCategory*,16> OptionCatSet; 116251662Sdimstatic ManagedStatic<OptionCatSet> RegisteredOptionCategories; 117193323Sed 118251662Sdim// Initialise the general option category. 119251662SdimOptionCategory llvm::cl::GeneralCategory("General options"); 120251662Sdim 121251662Sdimvoid OptionCategory::registerCategory() 122251662Sdim{ 123251662Sdim RegisteredOptionCategories->insert(this); 124251662Sdim} 125251662Sdim 126193323Sed//===----------------------------------------------------------------------===// 127193323Sed// Basic, shared command line option processing machinery. 128193323Sed// 129193323Sed 130193323Sed/// GetOptionInfo - Scan the list of registered options, turning them into data 131193323Sed/// structures that are easier to handle. 132198090Srdivackystatic void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 133198090Srdivacky SmallVectorImpl<Option*> &SinkOpts, 134198090Srdivacky StringMap<Option*> &OptionsMap) { 135198090Srdivacky SmallVector<const char*, 16> OptionNames; 136193323Sed Option *CAOpt = 0; // The ConsumeAfter option if it exists. 137193323Sed for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 138193323Sed // If this option wants to handle multiple option names, get the full set. 139193323Sed // This handles enum options like "-O1 -O2" etc. 140193323Sed O->getExtraOptionNames(OptionNames); 141193323Sed if (O->ArgStr[0]) 142193323Sed OptionNames.push_back(O->ArgStr); 143193323Sed 144193323Sed // Handle named options. 145193323Sed for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 146193323Sed // Add argument to the argument map! 147198090Srdivacky if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 148198090Srdivacky errs() << ProgramName << ": CommandLine Error: Argument '" 149193323Sed << OptionNames[i] << "' defined more than once!\n"; 150193323Sed } 151193323Sed } 152193323Sed 153193323Sed OptionNames.clear(); 154193323Sed 155193323Sed // Remember information about positional options. 156193323Sed if (O->getFormattingFlag() == cl::Positional) 157193323Sed PositionalOpts.push_back(O); 158193323Sed else if (O->getMiscFlags() & cl::Sink) // Remember sink options 159193323Sed SinkOpts.push_back(O); 160193323Sed else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 161193323Sed if (CAOpt) 162193323Sed O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 163193323Sed CAOpt = O; 164193323Sed } 165193323Sed } 166193323Sed 167193323Sed if (CAOpt) 168193323Sed PositionalOpts.push_back(CAOpt); 169193323Sed 170193323Sed // Make sure that they are in order of registration not backwards. 171193323Sed std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 172193323Sed} 173193323Sed 174193323Sed 175193323Sed/// LookupOption - Lookup the option specified by the specified option on the 176193323Sed/// command line. If there is a value specified (after an equal sign) return 177198090Srdivacky/// that as well. This assumes that leading dashes have already been stripped. 178198090Srdivackystatic Option *LookupOption(StringRef &Arg, StringRef &Value, 179198090Srdivacky const StringMap<Option*> &OptionsMap) { 180198090Srdivacky // Reject all dashes. 181198090Srdivacky if (Arg.empty()) return 0; 182199989Srdivacky 183198090Srdivacky size_t EqualPos = Arg.find('='); 184199989Srdivacky 185198090Srdivacky // If we have an equals sign, remember the value. 186198090Srdivacky if (EqualPos == StringRef::npos) { 187198090Srdivacky // Look up the option. 188198090Srdivacky StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 189198090Srdivacky return I != OptionsMap.end() ? I->second : 0; 190198090Srdivacky } 191193323Sed 192198090Srdivacky // If the argument before the = is a valid option name, we match. If not, 193198090Srdivacky // return Arg unmolested. 194198090Srdivacky StringMap<Option*>::const_iterator I = 195198090Srdivacky OptionsMap.find(Arg.substr(0, EqualPos)); 196198090Srdivacky if (I == OptionsMap.end()) return 0; 197199989Srdivacky 198198090Srdivacky Value = Arg.substr(EqualPos+1); 199198090Srdivacky Arg = Arg.substr(0, EqualPos); 200198090Srdivacky return I->second; 201198090Srdivacky} 202193323Sed 203218893Sdim/// LookupNearestOption - Lookup the closest match to the option specified by 204218893Sdim/// the specified option on the command line. If there is a value specified 205218893Sdim/// (after an equal sign) return that as well. This assumes that leading dashes 206218893Sdim/// have already been stripped. 207218893Sdimstatic Option *LookupNearestOption(StringRef Arg, 208218893Sdim const StringMap<Option*> &OptionsMap, 209221345Sdim std::string &NearestString) { 210218893Sdim // Reject all dashes. 211218893Sdim if (Arg.empty()) return 0; 212218893Sdim 213218893Sdim // Split on any equal sign. 214221345Sdim std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 215221345Sdim StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 216221345Sdim StringRef &RHS = SplitArg.second; 217218893Sdim 218218893Sdim // Find the closest match. 219218893Sdim Option *Best = 0; 220218893Sdim unsigned BestDistance = 0; 221218893Sdim for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), 222218893Sdim ie = OptionsMap.end(); it != ie; ++it) { 223218893Sdim Option *O = it->second; 224218893Sdim SmallVector<const char*, 16> OptionNames; 225218893Sdim O->getExtraOptionNames(OptionNames); 226218893Sdim if (O->ArgStr[0]) 227218893Sdim OptionNames.push_back(O->ArgStr); 228218893Sdim 229221345Sdim bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 230221345Sdim StringRef Flag = PermitValue ? LHS : Arg; 231218893Sdim for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 232218893Sdim StringRef Name = OptionNames[i]; 233218893Sdim unsigned Distance = StringRef(Name).edit_distance( 234221345Sdim Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 235218893Sdim if (!Best || Distance < BestDistance) { 236218893Sdim Best = O; 237218893Sdim BestDistance = Distance; 238239462Sdim if (RHS.empty() || !PermitValue) 239239462Sdim NearestString = OptionNames[i]; 240239462Sdim else 241239462Sdim NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 242218893Sdim } 243218893Sdim } 244218893Sdim } 245218893Sdim 246218893Sdim return Best; 247218893Sdim} 248218893Sdim 249199989Srdivacky/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that 250199989Srdivacky/// does special handling of cl::CommaSeparated options. 251199989Srdivackystatic bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, 252199989Srdivacky StringRef ArgName, 253199989Srdivacky StringRef Value, bool MultiArg = false) 254199989Srdivacky{ 255199989Srdivacky // Check to see if this option accepts a comma separated list of values. If 256199989Srdivacky // it does, we have to split up the value into multiple values. 257199989Srdivacky if (Handler->getMiscFlags() & CommaSeparated) { 258199989Srdivacky StringRef Val(Value); 259199989Srdivacky StringRef::size_type Pos = Val.find(','); 260193323Sed 261199989Srdivacky while (Pos != StringRef::npos) { 262199989Srdivacky // Process the portion before the comma. 263199989Srdivacky if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 264199989Srdivacky return true; 265199989Srdivacky // Erase the portion before the comma, AND the comma. 266199989Srdivacky Val = Val.substr(Pos+1); 267199989Srdivacky Value.substr(Pos+1); // Increment the original value pointer as well. 268199989Srdivacky // Check for another comma. 269199989Srdivacky Pos = Val.find(','); 270199989Srdivacky } 271193323Sed 272199989Srdivacky Value = Val; 273199989Srdivacky } 274199989Srdivacky 275199989Srdivacky if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 276199989Srdivacky return true; 277199989Srdivacky 278199989Srdivacky return false; 279199989Srdivacky} 280199989Srdivacky 281198090Srdivacky/// ProvideOption - For Value, this differentiates between an empty value ("") 282198090Srdivacky/// and a null value (StringRef()). The later is accepted for arguments that 283198090Srdivacky/// don't allow a value (-foo) the former is rejected (-foo=). 284198090Srdivackystatic inline bool ProvideOption(Option *Handler, StringRef ArgName, 285234353Sdim StringRef Value, int argc, 286234353Sdim const char *const *argv, int &i) { 287193323Sed // Is this a multi-argument option? 288193323Sed unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 289193323Sed 290193323Sed // Enforce value requirements 291193323Sed switch (Handler->getValueExpectedFlag()) { 292193323Sed case ValueRequired: 293198090Srdivacky if (Value.data() == 0) { // No value specified? 294198090Srdivacky if (i+1 >= argc) 295198090Srdivacky return Handler->error("requires a value!"); 296198090Srdivacky // Steal the next argument, like for '-o filename' 297198090Srdivacky Value = argv[++i]; 298193323Sed } 299193323Sed break; 300193323Sed case ValueDisallowed: 301193323Sed if (NumAdditionalVals > 0) 302198090Srdivacky return Handler->error("multi-valued option specified" 303198090Srdivacky " with ValueDisallowed modifier!"); 304193323Sed 305198090Srdivacky if (Value.data()) 306198090Srdivacky return Handler->error("does not allow a value! '" + 307198090Srdivacky Twine(Value) + "' specified."); 308193323Sed break; 309193323Sed case ValueOptional: 310193323Sed break; 311193323Sed } 312193323Sed 313193323Sed // If this isn't a multi-arg option, just run the handler. 314198090Srdivacky if (NumAdditionalVals == 0) 315199989Srdivacky return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); 316198090Srdivacky 317193323Sed // If it is, run the handle several times. 318198090Srdivacky bool MultiArg = false; 319193323Sed 320198090Srdivacky if (Value.data()) { 321199989Srdivacky if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 322198090Srdivacky return true; 323198090Srdivacky --NumAdditionalVals; 324198090Srdivacky MultiArg = true; 325198090Srdivacky } 326193323Sed 327198090Srdivacky while (NumAdditionalVals > 0) { 328198090Srdivacky if (i+1 >= argc) 329198090Srdivacky return Handler->error("not enough values!"); 330198090Srdivacky Value = argv[++i]; 331199989Srdivacky 332199989Srdivacky if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 333198090Srdivacky return true; 334198090Srdivacky MultiArg = true; 335198090Srdivacky --NumAdditionalVals; 336193323Sed } 337198090Srdivacky return false; 338193323Sed} 339193323Sed 340198090Srdivackystatic bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 341193323Sed int Dummy = i; 342198090Srdivacky return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 343193323Sed} 344193323Sed 345193323Sed 346193323Sed// Option predicates... 347193323Sedstatic inline bool isGrouping(const Option *O) { 348193323Sed return O->getFormattingFlag() == cl::Grouping; 349193323Sed} 350193323Sedstatic inline bool isPrefixedOrGrouping(const Option *O) { 351193323Sed return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 352193323Sed} 353193323Sed 354193323Sed// getOptionPred - Check to see if there are any options that satisfy the 355193323Sed// specified predicate with names that are the prefixes in Name. This is 356193323Sed// checked by progressively stripping characters off of the name, checking to 357193323Sed// see if there options that satisfy the predicate. If we find one, return it, 358193323Sed// otherwise return null. 359193323Sed// 360198090Srdivackystatic Option *getOptionPred(StringRef Name, size_t &Length, 361193323Sed bool (*Pred)(const Option*), 362198090Srdivacky const StringMap<Option*> &OptionsMap) { 363193323Sed 364198090Srdivacky StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 365193323Sed 366198090Srdivacky // Loop while we haven't found an option and Name still has at least two 367198090Srdivacky // characters in it (so that the next iteration will not be the empty 368198090Srdivacky // string. 369198090Srdivacky while (OMI == OptionsMap.end() && Name.size() > 1) { 370198090Srdivacky Name = Name.substr(0, Name.size()-1); // Chop off the last character. 371193323Sed OMI = OptionsMap.find(Name); 372198090Srdivacky } 373193323Sed 374193323Sed if (OMI != OptionsMap.end() && Pred(OMI->second)) { 375198090Srdivacky Length = Name.size(); 376193323Sed return OMI->second; // Found one! 377193323Sed } 378193323Sed return 0; // No option found! 379193323Sed} 380193323Sed 381198090Srdivacky/// HandlePrefixedOrGroupedOption - The specified argument string (which started 382198090Srdivacky/// with at least one '-') does not fully match an available option. Check to 383198090Srdivacky/// see if this is a prefix or grouped option. If so, split arg into output an 384198090Srdivacky/// Arg/Value pair and return the Option to parse it with. 385198090Srdivackystatic Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 386198090Srdivacky bool &ErrorParsing, 387198090Srdivacky const StringMap<Option*> &OptionsMap) { 388198090Srdivacky if (Arg.size() == 1) return 0; 389198090Srdivacky 390198090Srdivacky // Do the lookup! 391198090Srdivacky size_t Length = 0; 392198090Srdivacky Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 393198090Srdivacky if (PGOpt == 0) return 0; 394199989Srdivacky 395198090Srdivacky // If the option is a prefixed option, then the value is simply the 396198090Srdivacky // rest of the name... so fall through to later processing, by 397198090Srdivacky // setting up the argument name flags and value fields. 398198090Srdivacky if (PGOpt->getFormattingFlag() == cl::Prefix) { 399198090Srdivacky Value = Arg.substr(Length); 400198090Srdivacky Arg = Arg.substr(0, Length); 401198090Srdivacky assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 402198090Srdivacky return PGOpt; 403198090Srdivacky } 404199989Srdivacky 405198090Srdivacky // This must be a grouped option... handle them now. Grouping options can't 406198090Srdivacky // have values. 407198090Srdivacky assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 408199989Srdivacky 409198090Srdivacky do { 410198090Srdivacky // Move current arg name out of Arg into OneArgName. 411198090Srdivacky StringRef OneArgName = Arg.substr(0, Length); 412198090Srdivacky Arg = Arg.substr(Length); 413199989Srdivacky 414198090Srdivacky // Because ValueRequired is an invalid flag for grouped arguments, 415198090Srdivacky // we don't need to pass argc/argv in. 416198090Srdivacky assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 417198090Srdivacky "Option can not be cl::Grouping AND cl::ValueRequired!"); 418202375Srdivacky int Dummy = 0; 419198090Srdivacky ErrorParsing |= ProvideOption(PGOpt, OneArgName, 420198090Srdivacky StringRef(), 0, 0, Dummy); 421199989Srdivacky 422198090Srdivacky // Get the next grouping option. 423198090Srdivacky PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 424198090Srdivacky } while (PGOpt && Length != Arg.size()); 425199989Srdivacky 426198090Srdivacky // Return the last option with Arg cut down to just the last one. 427198090Srdivacky return PGOpt; 428198090Srdivacky} 429198090Srdivacky 430198090Srdivacky 431198090Srdivacky 432193323Sedstatic bool RequiresValue(const Option *O) { 433193323Sed return O->getNumOccurrencesFlag() == cl::Required || 434193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 435193323Sed} 436193323Sed 437193323Sedstatic bool EatsUnboundedNumberOfValues(const Option *O) { 438193323Sed return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 439193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 440193323Sed} 441193323Sed 442263508Sdimstatic bool isWhitespace(char C) { 443263508Sdim return strchr(" \t\n\r\f\v", C); 444263508Sdim} 445263508Sdim 446263508Sdimstatic bool isQuote(char C) { 447263508Sdim return C == '\"' || C == '\''; 448263508Sdim} 449263508Sdim 450263508Sdimstatic bool isGNUSpecial(char C) { 451263508Sdim return strchr("\\\"\' ", C); 452263508Sdim} 453263508Sdim 454263508Sdimvoid cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver, 455263508Sdim SmallVectorImpl<const char *> &NewArgv) { 456263508Sdim SmallString<128> Token; 457263508Sdim for (size_t I = 0, E = Src.size(); I != E; ++I) { 458263508Sdim // Consume runs of whitespace. 459263508Sdim if (Token.empty()) { 460263508Sdim while (I != E && isWhitespace(Src[I])) 461263508Sdim ++I; 462263508Sdim if (I == E) break; 463263508Sdim } 464263508Sdim 465263508Sdim // Backslashes can escape backslashes, spaces, and other quotes. Otherwise 466263508Sdim // they are literal. This makes it much easier to read Windows file paths. 467263508Sdim if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) { 468263508Sdim ++I; // Skip the escape. 469263508Sdim Token.push_back(Src[I]); 470263508Sdim continue; 471263508Sdim } 472263508Sdim 473263508Sdim // Consume a quoted string. 474263508Sdim if (isQuote(Src[I])) { 475263508Sdim char Quote = Src[I++]; 476263508Sdim while (I != E && Src[I] != Quote) { 477263508Sdim // Backslashes are literal, unless they escape a special character. 478263508Sdim if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1])) 479263508Sdim ++I; 480263508Sdim Token.push_back(Src[I]); 481263508Sdim ++I; 482263508Sdim } 483263508Sdim if (I == E) break; 484263508Sdim continue; 485263508Sdim } 486263508Sdim 487263508Sdim // End the token if this is whitespace. 488263508Sdim if (isWhitespace(Src[I])) { 489263508Sdim if (!Token.empty()) 490263508Sdim NewArgv.push_back(Saver.SaveString(Token.c_str())); 491263508Sdim Token.clear(); 492263508Sdim continue; 493263508Sdim } 494263508Sdim 495263508Sdim // This is a normal character. Append it. 496263508Sdim Token.push_back(Src[I]); 497263508Sdim } 498263508Sdim 499263508Sdim // Append the last token after hitting EOF with no whitespace. 500263508Sdim if (!Token.empty()) 501263508Sdim NewArgv.push_back(Saver.SaveString(Token.c_str())); 502263508Sdim} 503263508Sdim 504263508Sdim/// Backslashes are interpreted in a rather complicated way in the Windows-style 505263508Sdim/// command line, because backslashes are used both to separate path and to 506263508Sdim/// escape double quote. This method consumes runs of backslashes as well as the 507263508Sdim/// following double quote if it's escaped. 508193323Sed/// 509263508Sdim/// * If an even number of backslashes is followed by a double quote, one 510263508Sdim/// backslash is output for every pair of backslashes, and the last double 511263508Sdim/// quote remains unconsumed. The double quote will later be interpreted as 512263508Sdim/// the start or end of a quoted string in the main loop outside of this 513263508Sdim/// function. 514263508Sdim/// 515263508Sdim/// * If an odd number of backslashes is followed by a double quote, one 516263508Sdim/// backslash is output for every pair of backslashes, and a double quote is 517263508Sdim/// output for the last pair of backslash-double quote. The double quote is 518263508Sdim/// consumed in this case. 519263508Sdim/// 520263508Sdim/// * Otherwise, backslashes are interpreted literally. 521263508Sdimstatic size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) { 522263508Sdim size_t E = Src.size(); 523263508Sdim int BackslashCount = 0; 524263508Sdim // Skip the backslashes. 525263508Sdim do { 526263508Sdim ++I; 527263508Sdim ++BackslashCount; 528263508Sdim } while (I != E && Src[I] == '\\'); 529193323Sed 530263508Sdim bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); 531263508Sdim if (FollowedByDoubleQuote) { 532263508Sdim Token.append(BackslashCount / 2, '\\'); 533263508Sdim if (BackslashCount % 2 == 0) 534263508Sdim return I - 1; 535263508Sdim Token.push_back('"'); 536263508Sdim return I; 537263508Sdim } 538263508Sdim Token.append(BackslashCount, '\\'); 539263508Sdim return I - 1; 540263508Sdim} 541263508Sdim 542263508Sdimvoid cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver, 543263508Sdim SmallVectorImpl<const char *> &NewArgv) { 544263508Sdim SmallString<128> Token; 545263508Sdim 546263508Sdim // This is a small state machine to consume characters until it reaches the 547263508Sdim // end of the source string. 548263508Sdim enum { INIT, UNQUOTED, QUOTED } State = INIT; 549263508Sdim for (size_t I = 0, E = Src.size(); I != E; ++I) { 550263508Sdim // INIT state indicates that the current input index is at the start of 551263508Sdim // the string or between tokens. 552263508Sdim if (State == INIT) { 553263508Sdim if (isWhitespace(Src[I])) 554263508Sdim continue; 555263508Sdim if (Src[I] == '"') { 556263508Sdim State = QUOTED; 557263508Sdim continue; 558263508Sdim } 559263508Sdim if (Src[I] == '\\') { 560263508Sdim I = parseBackslash(Src, I, Token); 561263508Sdim State = UNQUOTED; 562263508Sdim continue; 563263508Sdim } 564263508Sdim Token.push_back(Src[I]); 565263508Sdim State = UNQUOTED; 566198090Srdivacky continue; 567193323Sed } 568199989Srdivacky 569263508Sdim // UNQUOTED state means that it's reading a token not quoted by double 570263508Sdim // quotes. 571263508Sdim if (State == UNQUOTED) { 572263508Sdim // Whitespace means the end of the token. 573263508Sdim if (isWhitespace(Src[I])) { 574263508Sdim NewArgv.push_back(Saver.SaveString(Token.c_str())); 575263508Sdim Token.clear(); 576263508Sdim State = INIT; 577263508Sdim continue; 578263508Sdim } 579263508Sdim if (Src[I] == '"') { 580263508Sdim State = QUOTED; 581263508Sdim continue; 582263508Sdim } 583263508Sdim if (Src[I] == '\\') { 584263508Sdim I = parseBackslash(Src, I, Token); 585263508Sdim continue; 586263508Sdim } 587263508Sdim Token.push_back(Src[I]); 588263508Sdim continue; 589263508Sdim } 590199989Srdivacky 591263508Sdim // QUOTED state means that it's reading a token quoted by double quotes. 592263508Sdim if (State == QUOTED) { 593263508Sdim if (Src[I] == '"') { 594263508Sdim State = UNQUOTED; 595263508Sdim continue; 596263508Sdim } 597263508Sdim if (Src[I] == '\\') { 598263508Sdim I = parseBackslash(Src, I, Token); 599263508Sdim continue; 600263508Sdim } 601263508Sdim Token.push_back(Src[I]); 602263508Sdim } 603263508Sdim } 604263508Sdim // Append the last token after hitting EOF with no whitespace. 605263508Sdim if (!Token.empty()) 606263508Sdim NewArgv.push_back(Saver.SaveString(Token.c_str())); 607263508Sdim} 608199989Srdivacky 609263508Sdimstatic bool ExpandResponseFile(const char *FName, StringSaver &Saver, 610263508Sdim TokenizerCallback Tokenizer, 611263508Sdim SmallVectorImpl<const char *> &NewArgv) { 612263508Sdim OwningPtr<MemoryBuffer> MemBuf; 613263508Sdim if (MemoryBuffer::getFile(FName, MemBuf)) 614263508Sdim return false; 615263508Sdim StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize()); 616263508Sdim 617263508Sdim // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. 618263508Sdim ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd()); 619263508Sdim std::string UTF8Buf; 620263508Sdim if (hasUTF16ByteOrderMark(BufRef)) { 621263508Sdim if (!convertUTF16ToUTF8String(BufRef, UTF8Buf)) 622263508Sdim return false; 623263508Sdim Str = StringRef(UTF8Buf); 624193323Sed } 625263508Sdim 626263508Sdim // Tokenize the contents into NewArgv. 627263508Sdim Tokenizer(Str, Saver, NewArgv); 628263508Sdim 629263508Sdim return true; 630193323Sed} 631193323Sed 632263508Sdim/// \brief Expand response files on a command line recursively using the given 633263508Sdim/// StringSaver and tokenization strategy. 634263508Sdimbool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, 635263508Sdim SmallVectorImpl<const char *> &Argv) { 636263508Sdim unsigned RspFiles = 0; 637263508Sdim bool AllExpanded = false; 638263508Sdim 639263508Sdim // Don't cache Argv.size() because it can change. 640263508Sdim for (unsigned I = 0; I != Argv.size(); ) { 641263508Sdim const char *Arg = Argv[I]; 642263508Sdim if (Arg[0] != '@') { 643263508Sdim ++I; 644263508Sdim continue; 645263508Sdim } 646263508Sdim 647263508Sdim // If we have too many response files, leave some unexpanded. This avoids 648263508Sdim // crashing on self-referential response files. 649263508Sdim if (RspFiles++ > 20) 650263508Sdim return false; 651263508Sdim 652263508Sdim // Replace this response file argument with the tokenization of its 653263508Sdim // contents. Nested response files are expanded in subsequent iterations. 654263508Sdim // FIXME: If a nested response file uses a relative path, is it relative to 655263508Sdim // the cwd of the process or the response file? 656263508Sdim SmallVector<const char *, 0> ExpandedArgv; 657263508Sdim if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) { 658263508Sdim AllExpanded = false; 659263508Sdim continue; 660263508Sdim } 661263508Sdim Argv.erase(Argv.begin() + I); 662263508Sdim Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end()); 663263508Sdim } 664263508Sdim return AllExpanded; 665263508Sdim} 666263508Sdim 667263508Sdimnamespace { 668263508Sdim class StrDupSaver : public StringSaver { 669263508Sdim std::vector<char*> Dups; 670263508Sdim public: 671263508Sdim ~StrDupSaver() { 672263508Sdim for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); 673263508Sdim I != E; ++I) { 674263508Sdim char *Dup = *I; 675263508Sdim free(Dup); 676263508Sdim } 677263508Sdim } 678263508Sdim const char *SaveString(const char *Str) LLVM_OVERRIDE { 679263508Sdim char *Dup = strdup(Str); 680263508Sdim Dups.push_back(Dup); 681263508Sdim return Dup; 682263508Sdim } 683263508Sdim }; 684263508Sdim} 685263508Sdim 686193323Sed/// ParseEnvironmentOptions - An alternative entry point to the 687193323Sed/// CommandLine library, which allows you to read the program's name 688193323Sed/// from the caller (as PROGNAME) and its command-line arguments from 689193323Sed/// an environment variable (whose name is given in ENVVAR). 690193323Sed/// 691193323Sedvoid cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 692243830Sdim const char *Overview) { 693193323Sed // Check args. 694193323Sed assert(progName && "Program name not specified"); 695193323Sed assert(envVar && "Environment variable name missing"); 696193323Sed 697193323Sed // Get the environment variable they want us to parse options out of. 698193323Sed const char *envValue = getenv(envVar); 699193323Sed if (!envValue) 700193323Sed return; 701193323Sed 702193323Sed // Get program's "name", which we wouldn't know without the caller 703193323Sed // telling us. 704263508Sdim SmallVector<const char *, 20> newArgv; 705263508Sdim StrDupSaver Saver; 706263508Sdim newArgv.push_back(Saver.SaveString(progName)); 707193323Sed 708193323Sed // Parse the value of the environment variable into a "command line" 709193323Sed // and hand it off to ParseCommandLineOptions(). 710263508Sdim TokenizeGNUCommandLine(envValue, Saver, newArgv); 711193323Sed int newArgc = static_cast<int>(newArgv.size()); 712243830Sdim ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 713193323Sed} 714193323Sed 715234353Sdimvoid cl::ParseCommandLineOptions(int argc, const char * const *argv, 716243830Sdim const char *Overview) { 717193323Sed // Process all registered options. 718198090Srdivacky SmallVector<Option*, 4> PositionalOpts; 719198090Srdivacky SmallVector<Option*, 4> SinkOpts; 720198090Srdivacky StringMap<Option*> Opts; 721193323Sed GetOptionInfo(PositionalOpts, SinkOpts, Opts); 722193323Sed 723193323Sed assert((!Opts.empty() || !PositionalOpts.empty()) && 724193323Sed "No options specified!"); 725193323Sed 726193323Sed // Expand response files. 727263508Sdim SmallVector<const char *, 20> newArgv; 728263508Sdim for (int i = 0; i != argc; ++i) 729263508Sdim newArgv.push_back(argv[i]); 730263508Sdim StrDupSaver Saver; 731263508Sdim ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv); 732243830Sdim argv = &newArgv[0]; 733243830Sdim argc = static_cast<int>(newArgv.size()); 734193323Sed 735193323Sed // Copy the program name into ProgName, making sure not to overflow it. 736218893Sdim std::string ProgName = sys::path::filename(argv[0]); 737203954Srdivacky size_t Len = std::min(ProgName.size(), size_t(79)); 738203954Srdivacky memcpy(ProgramName, ProgName.data(), Len); 739203954Srdivacky ProgramName[Len] = '\0'; 740193323Sed 741193323Sed ProgramOverview = Overview; 742193323Sed bool ErrorParsing = false; 743193323Sed 744193323Sed // Check out the positional arguments to collect information about them. 745193323Sed unsigned NumPositionalRequired = 0; 746193323Sed 747193323Sed // Determine whether or not there are an unlimited number of positionals 748193323Sed bool HasUnlimitedPositionals = false; 749193323Sed 750193323Sed Option *ConsumeAfterOpt = 0; 751193323Sed if (!PositionalOpts.empty()) { 752193323Sed if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 753193323Sed assert(PositionalOpts.size() > 1 && 754193323Sed "Cannot specify cl::ConsumeAfter without a positional argument!"); 755193323Sed ConsumeAfterOpt = PositionalOpts[0]; 756193323Sed } 757193323Sed 758193323Sed // Calculate how many positional values are _required_. 759193323Sed bool UnboundedFound = false; 760193323Sed for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 761193323Sed i != e; ++i) { 762193323Sed Option *Opt = PositionalOpts[i]; 763193323Sed if (RequiresValue(Opt)) 764193323Sed ++NumPositionalRequired; 765193323Sed else if (ConsumeAfterOpt) { 766193323Sed // ConsumeAfter cannot be combined with "optional" positional options 767193323Sed // unless there is only one positional argument... 768193323Sed if (PositionalOpts.size() > 2) 769193323Sed ErrorParsing |= 770198090Srdivacky Opt->error("error - this positional option will never be matched, " 771193323Sed "because it does not Require a value, and a " 772193323Sed "cl::ConsumeAfter option is active!"); 773193323Sed } else if (UnboundedFound && !Opt->ArgStr[0]) { 774193323Sed // This option does not "require" a value... Make sure this option is 775193323Sed // not specified after an option that eats all extra arguments, or this 776193323Sed // one will never get any! 777193323Sed // 778198090Srdivacky ErrorParsing |= Opt->error("error - option can never match, because " 779193323Sed "another positional argument will match an " 780193323Sed "unbounded number of values, and this option" 781193323Sed " does not require a value!"); 782193323Sed } 783193323Sed UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 784193323Sed } 785193323Sed HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 786193323Sed } 787193323Sed 788193323Sed // PositionalVals - A vector of "positional" arguments we accumulate into 789198090Srdivacky // the process at the end. 790193323Sed // 791198090Srdivacky SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 792193323Sed 793193323Sed // If the program has named positional arguments, and the name has been run 794193323Sed // across, keep track of which positional argument was named. Otherwise put 795193323Sed // the positional args into the PositionalVals list... 796193323Sed Option *ActivePositionalArg = 0; 797193323Sed 798193323Sed // Loop over all of the arguments... processing them. 799193323Sed bool DashDashFound = false; // Have we read '--'? 800193323Sed for (int i = 1; i < argc; ++i) { 801193323Sed Option *Handler = 0; 802218893Sdim Option *NearestHandler = 0; 803221345Sdim std::string NearestHandlerString; 804198090Srdivacky StringRef Value; 805198090Srdivacky StringRef ArgName = ""; 806193323Sed 807193323Sed // If the option list changed, this means that some command line 808193323Sed // option has just been registered or deregistered. This can occur in 809193323Sed // response to things like -load, etc. If this happens, rescan the options. 810193323Sed if (OptionListChanged) { 811193323Sed PositionalOpts.clear(); 812193323Sed SinkOpts.clear(); 813193323Sed Opts.clear(); 814193323Sed GetOptionInfo(PositionalOpts, SinkOpts, Opts); 815193323Sed OptionListChanged = false; 816193323Sed } 817193323Sed 818193323Sed // Check to see if this is a positional argument. This argument is 819193323Sed // considered to be positional if it doesn't start with '-', if it is "-" 820193323Sed // itself, or if we have seen "--" already. 821193323Sed // 822193323Sed if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 823193323Sed // Positional argument! 824193323Sed if (ActivePositionalArg) { 825193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 826193323Sed continue; // We are done! 827198090Srdivacky } 828199989Srdivacky 829198090Srdivacky if (!PositionalOpts.empty()) { 830193323Sed PositionalVals.push_back(std::make_pair(argv[i],i)); 831193323Sed 832193323Sed // All of the positional arguments have been fulfulled, give the rest to 833193323Sed // the consume after option... if it's specified... 834193323Sed // 835193323Sed if (PositionalVals.size() >= NumPositionalRequired && 836193323Sed ConsumeAfterOpt != 0) { 837193323Sed for (++i; i < argc; ++i) 838193323Sed PositionalVals.push_back(std::make_pair(argv[i],i)); 839193323Sed break; // Handle outside of the argument processing loop... 840193323Sed } 841193323Sed 842193323Sed // Delay processing positional arguments until the end... 843193323Sed continue; 844193323Sed } 845193323Sed } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 846193323Sed !DashDashFound) { 847193323Sed DashDashFound = true; // This is the mythical "--"? 848193323Sed continue; // Don't try to process it as an argument itself. 849193323Sed } else if (ActivePositionalArg && 850193323Sed (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 851193323Sed // If there is a positional argument eating options, check to see if this 852193323Sed // option is another positional argument. If so, treat it as an argument, 853193323Sed // otherwise feed it to the eating positional. 854193323Sed ArgName = argv[i]+1; 855198090Srdivacky // Eat leading dashes. 856198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 857198090Srdivacky ArgName = ArgName.substr(1); 858199989Srdivacky 859193323Sed Handler = LookupOption(ArgName, Value, Opts); 860193323Sed if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 861193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 862193323Sed continue; // We are done! 863193323Sed } 864193323Sed 865198090Srdivacky } else { // We start with a '-', must be an argument. 866193323Sed ArgName = argv[i]+1; 867198090Srdivacky // Eat leading dashes. 868198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 869198090Srdivacky ArgName = ArgName.substr(1); 870199989Srdivacky 871193323Sed Handler = LookupOption(ArgName, Value, Opts); 872193323Sed 873193323Sed // Check to see if this "option" is really a prefixed or grouped argument. 874198090Srdivacky if (Handler == 0) 875198090Srdivacky Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 876198090Srdivacky ErrorParsing, Opts); 877218893Sdim 878218893Sdim // Otherwise, look for the closest available option to report to the user 879218893Sdim // in the upcoming error. 880218893Sdim if (Handler == 0 && SinkOpts.empty()) 881218893Sdim NearestHandler = LookupNearestOption(ArgName, Opts, 882218893Sdim NearestHandlerString); 883193323Sed } 884193323Sed 885193323Sed if (Handler == 0) { 886193323Sed if (SinkOpts.empty()) { 887198090Srdivacky errs() << ProgramName << ": Unknown command line argument '" 888204642Srdivacky << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 889218893Sdim 890218893Sdim if (NearestHandler) { 891218893Sdim // If we know a near match, report it as well. 892218893Sdim errs() << ProgramName << ": Did you mean '-" 893218893Sdim << NearestHandlerString << "'?\n"; 894218893Sdim } 895218893Sdim 896193323Sed ErrorParsing = true; 897193323Sed } else { 898198090Srdivacky for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 899193323Sed E = SinkOpts.end(); I != E ; ++I) 900193323Sed (*I)->addOccurrence(i, "", argv[i]); 901193323Sed } 902193323Sed continue; 903193323Sed } 904193323Sed 905193323Sed // If this is a named positional argument, just remember that it is the 906193323Sed // active one... 907193323Sed if (Handler->getFormattingFlag() == cl::Positional) 908193323Sed ActivePositionalArg = Handler; 909193323Sed else 910193323Sed ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 911193323Sed } 912193323Sed 913193323Sed // Check and handle positional arguments now... 914193323Sed if (NumPositionalRequired > PositionalVals.size()) { 915198090Srdivacky errs() << ProgramName 916193323Sed << ": Not enough positional command line arguments specified!\n" 917193323Sed << "Must specify at least " << NumPositionalRequired 918204642Srdivacky << " positional arguments: See: " << argv[0] << " -help\n"; 919193323Sed 920193323Sed ErrorParsing = true; 921206083Srdivacky } else if (!HasUnlimitedPositionals && 922206083Srdivacky PositionalVals.size() > PositionalOpts.size()) { 923198090Srdivacky errs() << ProgramName 924193323Sed << ": Too many positional arguments specified!\n" 925193323Sed << "Can specify at most " << PositionalOpts.size() 926204642Srdivacky << " positional arguments: See: " << argv[0] << " -help\n"; 927193323Sed ErrorParsing = true; 928193323Sed 929193323Sed } else if (ConsumeAfterOpt == 0) { 930198090Srdivacky // Positional args have already been handled if ConsumeAfter is specified. 931193323Sed unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 932193323Sed for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 933193323Sed if (RequiresValue(PositionalOpts[i])) { 934193323Sed ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 935193323Sed PositionalVals[ValNo].second); 936193323Sed ValNo++; 937193323Sed --NumPositionalRequired; // We fulfilled our duty... 938193323Sed } 939193323Sed 940193323Sed // If we _can_ give this option more arguments, do so now, as long as we 941193323Sed // do not give it values that others need. 'Done' controls whether the 942193323Sed // option even _WANTS_ any more. 943193323Sed // 944193323Sed bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 945193323Sed while (NumVals-ValNo > NumPositionalRequired && !Done) { 946193323Sed switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 947193323Sed case cl::Optional: 948193323Sed Done = true; // Optional arguments want _at most_ one value 949193323Sed // FALL THROUGH 950193323Sed case cl::ZeroOrMore: // Zero or more will take all they can get... 951193323Sed case cl::OneOrMore: // One or more will take all they can get... 952193323Sed ProvidePositionalOption(PositionalOpts[i], 953193323Sed PositionalVals[ValNo].first, 954193323Sed PositionalVals[ValNo].second); 955193323Sed ValNo++; 956193323Sed break; 957193323Sed default: 958198090Srdivacky llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 959193323Sed "positional argument processing!"); 960193323Sed } 961193323Sed } 962193323Sed } 963193323Sed } else { 964193323Sed assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 965193323Sed unsigned ValNo = 0; 966193323Sed for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 967193323Sed if (RequiresValue(PositionalOpts[j])) { 968193323Sed ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 969193323Sed PositionalVals[ValNo].first, 970193323Sed PositionalVals[ValNo].second); 971193323Sed ValNo++; 972193323Sed } 973193323Sed 974193323Sed // Handle the case where there is just one positional option, and it's 975193323Sed // optional. In this case, we want to give JUST THE FIRST option to the 976193323Sed // positional option and keep the rest for the consume after. The above 977193323Sed // loop would have assigned no values to positional options in this case. 978193323Sed // 979193323Sed if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 980193323Sed ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 981193323Sed PositionalVals[ValNo].first, 982193323Sed PositionalVals[ValNo].second); 983193323Sed ValNo++; 984193323Sed } 985193323Sed 986193323Sed // Handle over all of the rest of the arguments to the 987193323Sed // cl::ConsumeAfter command line option... 988193323Sed for (; ValNo != PositionalVals.size(); ++ValNo) 989193323Sed ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 990193323Sed PositionalVals[ValNo].first, 991193323Sed PositionalVals[ValNo].second); 992193323Sed } 993193323Sed 994193323Sed // Loop over args and make sure all required args are specified! 995198090Srdivacky for (StringMap<Option*>::iterator I = Opts.begin(), 996193323Sed E = Opts.end(); I != E; ++I) { 997193323Sed switch (I->second->getNumOccurrencesFlag()) { 998193323Sed case Required: 999193323Sed case OneOrMore: 1000193323Sed if (I->second->getNumOccurrences() == 0) { 1001198090Srdivacky I->second->error("must be specified at least once!"); 1002193323Sed ErrorParsing = true; 1003193323Sed } 1004193323Sed // Fall through 1005193323Sed default: 1006193323Sed break; 1007193323Sed } 1008193323Sed } 1009193323Sed 1010218893Sdim // Now that we know if -debug is specified, we can use it. 1011218893Sdim // Note that if ReadResponseFiles == true, this must be done before the 1012218893Sdim // memory allocated for the expanded command line is free()d below. 1013218893Sdim DEBUG(dbgs() << "Args: "; 1014218893Sdim for (int i = 0; i < argc; ++i) 1015218893Sdim dbgs() << argv[i] << ' '; 1016218893Sdim dbgs() << '\n'; 1017218893Sdim ); 1018218893Sdim 1019193323Sed // Free all of the memory allocated to the map. Command line options may only 1020193323Sed // be processed once! 1021193323Sed Opts.clear(); 1022193323Sed PositionalOpts.clear(); 1023193323Sed MoreHelp->clear(); 1024193323Sed 1025193323Sed // If we had an error processing our arguments, don't let the program execute 1026193323Sed if (ErrorParsing) exit(1); 1027193323Sed} 1028193323Sed 1029193323Sed//===----------------------------------------------------------------------===// 1030193323Sed// Option Base class implementation 1031193323Sed// 1032193323Sed 1033198090Srdivackybool Option::error(const Twine &Message, StringRef ArgName) { 1034198090Srdivacky if (ArgName.data() == 0) ArgName = ArgStr; 1035198090Srdivacky if (ArgName.empty()) 1036198090Srdivacky errs() << HelpStr; // Be nice for positional arguments 1037193323Sed else 1038198090Srdivacky errs() << ProgramName << ": for the -" << ArgName; 1039193323Sed 1040198090Srdivacky errs() << " option: " << Message << "\n"; 1041193323Sed return true; 1042193323Sed} 1043193323Sed 1044198090Srdivackybool Option::addOccurrence(unsigned pos, StringRef ArgName, 1045198090Srdivacky StringRef Value, bool MultiArg) { 1046193323Sed if (!MultiArg) 1047193323Sed NumOccurrences++; // Increment the number of times we have been seen 1048193323Sed 1049193323Sed switch (getNumOccurrencesFlag()) { 1050193323Sed case Optional: 1051193323Sed if (NumOccurrences > 1) 1052198090Srdivacky return error("may only occur zero or one times!", ArgName); 1053193323Sed break; 1054193323Sed case Required: 1055193323Sed if (NumOccurrences > 1) 1056198090Srdivacky return error("must occur exactly one time!", ArgName); 1057193323Sed // Fall through 1058193323Sed case OneOrMore: 1059193323Sed case ZeroOrMore: 1060193323Sed case ConsumeAfter: break; 1061193323Sed } 1062193323Sed 1063193323Sed return handleOccurrence(pos, ArgName, Value); 1064193323Sed} 1065193323Sed 1066193323Sed 1067193323Sed// getValueStr - Get the value description string, using "DefaultMsg" if nothing 1068193323Sed// has been specified yet. 1069193323Sed// 1070193323Sedstatic const char *getValueStr(const Option &O, const char *DefaultMsg) { 1071193323Sed if (O.ValueStr[0] == 0) return DefaultMsg; 1072193323Sed return O.ValueStr; 1073193323Sed} 1074193323Sed 1075193323Sed//===----------------------------------------------------------------------===// 1076193323Sed// cl::alias class implementation 1077193323Sed// 1078193323Sed 1079193323Sed// Return the width of the option tag for printing... 1080193323Sedsize_t alias::getOptionWidth() const { 1081193323Sed return std::strlen(ArgStr)+6; 1082193323Sed} 1083193323Sed 1084263508Sdimstatic void printHelpStr(StringRef HelpStr, size_t Indent, 1085263508Sdim size_t FirstLineIndentedBy) { 1086263508Sdim std::pair<StringRef, StringRef> Split = HelpStr.split('\n'); 1087263508Sdim outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n"; 1088263508Sdim while (!Split.second.empty()) { 1089263508Sdim Split = Split.second.split('\n'); 1090263508Sdim outs().indent(Indent) << Split.first << "\n"; 1091263508Sdim } 1092263508Sdim} 1093263508Sdim 1094193323Sed// Print out the option for the alias. 1095193323Sedvoid alias::printOptionInfo(size_t GlobalWidth) const { 1096224145Sdim outs() << " -" << ArgStr; 1097263508Sdim printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6); 1098193323Sed} 1099193323Sed 1100193323Sed//===----------------------------------------------------------------------===// 1101193323Sed// Parser Implementation code... 1102193323Sed// 1103193323Sed 1104193323Sed// basic_parser implementation 1105193323Sed// 1106193323Sed 1107193323Sed// Return the width of the option tag for printing... 1108193323Sedsize_t basic_parser_impl::getOptionWidth(const Option &O) const { 1109193323Sed size_t Len = std::strlen(O.ArgStr); 1110193323Sed if (const char *ValName = getValueName()) 1111193323Sed Len += std::strlen(getValueStr(O, ValName))+3; 1112193323Sed 1113193323Sed return Len + 6; 1114193323Sed} 1115193323Sed 1116193323Sed// printOptionInfo - Print out information about this option. The 1117193323Sed// to-be-maintained width is specified. 1118193323Sed// 1119193323Sedvoid basic_parser_impl::printOptionInfo(const Option &O, 1120193323Sed size_t GlobalWidth) const { 1121198090Srdivacky outs() << " -" << O.ArgStr; 1122193323Sed 1123193323Sed if (const char *ValName = getValueName()) 1124198090Srdivacky outs() << "=<" << getValueStr(O, ValName) << '>'; 1125193323Sed 1126263508Sdim printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 1127193323Sed} 1128193323Sed 1129221345Sdimvoid basic_parser_impl::printOptionName(const Option &O, 1130221345Sdim size_t GlobalWidth) const { 1131221345Sdim outs() << " -" << O.ArgStr; 1132221345Sdim outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1133221345Sdim} 1134193323Sed 1135193323Sed 1136193323Sed// parser<bool> implementation 1137193323Sed// 1138198090Srdivackybool parser<bool>::parse(Option &O, StringRef ArgName, 1139198090Srdivacky StringRef Arg, bool &Value) { 1140193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1141193323Sed Arg == "1") { 1142193323Sed Value = true; 1143198090Srdivacky return false; 1144198090Srdivacky } 1145199989Srdivacky 1146198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1147193323Sed Value = false; 1148198090Srdivacky return false; 1149193323Sed } 1150198090Srdivacky return O.error("'" + Arg + 1151198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 1152193323Sed} 1153193323Sed 1154193323Sed// parser<boolOrDefault> implementation 1155193323Sed// 1156198090Srdivackybool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 1157198090Srdivacky StringRef Arg, boolOrDefault &Value) { 1158193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 1159193323Sed Arg == "1") { 1160193323Sed Value = BOU_TRUE; 1161198090Srdivacky return false; 1162198090Srdivacky } 1163198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 1164193323Sed Value = BOU_FALSE; 1165198090Srdivacky return false; 1166193323Sed } 1167199989Srdivacky 1168198090Srdivacky return O.error("'" + Arg + 1169198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 1170193323Sed} 1171193323Sed 1172193323Sed// parser<int> implementation 1173193323Sed// 1174198090Srdivackybool parser<int>::parse(Option &O, StringRef ArgName, 1175198090Srdivacky StringRef Arg, int &Value) { 1176198090Srdivacky if (Arg.getAsInteger(0, Value)) 1177198090Srdivacky return O.error("'" + Arg + "' value invalid for integer argument!"); 1178193323Sed return false; 1179193323Sed} 1180193323Sed 1181193323Sed// parser<unsigned> implementation 1182193323Sed// 1183198090Srdivackybool parser<unsigned>::parse(Option &O, StringRef ArgName, 1184198090Srdivacky StringRef Arg, unsigned &Value) { 1185198090Srdivacky 1186198090Srdivacky if (Arg.getAsInteger(0, Value)) 1187198090Srdivacky return O.error("'" + Arg + "' value invalid for uint argument!"); 1188193323Sed return false; 1189193323Sed} 1190193323Sed 1191226633Sdim// parser<unsigned long long> implementation 1192226633Sdim// 1193226633Sdimbool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1194226633Sdim StringRef Arg, unsigned long long &Value){ 1195226633Sdim 1196226633Sdim if (Arg.getAsInteger(0, Value)) 1197226633Sdim return O.error("'" + Arg + "' value invalid for uint argument!"); 1198226633Sdim return false; 1199226633Sdim} 1200226633Sdim 1201193323Sed// parser<double>/parser<float> implementation 1202193323Sed// 1203198090Srdivackystatic bool parseDouble(Option &O, StringRef Arg, double &Value) { 1204198090Srdivacky SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1205198090Srdivacky const char *ArgStart = TmpStr.c_str(); 1206193323Sed char *End; 1207193323Sed Value = strtod(ArgStart, &End); 1208193323Sed if (*End != 0) 1209198090Srdivacky return O.error("'" + Arg + "' value invalid for floating point argument!"); 1210193323Sed return false; 1211193323Sed} 1212193323Sed 1213198090Srdivackybool parser<double>::parse(Option &O, StringRef ArgName, 1214198090Srdivacky StringRef Arg, double &Val) { 1215193323Sed return parseDouble(O, Arg, Val); 1216193323Sed} 1217193323Sed 1218198090Srdivackybool parser<float>::parse(Option &O, StringRef ArgName, 1219198090Srdivacky StringRef Arg, float &Val) { 1220193323Sed double dVal; 1221193323Sed if (parseDouble(O, Arg, dVal)) 1222193323Sed return true; 1223193323Sed Val = (float)dVal; 1224193323Sed return false; 1225193323Sed} 1226193323Sed 1227193323Sed 1228193323Sed 1229193323Sed// generic_parser_base implementation 1230193323Sed// 1231193323Sed 1232193323Sed// findOption - Return the option number corresponding to the specified 1233193323Sed// argument string. If the option is not found, getNumOptions() is returned. 1234193323Sed// 1235193323Sedunsigned generic_parser_base::findOption(const char *Name) { 1236198090Srdivacky unsigned e = getNumOptions(); 1237193323Sed 1238198090Srdivacky for (unsigned i = 0; i != e; ++i) { 1239198090Srdivacky if (strcmp(getOption(i), Name) == 0) 1240193323Sed return i; 1241198090Srdivacky } 1242193323Sed return e; 1243193323Sed} 1244193323Sed 1245193323Sed 1246193323Sed// Return the width of the option tag for printing... 1247193323Sedsize_t generic_parser_base::getOptionWidth(const Option &O) const { 1248193323Sed if (O.hasArgStr()) { 1249193323Sed size_t Size = std::strlen(O.ArgStr)+6; 1250193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1251193323Sed Size = std::max(Size, std::strlen(getOption(i))+8); 1252193323Sed return Size; 1253193323Sed } else { 1254193323Sed size_t BaseSize = 0; 1255193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1256193323Sed BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1257193323Sed return BaseSize; 1258193323Sed } 1259193323Sed} 1260193323Sed 1261193323Sed// printOptionInfo - Print out information about this option. The 1262193323Sed// to-be-maintained width is specified. 1263193323Sed// 1264193323Sedvoid generic_parser_base::printOptionInfo(const Option &O, 1265193323Sed size_t GlobalWidth) const { 1266193323Sed if (O.hasArgStr()) { 1267198090Srdivacky outs() << " -" << O.ArgStr; 1268263508Sdim printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6); 1269193323Sed 1270193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1271193323Sed size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1272198090Srdivacky outs() << " =" << getOption(i); 1273198090Srdivacky outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1274193323Sed } 1275193323Sed } else { 1276193323Sed if (O.HelpStr[0]) 1277198090Srdivacky outs() << " " << O.HelpStr << '\n'; 1278193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1279263508Sdim const char *Option = getOption(i); 1280263508Sdim outs() << " -" << Option; 1281263508Sdim printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8); 1282193323Sed } 1283193323Sed } 1284193323Sed} 1285193323Sed 1286221345Sdimstatic const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1287193323Sed 1288221345Sdim// printGenericOptionDiff - Print the value of this option and it's default. 1289221345Sdim// 1290221345Sdim// "Generic" options have each value mapped to a name. 1291221345Sdimvoid generic_parser_base:: 1292221345SdimprintGenericOptionDiff(const Option &O, const GenericOptionValue &Value, 1293221345Sdim const GenericOptionValue &Default, 1294221345Sdim size_t GlobalWidth) const { 1295221345Sdim outs() << " -" << O.ArgStr; 1296221345Sdim outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1297221345Sdim 1298221345Sdim unsigned NumOpts = getNumOptions(); 1299221345Sdim for (unsigned i = 0; i != NumOpts; ++i) { 1300221345Sdim if (Value.compare(getOptionValue(i))) 1301221345Sdim continue; 1302221345Sdim 1303221345Sdim outs() << "= " << getOption(i); 1304221345Sdim size_t L = std::strlen(getOption(i)); 1305221345Sdim size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1306221345Sdim outs().indent(NumSpaces) << " (default: "; 1307221345Sdim for (unsigned j = 0; j != NumOpts; ++j) { 1308221345Sdim if (Default.compare(getOptionValue(j))) 1309221345Sdim continue; 1310221345Sdim outs() << getOption(j); 1311221345Sdim break; 1312221345Sdim } 1313221345Sdim outs() << ")\n"; 1314221345Sdim return; 1315221345Sdim } 1316221345Sdim outs() << "= *unknown option value*\n"; 1317221345Sdim} 1318221345Sdim 1319221345Sdim// printOptionDiff - Specializations for printing basic value types. 1320221345Sdim// 1321221345Sdim#define PRINT_OPT_DIFF(T) \ 1322221345Sdim void parser<T>:: \ 1323221345Sdim printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1324221345Sdim size_t GlobalWidth) const { \ 1325221345Sdim printOptionName(O, GlobalWidth); \ 1326221345Sdim std::string Str; \ 1327221345Sdim { \ 1328221345Sdim raw_string_ostream SS(Str); \ 1329221345Sdim SS << V; \ 1330221345Sdim } \ 1331221345Sdim outs() << "= " << Str; \ 1332221345Sdim size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\ 1333221345Sdim outs().indent(NumSpaces) << " (default: "; \ 1334221345Sdim if (D.hasValue()) \ 1335221345Sdim outs() << D.getValue(); \ 1336221345Sdim else \ 1337221345Sdim outs() << "*no default*"; \ 1338221345Sdim outs() << ")\n"; \ 1339221345Sdim } \ 1340221345Sdim 1341221345SdimPRINT_OPT_DIFF(bool) 1342221345SdimPRINT_OPT_DIFF(boolOrDefault) 1343221345SdimPRINT_OPT_DIFF(int) 1344221345SdimPRINT_OPT_DIFF(unsigned) 1345226633SdimPRINT_OPT_DIFF(unsigned long long) 1346221345SdimPRINT_OPT_DIFF(double) 1347221345SdimPRINT_OPT_DIFF(float) 1348221345SdimPRINT_OPT_DIFF(char) 1349221345Sdim 1350221345Sdimvoid parser<std::string>:: 1351221345SdimprintOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, 1352221345Sdim size_t GlobalWidth) const { 1353221345Sdim printOptionName(O, GlobalWidth); 1354221345Sdim outs() << "= " << V; 1355221345Sdim size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1356221345Sdim outs().indent(NumSpaces) << " (default: "; 1357221345Sdim if (D.hasValue()) 1358221345Sdim outs() << D.getValue(); 1359221345Sdim else 1360221345Sdim outs() << "*no default*"; 1361221345Sdim outs() << ")\n"; 1362221345Sdim} 1363221345Sdim 1364221345Sdim// Print a placeholder for options that don't yet support printOptionDiff(). 1365221345Sdimvoid basic_parser_impl:: 1366221345SdimprintOptionNoValue(const Option &O, size_t GlobalWidth) const { 1367221345Sdim printOptionName(O, GlobalWidth); 1368221345Sdim outs() << "= *cannot print option value*\n"; 1369221345Sdim} 1370221345Sdim 1371193323Sed//===----------------------------------------------------------------------===// 1372204642Srdivacky// -help and -help-hidden option implementation 1373193323Sed// 1374193323Sed 1375198090Srdivackystatic int OptNameCompare(const void *LHS, const void *RHS) { 1376198090Srdivacky typedef std::pair<const char *, Option*> pair_ty; 1377199989Srdivacky 1378234353Sdim return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first); 1379198090Srdivacky} 1380198090Srdivacky 1381221345Sdim// Copy Options into a vector so we can sort them as we like. 1382221345Sdimstatic void 1383221345SdimsortOpts(StringMap<Option*> &OptMap, 1384221345Sdim SmallVectorImpl< std::pair<const char *, Option*> > &Opts, 1385221345Sdim bool ShowHidden) { 1386221345Sdim SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1387221345Sdim 1388221345Sdim for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1389221345Sdim I != E; ++I) { 1390221345Sdim // Ignore really-hidden options. 1391221345Sdim if (I->second->getOptionHiddenFlag() == ReallyHidden) 1392221345Sdim continue; 1393221345Sdim 1394221345Sdim // Unless showhidden is set, ignore hidden flags. 1395221345Sdim if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1396221345Sdim continue; 1397221345Sdim 1398221345Sdim // If we've already seen this option, don't add it to the list again. 1399221345Sdim if (!OptionSet.insert(I->second)) 1400221345Sdim continue; 1401221345Sdim 1402221345Sdim Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1403221345Sdim I->second)); 1404221345Sdim } 1405221345Sdim 1406221345Sdim // Sort the options list alphabetically. 1407221345Sdim qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1408221345Sdim} 1409221345Sdim 1410193323Sednamespace { 1411193323Sed 1412193323Sedclass HelpPrinter { 1413251662Sdimprotected: 1414193323Sed const bool ShowHidden; 1415251662Sdim typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector; 1416251662Sdim // Print the options. Opts is assumed to be alphabetically sorted. 1417251662Sdim virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1418251662Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1419251662Sdim Opts[i].second->printOptionInfo(MaxArgLen); 1420251662Sdim } 1421193323Sed 1422193323Sedpublic: 1423249423Sdim explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1424251662Sdim virtual ~HelpPrinter() {} 1425193323Sed 1426251662Sdim // Invoke the printer. 1427193323Sed void operator=(bool Value) { 1428193323Sed if (Value == false) return; 1429193323Sed 1430193323Sed // Get all the options. 1431198090Srdivacky SmallVector<Option*, 4> PositionalOpts; 1432198090Srdivacky SmallVector<Option*, 4> SinkOpts; 1433198090Srdivacky StringMap<Option*> OptMap; 1434193323Sed GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1435193323Sed 1436251662Sdim StrOptionPairVector Opts; 1437221345Sdim sortOpts(OptMap, Opts, ShowHidden); 1438193323Sed 1439193323Sed if (ProgramOverview) 1440198090Srdivacky outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1441193323Sed 1442198090Srdivacky outs() << "USAGE: " << ProgramName << " [options]"; 1443193323Sed 1444193323Sed // Print out the positional options. 1445193323Sed Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1446193323Sed if (!PositionalOpts.empty() && 1447193323Sed PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1448193323Sed CAOpt = PositionalOpts[0]; 1449193323Sed 1450193323Sed for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1451193323Sed if (PositionalOpts[i]->ArgStr[0]) 1452198090Srdivacky outs() << " --" << PositionalOpts[i]->ArgStr; 1453198090Srdivacky outs() << " " << PositionalOpts[i]->HelpStr; 1454193323Sed } 1455193323Sed 1456193323Sed // Print the consume after option info if it exists... 1457198090Srdivacky if (CAOpt) outs() << " " << CAOpt->HelpStr; 1458193323Sed 1459198090Srdivacky outs() << "\n\n"; 1460193323Sed 1461193323Sed // Compute the maximum argument length... 1462249423Sdim size_t MaxArgLen = 0; 1463193323Sed for (size_t i = 0, e = Opts.size(); i != e; ++i) 1464193323Sed MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1465193323Sed 1466198090Srdivacky outs() << "OPTIONS:\n"; 1467251662Sdim printOptions(Opts, MaxArgLen); 1468193323Sed 1469193323Sed // Print any extra help the user has declared. 1470193323Sed for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1471251662Sdim E = MoreHelp->end(); 1472251662Sdim I != E; ++I) 1473198090Srdivacky outs() << *I; 1474193323Sed MoreHelp->clear(); 1475193323Sed 1476193323Sed // Halt the program since help information was printed 1477193323Sed exit(1); 1478193323Sed } 1479193323Sed}; 1480251662Sdim 1481251662Sdimclass CategorizedHelpPrinter : public HelpPrinter { 1482251662Sdimpublic: 1483251662Sdim explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1484251662Sdim 1485251662Sdim // Helper function for printOptions(). 1486251662Sdim // It shall return true if A's name should be lexographically 1487251662Sdim // ordered before B's name. It returns false otherwise. 1488251662Sdim static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) { 1489251662Sdim int Length = strcmp(A->getName(), B->getName()); 1490251662Sdim assert(Length != 0 && "Duplicate option categories"); 1491251662Sdim return Length < 0; 1492251662Sdim } 1493251662Sdim 1494251662Sdim // Make sure we inherit our base class's operator=() 1495251662Sdim using HelpPrinter::operator= ; 1496251662Sdim 1497251662Sdimprotected: 1498251662Sdim virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1499251662Sdim std::vector<OptionCategory *> SortedCategories; 1500251662Sdim std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions; 1501251662Sdim 1502251662Sdim // Collect registered option categories into vector in preperation for 1503251662Sdim // sorting. 1504251662Sdim for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(), 1505251662Sdim E = RegisteredOptionCategories->end(); 1506251662Sdim I != E; ++I) 1507251662Sdim SortedCategories.push_back(*I); 1508251662Sdim 1509251662Sdim // Sort the different option categories alphabetically. 1510251662Sdim assert(SortedCategories.size() > 0 && "No option categories registered!"); 1511251662Sdim std::sort(SortedCategories.begin(), SortedCategories.end(), 1512251662Sdim OptionCategoryCompare); 1513251662Sdim 1514251662Sdim // Create map to empty vectors. 1515251662Sdim for (std::vector<OptionCategory *>::const_iterator 1516251662Sdim I = SortedCategories.begin(), 1517251662Sdim E = SortedCategories.end(); 1518251662Sdim I != E; ++I) 1519251662Sdim CategorizedOptions[*I] = std::vector<Option *>(); 1520251662Sdim 1521251662Sdim // Walk through pre-sorted options and assign into categories. 1522251662Sdim // Because the options are already alphabetically sorted the 1523251662Sdim // options within categories will also be alphabetically sorted. 1524251662Sdim for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1525251662Sdim Option *Opt = Opts[I].second; 1526251662Sdim assert(CategorizedOptions.count(Opt->Category) > 0 && 1527251662Sdim "Option has an unregistered category"); 1528251662Sdim CategorizedOptions[Opt->Category].push_back(Opt); 1529251662Sdim } 1530251662Sdim 1531251662Sdim // Now do printing. 1532251662Sdim for (std::vector<OptionCategory *>::const_iterator 1533251662Sdim Category = SortedCategories.begin(), 1534251662Sdim E = SortedCategories.end(); 1535251662Sdim Category != E; ++Category) { 1536251662Sdim // Hide empty categories for -help, but show for -help-hidden. 1537251662Sdim bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1538251662Sdim if (!ShowHidden && IsEmptyCategory) 1539251662Sdim continue; 1540251662Sdim 1541251662Sdim // Print category information. 1542251662Sdim outs() << "\n"; 1543251662Sdim outs() << (*Category)->getName() << ":\n"; 1544251662Sdim 1545251662Sdim // Check if description is set. 1546251662Sdim if ((*Category)->getDescription() != 0) 1547251662Sdim outs() << (*Category)->getDescription() << "\n\n"; 1548251662Sdim else 1549251662Sdim outs() << "\n"; 1550251662Sdim 1551251662Sdim // When using -help-hidden explicitly state if the category has no 1552251662Sdim // options associated with it. 1553251662Sdim if (IsEmptyCategory) { 1554251662Sdim outs() << " This option category has no options.\n"; 1555251662Sdim continue; 1556251662Sdim } 1557251662Sdim // Loop over the options in the category and print. 1558251662Sdim for (std::vector<Option *>::const_iterator 1559251662Sdim Opt = CategorizedOptions[*Category].begin(), 1560251662Sdim E = CategorizedOptions[*Category].end(); 1561251662Sdim Opt != E; ++Opt) 1562251662Sdim (*Opt)->printOptionInfo(MaxArgLen); 1563251662Sdim } 1564251662Sdim } 1565251662Sdim}; 1566251662Sdim 1567251662Sdim// This wraps the Uncategorizing and Categorizing printers and decides 1568251662Sdim// at run time which should be invoked. 1569251662Sdimclass HelpPrinterWrapper { 1570251662Sdimprivate: 1571251662Sdim HelpPrinter &UncategorizedPrinter; 1572251662Sdim CategorizedHelpPrinter &CategorizedPrinter; 1573251662Sdim 1574251662Sdimpublic: 1575251662Sdim explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1576251662Sdim CategorizedHelpPrinter &CategorizedPrinter) : 1577251662Sdim UncategorizedPrinter(UncategorizedPrinter), 1578251662Sdim CategorizedPrinter(CategorizedPrinter) { } 1579251662Sdim 1580251662Sdim // Invoke the printer. 1581251662Sdim void operator=(bool Value); 1582251662Sdim}; 1583251662Sdim 1584193323Sed} // End anonymous namespace 1585193323Sed 1586251662Sdim// Declare the four HelpPrinter instances that are used to print out help, or 1587251662Sdim// help-hidden as an uncategorized list or in categories. 1588251662Sdimstatic HelpPrinter UncategorizedNormalPrinter(false); 1589251662Sdimstatic HelpPrinter UncategorizedHiddenPrinter(true); 1590251662Sdimstatic CategorizedHelpPrinter CategorizedNormalPrinter(false); 1591251662Sdimstatic CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1592193323Sed 1593251662Sdim 1594251662Sdim// Declare HelpPrinter wrappers that will decide whether or not to invoke 1595251662Sdim// a categorizing help printer 1596251662Sdimstatic HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1597251662Sdim CategorizedNormalPrinter); 1598251662Sdimstatic HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1599251662Sdim CategorizedHiddenPrinter); 1600251662Sdim 1601251662Sdim// Define uncategorized help printers. 1602251662Sdim// -help-list is hidden by default because if Option categories are being used 1603251662Sdim// then -help behaves the same as -help-list. 1604193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> > 1605251662SdimHLOp("help-list", 1606251662Sdim cl::desc("Display list of available options (-help-list-hidden for more)"), 1607251662Sdim cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed); 1608251662Sdim 1609251662Sdimstatic cl::opt<HelpPrinter, true, parser<bool> > 1610251662SdimHLHOp("help-list-hidden", 1611251662Sdim cl::desc("Display list of all available options"), 1612251662Sdim cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1613251662Sdim 1614251662Sdim// Define uncategorized/categorized help printers. These printers change their 1615251662Sdim// behaviour at runtime depending on whether one or more Option categories have 1616251662Sdim// been declared. 1617251662Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool> > 1618204642SrdivackyHOp("help", cl::desc("Display available options (-help-hidden for more)"), 1619251662Sdim cl::location(WrappedNormalPrinter), cl::ValueDisallowed); 1620193323Sed 1621251662Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool> > 1622193323SedHHOp("help-hidden", cl::desc("Display all available options"), 1623251662Sdim cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1624193323Sed 1625251662Sdim 1626251662Sdim 1627221345Sdimstatic cl::opt<bool> 1628221345SdimPrintOptions("print-options", 1629221345Sdim cl::desc("Print non-default options after command line parsing"), 1630221345Sdim cl::Hidden, cl::init(false)); 1631221345Sdim 1632221345Sdimstatic cl::opt<bool> 1633221345SdimPrintAllOptions("print-all-options", 1634221345Sdim cl::desc("Print all option values after command line parsing"), 1635221345Sdim cl::Hidden, cl::init(false)); 1636221345Sdim 1637251662Sdimvoid HelpPrinterWrapper::operator=(bool Value) { 1638251662Sdim if (Value == false) 1639251662Sdim return; 1640251662Sdim 1641251662Sdim // Decide which printer to invoke. If more than one option category is 1642251662Sdim // registered then it is useful to show the categorized help instead of 1643251662Sdim // uncategorized help. 1644251662Sdim if (RegisteredOptionCategories->size() > 1) { 1645251662Sdim // unhide -help-list option so user can have uncategorized output if they 1646251662Sdim // want it. 1647251662Sdim HLOp.setHiddenFlag(NotHidden); 1648251662Sdim 1649251662Sdim CategorizedPrinter = true; // Invoke categorized printer 1650251662Sdim } 1651251662Sdim else 1652251662Sdim UncategorizedPrinter = true; // Invoke uncategorized printer 1653251662Sdim} 1654251662Sdim 1655221345Sdim// Print the value of each option. 1656221345Sdimvoid cl::PrintOptionValues() { 1657221345Sdim if (!PrintOptions && !PrintAllOptions) return; 1658221345Sdim 1659221345Sdim // Get all the options. 1660221345Sdim SmallVector<Option*, 4> PositionalOpts; 1661221345Sdim SmallVector<Option*, 4> SinkOpts; 1662221345Sdim StringMap<Option*> OptMap; 1663221345Sdim GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1664221345Sdim 1665221345Sdim SmallVector<std::pair<const char *, Option*>, 128> Opts; 1666221345Sdim sortOpts(OptMap, Opts, /*ShowHidden*/true); 1667221345Sdim 1668221345Sdim // Compute the maximum argument length... 1669221345Sdim size_t MaxArgLen = 0; 1670221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1671221345Sdim MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1672221345Sdim 1673221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1674221345Sdim Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1675221345Sdim} 1676221345Sdim 1677193323Sedstatic void (*OverrideVersionPrinter)() = 0; 1678193323Sed 1679226633Sdimstatic std::vector<void (*)()>* ExtraVersionPrinters = 0; 1680198090Srdivacky 1681193323Sednamespace { 1682193323Sedclass VersionPrinter { 1683193323Sedpublic: 1684193323Sed void print() { 1685198090Srdivacky raw_ostream &OS = outs(); 1686234353Sdim OS << "LLVM (http://llvm.org/):\n" 1687198090Srdivacky << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1688193323Sed#ifdef LLVM_VERSION_INFO 1689198090Srdivacky OS << LLVM_VERSION_INFO; 1690193323Sed#endif 1691198090Srdivacky OS << "\n "; 1692193323Sed#ifndef __OPTIMIZE__ 1693198090Srdivacky OS << "DEBUG build"; 1694193323Sed#else 1695198090Srdivacky OS << "Optimized build"; 1696193323Sed#endif 1697193323Sed#ifndef NDEBUG 1698198090Srdivacky OS << " with assertions"; 1699193323Sed#endif 1700199481Srdivacky std::string CPU = sys::getHostCPUName(); 1701199481Srdivacky if (CPU == "generic") CPU = "(unknown)"; 1702198090Srdivacky OS << ".\n" 1703226633Sdim#if (ENABLE_TIMESTAMPS == 1) 1704198090Srdivacky << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1705208599Srdivacky#endif 1706234353Sdim << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1707226633Sdim << " Host CPU: " << CPU << '\n'; 1708193323Sed } 1709193323Sed void operator=(bool OptionWasSpecified) { 1710198090Srdivacky if (!OptionWasSpecified) return; 1711199989Srdivacky 1712226633Sdim if (OverrideVersionPrinter != 0) { 1713226633Sdim (*OverrideVersionPrinter)(); 1714198090Srdivacky exit(1); 1715193323Sed } 1716226633Sdim print(); 1717226633Sdim 1718226633Sdim // Iterate over any registered extra printers and call them to add further 1719226633Sdim // information. 1720226633Sdim if (ExtraVersionPrinters != 0) { 1721226633Sdim outs() << '\n'; 1722226633Sdim for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1723226633Sdim E = ExtraVersionPrinters->end(); 1724226633Sdim I != E; ++I) 1725226633Sdim (*I)(); 1726226633Sdim } 1727226633Sdim 1728198090Srdivacky exit(1); 1729193323Sed } 1730193323Sed}; 1731193323Sed} // End anonymous namespace 1732193323Sed 1733193323Sed 1734193323Sed// Define the --version option that prints out the LLVM version for the tool 1735193323Sedstatic VersionPrinter VersionPrinterInstance; 1736193323Sed 1737193323Sedstatic cl::opt<VersionPrinter, true, parser<bool> > 1738193323SedVersOp("version", cl::desc("Display the version of this program"), 1739193323Sed cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1740193323Sed 1741193323Sed// Utility function for printing the help message. 1742251662Sdimvoid cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1743251662Sdim // This looks weird, but it actually prints the help message. The Printers are 1744251662Sdim // types of HelpPrinter and the help gets printed when its operator= is 1745251662Sdim // invoked. That's because the "normal" usages of the help printer is to be 1746251662Sdim // assigned true/false depending on whether -help or -help-hidden was given or 1747251662Sdim // not. Since we're circumventing that we have to make it look like -help or 1748251662Sdim // -help-hidden were given, so we assign true. 1749251662Sdim 1750251662Sdim if (!Hidden && !Categorized) 1751251662Sdim UncategorizedNormalPrinter = true; 1752251662Sdim else if (!Hidden && Categorized) 1753251662Sdim CategorizedNormalPrinter = true; 1754251662Sdim else if (Hidden && !Categorized) 1755251662Sdim UncategorizedHiddenPrinter = true; 1756251662Sdim else 1757251662Sdim CategorizedHiddenPrinter = true; 1758193323Sed} 1759193323Sed 1760193323Sed/// Utility function for printing version number. 1761193323Sedvoid cl::PrintVersionMessage() { 1762193323Sed VersionPrinterInstance.print(); 1763193323Sed} 1764193323Sed 1765193323Sedvoid cl::SetVersionPrinter(void (*func)()) { 1766193323Sed OverrideVersionPrinter = func; 1767193323Sed} 1768226633Sdim 1769226633Sdimvoid cl::AddExtraVersionPrinter(void (*func)()) { 1770226633Sdim if (ExtraVersionPrinters == 0) 1771226633Sdim ExtraVersionPrinters = new std::vector<void (*)()>; 1772226633Sdim 1773226633Sdim ExtraVersionPrinters->push_back(func); 1774226633Sdim} 1775251662Sdim 1776251662Sdimvoid cl::getRegisteredOptions(StringMap<Option*> &Map) 1777251662Sdim{ 1778251662Sdim // Get all the options. 1779251662Sdim SmallVector<Option*, 4> PositionalOpts; //NOT USED 1780251662Sdim SmallVector<Option*, 4> SinkOpts; //NOT USED 1781251662Sdim assert(Map.size() == 0 && "StringMap must be empty"); 1782251662Sdim GetOptionInfo(PositionalOpts, SinkOpts, Map); 1783251662Sdim return; 1784251662Sdim} 1785