1 //===- ClangOptionDocEmitter.cpp - Documentation for command line flags ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // FIXME: Once this has stabilized, consider moving it to LLVM.
9 //
10 //===----------------------------------------------------------------------===//
11 
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"
19 #include <cctype>
20 #include <cstring>
21 #include <map>
22 
23 using namespace llvm;
24 
25 namespace clang {
26 namespace docs {
27 namespace {
28 struct DocumentedOption {
29   Record *Option;
30   std::vector<Record*> Aliases;
31 };
32 struct DocumentedGroup;
33 struct Documentation {
34   std::vector<DocumentedGroup> Groups;
35   std::vector<DocumentedOption> Options;
36 };
37 struct DocumentedGroup : Documentation {
38   Record *Group;
39 };
40 
41 // Reorganize the records into a suitable form for emitting documentation.
42 Documentation extractDocumentation(RecordKeeper &Records) {
43   Documentation Result;
44 
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;
50 
51   std::map<std::string, Record*> OptionsByName;
52   for (Record *R : Records.getAllDerivedDefinitions("Option"))
53     OptionsByName[R->getValueAsString("Name")] = R;
54 
55   auto Flatten = [](Record *R) {
56     return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
57   };
58 
59   auto SkipFlattened = [&](Record *R) -> Record* {
60     while (R && Flatten(R)) {
61       auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));
62       if (!G)
63         return nullptr;
64       R = G->getDef();
65     }
66     return R;
67   };
68 
69   for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
70     if (Flatten(R))
71       continue;
72 
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);
77   }
78 
79   for (Record *R : Records.getAllDerivedDefinitions("Option")) {
80     if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {
81       Aliases[A->getDef()].push_back(R);
82       continue;
83     }
84 
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);
90         continue;
91       }
92       if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {
93         Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);
94         continue;
95       }
96     }
97 
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);
102   }
103 
104   auto CompareByName = [](Record *A, Record *B) {
105     return A->getValueAsString("Name") < B->getValueAsString("Name");
106   };
107 
108   auto CompareByLocation = [](Record *A, Record *B) {
109     return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
110   };
111 
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)};
116   };
117 
118   std::function<Documentation(Record *)> DocumentationForGroup =
119       [&](Record *R) -> Documentation {
120     Documentation D;
121 
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);
129     }
130 
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));
135 
136     return D;
137   };
138 
139   return DocumentationForGroup(nullptr);
140 }
141 
142 // Get the first and successive separators to use for an OptionKind.
143 std::pair<StringRef,StringRef> getSeparatorsForKind(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({" ", " "});
150 }
151 
152 const unsigned UnlimitedArgs = unsigned(-1);
153 
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, 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"))
163     .Default(0);
164 }
165 
166 bool hasFlag(const Record *OptionOrGroup, StringRef OptionFlag) {
167   for (const Record *Flag : OptionOrGroup->getValueAsListOfDefs("Flags"))
168     if (Flag->getName() == OptionFlag)
169       return true;
170   return false;
171 }
172 
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))
177       return true;
178   return false;
179 }
180 
181 std::string escapeRST(StringRef Str) {
182   std::string Out;
183   for (auto K : Str) {
184     if (StringRef("`*|_[]\\").count(K))
185       Out.push_back('\\');
186     Out.push_back(K);
187   }
188   return Out;
189 }
190 
191 bool canSphinxCopeWithOption(const Record *Option) {
192   // HACK: Work arond sphinx's inability to cope with punctuation-only options
193   // such as /? by suppressing them from the option list.
194   for (char C : Option->getValueAsString("Name"))
195     if (isalnum(C))
196       return true;
197   return false;
198 }
199 
200 void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {
201   assert(Depth < 8 && "groups nested too deeply");
202   OS << Heading << '\n'
203      << std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";
204 }
205 
206 /// Get the value of field \p Primary, if possible. If \p Primary does not
207 /// exist, get the value of \p Fallback and escape it for rST emission.
208 std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,
209                                          StringRef Fallback) {
210   for (auto Field : {Primary, Fallback}) {
211     if (auto *V = R->getValue(Field)) {
212       StringRef Value;
213       if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))
214         Value = SV->getValue();
215       else if (auto *CV = dyn_cast_or_null<CodeInit>(V->getValue()))
216         Value = CV->getValue();
217       if (!Value.empty())
218         return Field == Primary ? Value.str() : escapeRST(Value);
219     }
220   }
221   return StringRef();
222 }
223 
224 void emitOptionWithArgs(StringRef Prefix, Record *Option,
225                                ArrayRef<std::string> Args, raw_ostream &OS) {
226   OS << Prefix << escapeRST(Option->getValueAsString("Name"));
227 
228   std::pair<StringRef, StringRef> Separators =
229       getSeparatorsForKind(Option->getValueAsDef("Kind"));
230 
231   StringRef Separator = Separators.first;
232   for (auto Arg : Args) {
233     OS << Separator << escapeRST(Arg);
234     Separator = Separators.second;
235   }
236 }
237 
238 void emitOptionName(StringRef Prefix, Record *Option, raw_ostream &OS) {
239   // Find the arguments to list after the option.
240   unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
241 
242   std::vector<std::string> Args;
243   if (!Option->isValueUnset("MetaVarName"))
244     Args.push_back(Option->getValueAsString("MetaVarName"));
245   else if (NumArgs == 1)
246     Args.push_back("<arg>");
247 
248   while (Args.size() < NumArgs) {
249     Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());
250     // Use '--args <arg1> <arg2>...' if any number of args are allowed.
251     if (Args.size() == 2 && NumArgs == UnlimitedArgs) {
252       Args.back() += "...";
253       break;
254     }
255   }
256 
257   emitOptionWithArgs(Prefix, Option, Args, OS);
258 
259   auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");
260   if (!AliasArgs.empty()) {
261     Record *Alias = Option->getValueAsDef("Alias");
262     OS << " (equivalent to ";
263     emitOptionWithArgs(Alias->getValueAsListOfStrings("Prefixes").front(),
264                        Alias, Option->getValueAsListOfStrings("AliasArgs"), OS);
265     OS << ")";
266   }
267 }
268 
269 bool emitOptionNames(Record *Option, raw_ostream &OS, bool EmittedAny) {
270   for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {
271     if (EmittedAny)
272       OS << ", ";
273     emitOptionName(Prefix, Option, OS);
274     EmittedAny = true;
275   }
276   return EmittedAny;
277 }
278 
279 void emitOption(const DocumentedOption &Option, const Record *DocInfo,
280                 raw_ostream &OS) {
281   if (isExcluded(Option.Option, DocInfo))
282     return;
283   if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
284       Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
285     return;
286   if (!canSphinxCopeWithOption(Option.Option))
287     return;
288 
289   // HACK: Emit a different program name with each option to work around
290   // sphinx's inability to cope with options that differ only by punctuation
291   // (eg -ObjC vs -ObjC++, -G vs -G=).
292   static int Emitted = 0;
293   OS << ".. program:: " << DocInfo->getValueAsString("Program") << Emitted++
294      << "\n";
295 
296   // Emit the names of the option.
297   OS << ".. option:: ";
298   bool EmittedAny = emitOptionNames(Option.Option, OS, false);
299   for (auto *Alias : Option.Aliases)
300     if (!isExcluded(Alias, DocInfo) && canSphinxCopeWithOption(Option.Option))
301       EmittedAny = emitOptionNames(Alias, OS, EmittedAny);
302   assert(EmittedAny && "no flags for option");
303   OS << "\n\n";
304 
305   // Emit the description, if we have one.
306   std::string Description =
307       getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
308   if (!Description.empty())
309     OS << Description << "\n\n";
310 }
311 
312 void emitDocumentation(int Depth, const Documentation &Doc,
313                        const Record *DocInfo, raw_ostream &OS);
314 
315 void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,
316                raw_ostream &OS) {
317   if (isExcluded(Group.Group, DocInfo))
318     return;
319 
320   emitHeading(Depth,
321               getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);
322 
323   // Emit the description, if we have one.
324   std::string Description =
325       getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");
326   if (!Description.empty())
327     OS << Description << "\n\n";
328 
329   // Emit contained options and groups.
330   emitDocumentation(Depth + 1, Group, DocInfo, OS);
331 }
332 
333 void emitDocumentation(int Depth, const Documentation &Doc,
334                        const Record *DocInfo, raw_ostream &OS) {
335   for (auto &O : Doc.Options)
336     emitOption(O, DocInfo, OS);
337   for (auto &G : Doc.Groups)
338     emitGroup(Depth, G, DocInfo, OS);
339 }
340 
341 }  // namespace
342 }  // namespace docs
343 
344 void EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {
345   using namespace docs;
346 
347   const Record *DocInfo = Records.getDef("GlobalDocumentation");
348   if (!DocInfo) {
349     PrintFatalError("The GlobalDocumentation top-level definition is missing, "
350                     "no documentation will be generated.");
351     return;
352   }
353   OS << DocInfo->getValueAsString("Intro") << "\n";
354   OS << ".. program:: " << DocInfo->getValueAsString("Program") << "\n";
355 
356   emitDocumentation(0, extractDocumentation(Records), DocInfo, OS);
357 }
358 } // end namespace clang
359