]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/utils/TableGen/ClangOptionDocEmitter.cpp
MFV r353143 (phillip):
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / utils / TableGen / ClangOptionDocEmitter.cpp
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
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
22 using namespace llvm;
23
24 namespace clang {
25 namespace docs {
26 namespace {
27 struct DocumentedOption {
28   Record *Option;
29   std::vector<Record*> Aliases;
30 };
31 struct DocumentedGroup;
32 struct Documentation {
33   std::vector<DocumentedGroup> Groups;
34   std::vector<DocumentedOption> Options;
35 };
36 struct DocumentedGroup : Documentation {
37   Record *Group;
38 };
39
40 // Reorganize the records into a suitable form for emitting documentation.
41 Documentation extractDocumentation(RecordKeeper &Records) {
42   Documentation Result;
43
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;
49
50   std::map<std::string, Record*> OptionsByName;
51   for (Record *R : Records.getAllDerivedDefinitions("Option"))
52     OptionsByName[R->getValueAsString("Name")] = R;
53
54   auto Flatten = [](Record *R) {
55     return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
56   };
57
58   auto SkipFlattened = [&](Record *R) -> Record* {
59     while (R && Flatten(R)) {
60       auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));
61       if (!G)
62         return nullptr;
63       R = G->getDef();
64     }
65     return R;
66   };
67
68   for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
69     if (Flatten(R))
70       continue;
71
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);
76   }
77
78   for (Record *R : Records.getAllDerivedDefinitions("Option")) {
79     if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {
80       Aliases[A->getDef()].push_back(R);
81       continue;
82     }
83
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);
89         continue;
90       }
91       if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {
92         Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);
93         continue;
94       }
95     }
96
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);
101   }
102
103   auto CompareByName = [](Record *A, Record *B) {
104     return A->getValueAsString("Name") < B->getValueAsString("Name");
105   };
106
107   auto CompareByLocation = [](Record *A, Record *B) {
108     return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
109   };
110
111   auto DocumentationForOption = [&](Record *R) -> DocumentedOption {
112     auto &A = Aliases[R];
113     llvm::sort(A, CompareByName);
114     return {R, std::move(A)};
115   };
116
117   std::function<Documentation(Record *)> DocumentationForGroup =
118       [&](Record *R) -> Documentation {
119     Documentation D;
120
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);
128     }
129
130     auto &Options = OptionsInGroup[R];
131     llvm::sort(Options, CompareByName);
132     for (Record *O : Options)
133       D.Options.push_back(DocumentationForOption(O));
134
135     return D;
136   };
137
138   return DocumentationForGroup(nullptr);
139 }
140
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({" ", " "});
149 }
150
151 const unsigned UnlimitedArgs = unsigned(-1);
152
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"))
162     .Default(0);
163 }
164
165 bool hasFlag(const Record *OptionOrGroup, StringRef OptionFlag) {
166   for (const Record *Flag : OptionOrGroup->getValueAsListOfDefs("Flags"))
167     if (Flag->getName() == OptionFlag)
168       return true;
169   return false;
170 }
171
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))
176       return true;
177   return false;
178 }
179
180 std::string escapeRST(StringRef Str) {
181   std::string Out;
182   for (auto K : Str) {
183     if (StringRef("`*|_[]\\").count(K))
184       Out.push_back('\\');
185     Out.push_back(K);
186   }
187   return Out;
188 }
189
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());
194   return OptionName;
195 }
196
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"))
201     if (isalnum(C))
202       return true;
203   return false;
204 }
205
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";
210 }
211
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)) {
218       StringRef Value;
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();
223       if (!Value.empty())
224         return Field == Primary ? Value.str() : escapeRST(Value);
225     }
226   }
227   return StringRef();
228 }
229
230 void emitOptionWithArgs(StringRef Prefix, const Record *Option,
231                         ArrayRef<StringRef> Args, raw_ostream &OS) {
232   OS << Prefix << escapeRST(Option->getValueAsString("Name"));
233
234   std::pair<StringRef, StringRef> Separators =
235       getSeparatorsForKind(Option->getValueAsDef("Kind"));
236
237   StringRef Separator = Separators.first;
238   for (auto Arg : Args) {
239     OS << Separator << escapeRST(Arg);
240     Separator = Separators.second;
241   }
242 }
243
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");
248
249   std::vector<std::string> Args;
250   if (HasMetaVarName)
251     Args.push_back(Option->getValueAsString("MetaVarName"));
252   else if (NumArgs == 1)
253     Args.push_back("<arg>");
254
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
259   // arguments.
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() += "...";
266         break;
267       }
268     }
269   }
270
271   emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);
272
273   auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
274   if (!AliasArgs.empty()) {
275     Record *Alias = Option->getValueAsDef("Alias");
276     OS << " (equivalent to ";
277     emitOptionWithArgs(
278         Alias->getValueAsListOfStrings("Prefixes").front(), Alias,
279         AliasArgs, OS);
280     OS << ")";
281   }
282 }
283
284 bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
285   for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
286     if (EmittedAny)
287       OS << ", ";
288     emitOptionName(Prefix, Option, OS);
289     EmittedAny = true;
290   }
291   return EmittedAny;
292 }
293
294 template <typename Fn>
295 void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
296                        Fn F) {
297   F(Option.Option);
298
299   for (auto *Alias : Option.Aliases)
300     if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
301       F(Alias);
302 }
303
304 void emitOption(const DocumentedOption &Option, const Record *DocInfo,
305                 raw_ostream &OS) {
306   if (isExcluded(Option.Option, DocInfo))
307     return;
308   if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
309       Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
310     return;
311   if (!canSphinxCopeWithOption(Option.Option))
312     return;
313
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()));
322   });
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];
329       })];
330   for (auto &S : SphinxOptionIDs)
331     NextSuffix[S] = SphinxWorkaroundSuffix + 1;
332   if (SphinxWorkaroundSuffix)
333     OS << ".. program:: " << DocInfo->getValueAsString("Program")
334        << SphinxWorkaroundSuffix << "\n";
335
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);
341   });
342   if (SphinxWorkaroundSuffix)
343     OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
344   OS << "\n\n";
345
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";
351 }
352
353 void emitDocumentation(int Depth, const Documentation &Doc,
354                        const Record *DocInfo, raw_ostream &OS);
355
356 void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
357                raw_ostream &OS) {
358   if (isExcluded(Group.Group, DocInfo))
359     return;
360
361   emitHeading(Depth,
362               getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
363
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";
369
370   // Emit contained options and groups.
371   emitDocumentation(Depth + 1, Group, DocInfo, OS);
372 }
373
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);
380 }
381
382 }  // namespace
383 }  // namespace docs
384
385 void EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
386   using namespace docs;
387
388   const Record *DocInfo = Records.getDef("GlobalDocumentation");
389   if (!DocInfo) {
390     PrintFatalError("The GlobalDocumentation top-level definition is missing, "
391                     "no documentation will be generated.");
392     return;
393   }
394   OS << DocInfo->getValueAsString("Intro") << "\n";
395   OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
396
397   emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
398 }
399 } // end namespace clang