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