ClangOptionDocEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
  146. // FIXME: Provide a flag to specify the set of exclusions.
  147. for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
  148. if (hasFlag(OptionOrGroup, Exclusion))
  149. return true;
  150. return false;
  151. }
  152. std::string escapeRST(StringRef Str) {
  153. std::string Out;
  154. for (auto K : Str) {
  155. if (StringRef("`*|_[]\\").count(K))
  156. Out.push_back('\\');
  157. Out.push_back(K);
  158. }
  159. return Out;
  160. }
  161. StringRef getSphinxOptionID(StringRef OptionName) {
  162. for (auto I = OptionName.begin(), E = OptionName.end(); I != E; ++I)
  163. if (!isalnum(*I) && *I != '-')
  164. return OptionName.substr(0, I - OptionName.begin());
  165. return OptionName;
  166. }
  167. bool canSphinxCopeWithOption(const Record *Option) {
  168. // HACK: Work arond sphinx's inability to cope with punctuation-only options
  169. // such as /? by suppressing them from the option list.
  170. for (char C : Option->getValueAsString("Name"))
  171. if (isalnum(C))
  172. return true;
  173. return false;
  174. }
  175. void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {
  176. assert(Depth < 8 && "groups nested too deeply");
  177. OS << Heading << '\n'
  178. << std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";
  179. }
  180. /// Get the value of field \p Primary, if possible. If \p Primary does not
  181. /// exist, get the value of \p Fallback and escape it for rST emission.
  182. std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,
  183. StringRef Fallback) {
  184. for (auto Field : {Primary, Fallback}) {
  185. if (auto *V = R->getValue(Field)) {
  186. StringRef Value;
  187. if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))
  188. Value = SV->getValue();
  189. if (!Value.empty())
  190. return Field == Primary ? Value.str() : escapeRST(Value);
  191. }
  192. }
  193. return std::string(StringRef());
  194. }
  195. void emitOptionWithArgs(StringRef Prefix, const Record *Option,
  196. ArrayRef<StringRef> Args, raw_ostream &OS) {
  197. OS << Prefix << escapeRST(Option->getValueAsString("Name"));
  198. std::pair<StringRef, StringRef> Separators =
  199. getSeparatorsForKind(Option->getValueAsDef("Kind"));
  200. StringRef Separator = Separators.first;
  201. for (auto Arg : Args) {
  202. OS << Separator << escapeRST(Arg);
  203. Separator = Separators.second;
  204. }
  205. }
  206. void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
  207. // Find the arguments to list after the option.
  208. unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
  209. bool HasMetaVarName = !Option->isValueUnset("MetaVarName");
  210. std::vector<std::string> Args;
  211. if (HasMetaVarName)
  212. Args.push_back(std::string(Option->getValueAsString("MetaVarName")));
  213. else if (NumArgs == 1)
  214. Args.push_back("<arg>");
  215. // Fill up arguments if this option didn't provide a meta var name or it
  216. // supports an unlimited number of arguments. We can't see how many arguments
  217. // already are in a meta var name, so assume it has right number. This is
  218. // needed for JoinedAndSeparate options so that there arent't too many
  219. // arguments.
  220. if (!HasMetaVarName || NumArgs == UnlimitedArgs) {
  221. while (Args.size() < NumArgs) {
  222. Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
  223. // Use '--args <arg1> <arg2>...' if any number of args are allowed.
  224. if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
  225. Args.back() += "...";
  226. break;
  227. }
  228. }
  229. }
  230. emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);
  231. auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
  232. if (!AliasArgs.empty()) {
  233. Record *Alias = Option->getValueAsDef("Alias");
  234. OS << " (equivalent to ";
  235. emitOptionWithArgs(
  236. Alias->getValueAsListOfStrings("Prefixes").front(), Alias,
  237. AliasArgs, OS);
  238. OS << ")";
  239. }
  240. }
  241. bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
  242. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
  243. if (EmittedAny)
  244. OS << ", ";
  245. emitOptionName(Prefix, Option, OS);
  246. EmittedAny = true;
  247. }
  248. return EmittedAny;
  249. }
  250. template <typename Fn>
  251. void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
  252. Fn F) {
  253. F(Option.Option);
  254. for (auto *Alias : Option.Aliases)
  255. if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
  256. F(Alias);
  257. }
  258. void emitOption(const DocumentedOption &Option, const Record *DocInfo,
  259. raw_ostream &OS) {
  260. if (isExcluded(Option.Option, DocInfo))
  261. return;
  262. if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
  263. Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
  264. return;
  265. if (!canSphinxCopeWithOption(Option.Option))
  266. return;
  267. // HACK: Emit a different program name with each option to work around
  268. // sphinx's inability to cope with options that differ only by punctuation
  269. // (eg -ObjC vs -ObjC++, -G vs -G=).
  270. std::vector<std::string> SphinxOptionIDs;
  271. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  272. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
  273. SphinxOptionIDs.push_back(std::string(getSphinxOptionID(
  274. (Prefix + Option->getValueAsString("Name")).str())));
  275. });
  276. assert(!SphinxOptionIDs.empty() && "no flags for option");
  277. static std::map<std::string, int> NextSuffix;
  278. int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(
  279. SphinxOptionIDs.begin(), SphinxOptionIDs.end(),
  280. [&](const std::string &A, const std::string &B) {
  281. return NextSuffix[A] < NextSuffix[B];
  282. })];
  283. for (auto &S : SphinxOptionIDs)
  284. NextSuffix[S] = SphinxWorkaroundSuffix + 1;
  285. if (SphinxWorkaroundSuffix)
  286. OS << ".. program:: " << DocInfo->getValueAsString("Program")
  287. << SphinxWorkaroundSuffix << "\n";
  288. // Emit the names of the option.
  289. OS << ".. option:: ";
  290. bool EmittedAny = false;
  291. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  292. EmittedAny = emitOptionNames(Option, OS, EmittedAny);
  293. });
  294. if (SphinxWorkaroundSuffix)
  295. OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
  296. OS << "\n\n";
  297. // Emit the description, if we have one.
  298. std::string Description =
  299. getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
  300. if (!Description.empty())
  301. OS << Description << "\n\n";
  302. }
  303. void emitDocumentation(int Depth, const Documentation &Doc,
  304. const Record *DocInfo, raw_ostream &OS);
  305. void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
  306. raw_ostream &OS) {
  307. if (isExcluded(Group.Group, DocInfo))
  308. return;
  309. emitHeading(Depth,
  310. getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
  311. // Emit the description, if we have one.
  312. std::string Description =
  313. getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
  314. if (!Description.empty())
  315. OS << Description << "\n\n";
  316. // Emit contained options and groups.
  317. emitDocumentation(Depth + 1, Group, DocInfo, OS);
  318. }
  319. void emitDocumentation(int Depth, const Documentation &Doc,
  320. const Record *DocInfo, raw_ostream &OS) {
  321. for (auto &O : Doc.Options)
  322. emitOption(O, DocInfo, OS);
  323. for (auto &G : Doc.Groups)
  324. emitGroup(Depth, G, DocInfo, OS);
  325. }
  326. } // namespace
  327. void clang::EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
  328. const Record *DocInfo = Records.getDef("GlobalDocumentation");
  329. if (!DocInfo) {
  330. PrintFatalError("The GlobalDocumentation top-level definition is missing, "
  331. "no documentation will be generated.");
  332. return;
  333. }
  334. OS << DocInfo->getValueAsString("Intro") << "\n";
  335. OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
  336. emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
  337. }