1 //===- ClangOptionDocEmitter.cpp - Documentation for command line flags ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 // FIXME: Once this has stabilized, consider moving it to LLVM.
10 //===----------------------------------------------------------------------===//
12 #include "llvm/TableGen/Error.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/TableGen/TableGenBackend.h"
28 struct DocumentedOption {
30 std::vector<Record*> Aliases;
32 struct DocumentedGroup;
33 struct Documentation {
34 std::vector<DocumentedGroup> Groups;
35 std::vector<DocumentedOption> Options;
37 struct DocumentedGroup : Documentation {
41 // Reorganize the records into a suitable form for emitting documentation.
42 Documentation extractDocumentation(RecordKeeper &Records) {
45 // Build the tree of groups. The root in the tree is the fake option group
46 // (Record*)nullptr, which contains all top-level groups and options.
47 std::map<Record*, std::vector<Record*> > OptionsInGroup;
48 std::map<Record*, std::vector<Record*> > GroupsInGroup;
49 std::map<Record*, std::vector<Record*> > Aliases;
51 std::map<std::string, Record*> OptionsByName;
52 for (Record *R : Records.getAllDerivedDefinitions("Option"))
53 OptionsByName[R->getValueAsString("Name")] = R;
55 auto Flatten = [](Record *R) {
56 return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
59 auto SkipFlattened = [&](Record *R) -> Record* {
60 while (R && Flatten(R)) {
61 auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));
69 for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
73 Record *Group = nullptr;
74 if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
75 Group = SkipFlattened(G->getDef());
76 GroupsInGroup[Group].push_back(R);
79 for (Record *R : Records.getAllDerivedDefinitions("Option")) {
80 if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {
81 Aliases[A->getDef()].push_back(R);
85 // Pretend no-X and Xno-Y options are aliases of X and XY.
86 auto Name = R->getValueAsString("Name");
87 if (Name.size() >= 4) {
88 if (Name.substr(0, 3) == "no-" && OptionsByName[Name.substr(3)]) {
89 Aliases[OptionsByName[Name.substr(3)]].push_back(R);
92 if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {
93 Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);
98 Record *Group = nullptr;
99 if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))
100 Group = SkipFlattened(G->getDef());
101 OptionsInGroup[Group].push_back(R);
104 auto CompareByName = [](Record *A, Record *B) {
105 return A->getValueAsString("Name") < B->getValueAsString("Name");
108 auto CompareByLocation = [](Record *A, Record *B) {
109 return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
112 auto DocumentationForOption = [&](Record *R) -> DocumentedOption {
113 auto &A = Aliases[R];
114 std::sort(A.begin(), A.end(), CompareByName);
115 return {R, std::move(A)};
118 std::function<Documentation(Record *)> DocumentationForGroup =
119 [&](Record *R) -> Documentation {
122 auto &Groups = GroupsInGroup[R];
123 std::sort(Groups.begin(), Groups.end(), CompareByLocation);
124 for (Record *G : Groups) {
125 D.Groups.emplace_back();
126 D.Groups.back().Group = G;
127 Documentation &Base = D.Groups.back();
128 Base = DocumentationForGroup(G);
131 auto &Options = OptionsInGroup[R];
132 std::sort(Options.begin(), Options.end(), CompareByName);
133 for (Record *O : Options)
134 D.Options.push_back(DocumentationForOption(O));
139 return DocumentationForGroup(nullptr);
142 // Get the first and successive separators to use for an OptionKind.
143 std::pair<StringRef,StringRef> getSeparatorsForKind(const Record *OptionKind) {
144 return StringSwitch<std::pair<StringRef, StringRef>>(OptionKind->getName())
145 .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE",
146 "KIND_JOINED_AND_SEPARATE",
147 "KIND_REMAINING_ARGS_JOINED", {"", " "})
148 .Case("KIND_COMMAJOINED", {"", ","})
149 .Default({" ", " "});
152 const unsigned UnlimitedArgs = unsigned(-1);
154 // Get the number of arguments expected for an option, or -1 if any number of
155 // arguments are accepted.
156 unsigned getNumArgsForKind(Record *OptionKind, const Record *Option) {
157 return StringSwitch<unsigned>(OptionKind->getName())
158 .Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE", "KIND_SEPARATE", 1)
159 .Cases("KIND_REMAINING_ARGS", "KIND_REMAINING_ARGS_JOINED",
160 "KIND_COMMAJOINED", UnlimitedArgs)
161 .Case("KIND_JOINED_AND_SEPARATE", 2)
162 .Case("KIND_MULTIARG", Option->getValueAsInt("NumArgs"))
166 bool hasFlag(const Record *OptionOrGroup, StringRef OptionFlag) {
167 for (const Record *Flag : OptionOrGroup->getValueAsListOfDefs("Flags"))
168 if (Flag->getName() == OptionFlag)
173 bool isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
174 // FIXME: Provide a flag to specify the set of exclusions.
175 for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
176 if (hasFlag(OptionOrGroup, Exclusion))
181 std::string escapeRST(StringRef Str) {
184 if (StringRef("`*|_[]\\").count(K))
191 StringRef getSphinxOptionID(StringRef OptionName) {
192 for (auto I = OptionName.begin(), E = OptionName.end(); I != E; ++I)
193 if (!isalnum(*I) && *I != '-')
194 return OptionName.substr(0, I - OptionName.begin());
198 bool canSphinxCopeWithOption(const Record *Option) {
199 // HACK: Work arond sphinx's inability to cope with punctuation-only options
200 // such as /? by suppressing them from the option list.
201 for (char C : Option->getValueAsString("Name"))
207 void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {
208 assert(Depth < 8 && "groups nested too deeply");
209 OS << Heading << '\n'
210 << std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";
213 /// Get the value of field \p Primary, if possible. If \p Primary does not
214 /// exist, get the value of \p Fallback and escape it for rST emission.
215 std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,
216 StringRef Fallback) {
217 for (auto Field : {Primary, Fallback}) {
218 if (auto *V = R->getValue(Field)) {
220 if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))
221 Value = SV->getValue();
222 else if (auto *CV = dyn_cast_or_null<CodeInit>(V->getValue()))
223 Value = CV->getValue();
225 return Field == Primary ? Value.str() : escapeRST(Value);
231 void emitOptionWithArgs(StringRef Prefix, const Record *Option,
232 ArrayRef<std::string> Args, raw_ostream &OS) {
233 OS << Prefix << escapeRST(Option->getValueAsString("Name"));
235 std::pair<StringRef, StringRef> Separators =
236 getSeparatorsForKind(Option->getValueAsDef("Kind"));
238 StringRef Separator = Separators.first;
239 for (auto Arg : Args) {
240 OS << Separator << escapeRST(Arg);
241 Separator = Separators.second;
245 void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
246 // Find the arguments to list after the option.
247 unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
249 std::vector<std::string> Args;
250 if (!Option->isValueUnset("MetaVarName"))
251 Args.push_back(Option->getValueAsString("MetaVarName"));
252 else if (NumArgs == 1)
253 Args.push_back("<arg>");
255 while (Args.size() < NumArgs) {
256 Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
257 // Use '--args <arg1> <arg2>...' if any number of args are allowed.
258 if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
259 Args.back() += "...";
264 emitOptionWithArgs(Prefix, Option, Args, OS);
266 auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
267 if (!AliasArgs.empty()) {
268 Record *Alias = Option->getValueAsDef("Alias");
269 OS << " (equivalent to ";
270 emitOptionWithArgs(Alias->getValueAsListOfStrings("Prefixes").front(),
271 Alias, Option->getValueAsListOfStrings("AliasArgs"), OS);
276 bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {
277 for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
280 emitOptionName(Prefix, Option, OS);
286 template <typename Fn>
287 void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,
291 for (auto *Alias : Option.Aliases)
292 if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
296 void emitOption(const DocumentedOption &Option, const Record *DocInfo,
298 if (isExcluded(Option.Option, DocInfo))
300 if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
301 Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
303 if (!canSphinxCopeWithOption(Option.Option))
306 // HACK: Emit a different program name with each option to work around
307 // sphinx's inability to cope with options that differ only by punctuation
308 // (eg -ObjC vs -ObjC++, -G vs -G=).
309 std::vector<std::string> SphinxOptionIDs;
310 forEachOptionName(Option, DocInfo, [&](const Record *Option) {
311 for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
312 SphinxOptionIDs.push_back(
313 getSphinxOptionID(Prefix + Option->getValueAsString("Name")));
315 assert(!SphinxOptionIDs.empty() && "no flags for option");
316 static std::map<std::string, int> NextSuffix;
317 int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(
318 SphinxOptionIDs.begin(), SphinxOptionIDs.end(),
319 [&](const std::string &A, const std::string &B) {
320 return NextSuffix[A] < NextSuffix[B];
322 for (auto &S : SphinxOptionIDs)
323 NextSuffix[S] = SphinxWorkaroundSuffix + 1;
324 if (SphinxWorkaroundSuffix)
325 OS << ".. program:: " << DocInfo->getValueAsString("Program")
326 << SphinxWorkaroundSuffix << "\n";
328 // Emit the names of the option.
329 OS << ".. option:: ";
330 bool EmittedAny = false;
331 forEachOptionName(Option, DocInfo, [&](const Record *Option) {
332 EmittedAny = emitOptionNames(Option, OS, EmittedAny);
334 if (SphinxWorkaroundSuffix)
335 OS << "\n.. program:: " << DocInfo->getValueAsString("Program");
338 // Emit the description, if we have one.
339 std::string Description =
340 getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
341 if (!Description.empty())
342 OS << Description << "\n\n";
345 void emitDocumentation(int Depth, const Documentation &Doc,
346 const Record *DocInfo, raw_ostream &OS);
348 void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
350 if (isExcluded(Group.Group, DocInfo))
354 getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
356 // Emit the description, if we have one.
357 std::string Description =
358 getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
359 if (!Description.empty())
360 OS << Description << "\n\n";
362 // Emit contained options and groups.
363 emitDocumentation(Depth + 1, Group, DocInfo, OS);
366 void emitDocumentation(int Depth, const Documentation &Doc,
367 const Record *DocInfo, raw_ostream &OS) {
368 for (auto &O : Doc.Options)
369 emitOption(O, DocInfo, OS);
370 for (auto &G : Doc.Groups)
371 emitGroup(Depth, G, DocInfo, OS);
377 void EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
378 using namespace docs;
380 const Record *DocInfo = Records.getDef("GlobalDocumentation");
382 PrintFatalError("The GlobalDocumentation top-level definition is missing, "
383 "no documentation will be generated.");
386 OS << DocInfo->getValueAsString("Intro") << "\n";
387 OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
389 emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
391 } // end namespace clang