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(const char *const *ArgBegin, 251 const char *const *ArgEnd, 252 unsigned &MissingArgIndex, 253 unsigned &MissingArgCount, 254 unsigned FlagsToInclude, 255 unsigned FlagsToExclude) const { 256 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd); 257 258 // FIXME: Handle '@' args (or at least error on them). 259 260 MissingArgIndex = MissingArgCount = 0; 261 unsigned Index = 0, End = ArgEnd - ArgBegin; 262 while (Index < End) { 263 // Ingore nullptrs, they are response file's EOL markers 264 if (Args->getArgString(Index) == nullptr) { 265 ++Index; 266 continue; 267 } 268 // Ignore empty arguments (other things may still take them as arguments). 269 StringRef Str = Args->getArgString(Index); 270 if (Str == "") { 271 ++Index; 272 continue; 273 } 274 275 unsigned Prev = Index; 276 Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude); 277 assert(Index > Prev && "Parser failed to consume argument."); 278 279 // Check for missing argument error. 280 if (!A) { 281 assert(Index >= End && "Unexpected parser error."); 282 assert(Index - Prev - 1 && "No missing arguments!"); 283 MissingArgIndex = Prev; 284 MissingArgCount = Index - Prev - 1; 285 break; 286 } 287 288 Args->append(A); 289 } 290 291 return Args; 292 } 293 294 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) { 295 const Option O = Opts.getOption(Id); 296 std::string Name = O.getPrefixedName(); 297 298 // Add metavar, if used. 299 switch (O.getKind()) { 300 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass: 301 llvm_unreachable("Invalid option with help text."); 302 303 case Option::MultiArgClass: 304 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) { 305 // For MultiArgs, metavar is full list of all argument names. 306 Name += ' '; 307 Name += MetaVarName; 308 } 309 else { 310 // For MultiArgs<N>, if metavar not supplied, print <value> N times. 311 for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) { 312 Name += " <value>"; 313 } 314 } 315 break; 316 317 case Option::FlagClass: 318 break; 319 320 case Option::SeparateClass: case Option::JoinedOrSeparateClass: 321 case Option::RemainingArgsClass: 322 Name += ' '; 323 // FALLTHROUGH 324 case Option::JoinedClass: case Option::CommaJoinedClass: 325 case Option::JoinedAndSeparateClass: 326 if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) 327 Name += MetaVarName; 328 else 329 Name += "<value>"; 330 break; 331 } 332 333 return Name; 334 } 335 336 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, 337 std::vector<std::pair<std::string, 338 const char*> > &OptionHelp) { 339 OS << Title << ":\n"; 340 341 // Find the maximum option length. 342 unsigned OptionFieldWidth = 0; 343 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 344 // Skip titles. 345 if (!OptionHelp[i].second) 346 continue; 347 348 // Limit the amount of padding we are willing to give up for alignment. 349 unsigned Length = OptionHelp[i].first.size(); 350 if (Length <= 23) 351 OptionFieldWidth = std::max(OptionFieldWidth, Length); 352 } 353 354 const unsigned InitialPad = 2; 355 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { 356 const std::string &Option = OptionHelp[i].first; 357 int Pad = OptionFieldWidth - int(Option.size()); 358 OS.indent(InitialPad) << Option; 359 360 // Break on long option names. 361 if (Pad < 0) { 362 OS << "\n"; 363 Pad = OptionFieldWidth + InitialPad; 364 } 365 OS.indent(Pad + 1) << OptionHelp[i].second << '\n'; 366 } 367 } 368 369 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) { 370 unsigned GroupID = Opts.getOptionGroupID(Id); 371 372 // If not in a group, return the default help group. 373 if (!GroupID) 374 return "OPTIONS"; 375 376 // Abuse the help text of the option groups to store the "help group" 377 // name. 378 // 379 // FIXME: Split out option groups. 380 if (const char *GroupHelp = Opts.getOptionHelpText(GroupID)) 381 return GroupHelp; 382 383 // Otherwise keep looking. 384 return getOptionHelpGroup(Opts, GroupID); 385 } 386 387 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title, 388 bool ShowHidden) const { 389 PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/ 390 (ShowHidden ? 0 : HelpHidden)); 391 } 392 393 394 void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title, 395 unsigned FlagsToInclude, 396 unsigned FlagsToExclude) const { 397 OS << "OVERVIEW: " << Title << "\n"; 398 OS << '\n'; 399 OS << "USAGE: " << Name << " [options] <inputs>\n"; 400 OS << '\n'; 401 402 // Render help text into a map of group-name to a list of (option, help) 403 // pairs. 404 typedef std::map<std::string, 405 std::vector<std::pair<std::string, const char*> > > helpmap_ty; 406 helpmap_ty GroupedOptionHelp; 407 408 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 409 unsigned Id = i + 1; 410 411 // FIXME: Split out option groups. 412 if (getOptionKind(Id) == Option::GroupClass) 413 continue; 414 415 unsigned Flags = getInfo(Id).Flags; 416 if (FlagsToInclude && !(Flags & FlagsToInclude)) 417 continue; 418 if (Flags & FlagsToExclude) 419 continue; 420 421 if (const char *Text = getOptionHelpText(Id)) { 422 const char *HelpGroup = getOptionHelpGroup(*this, Id); 423 const std::string &OptName = getOptionHelpName(*this, Id); 424 GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text)); 425 } 426 } 427 428 for (helpmap_ty::iterator it = GroupedOptionHelp .begin(), 429 ie = GroupedOptionHelp.end(); it != ie; ++it) { 430 if (it != GroupedOptionHelp .begin()) 431 OS << "\n"; 432 PrintHelpOptionList(OS, it->first, it->second); 433 } 434 435 OS.flush(); 436 } 437