ClangOptionDocEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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[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 = 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. else if (auto *CV = dyn_cast_or_null<CodeInit>(V->getValue()))
  190. Value = CV->getValue();
  191. if (!Value.empty())
  192. return Field == Primary ? Value.str() : escapeRST(Value);
  193. }
  194. }
  195. return StringRef();
  196. }
  197. void emitOptionWithArgs(StringRef Prefix, const Record *Option,
  198. ArrayRef<StringRef> Args, raw_ostream &OS) {
  199. OS << Prefix << escapeRST(Option->getValueAsString("Name"));
  200. std::pair<StringRef, StringRef> Separators =
  201. getSeparatorsForKind(Option->getValueAsDef("Kind"));
  202. StringRef Separator = Separators.first;
  203. for (auto Arg : Args) {
  204. OS << Separator << escapeRST(Arg);
  205. Separator = Separators.second;
  206. }
  207. }
  208. void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
  209. // Find the arguments to list after the option.
  210. unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
  211. bool HasMetaVarName = !Option->isValueUnset("MetaVarName");
  212. std::vector<std::string> Args;
  213. if (HasMetaVarName)
  214. Args.push_back(Option->getValueAsString("MetaVarName"));
  215. else if (NumArgs == 1)
  216. Args.push_back("<arg>");
  217. // Fill up arguments if this option didn't provide a meta var name or it
  218. // supports an unlimited number of arguments. We can't see how many arguments
  219. // already are in a meta var name, so assume it has right number. This is
  220. // needed for JoinedAndSeparate options so that there arent't too many
  221. // arguments.
  222. if (!HasMetaVarName || NumArgs == UnlimitedArgs) {
  223. while (Args.size() < NumArgs) {
  224. Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
  225. // Use '--args <arg1> <arg2>...' if any number of args are allowed.
  226. if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
  227. Args.back() += "...";
  228. break;
  229. }
  230. }
  231. }
  232. emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);
  233. auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
  234. if (!AliasArgs.empty()) {
  235. Record *Alias = Option->getValueAsDef("Alias");
  236. OS << " (equivalent to ";
  237. emitOptionWithArgs(
  238. Alias->getValueAsListOfStrings("Prefixes").front(), Alias,
  239. AliasArgs, OS);
  240. OS << ")";
  241. }
  242. }
  243. bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
  244. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
  245. if (EmittedAny)
  246. OS << ", ";
  247. emitOptionName(Prefix, Option, OS);
  248. EmittedAny = true;
  249. }
  250. return EmittedAny;
  251. }
  252. template <typename Fn>
  253. void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
  254. Fn F) {
  255. F(Option.Option);
  256. for (auto *Alias : Option.Aliases)
  257. if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
  258. F(Alias);
  259. }
  260. void emitOption(const DocumentedOption &Option, const Record *DocInfo,
  261. raw_ostream &OS) {
  262. if (isExcluded(Option.Option, DocInfo))
  263. return;
  264. if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
  265. Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
  266. return;
  267. if (!canSphinxCopeWithOption(Option.Option))
  268. return;
  269. // HACK: Emit a different program name with each option to work around
  270. // sphinx's inability to cope with options that differ only by punctuation
  271. // (eg -ObjC vs -ObjC++, -G vs -G=).
  272. std::vector<std::string> SphinxOptionIDs;
  273. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  274. for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
  275. SphinxOptionIDs.push_back(
  276. getSphinxOptionID((Prefix + Option->getValueAsString("Name")).str()));
  277. });
  278. assert(!SphinxOptionIDs.empty() && "no flags for option");
  279. static std::map<std::string, int> NextSuffix;
  280. int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(
  281. SphinxOptionIDs.begin(), SphinxOptionIDs.end(),
  282. [&](const std::string &A, const std::string &B) {
  283. return NextSuffix[A] < NextSuffix[B];
  284. })];
  285. for (auto &S : SphinxOptionIDs)
  286. NextSuffix[S] = SphinxWorkaroundSuffix + 1;
  287. if (SphinxWorkaroundSuffix)
  288. OS << ".. program:: " << DocInfo->getValueAsString("Program")
  289. << SphinxWorkaroundSuffix << "\n";
  290. // Emit the names of the option.
  291. OS << ".. option:: ";
  292. bool EmittedAny = false;
  293. forEachOptionName(Option, DocInfo, [&](const Record *Option) {
  294. EmittedAny = emitOptionNames(Option, OS, EmittedAny);
  295. });
  296. if (SphinxWorkaroundSuffix)
  297. OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
  298. OS << "\n\n";
  299. // Emit the description, if we have one.
  300. std::string Description =
  301. getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
  302. if (!Description.empty())
  303. OS << Description << "\n\n";
  304. }
  305. void emitDocumentation(int Depth, const Documentation &Doc,
  306. const Record *DocInfo, raw_ostream &OS);
  307. void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
  308. raw_ostream &OS) {
  309. if (isExcluded(Group.Group, DocInfo))
  310. return;
  311. emitHeading(Depth,
  312. getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
  313. // Emit the description, if we have one.
  314. std::string Description =
  315. getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
  316. if (!Description.empty())
  317. OS << Description << "\n\n";
  318. // Emit contained options and groups.
  319. emitDocumentation(Depth + 1, Group, DocInfo, OS);
  320. }
  321. void emitDocumentation(int Depth, const Documentation &Doc,
  322. const Record *DocInfo, raw_ostream &OS) {
  323. for (auto &O : Doc.Options)
  324. emitOption(O, DocInfo, OS);
  325. for (auto &G : Doc.Groups)
  326. emitGroup(Depth, G, DocInfo, OS);
  327. }
  328. } // namespace
  329. void clang::EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
  330. const Record *DocInfo = Records.getDef("GlobalDocumentation");
  331. if (!DocInfo) {
  332. PrintFatalError("The GlobalDocumentation top-level definition is missing, "
  333. "no documentation will be generated.");
  334. return;
  335. }
  336. OS << DocInfo->getValueAsString("Intro") << "\n";
  337. OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
  338. emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
  339. }