1 //===- ClangOptionDocEmitter.cpp - Documentation for command line flags ---===//
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
7 // FIXME: Once this has stabilized, consider moving it to LLVM.
9 //===----------------------------------------------------------------------===//
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"
27 struct DocumentedOption {
29 std::vector<Record*> Aliases;
31 struct DocumentedGroup;
32 struct Documentation {
33 std::vector<DocumentedGroup> Groups;
34 std::vector<DocumentedOption> Options;
36 struct DocumentedGroup : Documentation {
40 // Reorganize the records into a suitable form for emitting documentation.
41 Documentation extractDocumentation(RecordKeeper &Records) {
44 // Build the tree of groups. The root in the tree is the fake option group
45 // (Record*)nullptr, which contains all top-level groups and options.
46 std::map<Record*, std::vector<Record*> > OptionsInGroup;
47 std::map<Record*, std::vector<Record*> > GroupsInGroup;
48 std::map<Record*, std::vector<Record*> > Aliases;
50 std::map<std::string, Record*> OptionsByName;
51 for (Record *R : Records.getAllDerivedDefinitions("Option"))
52 OptionsByName[R->getValueAsString("Name")] = R;
54 auto Flatten = [](Record *R) {
55 return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
58 auto SkipFlattened = [&](Record *R) -> Record* {
59 while (R && Flatten(R)) {
60 auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));
68 for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
72 Record *Group = nullptr;
73 if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
74 Group = SkipFlattened(G->getDef());
75 GroupsInGroup[Group].push_back(R);
78 for (Record *R : Records.getAllDerivedDefinitions("Option")) {
79 if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {
80 Aliases[A->getDef()].push_back(R);
84 // Pretend no-X and Xno-Y options are aliases of X and XY.
85 std::string Name = R->getValueAsString("Name");
86 if (Name.size() >= 4) {
87 if (Name.substr(0, 3) == "no-" && OptionsByName[Name.substr(3)]) {
88 Aliases[OptionsByName[Name.substr(3)]].push_back(R);
91 if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {
92 Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);
97 Record *Group = nullptr;
98 if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
99 Group = SkipFlattened(G->getDef());
100 OptionsInGroup[Group].push_back(R);
103 auto CompareByName = [](Record *A, Record *B) {
104 return A->getValueAsString("Name") < B->getValueAsString("Name");
107 auto CompareByLocation = [](Record *A, Record *B) {
108 return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
111 auto DocumentationForOption = [&](Record *R) -> DocumentedOption {
112 auto &A = Aliases[R];
113 llvm::sort(A, CompareByName);
114 return {R, std::move(A)};
117 std::function<Documentation(Record *)> DocumentationForGroup =
118 [&](Record *R) -> Documentation {
121 auto &Groups = GroupsInGroup[R];
122 llvm::sort(Groups, CompareByLocation);
123 for (Record *G : Groups) {
124 D.Groups.emplace_back();
125 D.Groups.back().Group = G;
126 Documentation &Base = D.Groups.back();
127 Base = DocumentationForGroup(G);
130 auto &Options = OptionsInGroup[R];
131 llvm::sort(Options, CompareByName);
132 for (Record *O : Options)
133 D.Options.push_back(DocumentationForOption(O));
138 return DocumentationForGroup(nullptr);
141 // Get the first and successive separators to use for an OptionKind.
142 std::pair<StringRef,StringRef> getSeparatorsForKind(const Record *OptionKind) {
143 return StringSwitch<std::pair<StringRef, StringRef>>(OptionKind->getName())
144 .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE",
145 "KIND_JOINED_AND_SEPARATE",
146 "KIND_REMAINING_ARGS_JOINED", {"", " "})
147 .Case("KIND_COMMAJOINED", {"", ","})
148 .Default({" ", " "});
151 const unsigned UnlimitedArgs = unsigned(-1);
153 // Get the number of arguments expected for an option, or -1 if any number of
154 // arguments are accepted.
155 unsigned getNumArgsForKind(Record *OptionKind, const Record *Option) {
156 return StringSwitch<unsigned>(OptionKind->getName())
157 .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE", "KIND_SEPARATE", 1)
158 .Cases("KIND_REMAINING_ARGS", "KIND_REMAINING_ARGS_JOINED",
159 "KIND_COMMAJOINED", UnlimitedArgs)
160 .Case("KIND_JOINED_AND_SEPARATE", 2)
161 .Case("KIND_MULTIARG", Option->getValueAsInt("NumArgs"))
165 bool hasFlag(const Record *OptionOrGroup, StringRef OptionFlag) {
166 for (const Record *Flag : OptionOrGroup->getValueAsListOfDefs("Flags"))
167 if (Flag->getName() == OptionFlag)
172 bool isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
173 // FIXME: Provide a flag to specify the set of exclusions.
174 for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
175 if (hasFlag(OptionOrGroup, Exclusion))
180 std::string escapeRST(StringRef Str) {
183 if (StringRef("`*|_[]\\").count(K))
190 StringRef getSphinxOptionID(StringRef OptionName) {
191 for (auto I = OptionName.begin(), E = OptionName.end(); I != E; ++I)
192 if (!isalnum(*I) && *I != '-')
193 return OptionName.substr(0, I - OptionName.begin());
197 bool canSphinxCopeWithOption(const Record *Option) {
198 // HACK: Work arond sphinx's inability to cope with punctuation-only options
199 // such as /? by suppressing them from the option list.
200 for (char C : Option->getValueAsString("Name"))
206 void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {
207 assert(Depth < 8 && "groups nested too deeply");
208 OS << Heading << '\n'
209 << std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";
212 /// Get the value of field \p Primary, if possible. If \p Primary does not
213 /// exist, get the value of \p Fallback and escape it for rST emission.
214 std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,
215 StringRef Fallback) {
216 for (auto Field : {Primary, Fallback}) {
217 if (auto *V = R->getValue(Field)) {
219 if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))
220 Value = SV->getValue();
221 else if (auto *CV = dyn_cast_or_null<CodeInit>(V->getValue()))
222 Value = CV->getValue();
224 return Field == Primary ? Value.str() : escapeRST(Value);
230 void emitOptionWithArgs(StringRef Prefix, const Record *Option,
231 ArrayRef<StringRef> Args, raw_ostream &OS) {
232 OS << Prefix << escapeRST(Option->getValueAsString("Name"));
234 std::pair<StringRef, StringRef> Separators =
235 getSeparatorsForKind(Option->getValueAsDef("Kind"));
237 StringRef Separator = Separators.first;
238 for (auto Arg : Args) {
239 OS << Separator << escapeRST(Arg);
240 Separator = Separators.second;
244 void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
245 // Find the arguments to list after the option.
246 unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
247 bool HasMetaVarName = !Option->isValueUnset("MetaVarName");
249 std::vector<std::string> Args;
251 Args.push_back(Option->getValueAsString("MetaVarName"));
252 else if (NumArgs == 1)
253 Args.push_back("<arg>");
255 // Fill up arguments if this option didn't provide a meta var name or it
256 // supports an unlimited number of arguments. We can't see how many arguments
257 // already are in a meta var name, so assume it has right number. This is
258 // needed for JoinedAndSeparate options so that there arent't too many
260 if (!HasMetaVarName || NumArgs == UnlimitedArgs) {
261 while (Args.size() < NumArgs) {
262 Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
263 // Use '--args <arg1> <arg2>...' if any number of args are allowed.
264 if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
265 Args.back() += "...";
271 emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);
273 auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
274 if (!AliasArgs.empty()) {
275 Record *Alias = Option->getValueAsDef("Alias");
276 OS << " (equivalent to ";
278 Alias->getValueAsListOfStrings("Prefixes").front(), Alias,
284 bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
285 for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
288 emitOptionName(Prefix, Option, OS);
294 template <typename Fn>
295 void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
299 for (auto *Alias : Option.Aliases)
300 if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
304 void emitOption(const DocumentedOption &Option, const Record *DocInfo,
306 if (isExcluded(Option.Option, DocInfo))
308 if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
309 Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
311 if (!canSphinxCopeWithOption(Option.Option))
314 // HACK: Emit a different program name with each option to work around
315 // sphinx's inability to cope with options that differ only by punctuation
316 // (eg -ObjC vs -ObjC++, -G vs -G=).
317 std::vector<std::string> SphinxOptionIDs;
318 forEachOptionName(Option, DocInfo, [&](const Record *Option) {
319 for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
320 SphinxOptionIDs.push_back(
321 getSphinxOptionID((Prefix + Option->getValueAsString("Name")).str()));
323 assert(!SphinxOptionIDs.empty() && "no flags for option");
324 static std::map<std::string, int> NextSuffix;
325 int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(
326 SphinxOptionIDs.begin(), SphinxOptionIDs.end(),
327 [&](const std::string &A, const std::string &B) {
328 return NextSuffix[A] < NextSuffix[B];
330 for (auto &S : SphinxOptionIDs)
331 NextSuffix[S] = SphinxWorkaroundSuffix + 1;
332 if (SphinxWorkaroundSuffix)
333 OS << ".. program:: " << DocInfo->getValueAsString("Program")
334 << SphinxWorkaroundSuffix << "\n";
336 // Emit the names of the option.
337 OS << ".. option:: ";
338 bool EmittedAny = false;
339 forEachOptionName(Option, DocInfo, [&](const Record *Option) {
340 EmittedAny = emitOptionNames(Option, OS, EmittedAny);
342 if (SphinxWorkaroundSuffix)
343 OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
346 // Emit the description, if we have one.
347 std::string Description =
348 getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
349 if (!Description.empty())
350 OS << Description << "\n\n";
353 void emitDocumentation(int Depth, const Documentation &Doc,
354 const Record *DocInfo, raw_ostream &OS);
356 void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
358 if (isExcluded(Group.Group, DocInfo))
362 getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
364 // Emit the description, if we have one.
365 std::string Description =
366 getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
367 if (!Description.empty())
368 OS << Description << "\n\n";
370 // Emit contained options and groups.
371 emitDocumentation(Depth + 1, Group, DocInfo, OS);
374 void emitDocumentation(int Depth, const Documentation &Doc,
375 const Record *DocInfo, raw_ostream &OS) {
376 for (auto &O : Doc.Options)
377 emitOption(O, DocInfo, OS);
378 for (auto &G : Doc.Groups)
379 emitGroup(Depth, G, DocInfo, OS);
385 void EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
386 using namespace docs;
388 const Record *DocInfo = Records.getDef("GlobalDocumentation");
390 PrintFatalError("The GlobalDocumentation top-level definition is missing, "
391 "no documentation will be generated.");
394 OS << DocInfo->getValueAsString("Intro") << "\n";
395 OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
397 emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
399 } // end namespace clang