ClangOptionDocEmitter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. //===- ClangOptionDocEmitter.cpp - Documentation for command line flags ---===//
  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. // FIXME: Once this has stabilized, consider moving it to LLVM.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. #include "TableGenBackends.h"
  11. #include "llvm/TableGen/Error.h"
  12. #include "llvm/ADT/STLExtras.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/TableGen/Record.h"
  17. #include "llvm/TableGen/TableGenBackend.h"
  18. #include <cctype>
  19. #include <cstring>
  20. #include <map>
  21. using namespace llvm;
  22. namespace {
  23. struct DocumentedOption {
  24. Record *Option;
  25. std::vector<Record*> Aliases;
  26. };
  27. struct DocumentedGroup;
  28. struct Documentation {
  29. std::vector<DocumentedGroup> Groups;
  30. std::vector<DocumentedOption> Options;
  31. };
  32. struct DocumentedGroup : Documentation {
  33. Record *Group;
  34. };
  35. // Reorganize the records into a suitable form for emitting documentation.
  36. Documentation extractDocumentation(RecordKeeper &Records) {
  37. Documentation Result;
  38. // Build the tree of groups. The root in the tree is the fake option group
  39. // (Record*)nullptr, which contains all top-level groups and options.
  40. std::map<Record*, std::vector<Record*> > OptionsInGroup;
  41. std::map<Record*, std::vector<Record*> > GroupsInGroup;
  42. std::map<Record*, std::vector<Record*> > Aliases;
  43. std::map<std::string, Record*> OptionsByName;
  44. for (Record *R : Records.getAllDerivedDefinitions("Option"))
  45. OptionsByName[std::string(R->getValueAsString("Name"))] = R;
  46. auto Flatten = [](Record *R) {
  47. return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
  48. };
  49. auto SkipFlattened = [&](Record *R) -> Record* {
  50. while (R && Flatten(R)) {
  51. auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));
  52. if (!G)
  53. return nullptr;
  54. R = G->getDef();
  55. }
  56. return R;
  57. };
  58. for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
  59. if (Flatten(R))
  60. continue;
  61. Record *Group = nullptr;
  62. if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
  63. Group = SkipFlattened(G->getDef());
  64. GroupsInGroup[Group].push_back(R);
  65. }
  66. for (Record *R : Records.getAllDerivedDefinitions("Option")) {
  67. if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {
  68. Aliases[A->getDef()].push_back(R);
  69. continue;
  70. }
  71. // Pretend no-X and Xno-Y options are aliases of X and XY.
  72. std::string Name = std::string(R->getValueAsString("Name"));
  73. if (Name.size() >= 4) {
  74. if (Name.substr(0, 3) == "no-" && OptionsByName[Name.substr(3)]) {
  75. Aliases[OptionsByName[Name.substr(3)]].push_back(R);
  76. continue;
  77. }
  78. if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {
  79. Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);
  80. continue;
  81. }
  82. }
  83. Record *Group = nullptr;
  84. if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
  85. Group = SkipFlattened(G->getDef());
  86. OptionsInGroup[Group].push_back(R);
  87. }
  88. auto CompareByName = [](Record *A, Record *B) {
  89. return A->getValueAsString("Name") < B->getValueAsString("Name");
  90. };
  91. auto CompareByLocation = [](Record *A, Record *B) {
  92. return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
  93. };
  94. auto DocumentationForOption = [&](Record *R) -> DocumentedOption {
  95. auto &A = Aliases[R];
  96. llvm::sort(A, CompareByName);
  97. return {R, std::move(A)};
  98. };
  99. std::function<Documentation(Record *)> DocumentationForGroup =
  100. [&](Record *R) -> Documentation {
  101. Documentation D;
  102. auto &Groups = GroupsInGroup[R];
  103. llvm::sort(Groups, CompareByLocation);
  104. for (Record *G : Groups) {
  105. D.Groups.emplace_back();
  106. D.Groups.back().Group = G;
  107. Documentation &Base = D.Groups.back();
  108. Base = DocumentationForGroup(G);
  109. }
  110. auto &Options = OptionsInGroup[R];
  111. llvm::sort(Options, CompareByName);
  112. for (Record *O : Options)
  113. D.Options.push_back(DocumentationForOption(O));
  114. return D;
  115. };
  116. return DocumentationForGroup(nullptr);
  117. }
  118. // Get the first and successive separators to use for an OptionKind.
  119. std::pair<StringRef,StringRef> getSeparatorsForKind(const Record *OptionKind) {
  120. return StringSwitch<std::pair<StringRef, StringRef>>(OptionKind->getName())
  121. .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE",
  122. "KIND_JOINED_AND_SEPARATE",
  123. "KIND_REMAINING_ARGS_JOINED", {"", " "})
  124. .Case("KIND_COMMAJOINED", {"", ","})
  125. .Default({" ", " "});
  126. }
  127. const unsigned UnlimitedArgs = unsigned(-1);
  128. // Get the number of arguments expected for an option, or -1 if any number of
  129. // arguments are accepted.
  130. unsigned getNumArgsForKind(Record *OptionKind, const Record *Option) {
  131. return StringSwitch<unsigned>(OptionKind->getName())
  132. .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE", "KIND_SEPARATE", 1)
  133. .Cases("KIND_REMAINING_ARGS", "KIND_REMAINING_ARGS_JOINED",
  134. "KIND_COMMAJOINED", UnlimitedArgs)
  135. .Case("KIND_JOINED_AND_SEPARATE", 2)
  136. .Case("KIND_MULTIARG", Option->getValueAsInt("NumArgs"))
  137. .Default(0);
  138. }
  139. bool hasFlag(const Record *OptionOrGroup, StringRef OptionFlag) {
  140. for (const Record *Flag : OptionOrGroup->getValueAsListOfDefs("Flags"))
  141. if (Flag->getName() == OptionFlag)
  142. return true;
  143. return false;
  144. }
  145. bool isIncluded(const Record *OptionOrGroup, const Record *DocInfo) {
  146. assert(DocInfo->getValue("IncludedFlags") && "Missing includeFlags");
  147. for (StringRef Inclusion : DocInfo->getValueAsListOfStrings("IncludedFlags"))
  148. if (hasFlag(OptionOrGroup, Inclusion))
  149. return true;
  150. return false;
  151. }
  152. bool isGroupIncluded(const DocumentedGroup &Group, const Record *DocInfo) {
  153. if (isIncluded(Group.Group, DocInfo))
  154. return true;
  155. for (auto &O : Group.Options)
  156. if (isIncluded(O.Option, DocInfo))
  157. return true;
  158. for (auto &G : Group.Groups) {
  159. if (isIncluded(G.Group, DocInfo))
  160. return true;
  161. if (isGroupIncluded(G, DocInfo))
  162. return true;
  163. }
  164. return false;
  165. }
  166. bool isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
  167. // FIXME: Provide a flag to specify the set of exclusions.
  168. for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
  169. if (hasFlag(OptionOrGroup, Exclusion))
  170. return true;
  171. return false;
  172. }
  173. std::string escapeRST(StringRef Str) {
  174. std::string Out;
  175. for (auto K : Str) {
  176. if (StringRef("`*|_[]\\").count(K))
  177. Out.push_back('\\');
  178. Out.push_back(K);
  179. }
  180. return Out;
  181. }
  182. StringRef getSphinxOptionID(StringRef OptionName) {
  183. for (auto I = OptionName.begin(), E = OptionName.end(); I != E; ++I)
  184. if (!isalnum(*I) && *I != '-')
  185. return OptionName.substr(0, I - OptionName.begin());
  186. return OptionName;
  187. }
  188. bool canSphinxCopeWithOption(const Record *Option) {
  189. // HACK: Work arond sphinx's inability to cope with punctuation-only options
  190. // such as /? by suppressing them from the option list.
  191. for (char C : Option->getValueAsString("Name"))
  192. if (isalnum(C))
  193. return true;
  194. return false;
  195. }
  196. void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {
  197. assert(Depth < 8 && "groups nested too deeply");
  198. OS << Heading << '\n'
  199. << std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";
  200. }
  201. /// Get the value of field \p Primary, if possible. If \p Primary does not
  202. /// exist, get the value of \p Fallback and escape it for rST emission.
  203. std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,
  204. StringRef Fallback) {
  205. for (auto Field : {Primary, Fallback}) {
  206. if (auto *V = R->getValue(Field)) {
  207. StringRef Value;
  208. if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))
  209. Value = SV->getValue();
  210. if (!Value.empty())
  211. return Field == Primary ? Value.str() : escapeRST(Value);
  212. }
  213. }
  214. return std::string(StringRef());
  215. }
  216. void emitOptionWithArgs(StringRef Prefix, const Record *Option,
  217. ArrayRef<StringRef> Args, raw_ostream &OS) {
  218. OS << Prefix << escapeRST(Option->getValueAsString("Name"));
  219. std::pair<StringRef, StringRef> Separators =
  220. getSeparatorsForKind(Option->getValueAsDef("Kind"));
  221. StringRef Separator = Separators.first;
  222. for (auto Arg : Args) {
  223. OS << Separator << escapeRST(Arg);
  224. Separator = Separators.second;
  225. }
  226. }
  227. constexpr StringLiteral DefaultMetaVarName = "<arg>";
  228. void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
  229. // Find the arguments to list after the option.
  230. unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
  231. bool HasMetaVarName = !Option->isValueUnset("MetaVarName");
  232. std::vector<std::string> Args;
  233. if (HasMetaVarName)
  234. Args.push_back(std::string(Option->getValueAsString("MetaVarName")));
  235. else if (NumArgs == 1)
  236. Args.push_back(DefaultMetaVarName.str());
  237. // Fill up arguments if this option didn't provide a meta var name or it
  238. // supports an unlimited number of arguments. We can't see how many arguments
  239. // already are in a meta var name, so assume it has right number. This is
  240. // needed for JoinedAndSeparate options so that there arent't too many
  241. // arguments.
  242. if (!HasMetaVarName || NumArgs == UnlimitedArgs) {
  243. while (Args.size() < NumArgs) {
  244. Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
  245. // Use '--args <arg1> <arg2>...' if any number of args are allowed.
  246. if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
  247. Args.back() += "...";
  248. break;
  249. }
  250. }
  251. }
  252. emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);
  253. auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
  254. if (!AliasArgs.empty()) {
  255. Record *Alias = Option->getValueAsDef("Alias");
  256. OS << " (equivalent to ";
  257. emitOptionWithArgs(
  258. Alias->getValueAsListOfStrings("Prefixes").front(), Alias,
  259. AliasArgs, OS);
  260. OS << ")";
  261. }
  262. }
  263. bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
  264. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
  265. if (EmittedAny)
  266. OS << ", ";
  267. emitOptionName(Prefix, Option, OS);
  268. EmittedAny = true;
  269. }
  270. return EmittedAny;
  271. }
  272. template <typename Fn>
  273. void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
  274. Fn F) {
  275. F(Option.Option);
  276. for (auto *Alias : Option.Aliases)
  277. if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
  278. F(Alias);
  279. }
  280. void emitOption(const DocumentedOption &Option, const Record *DocInfo,
  281. raw_ostream &OS) {
  282. if (isExcluded(Option.Option, DocInfo))
  283. return;
  284. if (DocInfo->getValue("IncludedFlags") && !isIncluded(Option.Option, DocInfo))
  285. return;
  286. if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
  287. Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
  288. return;
  289. if (!canSphinxCopeWithOption(Option.Option))
  290. return;
  291. // HACK: Emit a different program name with each option to work around
  292. // sphinx's inability to cope with options that differ only by punctuation
  293. // (eg -ObjC vs -ObjC++, -G vs -G=).
  294. std::vector<std::string> SphinxOptionIDs;
  295. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  296. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
  297. SphinxOptionIDs.push_back(std::string(getSphinxOptionID(
  298. (Prefix + Option->getValueAsString("Name")).str())));
  299. });
  300. assert(!SphinxOptionIDs.empty() && "no flags for option");
  301. static std::map<std::string, int> NextSuffix;
  302. int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(
  303. SphinxOptionIDs.begin(), SphinxOptionIDs.end(),
  304. [&](const std::string &A, const std::string &B) {
  305. return NextSuffix[A] < NextSuffix[B];
  306. })];
  307. for (auto &S : SphinxOptionIDs)
  308. NextSuffix[S] = SphinxWorkaroundSuffix + 1;
  309. if (SphinxWorkaroundSuffix)
  310. OS << ".. program:: " << DocInfo->getValueAsString("Program")
  311. << SphinxWorkaroundSuffix << "\n";
  312. // Emit the names of the option.
  313. OS << ".. option:: ";
  314. bool EmittedAny = false;
  315. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  316. EmittedAny = emitOptionNames(Option, OS, EmittedAny);
  317. });
  318. if (SphinxWorkaroundSuffix)
  319. OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
  320. OS << "\n\n";
  321. // Emit the description, if we have one.
  322. const Record *R = Option.Option;
  323. std::string Description =
  324. getRSTStringWithTextFallback(R, "DocBrief", "HelpText");
  325. if (!isa<UnsetInit>(R->getValueInit("Values"))) {
  326. if (!Description.empty() && Description.back() != '.')
  327. Description.push_back('.');
  328. StringRef MetaVarName;
  329. if (!isa<UnsetInit>(R->getValueInit("MetaVarName")))
  330. MetaVarName = R->getValueAsString("MetaVarName");
  331. else
  332. MetaVarName = DefaultMetaVarName;
  333. SmallVector<StringRef> Values;
  334. SplitString(R->getValueAsString("Values"), Values, ",");
  335. Description += (" " + MetaVarName + " must be '").str();
  336. if (Values.size() > 1) {
  337. Description += join(Values.begin(), Values.end() - 1, "', '");
  338. Description += "' or '";
  339. }
  340. Description += (Values.back() + "'.").str();
  341. }
  342. if (!Description.empty())
  343. OS << Description << "\n\n";
  344. }
  345. void emitDocumentation(int Depth, const Documentation &Doc,
  346. const Record *DocInfo, raw_ostream &OS);
  347. void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
  348. raw_ostream &OS) {
  349. if (isExcluded(Group.Group, DocInfo))
  350. return;
  351. if (DocInfo->getValue("IncludedFlags") && !isGroupIncluded(Group, DocInfo))
  352. return;
  353. emitHeading(Depth,
  354. getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
  355. // Emit the description, if we have one.
  356. std::string Description =
  357. getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
  358. if (!Description.empty())
  359. OS << Description << "\n\n";
  360. // Emit contained options and groups.
  361. emitDocumentation(Depth + 1, Group, DocInfo, OS);
  362. }
  363. void emitDocumentation(int Depth, const Documentation &Doc,
  364. const Record *DocInfo, raw_ostream &OS) {
  365. for (auto &O : Doc.Options)
  366. emitOption(O, DocInfo, OS);
  367. for (auto &G : Doc.Groups)
  368. emitGroup(Depth, G, DocInfo, OS);
  369. }
  370. } // namespace
  371. void clang::EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
  372. const Record *DocInfo = Records.getDef("GlobalDocumentation");
  373. if (!DocInfo) {
  374. PrintFatalError("The GlobalDocumentation top-level definition is missing, "
  375. "no documentation will be generated.");
  376. return;
  377. }
  378. OS << DocInfo->getValueAsString("Intro") << "\n";
  379. OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
  380. emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
  381. }