OptTable.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. //===- OptTable.cpp - Option Table Implementation -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Option/OptTable.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/StringSet.h"
  12. #include "llvm/Option/Arg.h"
  13. #include "llvm/Option/ArgList.h"
  14. #include "llvm/Option/OptSpecifier.h"
  15. #include "llvm/Option/Option.h"
  16. #include "llvm/Support/CommandLine.h" // for expandResponseFiles
  17. #include "llvm/Support/Compiler.h"
  18. #include "llvm/Support/ErrorHandling.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <cctype>
  23. #include <cstring>
  24. #include <map>
  25. #include <string>
  26. #include <utility>
  27. #include <vector>
  28. using namespace llvm;
  29. using namespace llvm::opt;
  30. namespace llvm {
  31. namespace opt {
  32. // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
  33. // with an exception. '\0' comes at the end of the alphabet instead of the
  34. // beginning (thus options precede any other options which prefix them).
  35. static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
  36. const char *X = A, *Y = B;
  37. char a = tolower(*A), b = tolower(*B);
  38. while (a == b) {
  39. if (a == '\0')
  40. return 0;
  41. a = tolower(*++X);
  42. b = tolower(*++Y);
  43. }
  44. if (a == '\0') // A is a prefix of B.
  45. return 1;
  46. if (b == '\0') // B is a prefix of A.
  47. return -1;
  48. // Otherwise lexicographic.
  49. return (a < b) ? -1 : 1;
  50. }
  51. #ifndef NDEBUG
  52. static int StrCmpOptionName(const char *A, const char *B) {
  53. if (int N = StrCmpOptionNameIgnoreCase(A, B))
  54. return N;
  55. return strcmp(A, B);
  56. }
  57. static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
  58. if (&A == &B)
  59. return false;
  60. if (int N = StrCmpOptionName(A.Name, B.Name))
  61. return N < 0;
  62. for (const char * const *APre = A.Prefixes,
  63. * const *BPre = B.Prefixes;
  64. *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
  65. if (int N = StrCmpOptionName(*APre, *BPre))
  66. return N < 0;
  67. }
  68. // Names are the same, check that classes are in order; exactly one
  69. // should be joined, and it should succeed the other.
  70. assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
  71. "Unexpected classes for options with same name.");
  72. return B.Kind == Option::JoinedClass;
  73. }
  74. #endif
  75. // Support lower_bound between info and an option name.
  76. static inline bool operator<(const OptTable::Info &I, const char *Name) {
  77. return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
  78. }
  79. } // end namespace opt
  80. } // end namespace llvm
  81. OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
  82. OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
  83. : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
  84. // Explicitly zero initialize the error to work around a bug in array
  85. // value-initialization on MinGW with gcc 4.3.5.
  86. // Find start of normal options.
  87. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  88. unsigned Kind = getInfo(i + 1).Kind;
  89. if (Kind == Option::InputClass) {
  90. assert(!TheInputOptionID && "Cannot have multiple input options!");
  91. TheInputOptionID = getInfo(i + 1).ID;
  92. } else if (Kind == Option::UnknownClass) {
  93. assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
  94. TheUnknownOptionID = getInfo(i + 1).ID;
  95. } else if (Kind != Option::GroupClass) {
  96. FirstSearchableIndex = i;
  97. break;
  98. }
  99. }
  100. assert(FirstSearchableIndex != 0 && "No searchable options?");
  101. #ifndef NDEBUG
  102. // Check that everything after the first searchable option is a
  103. // regular option class.
  104. for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
  105. Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
  106. assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
  107. Kind != Option::GroupClass) &&
  108. "Special options should be defined first!");
  109. }
  110. // Check that options are in order.
  111. for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
  112. if (!(getInfo(i) < getInfo(i + 1))) {
  113. getOption(i).dump();
  114. getOption(i + 1).dump();
  115. llvm_unreachable("Options are not in order!");
  116. }
  117. }
  118. #endif
  119. // Build prefixes.
  120. for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
  121. i != e; ++i) {
  122. if (const char *const *P = getInfo(i).Prefixes) {
  123. for (; *P != nullptr; ++P) {
  124. PrefixesUnion.insert(*P);
  125. }
  126. }
  127. }
  128. // Build prefix chars.
  129. for (StringSet<>::const_iterator I = PrefixesUnion.begin(),
  130. E = PrefixesUnion.end(); I != E; ++I) {
  131. StringRef Prefix = I->getKey();
  132. for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
  133. C != CE; ++C)
  134. if (!is_contained(PrefixChars, *C))
  135. PrefixChars.push_back(*C);
  136. }
  137. }
  138. OptTable::~OptTable() = default;
  139. const Option OptTable::getOption(OptSpecifier Opt) const {
  140. unsigned id = Opt.getID();
  141. if (id == 0)
  142. return Option(nullptr, nullptr);
  143. assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
  144. return Option(&getInfo(id), this);
  145. }
  146. static bool isInput(const StringSet<> &Prefixes, StringRef Arg) {
  147. if (Arg == "-")
  148. return true;
  149. for (StringSet<>::const_iterator I = Prefixes.begin(),
  150. E = Prefixes.end(); I != E; ++I)
  151. if (Arg.startswith(I->getKey()))
  152. return false;
  153. return true;
  154. }
  155. /// \returns Matched size. 0 means no match.
  156. static unsigned matchOption(const OptTable::Info *I, StringRef Str,
  157. bool IgnoreCase) {
  158. for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
  159. StringRef Prefix(*Pre);
  160. if (Str.startswith(Prefix)) {
  161. StringRef Rest = Str.substr(Prefix.size());
  162. bool Matched = IgnoreCase
  163. ? Rest.startswith_lower(I->Name)
  164. : Rest.startswith(I->Name);
  165. if (Matched)
  166. return Prefix.size() + StringRef(I->Name).size();
  167. }
  168. }
  169. return 0;
  170. }
  171. // Returns true if one of the Prefixes + In.Names matches Option
  172. static bool optionMatches(const OptTable::Info &In, StringRef Option) {
  173. if (In.Prefixes) {
  174. StringRef InName(In.Name);
  175. for (size_t I = 0; In.Prefixes[I]; I++)
  176. if (Option.endswith(InName))
  177. if (Option.slice(0, Option.size() - InName.size()) == In.Prefixes[I])
  178. return true;
  179. }
  180. return false;
  181. }
  182. // This function is for flag value completion.
  183. // Eg. When "-stdlib=" and "l" was passed to this function, it will return
  184. // appropiriate values for stdlib, which starts with l.
  185. std::vector<std::string>
  186. OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
  187. // Search all options and return possible values.
  188. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  189. const Info &In = OptionInfos[I];
  190. if (!In.Values || !optionMatches(In, Option))
  191. continue;
  192. SmallVector<StringRef, 8> Candidates;
  193. StringRef(In.Values).split(Candidates, ",", -1, false);
  194. std::vector<std::string> Result;
  195. for (StringRef Val : Candidates)
  196. if (Val.startswith(Arg) && Arg.compare(Val))
  197. Result.push_back(std::string(Val));
  198. return Result;
  199. }
  200. return {};
  201. }
  202. std::vector<std::string>
  203. OptTable::findByPrefix(StringRef Cur, unsigned int DisableFlags) const {
  204. std::vector<std::string> Ret;
  205. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  206. const Info &In = OptionInfos[I];
  207. if (!In.Prefixes || (!In.HelpText && !In.GroupID))
  208. continue;
  209. if (In.Flags & DisableFlags)
  210. continue;
  211. for (int I = 0; In.Prefixes[I]; I++) {
  212. std::string S = std::string(In.Prefixes[I]) + std::string(In.Name) + "\t";
  213. if (In.HelpText)
  214. S += In.HelpText;
  215. if (StringRef(S).startswith(Cur) && S != std::string(Cur) + "\t")
  216. Ret.push_back(S);
  217. }
  218. }
  219. return Ret;
  220. }
  221. unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
  222. unsigned FlagsToInclude, unsigned FlagsToExclude,
  223. unsigned MinimumLength) const {
  224. assert(!Option.empty());
  225. // Consider each [option prefix + option name] pair as a candidate, finding
  226. // the closest match.
  227. unsigned BestDistance = UINT_MAX;
  228. for (const Info &CandidateInfo :
  229. ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
  230. StringRef CandidateName = CandidateInfo.Name;
  231. // We can eliminate some option prefix/name pairs as candidates right away:
  232. // * Ignore option candidates with empty names, such as "--", or names
  233. // that do not meet the minimum length.
  234. if (CandidateName.empty() || CandidateName.size() < MinimumLength)
  235. continue;
  236. // * If FlagsToInclude were specified, ignore options that don't include
  237. // those flags.
  238. if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
  239. continue;
  240. // * Ignore options that contain the FlagsToExclude.
  241. if (CandidateInfo.Flags & FlagsToExclude)
  242. continue;
  243. // * Ignore positional argument option candidates (which do not
  244. // have prefixes).
  245. if (!CandidateInfo.Prefixes)
  246. continue;
  247. // Now check if the candidate ends with a character commonly used when
  248. // delimiting an option from its value, such as '=' or ':'. If it does,
  249. // attempt to split the given option based on that delimiter.
  250. StringRef LHS, RHS;
  251. char Last = CandidateName.back();
  252. bool CandidateHasDelimiter = Last == '=' || Last == ':';
  253. std::string NormalizedName = std::string(Option);
  254. if (CandidateHasDelimiter) {
  255. std::tie(LHS, RHS) = Option.split(Last);
  256. NormalizedName = std::string(LHS);
  257. if (Option.find(Last) == LHS.size())
  258. NormalizedName += Last;
  259. }
  260. // Consider each possible prefix for each candidate to find the most
  261. // appropriate one. For example, if a user asks for "--helm", suggest
  262. // "--help" over "-help".
  263. for (int P = 0;
  264. const char *const CandidatePrefix = CandidateInfo.Prefixes[P]; P++) {
  265. std::string Candidate = (CandidatePrefix + CandidateName).str();
  266. StringRef CandidateRef = Candidate;
  267. unsigned Distance =
  268. CandidateRef.edit_distance(NormalizedName, /*AllowReplacements=*/true,
  269. /*MaxEditDistance=*/BestDistance);
  270. if (RHS.empty() && CandidateHasDelimiter) {
  271. // The Candidate ends with a = or : delimiter, but the option passed in
  272. // didn't contain the delimiter (or doesn't have anything after it).
  273. // In that case, penalize the correction: `-nodefaultlibs` is more
  274. // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
  275. // though both have an unmodified editing distance of 1, since the
  276. // latter would need an argument.
  277. ++Distance;
  278. }
  279. if (Distance < BestDistance) {
  280. BestDistance = Distance;
  281. NearestString = (Candidate + RHS).str();
  282. }
  283. }
  284. }
  285. return BestDistance;
  286. }
  287. bool OptTable::addValues(const char *Option, const char *Values) {
  288. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  289. Info &In = OptionInfos[I];
  290. if (optionMatches(In, Option)) {
  291. In.Values = Values;
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. // Parse a single argument, return the new argument, and update Index. If
  298. // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
  299. // be updated to "-bc". This overload does not support
  300. // FlagsToInclude/FlagsToExclude or case insensitive options.
  301. Arg *OptTable::parseOneArgGrouped(InputArgList &Args, unsigned &Index) const {
  302. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  303. // itself.
  304. const char *CStr = Args.getArgString(Index);
  305. StringRef Str(CStr);
  306. if (isInput(PrefixesUnion, Str))
  307. return new Arg(getOption(TheInputOptionID), Str, Index++, CStr);
  308. const Info *End = OptionInfos.data() + OptionInfos.size();
  309. StringRef Name = Str.ltrim(PrefixChars);
  310. const Info *Start = std::lower_bound(
  311. OptionInfos.data() + FirstSearchableIndex, End, Name.data());
  312. const Info *Fallback = nullptr;
  313. unsigned Prev = Index;
  314. // Search for the option which matches Str.
  315. for (; Start != End; ++Start) {
  316. unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
  317. if (!ArgSize)
  318. continue;
  319. Option Opt(Start, this);
  320. if (Arg *A = Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
  321. false, Index))
  322. return A;
  323. // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
  324. // the current argument (e.g. "-abc"). Match it as a fallback if no longer
  325. // option (e.g. "-ab") exists.
  326. if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
  327. Fallback = Start;
  328. // Otherwise, see if the argument is missing.
  329. if (Prev != Index)
  330. return nullptr;
  331. }
  332. if (Fallback) {
  333. Option Opt(Fallback, this);
  334. if (Arg *A = Opt.accept(Args, Str.substr(0, 2), true, Index)) {
  335. if (Str.size() == 2)
  336. ++Index;
  337. else
  338. Args.replaceArgString(Index, Twine('-') + Str.substr(2));
  339. return A;
  340. }
  341. }
  342. return new Arg(getOption(TheUnknownOptionID), Str, Index++, CStr);
  343. }
  344. Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
  345. unsigned FlagsToInclude,
  346. unsigned FlagsToExclude) const {
  347. unsigned Prev = Index;
  348. const char *Str = Args.getArgString(Index);
  349. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  350. // itself.
  351. if (isInput(PrefixesUnion, Str))
  352. return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
  353. const Info *Start = OptionInfos.data() + FirstSearchableIndex;
  354. const Info *End = OptionInfos.data() + OptionInfos.size();
  355. StringRef Name = StringRef(Str).ltrim(PrefixChars);
  356. // Search for the first next option which could be a prefix.
  357. Start = std::lower_bound(Start, End, Name.data());
  358. // Options are stored in sorted order, with '\0' at the end of the
  359. // alphabet. Since the only options which can accept a string must
  360. // prefix it, we iteratively search for the next option which could
  361. // be a prefix.
  362. //
  363. // FIXME: This is searching much more than necessary, but I am
  364. // blanking on the simplest way to make it fast. We can solve this
  365. // problem when we move to TableGen.
  366. for (; Start != End; ++Start) {
  367. unsigned ArgSize = 0;
  368. // Scan for first option which is a proper prefix.
  369. for (; Start != End; ++Start)
  370. if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
  371. break;
  372. if (Start == End)
  373. break;
  374. Option Opt(Start, this);
  375. if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
  376. continue;
  377. if (Opt.hasFlag(FlagsToExclude))
  378. continue;
  379. // See if this option matches.
  380. if (Arg *A = Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
  381. false, Index))
  382. return A;
  383. // Otherwise, see if this argument was missing values.
  384. if (Prev != Index)
  385. return nullptr;
  386. }
  387. // If we failed to find an option and this arg started with /, then it's
  388. // probably an input path.
  389. if (Str[0] == '/')
  390. return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
  391. return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
  392. }
  393. InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
  394. unsigned &MissingArgIndex,
  395. unsigned &MissingArgCount,
  396. unsigned FlagsToInclude,
  397. unsigned FlagsToExclude) const {
  398. InputArgList Args(ArgArr.begin(), ArgArr.end());
  399. // FIXME: Handle '@' args (or at least error on them).
  400. MissingArgIndex = MissingArgCount = 0;
  401. unsigned Index = 0, End = ArgArr.size();
  402. while (Index < End) {
  403. // Ingore nullptrs, they are response file's EOL markers
  404. if (Args.getArgString(Index) == nullptr) {
  405. ++Index;
  406. continue;
  407. }
  408. // Ignore empty arguments (other things may still take them as arguments).
  409. StringRef Str = Args.getArgString(Index);
  410. if (Str == "") {
  411. ++Index;
  412. continue;
  413. }
  414. unsigned Prev = Index;
  415. Arg *A = GroupedShortOptions
  416. ? parseOneArgGrouped(Args, Index)
  417. : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
  418. assert((Index > Prev || GroupedShortOptions) &&
  419. "Parser failed to consume argument.");
  420. // Check for missing argument error.
  421. if (!A) {
  422. assert(Index >= End && "Unexpected parser error.");
  423. assert(Index - Prev - 1 && "No missing arguments!");
  424. MissingArgIndex = Prev;
  425. MissingArgCount = Index - Prev - 1;
  426. break;
  427. }
  428. Args.append(A);
  429. }
  430. return Args;
  431. }
  432. InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
  433. OptSpecifier Unknown, StringSaver &Saver,
  434. function_ref<void(StringRef)> ErrorFn) const {
  435. SmallVector<const char *, 0> NewArgv;
  436. // The environment variable specifies initial options which can be overridden
  437. // by commnad line options.
  438. cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
  439. unsigned MAI, MAC;
  440. opt::InputArgList Args = ParseArgs(makeArrayRef(NewArgv), MAI, MAC);
  441. if (MAC)
  442. ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
  443. // For each unknwon option, call ErrorFn with a formatted error message. The
  444. // message includes a suggested alternative option spelling if available.
  445. std::string Nearest;
  446. for (const opt::Arg *A : Args.filtered(Unknown)) {
  447. std::string Spelling = A->getAsString(Args);
  448. if (findNearest(Spelling, Nearest) > 1)
  449. ErrorFn("unknown argument '" + A->getAsString(Args) + "'");
  450. else
  451. ErrorFn("unknown argument '" + A->getAsString(Args) +
  452. "', did you mean '" + Nearest + "'?");
  453. }
  454. return Args;
  455. }
  456. static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
  457. const Option O = Opts.getOption(Id);
  458. std::string Name = O.getPrefixedName();
  459. // Add metavar, if used.
  460. switch (O.getKind()) {
  461. case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
  462. llvm_unreachable("Invalid option with help text.");
  463. case Option::MultiArgClass:
  464. if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
  465. // For MultiArgs, metavar is full list of all argument names.
  466. Name += ' ';
  467. Name += MetaVarName;
  468. }
  469. else {
  470. // For MultiArgs<N>, if metavar not supplied, print <value> N times.
  471. for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
  472. Name += " <value>";
  473. }
  474. }
  475. break;
  476. case Option::FlagClass:
  477. break;
  478. case Option::ValuesClass:
  479. break;
  480. case Option::SeparateClass: case Option::JoinedOrSeparateClass:
  481. case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
  482. Name += ' ';
  483. LLVM_FALLTHROUGH;
  484. case Option::JoinedClass: case Option::CommaJoinedClass:
  485. case Option::JoinedAndSeparateClass:
  486. if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
  487. Name += MetaVarName;
  488. else
  489. Name += "<value>";
  490. break;
  491. }
  492. return Name;
  493. }
  494. namespace {
  495. struct OptionInfo {
  496. std::string Name;
  497. StringRef HelpText;
  498. };
  499. } // namespace
  500. static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
  501. std::vector<OptionInfo> &OptionHelp) {
  502. OS << Title << ":\n";
  503. // Find the maximum option length.
  504. unsigned OptionFieldWidth = 0;
  505. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  506. // Limit the amount of padding we are willing to give up for alignment.
  507. unsigned Length = OptionHelp[i].Name.size();
  508. if (Length <= 23)
  509. OptionFieldWidth = std::max(OptionFieldWidth, Length);
  510. }
  511. const unsigned InitialPad = 2;
  512. for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
  513. const std::string &Option = OptionHelp[i].Name;
  514. int Pad = OptionFieldWidth - int(Option.size());
  515. OS.indent(InitialPad) << Option;
  516. // Break on long option names.
  517. if (Pad < 0) {
  518. OS << "\n";
  519. Pad = OptionFieldWidth + InitialPad;
  520. }
  521. OS.indent(Pad + 1) << OptionHelp[i].HelpText << '\n';
  522. }
  523. }
  524. static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
  525. unsigned GroupID = Opts.getOptionGroupID(Id);
  526. // If not in a group, return the default help group.
  527. if (!GroupID)
  528. return "OPTIONS";
  529. // Abuse the help text of the option groups to store the "help group"
  530. // name.
  531. //
  532. // FIXME: Split out option groups.
  533. if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
  534. return GroupHelp;
  535. // Otherwise keep looking.
  536. return getOptionHelpGroup(Opts, GroupID);
  537. }
  538. void OptTable::PrintHelp(raw_ostream &OS, const char *Usage, const char *Title,
  539. bool ShowHidden, bool ShowAllAliases) const {
  540. PrintHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
  541. (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
  542. }
  543. void OptTable::PrintHelp(raw_ostream &OS, const char *Usage, const char *Title,
  544. unsigned FlagsToInclude, unsigned FlagsToExclude,
  545. bool ShowAllAliases) const {
  546. OS << "OVERVIEW: " << Title << "\n\n";
  547. OS << "USAGE: " << Usage << "\n\n";
  548. // Render help text into a map of group-name to a list of (option, help)
  549. // pairs.
  550. std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
  551. for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
  552. // FIXME: Split out option groups.
  553. if (getOptionKind(Id) == Option::GroupClass)
  554. continue;
  555. unsigned Flags = getInfo(Id).Flags;
  556. if (FlagsToInclude && !(Flags & FlagsToInclude))
  557. continue;
  558. if (Flags & FlagsToExclude)
  559. continue;
  560. // If an alias doesn't have a help text, show a help text for the aliased
  561. // option instead.
  562. const char *HelpText = getOptionHelpText(Id);
  563. if (!HelpText && ShowAllAliases) {
  564. const Option Alias = getOption(Id).getAlias();
  565. if (Alias.isValid())
  566. HelpText = getOptionHelpText(Alias.getID());
  567. }
  568. if (HelpText) {
  569. const char *HelpGroup = getOptionHelpGroup(*this, Id);
  570. const std::string &OptName = getOptionHelpName(*this, Id);
  571. GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
  572. }
  573. }
  574. for (auto& OptionGroup : GroupedOptionHelp) {
  575. if (OptionGroup.first != GroupedOptionHelp.begin()->first)
  576. OS << "\n";
  577. PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
  578. }
  579. OS.flush();
  580. }