1 //===--- OptTable.cpp - Option Table Implementation -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Option/OptTable.h" 11 #include "llvm/Option/Arg.h" 12 #include "llvm/Option/ArgList.h" 13 #include "llvm/Option/Option.h" 14 #include "llvm/Support/ErrorHandling.h" 15 #include "llvm/Support/raw_ostream.h" 16 #include <algorithm> 17 #include <cctype> 18 #include <map> 19 20 using namespace llvm; 21 using namespace llvm::opt; 22 23 namespace llvm { 24 namespace opt { 25 26 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic, 27 // with an exceptions. '\0' comes at the end of the alphabet instead of the 28 // beginning (thus options precede any other options which prefix them). 29 static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) { 30 const char *X = A, *Y = B; 31 char a = tolower(*A), b = tolower(*B); 32 while (a == b) { 33 if (a == '\0') 34 return 0; 35 36 a = tolower(*++X); 37 b = tolower(*++Y); 38 } 39 40 if (a == '\0') // A is a prefix of B. 41 return 1; 42 if (b == '\0') // B is a prefix of A. 43 return -1; 44 45 // Otherwise lexicographic. 46 return (a < b) ? -1 : 1; 47 } 48 49 #ifndef NDEBUG 50 static int StrCmpOptionName(const char *A, const char *B) { 51 if (int N = StrCmpOptionNameIgnoreCase(A, B)) 52 return N; 53 return strcmp(A, B); 54 } 55 56 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) { 57 if (&A == &B) 58 return false; 59 60 if (int N = StrCmpOptionName(A.Name, B.Name)) 61 return N < 0; 62 63 for (const char * const *APre = A.Prefixes, 64 * const *BPre = B.Prefixes; 65 *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){ 66 if (int N = StrCmpOptionName(*APre, *BPre)) 67 return N < 0; 68 } 69 70 // Names are the same, check that classes are in order; exactly one 71 // should be joined, and it should succeed the other. 72 assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) && 73 "Unexpected classes for options with same name."); 74 return B.Kind == Option::JoinedClass; 75 } 76 #endif 77 78 // Support lower_bound between info and an option name. 79 static inline bool operator<(const OptTable::Info &I, const char *Name) { 80 return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0; 81 } 82 } 83 } 84 85 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {} 86 87 OptTable::OptTable(const Info *OptionInfos, unsigned NumOptionInfos, 88 bool IgnoreCase) 89 : OptionInfos(OptionInfos), NumOptionInfos(NumOptionInfos), 90 IgnoreCase(IgnoreCase), TheInputOptionID(0), TheUnknownOptionID(0), 91 FirstSearchableIndex(0) { 92 // Explicitly zero initialize the error to work around a bug in array 93 // value-initialization on MinGW with gcc 4.3.5. 94 95 // Find start of normal options. 96 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 97 unsigned Kind = getInfo(i + 1).Kind; 98 if (Kind == Option::InputClass) { 99 assert(!TheInputOptionID && "Cannot have multiple input options!"); 100 TheInputOptionID = getInfo(i + 1).ID; 101 } else if (Kind == Option::UnknownClass) { 102 assert(!TheUnknownOptionID && "Cannot have multiple unknown options!"); 103 TheUnknownOptionID = getInfo(i + 1).ID; 104 } else if (Kind != Option::GroupClass) { 105 FirstSearchableIndex = i; 106 break; 107 } 108 } 109 assert(FirstSearchableIndex != 0 && "No searchable options?"); 110 111 #ifndef NDEBUG 112 // Check that everything after the first searchable option is a 113 // regular option class. 114 for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) { 115 Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind; 116 assert((Kind != Option::InputClass && Kind != Option::UnknownClass && 117 Kind != Option::GroupClass) && 118 "Special options should be defined first!"); 119 } 120 121 // Check that options are in order. 122 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){ 123 if (!(getInfo(i) < getInfo(i + 1))) { 124 getOption(i).dump(); 125 getOption(i + 1).dump(); 126 llvm_unreachable("Options are not in order!"); 127 } 128 } 129 #endif 130 131 // Build prefixes. 132 for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1; 133 i != e; ++i) { 134 if (const char *const *P = getInfo(i).Prefixes) { 135 for (; *P != nullptr; ++P) { 136 PrefixesUnion.insert(*P); 137 } 138 } 139 } 140 141 // Build prefix chars. 142 for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(), 143 E = PrefixesUnion.end(); I != E; ++I) { 144 StringRef Prefix = I->getKey(); 145 for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end(); 146 C != CE; ++C) 147 if (std::find(PrefixChars.begin(), PrefixChars.end(), *C) 148 == PrefixChars.end()) 149 PrefixChars.push_back(*C); 150 } 151 } 152 153 OptTable::~OptTable() { 154 } 155 156 const Option OptTable::getOption(OptSpecifier Opt) const { 157 unsigned id = Opt.getID(); 158 if (id == 0) 159 return Option(nullptr, nullptr); 160 assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID."); 161 return Option(&getInfo(id), this); 162 } 163 164 static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) { 165 if (Arg == "-") 166 return true; 167 for (llvm::StringSet<>::const_iterator I = Prefixes.begin(), 168 E = Prefixes.end(); I != E; ++I) 169 if (Arg.startswith(I->getKey())) 170 return false; 171 return true; 172 } 173 174 /// \returns Matched size. 0 means no match. 175 static unsigned matchOption(const OptTable::Info *I, StringRef Str, 176 bool IgnoreCase) { 177 for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) { 178 StringRef Prefix(*Pre); 179 if (Str.startswith(Prefix)) { 180 StringRef Rest = Str.substr(Prefix.size()); 181 bool Matched = IgnoreCase 182 ? Rest.startswith_lower(I->Name) 183 : Rest.startswith(I->Name); 184 if (Matched) 185 return Prefix.size() + StringRef(I->Name).size(); 186 } 187 } 188 return 0; 189 } 190 191 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index, 192 unsigned FlagsToInclude, 193 unsigned FlagsToExclude) const { 194 unsigned Prev = Index; 195 const char *Str = Args.getArgString(Index); 196 197 // Anything that doesn't start with PrefixesUnion is an input, as is '-' 198 // itself. 199 if (isInput(PrefixesUnion, Str)) 200 return new Arg(getOption(TheInputOptionID), Str, Index++, Str); 201 202 const Info *Start = OptionInfos + FirstSearchableIndex; 203 const Info *End = OptionInfos + getNumOptions(); 204 StringRef Name = StringRef(Str).ltrim(PrefixChars); 205 206 // Search for the first next option which could be a prefix. 207 Start = std::lower_bound(Start, End, Name.data()); 208 209 // Options are stored in sorted order, with '\0' at the end of the 210 // alphabet. Since the only options which can accept a string must 211 // prefix it, we iteratively search for the next option which could 212 // be a prefix. 213 // 214 // FIXME: This is searching much more than necessary, but I am 215 // blanking on the simplest way to make it fast. We can solve this 216 // problem when we move to TableGen. 217 for (; Start != End; ++Start) { 218 unsigned ArgSize = 0; 219 // Scan for first option which is a proper prefix. 220 for (; Start != End; ++Start) 221 if ((ArgSize = matchOption(Start, Str, IgnoreCase))) 222 break; 223 if (Start == End) 224 break; 225 226 Option Opt(Start, this); 227 228 if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude)) 229 continue; 230 if (Opt.hasFlag(FlagsToExclude)) 231 continue; 232 233 // See if this option matches. 234 if (Arg *A = Opt.accept(Args, Index, ArgSize)) 235 return A; 236 237 // Otherwise, see if this argument was missing values. 238 if (Prev != Index) 239 return nullptr; 240 } 241 242 // If we failed to find an option and this arg started with /, then it's 243 // probably an input path. 244 if (Str[0] == '/') 245 return new Arg(getOption(TheInputOptionID), Str, Index++, Str); 246 247 return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str); 248 } 249 250 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr, 251 unsigned &MissingArgIndex, 252 unsigned &MissingArgCount, 253 unsigned FlagsToInclude, 254 unsigned FlagsToExclude) const { 255 InputArgList Args(ArgArr.begin(), ArgArr.end()); 256 257 // FIXME: Handle '@' args (or at least error on them). 258 259 MissingArgIndex = MissingArgCount = 0; 260 unsigned Index = 0, End = ArgArr.size(); 261 while (Index < End) { 262 // Ingore nullptrs, they are response file's EOL markers 263 if (Args.getArgString(Index) == nullptr) { 264 ++Index; 265 continue; 266 } 267 // Ignore empty arguments (other things may still take them as arguments). 268 StringRef Str = Args.getArgString(Index); 269 if (Str == "") { 270 ++Index; 271 continue; 272 } 273 274 unsigned Prev = Index; 275 Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude); 276 assert(Index > Prev && "Parser failed to consume argument."); 277 278 // Check for missing argument error. 279 if (!A) { 280 assert(Index >= End && "Unexpected parser error."); 281 assert(Index - Prev - 1 && "No missing arguments!"); 282 MissingArgIndex = Prev; 283 MissingArgCount = Index - Prev - 1; 284 break; 285 } 286 287 Args.append(A); 288 } 289 290 return Args; 291 } 292 293 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) { 294 const Option O = Opts.getOption(Id); 295 std::string Name = O.getPrefixedName(); 296 297 // Add metavar, if used. 298 switch (O.getKind()) { 299 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass: 300 llvm_unreachable("Invalid option with help text."); 301 302 case Option::MultiArgClass: 303 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) { 304 // For MultiArgs, metavar is full list of all argument names. 305 Name += ' '; 306 Name += MetaVarName; 307 } 308 else { 309 // For MultiArgs<N>, if metavar not supplied, print <value> N times. 310 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) { 311 Name += " <value>"; 312 } 313 } 314 break; 315 316 case Option::FlagClass: 317 break; 318 319 case Option::SeparateClass: case Option::JoinedOrSeparateClass: 320 case Option::RemainingArgsClass: 321 Name += ' '; 322 // FALLTHROUGH 323 case Option::JoinedClass: case Option::CommaJoinedClass: 324 case Option::JoinedAndSeparateClass: 325 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) 326 Name += MetaVarName; 327 else 328 Name += "<value>"; 329 break; 330 } 331 332 return Name; 333 } 334 335 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, 336 std::vector<std::pair<std::string, 337 const char*> > &OptionHelp) { 338 OS << Title << ":\n"; 339 340 // Find the maximum option length. 341 unsigned OptionFieldWidth = 0; 342 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 343 // Skip titles. 344 if (!OptionHelp[i].second) 345 continue; 346 347 // Limit the amount of padding we are willing to give up for alignment. 348 unsigned Length = OptionHelp[i].first.size(); 349 if (Length <= 23) 350 OptionFieldWidth = std::max(OptionFieldWidth, Length); 351 } 352 353 const unsigned InitialPad = 2; 354 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 355 const std::string &Option = OptionHelp[i].first; 356 int Pad = OptionFieldWidth - int(Option.size()); 357 OS.indent(InitialPad) << Option; 358 359 // Break on long option names. 360 if (Pad < 0) { 361 OS << "\n"; 362 Pad = OptionFieldWidth + InitialPad; 363 } 364 OS.indent(Pad + 1) << OptionHelp[i].second << '\n'; 365 } 366 } 367 368 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) { 369 unsigned GroupID = Opts.getOptionGroupID(Id); 370 371 // If not in a group, return the default help group. 372 if (!GroupID) 373 return "OPTIONS"; 374 375 // Abuse the help text of the option groups to store the "help group" 376 // name. 377 // 378 // FIXME: Split out option groups. 379 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID)) 380 return GroupHelp; 381 382 // Otherwise keep looking. 383 return getOptionHelpGroup(Opts, GroupID); 384 } 385 386 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title, 387 bool ShowHidden) const { 388 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/ 389 (ShowHidden ? 0 : HelpHidden)); 390 } 391 392 393 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title, 394 unsigned FlagsToInclude, 395 unsigned FlagsToExclude) const { 396 OS << "OVERVIEW: " << Title << "\n"; 397 OS << '\n'; 398 OS << "USAGE: " << Name << " [options] <inputs>\n"; 399 OS << '\n'; 400 401 // Render help text into a map of group-name to a list of (option, help) 402 // pairs. 403 typedef std::map<std::string, 404 std::vector<std::pair<std::string, const char*> > > helpmap_ty; 405 helpmap_ty GroupedOptionHelp; 406 407 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 408 unsigned Id = i + 1; 409 410 // FIXME: Split out option groups. 411 if (getOptionKind(Id) == Option::GroupClass) 412 continue; 413 414 unsigned Flags = getInfo(Id).Flags; 415 if (FlagsToInclude && !(Flags & FlagsToInclude)) 416 continue; 417 if (Flags & FlagsToExclude) 418 continue; 419 420 if (const char *Text = getOptionHelpText(Id)) { 421 const char *HelpGroup = getOptionHelpGroup(*this, Id); 422 const std::string &OptName = getOptionHelpName(*this, Id); 423 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text)); 424 } 425 } 426 427 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(), 428 ie = GroupedOptionHelp.end(); it != ie; ++it) { 429 if (it != GroupedOptionHelp .begin()) 430 OS << "\n"; 431 PrintHelpOptionList(OS, it->first, it->second); 432 } 433 434 OS.flush(); 435 } 436