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" 20198090Srdivacky#include "llvm/ADT/OwningPtr.h" 21198090Srdivacky#include "llvm/ADT/SmallPtrSet.h" 22198090Srdivacky#include "llvm/ADT/SmallString.h" 23198090Srdivacky#include "llvm/ADT/StringMap.h" 24198090Srdivacky#include "llvm/ADT/Twine.h" 25198090Srdivacky#include "llvm/Config/config.h" 26249423Sdim#include "llvm/Support/Debug.h" 27249423Sdim#include "llvm/Support/ErrorHandling.h" 28249423Sdim#include "llvm/Support/Host.h" 29249423Sdim#include "llvm/Support/ManagedStatic.h" 30249423Sdim#include "llvm/Support/MemoryBuffer.h" 31249423Sdim#include "llvm/Support/Path.h" 32249423Sdim#include "llvm/Support/raw_ostream.h" 33249423Sdim#include "llvm/Support/system_error.h" 34198090Srdivacky#include <cerrno> 35193323Sed#include <cstdlib> 36251662Sdim#include <map> 37193323Sedusing namespace llvm; 38193323Sedusing namespace cl; 39193323Sed 40193323Sed//===----------------------------------------------------------------------===// 41193323Sed// Template instantiations and anchors. 42193323Sed// 43199989Srdivackynamespace llvm { namespace cl { 44193323SedTEMPLATE_INSTANTIATION(class basic_parser<bool>); 45193323SedTEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 46193323SedTEMPLATE_INSTANTIATION(class basic_parser<int>); 47193323SedTEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 48226633SdimTEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); 49193323SedTEMPLATE_INSTANTIATION(class basic_parser<double>); 50193323SedTEMPLATE_INSTANTIATION(class basic_parser<float>); 51193323SedTEMPLATE_INSTANTIATION(class basic_parser<std::string>); 52193323SedTEMPLATE_INSTANTIATION(class basic_parser<char>); 53193323Sed 54193323SedTEMPLATE_INSTANTIATION(class opt<unsigned>); 55193323SedTEMPLATE_INSTANTIATION(class opt<int>); 56193323SedTEMPLATE_INSTANTIATION(class opt<std::string>); 57193323SedTEMPLATE_INSTANTIATION(class opt<char>); 58193323SedTEMPLATE_INSTANTIATION(class opt<bool>); 59199989Srdivacky} } // end namespace llvm::cl 60193323Sed 61234353Sdimvoid GenericOptionValue::anchor() {} 62234353Sdimvoid OptionValue<boolOrDefault>::anchor() {} 63234353Sdimvoid OptionValue<std::string>::anchor() {} 64193323Sedvoid Option::anchor() {} 65193323Sedvoid basic_parser_impl::anchor() {} 66193323Sedvoid parser<bool>::anchor() {} 67193323Sedvoid parser<boolOrDefault>::anchor() {} 68193323Sedvoid parser<int>::anchor() {} 69193323Sedvoid parser<unsigned>::anchor() {} 70226633Sdimvoid parser<unsigned long long>::anchor() {} 71193323Sedvoid parser<double>::anchor() {} 72193323Sedvoid parser<float>::anchor() {} 73193323Sedvoid parser<std::string>::anchor() {} 74193323Sedvoid parser<char>::anchor() {} 75193323Sed 76193323Sed//===----------------------------------------------------------------------===// 77193323Sed 78193323Sed// Globals for name and overview of program. Program name is not a string to 79193323Sed// avoid static ctor/dtor issues. 80193323Sedstatic char ProgramName[80] = "<premain>"; 81193323Sedstatic const char *ProgramOverview = 0; 82193323Sed 83193323Sed// This collects additional help to be printed. 84193323Sedstatic ManagedStatic<std::vector<const char*> > MoreHelp; 85193323Sed 86193323Sedextrahelp::extrahelp(const char *Help) 87193323Sed : morehelp(Help) { 88193323Sed MoreHelp->push_back(Help); 89193323Sed} 90193323Sed 91193323Sedstatic bool OptionListChanged = false; 92193323Sed 93193323Sed// MarkOptionsChanged - Internal helper function. 94193323Sedvoid cl::MarkOptionsChanged() { 95193323Sed OptionListChanged = true; 96193323Sed} 97193323Sed 98193323Sed/// RegisteredOptionList - This is the list of the command line options that 99193323Sed/// have statically constructed themselves. 100193323Sedstatic Option *RegisteredOptionList = 0; 101193323Sed 102193323Sedvoid Option::addArgument() { 103193323Sed assert(NextRegistered == 0 && "argument multiply registered!"); 104193323Sed 105193323Sed NextRegistered = RegisteredOptionList; 106193323Sed RegisteredOptionList = this; 107193323Sed MarkOptionsChanged(); 108193323Sed} 109193323Sed 110251662Sdim// This collects the different option categories that have been registered. 111251662Sdimtypedef SmallPtrSet<OptionCategory*,16> OptionCatSet; 112251662Sdimstatic ManagedStatic<OptionCatSet> RegisteredOptionCategories; 113193323Sed 114251662Sdim// Initialise the general option category. 115251662SdimOptionCategory llvm::cl::GeneralCategory("General options"); 116251662Sdim 117251662Sdimvoid OptionCategory::registerCategory() 118251662Sdim{ 119251662Sdim RegisteredOptionCategories->insert(this); 120251662Sdim} 121251662Sdim 122193323Sed//===----------------------------------------------------------------------===// 123193323Sed// Basic, shared command line option processing machinery. 124193323Sed// 125193323Sed 126193323Sed/// GetOptionInfo - Scan the list of registered options, turning them into data 127193323Sed/// structures that are easier to handle. 128198090Srdivackystatic void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 129198090Srdivacky SmallVectorImpl<Option*> &SinkOpts, 130198090Srdivacky StringMap<Option*> &OptionsMap) { 131198090Srdivacky SmallVector<const char*, 16> OptionNames; 132193323Sed Option *CAOpt = 0; // The ConsumeAfter option if it exists. 133193323Sed for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 134193323Sed // If this option wants to handle multiple option names, get the full set. 135193323Sed // This handles enum options like "-O1 -O2" etc. 136193323Sed O->getExtraOptionNames(OptionNames); 137193323Sed if (O->ArgStr[0]) 138193323Sed OptionNames.push_back(O->ArgStr); 139193323Sed 140193323Sed // Handle named options. 141193323Sed for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 142193323Sed // Add argument to the argument map! 143198090Srdivacky if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 144198090Srdivacky errs() << ProgramName << ": CommandLine Error: Argument '" 145193323Sed << OptionNames[i] << "' defined more than once!\n"; 146193323Sed } 147193323Sed } 148193323Sed 149193323Sed OptionNames.clear(); 150193323Sed 151193323Sed // Remember information about positional options. 152193323Sed if (O->getFormattingFlag() == cl::Positional) 153193323Sed PositionalOpts.push_back(O); 154193323Sed else if (O->getMiscFlags() & cl::Sink) // Remember sink options 155193323Sed SinkOpts.push_back(O); 156193323Sed else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 157193323Sed if (CAOpt) 158193323Sed O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 159193323Sed CAOpt = O; 160193323Sed } 161193323Sed } 162193323Sed 163193323Sed if (CAOpt) 164193323Sed PositionalOpts.push_back(CAOpt); 165193323Sed 166193323Sed // Make sure that they are in order of registration not backwards. 167193323Sed std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 168193323Sed} 169193323Sed 170193323Sed 171193323Sed/// LookupOption - Lookup the option specified by the specified option on the 172193323Sed/// command line. If there is a value specified (after an equal sign) return 173198090Srdivacky/// that as well. This assumes that leading dashes have already been stripped. 174198090Srdivackystatic Option *LookupOption(StringRef &Arg, StringRef &Value, 175198090Srdivacky const StringMap<Option*> &OptionsMap) { 176198090Srdivacky // Reject all dashes. 177198090Srdivacky if (Arg.empty()) return 0; 178199989Srdivacky 179198090Srdivacky size_t EqualPos = Arg.find('='); 180199989Srdivacky 181198090Srdivacky // If we have an equals sign, remember the value. 182198090Srdivacky if (EqualPos == StringRef::npos) { 183198090Srdivacky // Look up the option. 184198090Srdivacky StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 185198090Srdivacky return I != OptionsMap.end() ? I->second : 0; 186198090Srdivacky } 187193323Sed 188198090Srdivacky // If the argument before the = is a valid option name, we match. If not, 189198090Srdivacky // return Arg unmolested. 190198090Srdivacky StringMap<Option*>::const_iterator I = 191198090Srdivacky OptionsMap.find(Arg.substr(0, EqualPos)); 192198090Srdivacky if (I == OptionsMap.end()) return 0; 193199989Srdivacky 194198090Srdivacky Value = Arg.substr(EqualPos+1); 195198090Srdivacky Arg = Arg.substr(0, EqualPos); 196198090Srdivacky return I->second; 197198090Srdivacky} 198193323Sed 199218893Sdim/// LookupNearestOption - Lookup the closest match to the option specified by 200218893Sdim/// the specified option on the command line. If there is a value specified 201218893Sdim/// (after an equal sign) return that as well. This assumes that leading dashes 202218893Sdim/// have already been stripped. 203218893Sdimstatic Option *LookupNearestOption(StringRef Arg, 204218893Sdim const StringMap<Option*> &OptionsMap, 205221345Sdim std::string &NearestString) { 206218893Sdim // Reject all dashes. 207218893Sdim if (Arg.empty()) return 0; 208218893Sdim 209218893Sdim // Split on any equal sign. 210221345Sdim std::pair<StringRef, StringRef> SplitArg = Arg.split('='); 211221345Sdim StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. 212221345Sdim StringRef &RHS = SplitArg.second; 213218893Sdim 214218893Sdim // Find the closest match. 215218893Sdim Option *Best = 0; 216218893Sdim unsigned BestDistance = 0; 217218893Sdim for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), 218218893Sdim ie = OptionsMap.end(); it != ie; ++it) { 219218893Sdim Option *O = it->second; 220218893Sdim SmallVector<const char*, 16> OptionNames; 221218893Sdim O->getExtraOptionNames(OptionNames); 222218893Sdim if (O->ArgStr[0]) 223218893Sdim OptionNames.push_back(O->ArgStr); 224218893Sdim 225221345Sdim bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; 226221345Sdim StringRef Flag = PermitValue ? LHS : Arg; 227218893Sdim for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 228218893Sdim StringRef Name = OptionNames[i]; 229218893Sdim unsigned Distance = StringRef(Name).edit_distance( 230221345Sdim Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); 231218893Sdim if (!Best || Distance < BestDistance) { 232218893Sdim Best = O; 233218893Sdim BestDistance = Distance; 234239462Sdim if (RHS.empty() || !PermitValue) 235239462Sdim NearestString = OptionNames[i]; 236239462Sdim else 237239462Sdim NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); 238218893Sdim } 239218893Sdim } 240218893Sdim } 241218893Sdim 242218893Sdim return Best; 243218893Sdim} 244218893Sdim 245199989Srdivacky/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that 246199989Srdivacky/// does special handling of cl::CommaSeparated options. 247199989Srdivackystatic bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, 248199989Srdivacky StringRef ArgName, 249199989Srdivacky StringRef Value, bool MultiArg = false) 250199989Srdivacky{ 251199989Srdivacky // Check to see if this option accepts a comma separated list of values. If 252199989Srdivacky // it does, we have to split up the value into multiple values. 253199989Srdivacky if (Handler->getMiscFlags() & CommaSeparated) { 254199989Srdivacky StringRef Val(Value); 255199989Srdivacky StringRef::size_type Pos = Val.find(','); 256193323Sed 257199989Srdivacky while (Pos != StringRef::npos) { 258199989Srdivacky // Process the portion before the comma. 259199989Srdivacky if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 260199989Srdivacky return true; 261199989Srdivacky // Erase the portion before the comma, AND the comma. 262199989Srdivacky Val = Val.substr(Pos+1); 263199989Srdivacky Value.substr(Pos+1); // Increment the original value pointer as well. 264199989Srdivacky // Check for another comma. 265199989Srdivacky Pos = Val.find(','); 266199989Srdivacky } 267193323Sed 268199989Srdivacky Value = Val; 269199989Srdivacky } 270199989Srdivacky 271199989Srdivacky if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 272199989Srdivacky return true; 273199989Srdivacky 274199989Srdivacky return false; 275199989Srdivacky} 276199989Srdivacky 277198090Srdivacky/// ProvideOption - For Value, this differentiates between an empty value ("") 278198090Srdivacky/// and a null value (StringRef()). The later is accepted for arguments that 279198090Srdivacky/// don't allow a value (-foo) the former is rejected (-foo=). 280198090Srdivackystatic inline bool ProvideOption(Option *Handler, StringRef ArgName, 281234353Sdim StringRef Value, int argc, 282234353Sdim const char *const *argv, int &i) { 283193323Sed // Is this a multi-argument option? 284193323Sed unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 285193323Sed 286193323Sed // Enforce value requirements 287193323Sed switch (Handler->getValueExpectedFlag()) { 288193323Sed case ValueRequired: 289198090Srdivacky if (Value.data() == 0) { // No value specified? 290198090Srdivacky if (i+1 >= argc) 291198090Srdivacky return Handler->error("requires a value!"); 292198090Srdivacky // Steal the next argument, like for '-o filename' 293198090Srdivacky Value = argv[++i]; 294193323Sed } 295193323Sed break; 296193323Sed case ValueDisallowed: 297193323Sed if (NumAdditionalVals > 0) 298198090Srdivacky return Handler->error("multi-valued option specified" 299198090Srdivacky " with ValueDisallowed modifier!"); 300193323Sed 301198090Srdivacky if (Value.data()) 302198090Srdivacky return Handler->error("does not allow a value! '" + 303198090Srdivacky Twine(Value) + "' specified."); 304193323Sed break; 305193323Sed case ValueOptional: 306193323Sed break; 307193323Sed } 308193323Sed 309193323Sed // If this isn't a multi-arg option, just run the handler. 310198090Srdivacky if (NumAdditionalVals == 0) 311199989Srdivacky return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); 312198090Srdivacky 313193323Sed // If it is, run the handle several times. 314198090Srdivacky bool MultiArg = false; 315193323Sed 316198090Srdivacky if (Value.data()) { 317199989Srdivacky if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 318198090Srdivacky return true; 319198090Srdivacky --NumAdditionalVals; 320198090Srdivacky MultiArg = true; 321198090Srdivacky } 322193323Sed 323198090Srdivacky while (NumAdditionalVals > 0) { 324198090Srdivacky if (i+1 >= argc) 325198090Srdivacky return Handler->error("not enough values!"); 326198090Srdivacky Value = argv[++i]; 327199989Srdivacky 328199989Srdivacky if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 329198090Srdivacky return true; 330198090Srdivacky MultiArg = true; 331198090Srdivacky --NumAdditionalVals; 332193323Sed } 333198090Srdivacky return false; 334193323Sed} 335193323Sed 336198090Srdivackystatic bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 337193323Sed int Dummy = i; 338198090Srdivacky return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 339193323Sed} 340193323Sed 341193323Sed 342193323Sed// Option predicates... 343193323Sedstatic inline bool isGrouping(const Option *O) { 344193323Sed return O->getFormattingFlag() == cl::Grouping; 345193323Sed} 346193323Sedstatic inline bool isPrefixedOrGrouping(const Option *O) { 347193323Sed return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 348193323Sed} 349193323Sed 350193323Sed// getOptionPred - Check to see if there are any options that satisfy the 351193323Sed// specified predicate with names that are the prefixes in Name. This is 352193323Sed// checked by progressively stripping characters off of the name, checking to 353193323Sed// see if there options that satisfy the predicate. If we find one, return it, 354193323Sed// otherwise return null. 355193323Sed// 356198090Srdivackystatic Option *getOptionPred(StringRef Name, size_t &Length, 357193323Sed bool (*Pred)(const Option*), 358198090Srdivacky const StringMap<Option*> &OptionsMap) { 359193323Sed 360198090Srdivacky StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 361193323Sed 362198090Srdivacky // Loop while we haven't found an option and Name still has at least two 363198090Srdivacky // characters in it (so that the next iteration will not be the empty 364198090Srdivacky // string. 365198090Srdivacky while (OMI == OptionsMap.end() && Name.size() > 1) { 366198090Srdivacky Name = Name.substr(0, Name.size()-1); // Chop off the last character. 367193323Sed OMI = OptionsMap.find(Name); 368198090Srdivacky } 369193323Sed 370193323Sed if (OMI != OptionsMap.end() && Pred(OMI->second)) { 371198090Srdivacky Length = Name.size(); 372193323Sed return OMI->second; // Found one! 373193323Sed } 374193323Sed return 0; // No option found! 375193323Sed} 376193323Sed 377198090Srdivacky/// HandlePrefixedOrGroupedOption - The specified argument string (which started 378198090Srdivacky/// with at least one '-') does not fully match an available option. Check to 379198090Srdivacky/// see if this is a prefix or grouped option. If so, split arg into output an 380198090Srdivacky/// Arg/Value pair and return the Option to parse it with. 381198090Srdivackystatic Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 382198090Srdivacky bool &ErrorParsing, 383198090Srdivacky const StringMap<Option*> &OptionsMap) { 384198090Srdivacky if (Arg.size() == 1) return 0; 385198090Srdivacky 386198090Srdivacky // Do the lookup! 387198090Srdivacky size_t Length = 0; 388198090Srdivacky Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 389198090Srdivacky if (PGOpt == 0) return 0; 390199989Srdivacky 391198090Srdivacky // If the option is a prefixed option, then the value is simply the 392198090Srdivacky // rest of the name... so fall through to later processing, by 393198090Srdivacky // setting up the argument name flags and value fields. 394198090Srdivacky if (PGOpt->getFormattingFlag() == cl::Prefix) { 395198090Srdivacky Value = Arg.substr(Length); 396198090Srdivacky Arg = Arg.substr(0, Length); 397198090Srdivacky assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 398198090Srdivacky return PGOpt; 399198090Srdivacky } 400199989Srdivacky 401198090Srdivacky // This must be a grouped option... handle them now. Grouping options can't 402198090Srdivacky // have values. 403198090Srdivacky assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 404199989Srdivacky 405198090Srdivacky do { 406198090Srdivacky // Move current arg name out of Arg into OneArgName. 407198090Srdivacky StringRef OneArgName = Arg.substr(0, Length); 408198090Srdivacky Arg = Arg.substr(Length); 409199989Srdivacky 410198090Srdivacky // Because ValueRequired is an invalid flag for grouped arguments, 411198090Srdivacky // we don't need to pass argc/argv in. 412198090Srdivacky assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 413198090Srdivacky "Option can not be cl::Grouping AND cl::ValueRequired!"); 414202375Srdivacky int Dummy = 0; 415198090Srdivacky ErrorParsing |= ProvideOption(PGOpt, OneArgName, 416198090Srdivacky StringRef(), 0, 0, Dummy); 417199989Srdivacky 418198090Srdivacky // Get the next grouping option. 419198090Srdivacky PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 420198090Srdivacky } while (PGOpt && Length != Arg.size()); 421199989Srdivacky 422198090Srdivacky // Return the last option with Arg cut down to just the last one. 423198090Srdivacky return PGOpt; 424198090Srdivacky} 425198090Srdivacky 426198090Srdivacky 427198090Srdivacky 428193323Sedstatic bool RequiresValue(const Option *O) { 429193323Sed return O->getNumOccurrencesFlag() == cl::Required || 430193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 431193323Sed} 432193323Sed 433193323Sedstatic bool EatsUnboundedNumberOfValues(const Option *O) { 434193323Sed return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 435193323Sed O->getNumOccurrencesFlag() == cl::OneOrMore; 436193323Sed} 437193323Sed 438193323Sed/// ParseCStringVector - Break INPUT up wherever one or more 439193323Sed/// whitespace characters are found, and store the resulting tokens in 440193323Sed/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated 441198090Srdivacky/// using strdup(), so it is the caller's responsibility to free() 442193323Sed/// them later. 443193323Sed/// 444198090Srdivackystatic void ParseCStringVector(std::vector<char *> &OutputVector, 445198090Srdivacky const char *Input) { 446193323Sed // Characters which will be treated as token separators: 447198090Srdivacky StringRef Delims = " \v\f\t\r\n"; 448193323Sed 449198090Srdivacky StringRef WorkStr(Input); 450198090Srdivacky while (!WorkStr.empty()) { 451198090Srdivacky // If the first character is a delimiter, strip them off. 452198090Srdivacky if (Delims.find(WorkStr[0]) != StringRef::npos) { 453198090Srdivacky size_t Pos = WorkStr.find_first_not_of(Delims); 454198090Srdivacky if (Pos == StringRef::npos) Pos = WorkStr.size(); 455198090Srdivacky WorkStr = WorkStr.substr(Pos); 456198090Srdivacky continue; 457193323Sed } 458199989Srdivacky 459198090Srdivacky // Find position of first delimiter. 460198090Srdivacky size_t Pos = WorkStr.find_first_of(Delims); 461198090Srdivacky if (Pos == StringRef::npos) Pos = WorkStr.size(); 462199989Srdivacky 463198090Srdivacky // Everything from 0 to Pos is the next word to copy. 464198090Srdivacky char *NewStr = (char*)malloc(Pos+1); 465198090Srdivacky memcpy(NewStr, WorkStr.data(), Pos); 466198090Srdivacky NewStr[Pos] = 0; 467198090Srdivacky OutputVector.push_back(NewStr); 468199989Srdivacky 469198090Srdivacky WorkStr = WorkStr.substr(Pos); 470193323Sed } 471193323Sed} 472193323Sed 473193323Sed/// ParseEnvironmentOptions - An alternative entry point to the 474193323Sed/// CommandLine library, which allows you to read the program's name 475193323Sed/// from the caller (as PROGNAME) and its command-line arguments from 476193323Sed/// an environment variable (whose name is given in ENVVAR). 477193323Sed/// 478193323Sedvoid cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 479243830Sdim const char *Overview) { 480193323Sed // Check args. 481193323Sed assert(progName && "Program name not specified"); 482193323Sed assert(envVar && "Environment variable name missing"); 483193323Sed 484193323Sed // Get the environment variable they want us to parse options out of. 485193323Sed const char *envValue = getenv(envVar); 486193323Sed if (!envValue) 487193323Sed return; 488193323Sed 489193323Sed // Get program's "name", which we wouldn't know without the caller 490193323Sed // telling us. 491193323Sed std::vector<char*> newArgv; 492193323Sed newArgv.push_back(strdup(progName)); 493193323Sed 494193323Sed // Parse the value of the environment variable into a "command line" 495193323Sed // and hand it off to ParseCommandLineOptions(). 496193323Sed ParseCStringVector(newArgv, envValue); 497193323Sed int newArgc = static_cast<int>(newArgv.size()); 498243830Sdim ParseCommandLineOptions(newArgc, &newArgv[0], Overview); 499193323Sed 500193323Sed // Free all the strdup()ed strings. 501193323Sed for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 502193323Sed i != e; ++i) 503198090Srdivacky free(*i); 504193323Sed} 505193323Sed 506193323Sed 507193323Sed/// ExpandResponseFiles - Copy the contents of argv into newArgv, 508193323Sed/// substituting the contents of the response files for the arguments 509193323Sed/// of type @file. 510234353Sdimstatic void ExpandResponseFiles(unsigned argc, const char*const* argv, 511193323Sed std::vector<char*>& newArgv) { 512198090Srdivacky for (unsigned i = 1; i != argc; ++i) { 513234353Sdim const char *arg = argv[i]; 514193323Sed 515193323Sed if (arg[0] == '@') { 516193323Sed sys::PathWithStatus respFile(++arg); 517193323Sed 518193323Sed // Check that the response file is not empty (mmap'ing empty 519193323Sed // files can be problematic). 520193323Sed const sys::FileStatus *FileStat = respFile.getFileStatus(); 521193323Sed if (FileStat && FileStat->getSize() != 0) { 522193323Sed 523193323Sed // If we could open the file, parse its contents, otherwise 524193323Sed // pass the @file option verbatim. 525193323Sed 526193323Sed // TODO: we should also support recursive loading of response files, 527193323Sed // since this is how gcc behaves. (From their man page: "The file may 528193323Sed // itself contain additional @file options; any such options will be 529193323Sed // processed recursively.") 530193323Sed 531218893Sdim // Mmap the response file into memory. 532218893Sdim OwningPtr<MemoryBuffer> respFilePtr; 533218893Sdim if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) { 534193323Sed ParseCStringVector(newArgv, respFilePtr->getBufferStart()); 535193323Sed continue; 536193323Sed } 537193323Sed } 538193323Sed } 539193323Sed newArgv.push_back(strdup(arg)); 540193323Sed } 541193323Sed} 542193323Sed 543234353Sdimvoid cl::ParseCommandLineOptions(int argc, const char * const *argv, 544243830Sdim const char *Overview) { 545193323Sed // Process all registered options. 546198090Srdivacky SmallVector<Option*, 4> PositionalOpts; 547198090Srdivacky SmallVector<Option*, 4> SinkOpts; 548198090Srdivacky StringMap<Option*> Opts; 549193323Sed GetOptionInfo(PositionalOpts, SinkOpts, Opts); 550193323Sed 551193323Sed assert((!Opts.empty() || !PositionalOpts.empty()) && 552193323Sed "No options specified!"); 553193323Sed 554193323Sed // Expand response files. 555193323Sed std::vector<char*> newArgv; 556243830Sdim newArgv.push_back(strdup(argv[0])); 557243830Sdim ExpandResponseFiles(argc, argv, newArgv); 558243830Sdim argv = &newArgv[0]; 559243830Sdim argc = static_cast<int>(newArgv.size()); 560193323Sed 561193323Sed // Copy the program name into ProgName, making sure not to overflow it. 562218893Sdim std::string ProgName = sys::path::filename(argv[0]); 563203954Srdivacky size_t Len = std::min(ProgName.size(), size_t(79)); 564203954Srdivacky memcpy(ProgramName, ProgName.data(), Len); 565203954Srdivacky ProgramName[Len] = '\0'; 566193323Sed 567193323Sed ProgramOverview = Overview; 568193323Sed bool ErrorParsing = false; 569193323Sed 570193323Sed // Check out the positional arguments to collect information about them. 571193323Sed unsigned NumPositionalRequired = 0; 572193323Sed 573193323Sed // Determine whether or not there are an unlimited number of positionals 574193323Sed bool HasUnlimitedPositionals = false; 575193323Sed 576193323Sed Option *ConsumeAfterOpt = 0; 577193323Sed if (!PositionalOpts.empty()) { 578193323Sed if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 579193323Sed assert(PositionalOpts.size() > 1 && 580193323Sed "Cannot specify cl::ConsumeAfter without a positional argument!"); 581193323Sed ConsumeAfterOpt = PositionalOpts[0]; 582193323Sed } 583193323Sed 584193323Sed // Calculate how many positional values are _required_. 585193323Sed bool UnboundedFound = false; 586193323Sed for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 587193323Sed i != e; ++i) { 588193323Sed Option *Opt = PositionalOpts[i]; 589193323Sed if (RequiresValue(Opt)) 590193323Sed ++NumPositionalRequired; 591193323Sed else if (ConsumeAfterOpt) { 592193323Sed // ConsumeAfter cannot be combined with "optional" positional options 593193323Sed // unless there is only one positional argument... 594193323Sed if (PositionalOpts.size() > 2) 595193323Sed ErrorParsing |= 596198090Srdivacky Opt->error("error - this positional option will never be matched, " 597193323Sed "because it does not Require a value, and a " 598193323Sed "cl::ConsumeAfter option is active!"); 599193323Sed } else if (UnboundedFound && !Opt->ArgStr[0]) { 600193323Sed // This option does not "require" a value... Make sure this option is 601193323Sed // not specified after an option that eats all extra arguments, or this 602193323Sed // one will never get any! 603193323Sed // 604198090Srdivacky ErrorParsing |= Opt->error("error - option can never match, because " 605193323Sed "another positional argument will match an " 606193323Sed "unbounded number of values, and this option" 607193323Sed " does not require a value!"); 608193323Sed } 609193323Sed UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 610193323Sed } 611193323Sed HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 612193323Sed } 613193323Sed 614193323Sed // PositionalVals - A vector of "positional" arguments we accumulate into 615198090Srdivacky // the process at the end. 616193323Sed // 617198090Srdivacky SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 618193323Sed 619193323Sed // If the program has named positional arguments, and the name has been run 620193323Sed // across, keep track of which positional argument was named. Otherwise put 621193323Sed // the positional args into the PositionalVals list... 622193323Sed Option *ActivePositionalArg = 0; 623193323Sed 624193323Sed // Loop over all of the arguments... processing them. 625193323Sed bool DashDashFound = false; // Have we read '--'? 626193323Sed for (int i = 1; i < argc; ++i) { 627193323Sed Option *Handler = 0; 628218893Sdim Option *NearestHandler = 0; 629221345Sdim std::string NearestHandlerString; 630198090Srdivacky StringRef Value; 631198090Srdivacky StringRef ArgName = ""; 632193323Sed 633193323Sed // If the option list changed, this means that some command line 634193323Sed // option has just been registered or deregistered. This can occur in 635193323Sed // response to things like -load, etc. If this happens, rescan the options. 636193323Sed if (OptionListChanged) { 637193323Sed PositionalOpts.clear(); 638193323Sed SinkOpts.clear(); 639193323Sed Opts.clear(); 640193323Sed GetOptionInfo(PositionalOpts, SinkOpts, Opts); 641193323Sed OptionListChanged = false; 642193323Sed } 643193323Sed 644193323Sed // Check to see if this is a positional argument. This argument is 645193323Sed // considered to be positional if it doesn't start with '-', if it is "-" 646193323Sed // itself, or if we have seen "--" already. 647193323Sed // 648193323Sed if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 649193323Sed // Positional argument! 650193323Sed if (ActivePositionalArg) { 651193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 652193323Sed continue; // We are done! 653198090Srdivacky } 654199989Srdivacky 655198090Srdivacky if (!PositionalOpts.empty()) { 656193323Sed PositionalVals.push_back(std::make_pair(argv[i],i)); 657193323Sed 658193323Sed // All of the positional arguments have been fulfulled, give the rest to 659193323Sed // the consume after option... if it's specified... 660193323Sed // 661193323Sed if (PositionalVals.size() >= NumPositionalRequired && 662193323Sed ConsumeAfterOpt != 0) { 663193323Sed for (++i; i < argc; ++i) 664193323Sed PositionalVals.push_back(std::make_pair(argv[i],i)); 665193323Sed break; // Handle outside of the argument processing loop... 666193323Sed } 667193323Sed 668193323Sed // Delay processing positional arguments until the end... 669193323Sed continue; 670193323Sed } 671193323Sed } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 672193323Sed !DashDashFound) { 673193323Sed DashDashFound = true; // This is the mythical "--"? 674193323Sed continue; // Don't try to process it as an argument itself. 675193323Sed } else if (ActivePositionalArg && 676193323Sed (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 677193323Sed // If there is a positional argument eating options, check to see if this 678193323Sed // option is another positional argument. If so, treat it as an argument, 679193323Sed // otherwise feed it to the eating positional. 680193323Sed ArgName = argv[i]+1; 681198090Srdivacky // Eat leading dashes. 682198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 683198090Srdivacky ArgName = ArgName.substr(1); 684199989Srdivacky 685193323Sed Handler = LookupOption(ArgName, Value, Opts); 686193323Sed if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 687193323Sed ProvidePositionalOption(ActivePositionalArg, argv[i], i); 688193323Sed continue; // We are done! 689193323Sed } 690193323Sed 691198090Srdivacky } else { // We start with a '-', must be an argument. 692193323Sed ArgName = argv[i]+1; 693198090Srdivacky // Eat leading dashes. 694198090Srdivacky while (!ArgName.empty() && ArgName[0] == '-') 695198090Srdivacky ArgName = ArgName.substr(1); 696199989Srdivacky 697193323Sed Handler = LookupOption(ArgName, Value, Opts); 698193323Sed 699193323Sed // Check to see if this "option" is really a prefixed or grouped argument. 700198090Srdivacky if (Handler == 0) 701198090Srdivacky Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 702198090Srdivacky ErrorParsing, Opts); 703218893Sdim 704218893Sdim // Otherwise, look for the closest available option to report to the user 705218893Sdim // in the upcoming error. 706218893Sdim if (Handler == 0 && SinkOpts.empty()) 707218893Sdim NearestHandler = LookupNearestOption(ArgName, Opts, 708218893Sdim NearestHandlerString); 709193323Sed } 710193323Sed 711193323Sed if (Handler == 0) { 712193323Sed if (SinkOpts.empty()) { 713198090Srdivacky errs() << ProgramName << ": Unknown command line argument '" 714204642Srdivacky << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 715218893Sdim 716218893Sdim if (NearestHandler) { 717218893Sdim // If we know a near match, report it as well. 718218893Sdim errs() << ProgramName << ": Did you mean '-" 719218893Sdim << NearestHandlerString << "'?\n"; 720218893Sdim } 721218893Sdim 722193323Sed ErrorParsing = true; 723193323Sed } else { 724198090Srdivacky for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 725193323Sed E = SinkOpts.end(); I != E ; ++I) 726193323Sed (*I)->addOccurrence(i, "", argv[i]); 727193323Sed } 728193323Sed continue; 729193323Sed } 730193323Sed 731193323Sed // If this is a named positional argument, just remember that it is the 732193323Sed // active one... 733193323Sed if (Handler->getFormattingFlag() == cl::Positional) 734193323Sed ActivePositionalArg = Handler; 735193323Sed else 736193323Sed ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 737193323Sed } 738193323Sed 739193323Sed // Check and handle positional arguments now... 740193323Sed if (NumPositionalRequired > PositionalVals.size()) { 741198090Srdivacky errs() << ProgramName 742193323Sed << ": Not enough positional command line arguments specified!\n" 743193323Sed << "Must specify at least " << NumPositionalRequired 744204642Srdivacky << " positional arguments: See: " << argv[0] << " -help\n"; 745193323Sed 746193323Sed ErrorParsing = true; 747206083Srdivacky } else if (!HasUnlimitedPositionals && 748206083Srdivacky PositionalVals.size() > PositionalOpts.size()) { 749198090Srdivacky errs() << ProgramName 750193323Sed << ": Too many positional arguments specified!\n" 751193323Sed << "Can specify at most " << PositionalOpts.size() 752204642Srdivacky << " positional arguments: See: " << argv[0] << " -help\n"; 753193323Sed ErrorParsing = true; 754193323Sed 755193323Sed } else if (ConsumeAfterOpt == 0) { 756198090Srdivacky // Positional args have already been handled if ConsumeAfter is specified. 757193323Sed unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 758193323Sed for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 759193323Sed if (RequiresValue(PositionalOpts[i])) { 760193323Sed ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 761193323Sed PositionalVals[ValNo].second); 762193323Sed ValNo++; 763193323Sed --NumPositionalRequired; // We fulfilled our duty... 764193323Sed } 765193323Sed 766193323Sed // If we _can_ give this option more arguments, do so now, as long as we 767193323Sed // do not give it values that others need. 'Done' controls whether the 768193323Sed // option even _WANTS_ any more. 769193323Sed // 770193323Sed bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 771193323Sed while (NumVals-ValNo > NumPositionalRequired && !Done) { 772193323Sed switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 773193323Sed case cl::Optional: 774193323Sed Done = true; // Optional arguments want _at most_ one value 775193323Sed // FALL THROUGH 776193323Sed case cl::ZeroOrMore: // Zero or more will take all they can get... 777193323Sed case cl::OneOrMore: // One or more will take all they can get... 778193323Sed ProvidePositionalOption(PositionalOpts[i], 779193323Sed PositionalVals[ValNo].first, 780193323Sed PositionalVals[ValNo].second); 781193323Sed ValNo++; 782193323Sed break; 783193323Sed default: 784198090Srdivacky llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 785193323Sed "positional argument processing!"); 786193323Sed } 787193323Sed } 788193323Sed } 789193323Sed } else { 790193323Sed assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 791193323Sed unsigned ValNo = 0; 792193323Sed for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 793193323Sed if (RequiresValue(PositionalOpts[j])) { 794193323Sed ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 795193323Sed PositionalVals[ValNo].first, 796193323Sed PositionalVals[ValNo].second); 797193323Sed ValNo++; 798193323Sed } 799193323Sed 800193323Sed // Handle the case where there is just one positional option, and it's 801193323Sed // optional. In this case, we want to give JUST THE FIRST option to the 802193323Sed // positional option and keep the rest for the consume after. The above 803193323Sed // loop would have assigned no values to positional options in this case. 804193323Sed // 805193323Sed if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 806193323Sed ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 807193323Sed PositionalVals[ValNo].first, 808193323Sed PositionalVals[ValNo].second); 809193323Sed ValNo++; 810193323Sed } 811193323Sed 812193323Sed // Handle over all of the rest of the arguments to the 813193323Sed // cl::ConsumeAfter command line option... 814193323Sed for (; ValNo != PositionalVals.size(); ++ValNo) 815193323Sed ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 816193323Sed PositionalVals[ValNo].first, 817193323Sed PositionalVals[ValNo].second); 818193323Sed } 819193323Sed 820193323Sed // Loop over args and make sure all required args are specified! 821198090Srdivacky for (StringMap<Option*>::iterator I = Opts.begin(), 822193323Sed E = Opts.end(); I != E; ++I) { 823193323Sed switch (I->second->getNumOccurrencesFlag()) { 824193323Sed case Required: 825193323Sed case OneOrMore: 826193323Sed if (I->second->getNumOccurrences() == 0) { 827198090Srdivacky I->second->error("must be specified at least once!"); 828193323Sed ErrorParsing = true; 829193323Sed } 830193323Sed // Fall through 831193323Sed default: 832193323Sed break; 833193323Sed } 834193323Sed } 835193323Sed 836218893Sdim // Now that we know if -debug is specified, we can use it. 837218893Sdim // Note that if ReadResponseFiles == true, this must be done before the 838218893Sdim // memory allocated for the expanded command line is free()d below. 839218893Sdim DEBUG(dbgs() << "Args: "; 840218893Sdim for (int i = 0; i < argc; ++i) 841218893Sdim dbgs() << argv[i] << ' '; 842218893Sdim dbgs() << '\n'; 843218893Sdim ); 844218893Sdim 845193323Sed // Free all of the memory allocated to the map. Command line options may only 846193323Sed // be processed once! 847193323Sed Opts.clear(); 848193323Sed PositionalOpts.clear(); 849193323Sed MoreHelp->clear(); 850193323Sed 851193323Sed // Free the memory allocated by ExpandResponseFiles. 852243830Sdim // Free all the strdup()ed strings. 853243830Sdim for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 854243830Sdim i != e; ++i) 855243830Sdim free(*i); 856193323Sed 857193323Sed // If we had an error processing our arguments, don't let the program execute 858193323Sed if (ErrorParsing) exit(1); 859193323Sed} 860193323Sed 861193323Sed//===----------------------------------------------------------------------===// 862193323Sed// Option Base class implementation 863193323Sed// 864193323Sed 865198090Srdivackybool Option::error(const Twine &Message, StringRef ArgName) { 866198090Srdivacky if (ArgName.data() == 0) ArgName = ArgStr; 867198090Srdivacky if (ArgName.empty()) 868198090Srdivacky errs() << HelpStr; // Be nice for positional arguments 869193323Sed else 870198090Srdivacky errs() << ProgramName << ": for the -" << ArgName; 871193323Sed 872198090Srdivacky errs() << " option: " << Message << "\n"; 873193323Sed return true; 874193323Sed} 875193323Sed 876198090Srdivackybool Option::addOccurrence(unsigned pos, StringRef ArgName, 877198090Srdivacky StringRef Value, bool MultiArg) { 878193323Sed if (!MultiArg) 879193323Sed NumOccurrences++; // Increment the number of times we have been seen 880193323Sed 881193323Sed switch (getNumOccurrencesFlag()) { 882193323Sed case Optional: 883193323Sed if (NumOccurrences > 1) 884198090Srdivacky return error("may only occur zero or one times!", ArgName); 885193323Sed break; 886193323Sed case Required: 887193323Sed if (NumOccurrences > 1) 888198090Srdivacky return error("must occur exactly one time!", ArgName); 889193323Sed // Fall through 890193323Sed case OneOrMore: 891193323Sed case ZeroOrMore: 892193323Sed case ConsumeAfter: break; 893193323Sed } 894193323Sed 895193323Sed return handleOccurrence(pos, ArgName, Value); 896193323Sed} 897193323Sed 898193323Sed 899193323Sed// getValueStr - Get the value description string, using "DefaultMsg" if nothing 900193323Sed// has been specified yet. 901193323Sed// 902193323Sedstatic const char *getValueStr(const Option &O, const char *DefaultMsg) { 903193323Sed if (O.ValueStr[0] == 0) return DefaultMsg; 904193323Sed return O.ValueStr; 905193323Sed} 906193323Sed 907193323Sed//===----------------------------------------------------------------------===// 908193323Sed// cl::alias class implementation 909193323Sed// 910193323Sed 911193323Sed// Return the width of the option tag for printing... 912193323Sedsize_t alias::getOptionWidth() const { 913193323Sed return std::strlen(ArgStr)+6; 914193323Sed} 915193323Sed 916193323Sed// Print out the option for the alias. 917193323Sedvoid alias::printOptionInfo(size_t GlobalWidth) const { 918193323Sed size_t L = std::strlen(ArgStr); 919224145Sdim outs() << " -" << ArgStr; 920224145Sdim outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n"; 921193323Sed} 922193323Sed 923193323Sed//===----------------------------------------------------------------------===// 924193323Sed// Parser Implementation code... 925193323Sed// 926193323Sed 927193323Sed// basic_parser implementation 928193323Sed// 929193323Sed 930193323Sed// Return the width of the option tag for printing... 931193323Sedsize_t basic_parser_impl::getOptionWidth(const Option &O) const { 932193323Sed size_t Len = std::strlen(O.ArgStr); 933193323Sed if (const char *ValName = getValueName()) 934193323Sed Len += std::strlen(getValueStr(O, ValName))+3; 935193323Sed 936193323Sed return Len + 6; 937193323Sed} 938193323Sed 939193323Sed// printOptionInfo - Print out information about this option. The 940193323Sed// to-be-maintained width is specified. 941193323Sed// 942193323Sedvoid basic_parser_impl::printOptionInfo(const Option &O, 943193323Sed size_t GlobalWidth) const { 944198090Srdivacky outs() << " -" << O.ArgStr; 945193323Sed 946193323Sed if (const char *ValName = getValueName()) 947198090Srdivacky outs() << "=<" << getValueStr(O, ValName) << '>'; 948193323Sed 949198090Srdivacky outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n'; 950193323Sed} 951193323Sed 952221345Sdimvoid basic_parser_impl::printOptionName(const Option &O, 953221345Sdim size_t GlobalWidth) const { 954221345Sdim outs() << " -" << O.ArgStr; 955221345Sdim outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 956221345Sdim} 957193323Sed 958193323Sed 959193323Sed// parser<bool> implementation 960193323Sed// 961198090Srdivackybool parser<bool>::parse(Option &O, StringRef ArgName, 962198090Srdivacky StringRef Arg, bool &Value) { 963193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 964193323Sed Arg == "1") { 965193323Sed Value = true; 966198090Srdivacky return false; 967198090Srdivacky } 968199989Srdivacky 969198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 970193323Sed Value = false; 971198090Srdivacky return false; 972193323Sed } 973198090Srdivacky return O.error("'" + Arg + 974198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 975193323Sed} 976193323Sed 977193323Sed// parser<boolOrDefault> implementation 978193323Sed// 979198090Srdivackybool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 980198090Srdivacky StringRef Arg, boolOrDefault &Value) { 981193323Sed if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 982193323Sed Arg == "1") { 983193323Sed Value = BOU_TRUE; 984198090Srdivacky return false; 985198090Srdivacky } 986198090Srdivacky if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 987193323Sed Value = BOU_FALSE; 988198090Srdivacky return false; 989193323Sed } 990199989Srdivacky 991198090Srdivacky return O.error("'" + Arg + 992198090Srdivacky "' is invalid value for boolean argument! Try 0 or 1"); 993193323Sed} 994193323Sed 995193323Sed// parser<int> implementation 996193323Sed// 997198090Srdivackybool parser<int>::parse(Option &O, StringRef ArgName, 998198090Srdivacky StringRef Arg, int &Value) { 999198090Srdivacky if (Arg.getAsInteger(0, Value)) 1000198090Srdivacky return O.error("'" + Arg + "' value invalid for integer argument!"); 1001193323Sed return false; 1002193323Sed} 1003193323Sed 1004193323Sed// parser<unsigned> implementation 1005193323Sed// 1006198090Srdivackybool parser<unsigned>::parse(Option &O, StringRef ArgName, 1007198090Srdivacky StringRef Arg, unsigned &Value) { 1008198090Srdivacky 1009198090Srdivacky if (Arg.getAsInteger(0, Value)) 1010198090Srdivacky return O.error("'" + Arg + "' value invalid for uint argument!"); 1011193323Sed return false; 1012193323Sed} 1013193323Sed 1014226633Sdim// parser<unsigned long long> implementation 1015226633Sdim// 1016226633Sdimbool parser<unsigned long long>::parse(Option &O, StringRef ArgName, 1017226633Sdim StringRef Arg, unsigned long long &Value){ 1018226633Sdim 1019226633Sdim if (Arg.getAsInteger(0, Value)) 1020226633Sdim return O.error("'" + Arg + "' value invalid for uint argument!"); 1021226633Sdim return false; 1022226633Sdim} 1023226633Sdim 1024193323Sed// parser<double>/parser<float> implementation 1025193323Sed// 1026198090Srdivackystatic bool parseDouble(Option &O, StringRef Arg, double &Value) { 1027198090Srdivacky SmallString<32> TmpStr(Arg.begin(), Arg.end()); 1028198090Srdivacky const char *ArgStart = TmpStr.c_str(); 1029193323Sed char *End; 1030193323Sed Value = strtod(ArgStart, &End); 1031193323Sed if (*End != 0) 1032198090Srdivacky return O.error("'" + Arg + "' value invalid for floating point argument!"); 1033193323Sed return false; 1034193323Sed} 1035193323Sed 1036198090Srdivackybool parser<double>::parse(Option &O, StringRef ArgName, 1037198090Srdivacky StringRef Arg, double &Val) { 1038193323Sed return parseDouble(O, Arg, Val); 1039193323Sed} 1040193323Sed 1041198090Srdivackybool parser<float>::parse(Option &O, StringRef ArgName, 1042198090Srdivacky StringRef Arg, float &Val) { 1043193323Sed double dVal; 1044193323Sed if (parseDouble(O, Arg, dVal)) 1045193323Sed return true; 1046193323Sed Val = (float)dVal; 1047193323Sed return false; 1048193323Sed} 1049193323Sed 1050193323Sed 1051193323Sed 1052193323Sed// generic_parser_base implementation 1053193323Sed// 1054193323Sed 1055193323Sed// findOption - Return the option number corresponding to the specified 1056193323Sed// argument string. If the option is not found, getNumOptions() is returned. 1057193323Sed// 1058193323Sedunsigned generic_parser_base::findOption(const char *Name) { 1059198090Srdivacky unsigned e = getNumOptions(); 1060193323Sed 1061198090Srdivacky for (unsigned i = 0; i != e; ++i) { 1062198090Srdivacky if (strcmp(getOption(i), Name) == 0) 1063193323Sed return i; 1064198090Srdivacky } 1065193323Sed return e; 1066193323Sed} 1067193323Sed 1068193323Sed 1069193323Sed// Return the width of the option tag for printing... 1070193323Sedsize_t generic_parser_base::getOptionWidth(const Option &O) const { 1071193323Sed if (O.hasArgStr()) { 1072193323Sed size_t Size = std::strlen(O.ArgStr)+6; 1073193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1074193323Sed Size = std::max(Size, std::strlen(getOption(i))+8); 1075193323Sed return Size; 1076193323Sed } else { 1077193323Sed size_t BaseSize = 0; 1078193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1079193323Sed BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1080193323Sed return BaseSize; 1081193323Sed } 1082193323Sed} 1083193323Sed 1084193323Sed// printOptionInfo - Print out information about this option. The 1085193323Sed// to-be-maintained width is specified. 1086193323Sed// 1087193323Sedvoid generic_parser_base::printOptionInfo(const Option &O, 1088193323Sed size_t GlobalWidth) const { 1089193323Sed if (O.hasArgStr()) { 1090193323Sed size_t L = std::strlen(O.ArgStr); 1091198090Srdivacky outs() << " -" << O.ArgStr; 1092198090Srdivacky outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n'; 1093193323Sed 1094193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1095193323Sed size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1096198090Srdivacky outs() << " =" << getOption(i); 1097198090Srdivacky outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1098193323Sed } 1099193323Sed } else { 1100193323Sed if (O.HelpStr[0]) 1101198090Srdivacky outs() << " " << O.HelpStr << '\n'; 1102193323Sed for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1103193323Sed size_t L = std::strlen(getOption(i)); 1104198090Srdivacky outs() << " -" << getOption(i); 1105198090Srdivacky outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n'; 1106193323Sed } 1107193323Sed } 1108193323Sed} 1109193323Sed 1110221345Sdimstatic const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff 1111193323Sed 1112221345Sdim// printGenericOptionDiff - Print the value of this option and it's default. 1113221345Sdim// 1114221345Sdim// "Generic" options have each value mapped to a name. 1115221345Sdimvoid generic_parser_base:: 1116221345SdimprintGenericOptionDiff(const Option &O, const GenericOptionValue &Value, 1117221345Sdim const GenericOptionValue &Default, 1118221345Sdim size_t GlobalWidth) const { 1119221345Sdim outs() << " -" << O.ArgStr; 1120221345Sdim outs().indent(GlobalWidth-std::strlen(O.ArgStr)); 1121221345Sdim 1122221345Sdim unsigned NumOpts = getNumOptions(); 1123221345Sdim for (unsigned i = 0; i != NumOpts; ++i) { 1124221345Sdim if (Value.compare(getOptionValue(i))) 1125221345Sdim continue; 1126221345Sdim 1127221345Sdim outs() << "= " << getOption(i); 1128221345Sdim size_t L = std::strlen(getOption(i)); 1129221345Sdim size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; 1130221345Sdim outs().indent(NumSpaces) << " (default: "; 1131221345Sdim for (unsigned j = 0; j != NumOpts; ++j) { 1132221345Sdim if (Default.compare(getOptionValue(j))) 1133221345Sdim continue; 1134221345Sdim outs() << getOption(j); 1135221345Sdim break; 1136221345Sdim } 1137221345Sdim outs() << ")\n"; 1138221345Sdim return; 1139221345Sdim } 1140221345Sdim outs() << "= *unknown option value*\n"; 1141221345Sdim} 1142221345Sdim 1143221345Sdim// printOptionDiff - Specializations for printing basic value types. 1144221345Sdim// 1145221345Sdim#define PRINT_OPT_DIFF(T) \ 1146221345Sdim void parser<T>:: \ 1147221345Sdim printOptionDiff(const Option &O, T V, OptionValue<T> D, \ 1148221345Sdim size_t GlobalWidth) const { \ 1149221345Sdim printOptionName(O, GlobalWidth); \ 1150221345Sdim std::string Str; \ 1151221345Sdim { \ 1152221345Sdim raw_string_ostream SS(Str); \ 1153221345Sdim SS << V; \ 1154221345Sdim } \ 1155221345Sdim outs() << "= " << Str; \ 1156221345Sdim size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\ 1157221345Sdim outs().indent(NumSpaces) << " (default: "; \ 1158221345Sdim if (D.hasValue()) \ 1159221345Sdim outs() << D.getValue(); \ 1160221345Sdim else \ 1161221345Sdim outs() << "*no default*"; \ 1162221345Sdim outs() << ")\n"; \ 1163221345Sdim } \ 1164221345Sdim 1165221345SdimPRINT_OPT_DIFF(bool) 1166221345SdimPRINT_OPT_DIFF(boolOrDefault) 1167221345SdimPRINT_OPT_DIFF(int) 1168221345SdimPRINT_OPT_DIFF(unsigned) 1169226633SdimPRINT_OPT_DIFF(unsigned long long) 1170221345SdimPRINT_OPT_DIFF(double) 1171221345SdimPRINT_OPT_DIFF(float) 1172221345SdimPRINT_OPT_DIFF(char) 1173221345Sdim 1174221345Sdimvoid parser<std::string>:: 1175221345SdimprintOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, 1176221345Sdim size_t GlobalWidth) const { 1177221345Sdim printOptionName(O, GlobalWidth); 1178221345Sdim outs() << "= " << V; 1179221345Sdim size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; 1180221345Sdim outs().indent(NumSpaces) << " (default: "; 1181221345Sdim if (D.hasValue()) 1182221345Sdim outs() << D.getValue(); 1183221345Sdim else 1184221345Sdim outs() << "*no default*"; 1185221345Sdim outs() << ")\n"; 1186221345Sdim} 1187221345Sdim 1188221345Sdim// Print a placeholder for options that don't yet support printOptionDiff(). 1189221345Sdimvoid basic_parser_impl:: 1190221345SdimprintOptionNoValue(const Option &O, size_t GlobalWidth) const { 1191221345Sdim printOptionName(O, GlobalWidth); 1192221345Sdim outs() << "= *cannot print option value*\n"; 1193221345Sdim} 1194221345Sdim 1195193323Sed//===----------------------------------------------------------------------===// 1196204642Srdivacky// -help and -help-hidden option implementation 1197193323Sed// 1198193323Sed 1199198090Srdivackystatic int OptNameCompare(const void *LHS, const void *RHS) { 1200198090Srdivacky typedef std::pair<const char *, Option*> pair_ty; 1201199989Srdivacky 1202234353Sdim return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first); 1203198090Srdivacky} 1204198090Srdivacky 1205221345Sdim// Copy Options into a vector so we can sort them as we like. 1206221345Sdimstatic void 1207221345SdimsortOpts(StringMap<Option*> &OptMap, 1208221345Sdim SmallVectorImpl< std::pair<const char *, Option*> > &Opts, 1209221345Sdim bool ShowHidden) { 1210221345Sdim SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1211221345Sdim 1212221345Sdim for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1213221345Sdim I != E; ++I) { 1214221345Sdim // Ignore really-hidden options. 1215221345Sdim if (I->second->getOptionHiddenFlag() == ReallyHidden) 1216221345Sdim continue; 1217221345Sdim 1218221345Sdim // Unless showhidden is set, ignore hidden flags. 1219221345Sdim if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1220221345Sdim continue; 1221221345Sdim 1222221345Sdim // If we've already seen this option, don't add it to the list again. 1223221345Sdim if (!OptionSet.insert(I->second)) 1224221345Sdim continue; 1225221345Sdim 1226221345Sdim Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1227221345Sdim I->second)); 1228221345Sdim } 1229221345Sdim 1230221345Sdim // Sort the options list alphabetically. 1231221345Sdim qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1232221345Sdim} 1233221345Sdim 1234193323Sednamespace { 1235193323Sed 1236193323Sedclass HelpPrinter { 1237251662Sdimprotected: 1238193323Sed const bool ShowHidden; 1239251662Sdim typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector; 1240251662Sdim // Print the options. Opts is assumed to be alphabetically sorted. 1241251662Sdim virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1242251662Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1243251662Sdim Opts[i].second->printOptionInfo(MaxArgLen); 1244251662Sdim } 1245193323Sed 1246193323Sedpublic: 1247249423Sdim explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {} 1248251662Sdim virtual ~HelpPrinter() {} 1249193323Sed 1250251662Sdim // Invoke the printer. 1251193323Sed void operator=(bool Value) { 1252193323Sed if (Value == false) return; 1253193323Sed 1254193323Sed // Get all the options. 1255198090Srdivacky SmallVector<Option*, 4> PositionalOpts; 1256198090Srdivacky SmallVector<Option*, 4> SinkOpts; 1257198090Srdivacky StringMap<Option*> OptMap; 1258193323Sed GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1259193323Sed 1260251662Sdim StrOptionPairVector Opts; 1261221345Sdim sortOpts(OptMap, Opts, ShowHidden); 1262193323Sed 1263193323Sed if (ProgramOverview) 1264198090Srdivacky outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1265193323Sed 1266198090Srdivacky outs() << "USAGE: " << ProgramName << " [options]"; 1267193323Sed 1268193323Sed // Print out the positional options. 1269193323Sed Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1270193323Sed if (!PositionalOpts.empty() && 1271193323Sed PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1272193323Sed CAOpt = PositionalOpts[0]; 1273193323Sed 1274193323Sed for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1275193323Sed if (PositionalOpts[i]->ArgStr[0]) 1276198090Srdivacky outs() << " --" << PositionalOpts[i]->ArgStr; 1277198090Srdivacky outs() << " " << PositionalOpts[i]->HelpStr; 1278193323Sed } 1279193323Sed 1280193323Sed // Print the consume after option info if it exists... 1281198090Srdivacky if (CAOpt) outs() << " " << CAOpt->HelpStr; 1282193323Sed 1283198090Srdivacky outs() << "\n\n"; 1284193323Sed 1285193323Sed // Compute the maximum argument length... 1286249423Sdim size_t MaxArgLen = 0; 1287193323Sed for (size_t i = 0, e = Opts.size(); i != e; ++i) 1288193323Sed MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1289193323Sed 1290198090Srdivacky outs() << "OPTIONS:\n"; 1291251662Sdim printOptions(Opts, MaxArgLen); 1292193323Sed 1293193323Sed // Print any extra help the user has declared. 1294193323Sed for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1295251662Sdim E = MoreHelp->end(); 1296251662Sdim I != E; ++I) 1297198090Srdivacky outs() << *I; 1298193323Sed MoreHelp->clear(); 1299193323Sed 1300193323Sed // Halt the program since help information was printed 1301193323Sed exit(1); 1302193323Sed } 1303193323Sed}; 1304251662Sdim 1305251662Sdimclass CategorizedHelpPrinter : public HelpPrinter { 1306251662Sdimpublic: 1307251662Sdim explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {} 1308251662Sdim 1309251662Sdim // Helper function for printOptions(). 1310251662Sdim // It shall return true if A's name should be lexographically 1311251662Sdim // ordered before B's name. It returns false otherwise. 1312251662Sdim static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) { 1313251662Sdim int Length = strcmp(A->getName(), B->getName()); 1314251662Sdim assert(Length != 0 && "Duplicate option categories"); 1315251662Sdim return Length < 0; 1316251662Sdim } 1317251662Sdim 1318251662Sdim // Make sure we inherit our base class's operator=() 1319251662Sdim using HelpPrinter::operator= ; 1320251662Sdim 1321251662Sdimprotected: 1322251662Sdim virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) { 1323251662Sdim std::vector<OptionCategory *> SortedCategories; 1324251662Sdim std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions; 1325251662Sdim 1326251662Sdim // Collect registered option categories into vector in preperation for 1327251662Sdim // sorting. 1328251662Sdim for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(), 1329251662Sdim E = RegisteredOptionCategories->end(); 1330251662Sdim I != E; ++I) 1331251662Sdim SortedCategories.push_back(*I); 1332251662Sdim 1333251662Sdim // Sort the different option categories alphabetically. 1334251662Sdim assert(SortedCategories.size() > 0 && "No option categories registered!"); 1335251662Sdim std::sort(SortedCategories.begin(), SortedCategories.end(), 1336251662Sdim OptionCategoryCompare); 1337251662Sdim 1338251662Sdim // Create map to empty vectors. 1339251662Sdim for (std::vector<OptionCategory *>::const_iterator 1340251662Sdim I = SortedCategories.begin(), 1341251662Sdim E = SortedCategories.end(); 1342251662Sdim I != E; ++I) 1343251662Sdim CategorizedOptions[*I] = std::vector<Option *>(); 1344251662Sdim 1345251662Sdim // Walk through pre-sorted options and assign into categories. 1346251662Sdim // Because the options are already alphabetically sorted the 1347251662Sdim // options within categories will also be alphabetically sorted. 1348251662Sdim for (size_t I = 0, E = Opts.size(); I != E; ++I) { 1349251662Sdim Option *Opt = Opts[I].second; 1350251662Sdim assert(CategorizedOptions.count(Opt->Category) > 0 && 1351251662Sdim "Option has an unregistered category"); 1352251662Sdim CategorizedOptions[Opt->Category].push_back(Opt); 1353251662Sdim } 1354251662Sdim 1355251662Sdim // Now do printing. 1356251662Sdim for (std::vector<OptionCategory *>::const_iterator 1357251662Sdim Category = SortedCategories.begin(), 1358251662Sdim E = SortedCategories.end(); 1359251662Sdim Category != E; ++Category) { 1360251662Sdim // Hide empty categories for -help, but show for -help-hidden. 1361251662Sdim bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0; 1362251662Sdim if (!ShowHidden && IsEmptyCategory) 1363251662Sdim continue; 1364251662Sdim 1365251662Sdim // Print category information. 1366251662Sdim outs() << "\n"; 1367251662Sdim outs() << (*Category)->getName() << ":\n"; 1368251662Sdim 1369251662Sdim // Check if description is set. 1370251662Sdim if ((*Category)->getDescription() != 0) 1371251662Sdim outs() << (*Category)->getDescription() << "\n\n"; 1372251662Sdim else 1373251662Sdim outs() << "\n"; 1374251662Sdim 1375251662Sdim // When using -help-hidden explicitly state if the category has no 1376251662Sdim // options associated with it. 1377251662Sdim if (IsEmptyCategory) { 1378251662Sdim outs() << " This option category has no options.\n"; 1379251662Sdim continue; 1380251662Sdim } 1381251662Sdim // Loop over the options in the category and print. 1382251662Sdim for (std::vector<Option *>::const_iterator 1383251662Sdim Opt = CategorizedOptions[*Category].begin(), 1384251662Sdim E = CategorizedOptions[*Category].end(); 1385251662Sdim Opt != E; ++Opt) 1386251662Sdim (*Opt)->printOptionInfo(MaxArgLen); 1387251662Sdim } 1388251662Sdim } 1389251662Sdim}; 1390251662Sdim 1391251662Sdim// This wraps the Uncategorizing and Categorizing printers and decides 1392251662Sdim// at run time which should be invoked. 1393251662Sdimclass HelpPrinterWrapper { 1394251662Sdimprivate: 1395251662Sdim HelpPrinter &UncategorizedPrinter; 1396251662Sdim CategorizedHelpPrinter &CategorizedPrinter; 1397251662Sdim 1398251662Sdimpublic: 1399251662Sdim explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter, 1400251662Sdim CategorizedHelpPrinter &CategorizedPrinter) : 1401251662Sdim UncategorizedPrinter(UncategorizedPrinter), 1402251662Sdim CategorizedPrinter(CategorizedPrinter) { } 1403251662Sdim 1404251662Sdim // Invoke the printer. 1405251662Sdim void operator=(bool Value); 1406251662Sdim}; 1407251662Sdim 1408193323Sed} // End anonymous namespace 1409193323Sed 1410251662Sdim// Declare the four HelpPrinter instances that are used to print out help, or 1411251662Sdim// help-hidden as an uncategorized list or in categories. 1412251662Sdimstatic HelpPrinter UncategorizedNormalPrinter(false); 1413251662Sdimstatic HelpPrinter UncategorizedHiddenPrinter(true); 1414251662Sdimstatic CategorizedHelpPrinter CategorizedNormalPrinter(false); 1415251662Sdimstatic CategorizedHelpPrinter CategorizedHiddenPrinter(true); 1416193323Sed 1417251662Sdim 1418251662Sdim// Declare HelpPrinter wrappers that will decide whether or not to invoke 1419251662Sdim// a categorizing help printer 1420251662Sdimstatic HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter, 1421251662Sdim CategorizedNormalPrinter); 1422251662Sdimstatic HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter, 1423251662Sdim CategorizedHiddenPrinter); 1424251662Sdim 1425251662Sdim// Define uncategorized help printers. 1426251662Sdim// -help-list is hidden by default because if Option categories are being used 1427251662Sdim// then -help behaves the same as -help-list. 1428193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> > 1429251662SdimHLOp("help-list", 1430251662Sdim cl::desc("Display list of available options (-help-list-hidden for more)"), 1431251662Sdim cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed); 1432251662Sdim 1433251662Sdimstatic cl::opt<HelpPrinter, true, parser<bool> > 1434251662SdimHLHOp("help-list-hidden", 1435251662Sdim cl::desc("Display list of all available options"), 1436251662Sdim cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1437251662Sdim 1438251662Sdim// Define uncategorized/categorized help printers. These printers change their 1439251662Sdim// behaviour at runtime depending on whether one or more Option categories have 1440251662Sdim// been declared. 1441251662Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool> > 1442204642SrdivackyHOp("help", cl::desc("Display available options (-help-hidden for more)"), 1443251662Sdim cl::location(WrappedNormalPrinter), cl::ValueDisallowed); 1444193323Sed 1445251662Sdimstatic cl::opt<HelpPrinterWrapper, true, parser<bool> > 1446193323SedHHOp("help-hidden", cl::desc("Display all available options"), 1447251662Sdim cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1448193323Sed 1449251662Sdim 1450251662Sdim 1451221345Sdimstatic cl::opt<bool> 1452221345SdimPrintOptions("print-options", 1453221345Sdim cl::desc("Print non-default options after command line parsing"), 1454221345Sdim cl::Hidden, cl::init(false)); 1455221345Sdim 1456221345Sdimstatic cl::opt<bool> 1457221345SdimPrintAllOptions("print-all-options", 1458221345Sdim cl::desc("Print all option values after command line parsing"), 1459221345Sdim cl::Hidden, cl::init(false)); 1460221345Sdim 1461251662Sdimvoid HelpPrinterWrapper::operator=(bool Value) { 1462251662Sdim if (Value == false) 1463251662Sdim return; 1464251662Sdim 1465251662Sdim // Decide which printer to invoke. If more than one option category is 1466251662Sdim // registered then it is useful to show the categorized help instead of 1467251662Sdim // uncategorized help. 1468251662Sdim if (RegisteredOptionCategories->size() > 1) { 1469251662Sdim // unhide -help-list option so user can have uncategorized output if they 1470251662Sdim // want it. 1471251662Sdim HLOp.setHiddenFlag(NotHidden); 1472251662Sdim 1473251662Sdim CategorizedPrinter = true; // Invoke categorized printer 1474251662Sdim } 1475251662Sdim else 1476251662Sdim UncategorizedPrinter = true; // Invoke uncategorized printer 1477251662Sdim} 1478251662Sdim 1479221345Sdim// Print the value of each option. 1480221345Sdimvoid cl::PrintOptionValues() { 1481221345Sdim if (!PrintOptions && !PrintAllOptions) return; 1482221345Sdim 1483221345Sdim // Get all the options. 1484221345Sdim SmallVector<Option*, 4> PositionalOpts; 1485221345Sdim SmallVector<Option*, 4> SinkOpts; 1486221345Sdim StringMap<Option*> OptMap; 1487221345Sdim GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1488221345Sdim 1489221345Sdim SmallVector<std::pair<const char *, Option*>, 128> Opts; 1490221345Sdim sortOpts(OptMap, Opts, /*ShowHidden*/true); 1491221345Sdim 1492221345Sdim // Compute the maximum argument length... 1493221345Sdim size_t MaxArgLen = 0; 1494221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1495221345Sdim MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1496221345Sdim 1497221345Sdim for (size_t i = 0, e = Opts.size(); i != e; ++i) 1498221345Sdim Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); 1499221345Sdim} 1500221345Sdim 1501193323Sedstatic void (*OverrideVersionPrinter)() = 0; 1502193323Sed 1503226633Sdimstatic std::vector<void (*)()>* ExtraVersionPrinters = 0; 1504198090Srdivacky 1505193323Sednamespace { 1506193323Sedclass VersionPrinter { 1507193323Sedpublic: 1508193323Sed void print() { 1509198090Srdivacky raw_ostream &OS = outs(); 1510234353Sdim OS << "LLVM (http://llvm.org/):\n" 1511198090Srdivacky << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1512193323Sed#ifdef LLVM_VERSION_INFO 1513198090Srdivacky OS << LLVM_VERSION_INFO; 1514193323Sed#endif 1515198090Srdivacky OS << "\n "; 1516193323Sed#ifndef __OPTIMIZE__ 1517198090Srdivacky OS << "DEBUG build"; 1518193323Sed#else 1519198090Srdivacky OS << "Optimized build"; 1520193323Sed#endif 1521193323Sed#ifndef NDEBUG 1522198090Srdivacky OS << " with assertions"; 1523193323Sed#endif 1524199481Srdivacky std::string CPU = sys::getHostCPUName(); 1525199481Srdivacky if (CPU == "generic") CPU = "(unknown)"; 1526198090Srdivacky OS << ".\n" 1527226633Sdim#if (ENABLE_TIMESTAMPS == 1) 1528198090Srdivacky << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1529208599Srdivacky#endif 1530234353Sdim << " Default target: " << sys::getDefaultTargetTriple() << '\n' 1531226633Sdim << " Host CPU: " << CPU << '\n'; 1532193323Sed } 1533193323Sed void operator=(bool OptionWasSpecified) { 1534198090Srdivacky if (!OptionWasSpecified) return; 1535199989Srdivacky 1536226633Sdim if (OverrideVersionPrinter != 0) { 1537226633Sdim (*OverrideVersionPrinter)(); 1538198090Srdivacky exit(1); 1539193323Sed } 1540226633Sdim print(); 1541226633Sdim 1542226633Sdim // Iterate over any registered extra printers and call them to add further 1543226633Sdim // information. 1544226633Sdim if (ExtraVersionPrinters != 0) { 1545226633Sdim outs() << '\n'; 1546226633Sdim for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), 1547226633Sdim E = ExtraVersionPrinters->end(); 1548226633Sdim I != E; ++I) 1549226633Sdim (*I)(); 1550226633Sdim } 1551226633Sdim 1552198090Srdivacky exit(1); 1553193323Sed } 1554193323Sed}; 1555193323Sed} // End anonymous namespace 1556193323Sed 1557193323Sed 1558193323Sed// Define the --version option that prints out the LLVM version for the tool 1559193323Sedstatic VersionPrinter VersionPrinterInstance; 1560193323Sed 1561193323Sedstatic cl::opt<VersionPrinter, true, parser<bool> > 1562193323SedVersOp("version", cl::desc("Display the version of this program"), 1563193323Sed cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1564193323Sed 1565193323Sed// Utility function for printing the help message. 1566251662Sdimvoid cl::PrintHelpMessage(bool Hidden, bool Categorized) { 1567251662Sdim // This looks weird, but it actually prints the help message. The Printers are 1568251662Sdim // types of HelpPrinter and the help gets printed when its operator= is 1569251662Sdim // invoked. That's because the "normal" usages of the help printer is to be 1570251662Sdim // assigned true/false depending on whether -help or -help-hidden was given or 1571251662Sdim // not. Since we're circumventing that we have to make it look like -help or 1572251662Sdim // -help-hidden were given, so we assign true. 1573251662Sdim 1574251662Sdim if (!Hidden && !Categorized) 1575251662Sdim UncategorizedNormalPrinter = true; 1576251662Sdim else if (!Hidden && Categorized) 1577251662Sdim CategorizedNormalPrinter = true; 1578251662Sdim else if (Hidden && !Categorized) 1579251662Sdim UncategorizedHiddenPrinter = true; 1580251662Sdim else 1581251662Sdim CategorizedHiddenPrinter = true; 1582193323Sed} 1583193323Sed 1584193323Sed/// Utility function for printing version number. 1585193323Sedvoid cl::PrintVersionMessage() { 1586193323Sed VersionPrinterInstance.print(); 1587193323Sed} 1588193323Sed 1589193323Sedvoid cl::SetVersionPrinter(void (*func)()) { 1590193323Sed OverrideVersionPrinter = func; 1591193323Sed} 1592226633Sdim 1593226633Sdimvoid cl::AddExtraVersionPrinter(void (*func)()) { 1594226633Sdim if (ExtraVersionPrinters == 0) 1595226633Sdim ExtraVersionPrinters = new std::vector<void (*)()>; 1596226633Sdim 1597226633Sdim ExtraVersionPrinters->push_back(func); 1598226633Sdim} 1599251662Sdim 1600251662Sdimvoid cl::getRegisteredOptions(StringMap<Option*> &Map) 1601251662Sdim{ 1602251662Sdim // Get all the options. 1603251662Sdim SmallVector<Option*, 4> PositionalOpts; //NOT USED 1604251662Sdim SmallVector<Option*, 4> SinkOpts; //NOT USED 1605251662Sdim assert(Map.size() == 0 && "StringMap must be empty"); 1606251662Sdim GetOptionInfo(PositionalOpts, SinkOpts, Map); 1607251662Sdim return; 1608251662Sdim} 1609