OptTable.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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(!InputOptionID && "Cannot have multiple input options!");
  91. InputOptionID = getInfo(i + 1).ID;
  92. } else if (Kind == Option::UnknownClass) {
  93. assert(!UnknownOptionID && "Cannot have multiple unknown options!");
  94. UnknownOptionID = 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 (char C : Prefix)
  133. if (!is_contained(PrefixChars, C))
  134. PrefixChars.push_back(C);
  135. }
  136. }
  137. OptTable::~OptTable() = default;
  138. const Option OptTable::getOption(OptSpecifier Opt) const {
  139. unsigned id = Opt.getID();
  140. if (id == 0)
  141. return Option(nullptr, nullptr);
  142. assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
  143. return Option(&getInfo(id), this);
  144. }
  145. static bool isInput(const StringSet<> &Prefixes, StringRef Arg) {
  146. if (Arg == "-")
  147. return true;
  148. for (StringSet<>::const_iterator I = Prefixes.begin(),
  149. E = Prefixes.end(); I != E; ++I)
  150. if (Arg.startswith(I->getKey()))
  151. return false;
  152. return true;
  153. }
  154. /// \returns Matched size. 0 means no match.
  155. static unsigned matchOption(const OptTable::Info *I, StringRef Str,
  156. bool IgnoreCase) {
  157. for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
  158. StringRef Prefix(*Pre);
  159. if (Str.startswith(Prefix)) {
  160. StringRef Rest = Str.substr(Prefix.size());
  161. bool Matched = IgnoreCase ? Rest.startswith_insensitive(I->Name)
  162. : Rest.startswith(I->Name);
  163. if (Matched)
  164. return Prefix.size() + StringRef(I->Name).size();
  165. }
  166. }
  167. return 0;
  168. }
  169. // Returns true if one of the Prefixes + In.Names matches Option
  170. static bool optionMatches(const OptTable::Info &In, StringRef Option) {
  171. if (In.Prefixes) {
  172. StringRef InName(In.Name);
  173. for (size_t I = 0; In.Prefixes[I]; I++)
  174. if (Option.endswith(InName))
  175. if (Option.slice(0, Option.size() - InName.size()) == In.Prefixes[I])
  176. return true;
  177. }
  178. return false;
  179. }
  180. // This function is for flag value completion.
  181. // Eg. When "-stdlib=" and "l" was passed to this function, it will return
  182. // appropiriate values for stdlib, which starts with l.
  183. std::vector<std::string>
  184. OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
  185. // Search all options and return possible values.
  186. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  187. const Info &In = OptionInfos[I];
  188. if (!In.Values || !optionMatches(In, Option))
  189. continue;
  190. SmallVector<StringRef, 8> Candidates;
  191. StringRef(In.Values).split(Candidates, ",", -1, false);
  192. std::vector<std::string> Result;
  193. for (StringRef Val : Candidates)
  194. if (Val.startswith(Arg) && Arg.compare(Val))
  195. Result.push_back(std::string(Val));
  196. return Result;
  197. }
  198. return {};
  199. }
  200. std::vector<std::string>
  201. OptTable::findByPrefix(StringRef Cur, unsigned int DisableFlags) const {
  202. std::vector<std::string> Ret;
  203. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  204. const Info &In = OptionInfos[I];
  205. if (!In.Prefixes || (!In.HelpText && !In.GroupID))
  206. continue;
  207. if (In.Flags & DisableFlags)
  208. continue;
  209. for (int I = 0; In.Prefixes[I]; I++) {
  210. std::string S = std::string(In.Prefixes[I]) + std::string(In.Name) + "\t";
  211. if (In.HelpText)
  212. S += In.HelpText;
  213. if (StringRef(S).startswith(Cur) && S != std::string(Cur) + "\t")
  214. Ret.push_back(S);
  215. }
  216. }
  217. return Ret;
  218. }
  219. unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
  220. unsigned FlagsToInclude, unsigned FlagsToExclude,
  221. unsigned MinimumLength) const {
  222. assert(!Option.empty());
  223. // Consider each [option prefix + option name] pair as a candidate, finding
  224. // the closest match.
  225. unsigned BestDistance = UINT_MAX;
  226. for (const Info &CandidateInfo :
  227. ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
  228. StringRef CandidateName = CandidateInfo.Name;
  229. // We can eliminate some option prefix/name pairs as candidates right away:
  230. // * Ignore option candidates with empty names, such as "--", or names
  231. // that do not meet the minimum length.
  232. if (CandidateName.empty() || CandidateName.size() < MinimumLength)
  233. continue;
  234. // * If FlagsToInclude were specified, ignore options that don't include
  235. // those flags.
  236. if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
  237. continue;
  238. // * Ignore options that contain the FlagsToExclude.
  239. if (CandidateInfo.Flags & FlagsToExclude)
  240. continue;
  241. // * Ignore positional argument option candidates (which do not
  242. // have prefixes).
  243. if (!CandidateInfo.Prefixes)
  244. continue;
  245. // Now check if the candidate ends with a character commonly used when
  246. // delimiting an option from its value, such as '=' or ':'. If it does,
  247. // attempt to split the given option based on that delimiter.
  248. StringRef LHS, RHS;
  249. char Last = CandidateName.back();
  250. bool CandidateHasDelimiter = Last == '=' || Last == ':';
  251. std::string NormalizedName = std::string(Option);
  252. if (CandidateHasDelimiter) {
  253. std::tie(LHS, RHS) = Option.split(Last);
  254. NormalizedName = std::string(LHS);
  255. if (Option.find(Last) == LHS.size())
  256. NormalizedName += Last;
  257. }
  258. // Consider each possible prefix for each candidate to find the most
  259. // appropriate one. For example, if a user asks for "--helm", suggest
  260. // "--help" over "-help".
  261. for (int P = 0;
  262. const char *const CandidatePrefix = CandidateInfo.Prefixes[P]; P++) {
  263. std::string Candidate = (CandidatePrefix + CandidateName).str();
  264. StringRef CandidateRef = Candidate;
  265. unsigned Distance =
  266. CandidateRef.edit_distance(NormalizedName, /*AllowReplacements=*/true,
  267. /*MaxEditDistance=*/BestDistance);
  268. if (RHS.empty() && CandidateHasDelimiter) {
  269. // The Candidate ends with a = or : delimiter, but the option passed in
  270. // didn't contain the delimiter (or doesn't have anything after it).
  271. // In that case, penalize the correction: `-nodefaultlibs` is more
  272. // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
  273. // though both have an unmodified editing distance of 1, since the
  274. // latter would need an argument.
  275. ++Distance;
  276. }
  277. if (Distance < BestDistance) {
  278. BestDistance = Distance;
  279. NearestString = (Candidate + RHS).str();
  280. }
  281. }
  282. }
  283. return BestDistance;
  284. }
  285. bool OptTable::addValues(const char *Option, const char *Values) {
  286. for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
  287. Info &In = OptionInfos[I];
  288. if (optionMatches(In, Option)) {
  289. In.Values = Values;
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. // Parse a single argument, return the new argument, and update Index. If
  296. // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
  297. // be updated to "-bc". This overload does not support
  298. // FlagsToInclude/FlagsToExclude or case insensitive options.
  299. std::unique_ptr<Arg> OptTable::parseOneArgGrouped(InputArgList &Args,
  300. unsigned &Index) const {
  301. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  302. // itself.
  303. const char *CStr = Args.getArgString(Index);
  304. StringRef Str(CStr);
  305. if (isInput(PrefixesUnion, Str))
  306. return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, CStr);
  307. const Info *End = OptionInfos.data() + OptionInfos.size();
  308. StringRef Name = Str.ltrim(PrefixChars);
  309. const Info *Start = std::lower_bound(
  310. OptionInfos.data() + FirstSearchableIndex, End, Name.data());
  311. const Info *Fallback = nullptr;
  312. unsigned Prev = Index;
  313. // Search for the option which matches Str.
  314. for (; Start != End; ++Start) {
  315. unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
  316. if (!ArgSize)
  317. continue;
  318. Option Opt(Start, this);
  319. if (std::unique_ptr<Arg> A =
  320. Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
  321. /*GroupedShortOption=*/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. // Check that the last option isn't a flag wrongly given an argument.
  335. if (Str[2] == '=')
  336. return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++,
  337. CStr);
  338. if (std::unique_ptr<Arg> A = Opt.accept(
  339. Args, Str.substr(0, 2), /*GroupedShortOption=*/true, Index)) {
  340. Args.replaceArgString(Index, Twine('-') + Str.substr(2));
  341. return A;
  342. }
  343. }
  344. // In the case of an incorrect short option extract the character and move to
  345. // the next one.
  346. if (Str[1] != '-') {
  347. CStr = Args.MakeArgString(Str.substr(0, 2));
  348. Args.replaceArgString(Index, Twine('-') + Str.substr(2));
  349. return std::make_unique<Arg>(getOption(UnknownOptionID), CStr, Index, CStr);
  350. }
  351. return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, CStr);
  352. }
  353. std::unique_ptr<Arg> OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
  354. unsigned FlagsToInclude,
  355. unsigned FlagsToExclude) const {
  356. unsigned Prev = Index;
  357. const char *Str = Args.getArgString(Index);
  358. // Anything that doesn't start with PrefixesUnion is an input, as is '-'
  359. // itself.
  360. if (isInput(PrefixesUnion, Str))
  361. return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, Str);
  362. const Info *Start = OptionInfos.data() + FirstSearchableIndex;
  363. const Info *End = OptionInfos.data() + OptionInfos.size();
  364. StringRef Name = StringRef(Str).ltrim(PrefixChars);
  365. // Search for the first next option which could be a prefix.
  366. Start = std::lower_bound(Start, End, Name.data());
  367. // Options are stored in sorted order, with '\0' at the end of the
  368. // alphabet. Since the only options which can accept a string must
  369. // prefix it, we iteratively search for the next option which could
  370. // be a prefix.
  371. //
  372. // FIXME: This is searching much more than necessary, but I am
  373. // blanking on the simplest way to make it fast. We can solve this
  374. // problem when we move to TableGen.
  375. for (; Start != End; ++Start) {
  376. unsigned ArgSize = 0;
  377. // Scan for first option which is a proper prefix.
  378. for (; Start != End; ++Start)
  379. if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
  380. break;
  381. if (Start == End)
  382. break;
  383. Option Opt(Start, this);
  384. if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
  385. continue;
  386. if (Opt.hasFlag(FlagsToExclude))
  387. continue;
  388. // See if this option matches.
  389. if (std::unique_ptr<Arg> A =
  390. Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
  391. /*GroupedShortOption=*/false, Index))
  392. return A;
  393. // Otherwise, see if this argument was missing values.
  394. if (Prev != Index)
  395. return nullptr;
  396. }
  397. // If we failed to find an option and this arg started with /, then it's
  398. // probably an input path.
  399. if (Str[0] == '/')
  400. return std::make_unique<Arg>(getOption(InputOptionID), Str, Index++, Str);
  401. return std::make_unique<Arg>(getOption(UnknownOptionID), Str, Index++, Str);
  402. }
  403. InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
  404. unsigned &MissingArgIndex,
  405. unsigned &MissingArgCount,
  406. unsigned FlagsToInclude,
  407. unsigned FlagsToExclude) const {
  408. InputArgList Args(ArgArr.begin(), ArgArr.end());
  409. // FIXME: Handle '@' args (or at least error on them).
  410. MissingArgIndex = MissingArgCount = 0;
  411. unsigned Index = 0, End = ArgArr.size();
  412. while (Index < End) {
  413. // Ingore nullptrs, they are response file's EOL markers
  414. if (Args.getArgString(Index) == nullptr) {
  415. ++Index;
  416. continue;
  417. }
  418. // Ignore empty arguments (other things may still take them as arguments).
  419. StringRef Str = Args.getArgString(Index);
  420. if (Str == "") {
  421. ++Index;
  422. continue;
  423. }
  424. unsigned Prev = Index;
  425. std::unique_ptr<Arg> A = GroupedShortOptions
  426. ? parseOneArgGrouped(Args, Index)
  427. : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
  428. assert((Index > Prev || GroupedShortOptions) &&
  429. "Parser failed to consume argument.");
  430. // Check for missing argument error.
  431. if (!A) {
  432. assert(Index >= End && "Unexpected parser error.");
  433. assert(Index - Prev - 1 && "No missing arguments!");
  434. MissingArgIndex = Prev;
  435. MissingArgCount = Index - Prev - 1;
  436. break;
  437. }
  438. Args.append(A.release());
  439. }
  440. return Args;
  441. }
  442. InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
  443. OptSpecifier Unknown, StringSaver &Saver,
  444. function_ref<void(StringRef)> ErrorFn) const {
  445. SmallVector<const char *, 0> NewArgv;
  446. // The environment variable specifies initial options which can be overridden
  447. // by commnad line options.
  448. cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
  449. unsigned MAI, MAC;
  450. opt::InputArgList Args = ParseArgs(makeArrayRef(NewArgv), MAI, MAC);
  451. if (MAC)
  452. ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
  453. // For each unknwon option, call ErrorFn with a formatted error message. The
  454. // message includes a suggested alternative option spelling if available.
  455. std::string Nearest;
  456. for (const opt::Arg *A : Args.filtered(Unknown)) {
  457. std::string Spelling = A->getAsString(Args);
  458. if (findNearest(Spelling, Nearest) > 1)
  459. ErrorFn("unknown argument '" + A->getAsString(Args) + "'");
  460. else
  461. ErrorFn("unknown argument '" + A->getAsString(Args) +
  462. "', did you mean '" + Nearest + "'?");
  463. }
  464. return Args;
  465. }
  466. static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
  467. const Option O = Opts.getOption(Id);
  468. std::string Name = O.getPrefixedName();
  469. // Add metavar, if used.
  470. switch (O.getKind()) {
  471. case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
  472. llvm_unreachable("Invalid option with help text.");
  473. case Option::MultiArgClass:
  474. if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
  475. // For MultiArgs, metavar is full list of all argument names.
  476. Name += ' ';
  477. Name += MetaVarName;
  478. }
  479. else {
  480. // For MultiArgs<N>, if metavar not supplied, print <value> N times.
  481. for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
  482. Name += " <value>";
  483. }
  484. }
  485. break;
  486. case Option::FlagClass:
  487. break;
  488. case Option::ValuesClass:
  489. break;
  490. case Option::SeparateClass: case Option::JoinedOrSeparateClass:
  491. case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
  492. Name += ' ';
  493. LLVM_FALLTHROUGH;
  494. case Option::JoinedClass: case Option::CommaJoinedClass:
  495. case Option::JoinedAndSeparateClass:
  496. if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
  497. Name += MetaVarName;
  498. else
  499. Name += "<value>";
  500. break;
  501. }
  502. return Name;
  503. }
  504. namespace {
  505. struct OptionInfo {
  506. std::string Name;
  507. StringRef HelpText;
  508. };
  509. } // namespace
  510. static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
  511. std::vector<OptionInfo> &OptionHelp) {
  512. OS << Title << ":\n";
  513. // Find the maximum option length.
  514. unsigned OptionFieldWidth = 0;
  515. for (const OptionInfo &Opt : OptionHelp) {
  516. // Limit the amount of padding we are willing to give up for alignment.
  517. unsigned Length = Opt.Name.size();
  518. if (Length <= 23)
  519. OptionFieldWidth = std::max(OptionFieldWidth, Length);
  520. }
  521. const unsigned InitialPad = 2;
  522. for (const OptionInfo &Opt : OptionHelp) {
  523. const std::string &Option = Opt.Name;
  524. int Pad = OptionFieldWidth - int(Option.size());
  525. OS.indent(InitialPad) << Option;
  526. // Break on long option names.
  527. if (Pad < 0) {
  528. OS << "\n";
  529. Pad = OptionFieldWidth + InitialPad;
  530. }
  531. OS.indent(Pad + 1) << Opt.HelpText << '\n';
  532. }
  533. }
  534. static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
  535. unsigned GroupID = Opts.getOptionGroupID(Id);
  536. // If not in a group, return the default help group.
  537. if (!GroupID)
  538. return "OPTIONS";
  539. // Abuse the help text of the option groups to store the "help group"
  540. // name.
  541. //
  542. // FIXME: Split out option groups.
  543. if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
  544. return GroupHelp;
  545. // Otherwise keep looking.
  546. return getOptionHelpGroup(Opts, GroupID);
  547. }
  548. void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
  549. bool ShowHidden, bool ShowAllAliases) const {
  550. printHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
  551. (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
  552. }
  553. void OptTable::printHelp(raw_ostream &OS, const char *Usage, const char *Title,
  554. unsigned FlagsToInclude, unsigned FlagsToExclude,
  555. bool ShowAllAliases) const {
  556. OS << "OVERVIEW: " << Title << "\n\n";
  557. OS << "USAGE: " << Usage << "\n\n";
  558. // Render help text into a map of group-name to a list of (option, help)
  559. // pairs.
  560. std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
  561. for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
  562. // FIXME: Split out option groups.
  563. if (getOptionKind(Id) == Option::GroupClass)
  564. continue;
  565. unsigned Flags = getInfo(Id).Flags;
  566. if (FlagsToInclude && !(Flags & FlagsToInclude))
  567. continue;
  568. if (Flags & FlagsToExclude)
  569. continue;
  570. // If an alias doesn't have a help text, show a help text for the aliased
  571. // option instead.
  572. const char *HelpText = getOptionHelpText(Id);
  573. if (!HelpText && ShowAllAliases) {
  574. const Option Alias = getOption(Id).getAlias();
  575. if (Alias.isValid())
  576. HelpText = getOptionHelpText(Alias.getID());
  577. }
  578. if (HelpText && (strlen(HelpText) != 0)) {
  579. const char *HelpGroup = getOptionHelpGroup(*this, Id);
  580. const std::string &OptName = getOptionHelpName(*this, Id);
  581. GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
  582. }
  583. }
  584. for (auto& OptionGroup : GroupedOptionHelp) {
  585. if (OptionGroup.first != GroupedOptionHelp.begin()->first)
  586. OS << "\n";
  587. PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
  588. }
  589. OS.flush();
  590. }