Path: blob/main/contrib/llvm-project/clang/utils/TableGen/ClangOptionDocEmitter.cpp
35230 views
//===- ClangOptionDocEmitter.cpp - Documentation for command line flags ---===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6// FIXME: Once this has stabilized, consider moving it to LLVM.7//8//===----------------------------------------------------------------------===//910#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>2122using namespace llvm;2324namespace {25struct DocumentedOption {26Record *Option;27std::vector<Record*> Aliases;28};29struct DocumentedGroup;30struct Documentation {31std::vector<DocumentedGroup> Groups;32std::vector<DocumentedOption> Options;3334bool empty() {35return Groups.empty() && Options.empty();36}37};38struct DocumentedGroup : Documentation {39Record *Group;40};4142static bool hasFlag(const Record *Option, StringRef OptionFlag,43StringRef FlagsField) {44for (const Record *Flag : Option->getValueAsListOfDefs(FlagsField))45if (Flag->getName() == OptionFlag)46return true;47if (const DefInit *DI = dyn_cast<DefInit>(Option->getValueInit("Group")))48for (const Record *Flag : DI->getDef()->getValueAsListOfDefs(FlagsField))49if (Flag->getName() == OptionFlag)50return true;51return false;52}5354static bool isOptionVisible(const Record *Option, const Record *DocInfo) {55for (StringRef IgnoredFlag : DocInfo->getValueAsListOfStrings("IgnoreFlags"))56if (hasFlag(Option, IgnoredFlag, "Flags"))57return false;58for (StringRef Mask : DocInfo->getValueAsListOfStrings("VisibilityMask"))59if (hasFlag(Option, Mask, "Visibility"))60return true;61return false;62}6364// Reorganize the records into a suitable form for emitting documentation.65Documentation extractDocumentation(RecordKeeper &Records,66const Record *DocInfo) {67Documentation Result;6869// Build the tree of groups. The root in the tree is the fake option group70// (Record*)nullptr, which contains all top-level groups and options.71std::map<Record*, std::vector<Record*> > OptionsInGroup;72std::map<Record*, std::vector<Record*> > GroupsInGroup;73std::map<Record*, std::vector<Record*> > Aliases;7475std::map<std::string, Record*> OptionsByName;76for (Record *R : Records.getAllDerivedDefinitions("Option"))77OptionsByName[std::string(R->getValueAsString("Name"))] = R;7879auto Flatten = [](Record *R) {80return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");81};8283auto SkipFlattened = [&](Record *R) -> Record* {84while (R && Flatten(R)) {85auto *G = dyn_cast<DefInit>(R->getValueInit("Group"));86if (!G)87return nullptr;88R = G->getDef();89}90return R;91};9293for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {94if (Flatten(R))95continue;9697Record *Group = nullptr;98if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))99Group = SkipFlattened(G->getDef());100GroupsInGroup[Group].push_back(R);101}102103for (Record *R : Records.getAllDerivedDefinitions("Option")) {104if (auto *A = dyn_cast<DefInit>(R->getValueInit("Alias"))) {105Aliases[A->getDef()].push_back(R);106continue;107}108109// Pretend no-X and Xno-Y options are aliases of X and XY.110std::string Name = std::string(R->getValueAsString("Name"));111if (Name.size() >= 4) {112if (Name.substr(0, 3) == "no-" && OptionsByName[Name.substr(3)]) {113Aliases[OptionsByName[Name.substr(3)]].push_back(R);114continue;115}116if (Name.substr(1, 3) == "no-" && OptionsByName[Name[0] + Name.substr(4)]) {117Aliases[OptionsByName[Name[0] + Name.substr(4)]].push_back(R);118continue;119}120}121122Record *Group = nullptr;123if (auto *G = dyn_cast<DefInit>(R->getValueInit("Group")))124Group = SkipFlattened(G->getDef());125OptionsInGroup[Group].push_back(R);126}127128auto CompareByName = [](Record *A, Record *B) {129return A->getValueAsString("Name") < B->getValueAsString("Name");130};131132auto CompareByLocation = [](Record *A, Record *B) {133return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();134};135136auto DocumentationForOption = [&](Record *R) -> DocumentedOption {137auto &A = Aliases[R];138llvm::sort(A, CompareByName);139return {R, std::move(A)};140};141142std::function<Documentation(Record *)> DocumentationForGroup =143[&](Record *R) -> Documentation {144Documentation D;145146auto &Groups = GroupsInGroup[R];147llvm::sort(Groups, CompareByLocation);148for (Record *G : Groups) {149D.Groups.emplace_back();150D.Groups.back().Group = G;151Documentation &Base = D.Groups.back();152Base = DocumentationForGroup(G);153if (Base.empty())154D.Groups.pop_back();155}156157auto &Options = OptionsInGroup[R];158llvm::sort(Options, CompareByName);159for (Record *O : Options)160if (isOptionVisible(O, DocInfo))161D.Options.push_back(DocumentationForOption(O));162163return D;164};165166return DocumentationForGroup(nullptr);167}168169// Get the first and successive separators to use for an OptionKind.170std::pair<StringRef,StringRef> getSeparatorsForKind(const Record *OptionKind) {171return StringSwitch<std::pair<StringRef, StringRef>>(OptionKind->getName())172.Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE",173"KIND_JOINED_AND_SEPARATE",174"KIND_REMAINING_ARGS_JOINED", {"", " "})175.Case("KIND_COMMAJOINED", {"", ","})176.Default({" ", " "});177}178179const unsigned UnlimitedArgs = unsigned(-1);180181// Get the number of arguments expected for an option, or -1 if any number of182// arguments are accepted.183unsigned getNumArgsForKind(Record *OptionKind, const Record *Option) {184return StringSwitch<unsigned>(OptionKind->getName())185.Cases("KIND_JOINED", "KIND_JOINED_OR_SEPARATE", "KIND_SEPARATE", 1)186.Cases("KIND_REMAINING_ARGS", "KIND_REMAINING_ARGS_JOINED",187"KIND_COMMAJOINED", UnlimitedArgs)188.Case("KIND_JOINED_AND_SEPARATE", 2)189.Case("KIND_MULTIARG", Option->getValueAsInt("NumArgs"))190.Default(0);191}192193std::string escapeRST(StringRef Str) {194std::string Out;195for (auto K : Str) {196if (StringRef("`*|[]\\").count(K))197Out.push_back('\\');198Out.push_back(K);199}200return Out;201}202203StringRef getSphinxOptionID(StringRef OptionName) {204for (auto I = OptionName.begin(), E = OptionName.end(); I != E; ++I)205if (!isalnum(*I) && *I != '-')206return OptionName.substr(0, I - OptionName.begin());207return OptionName;208}209210bool canSphinxCopeWithOption(const Record *Option) {211// HACK: Work arond sphinx's inability to cope with punctuation-only options212// such as /? by suppressing them from the option list.213for (char C : Option->getValueAsString("Name"))214if (isalnum(C))215return true;216return false;217}218219void emitHeading(int Depth, std::string Heading, raw_ostream &OS) {220assert(Depth < 8 && "groups nested too deeply");221OS << Heading << '\n'222<< std::string(Heading.size(), "=~-_'+<>"[Depth]) << "\n";223}224225/// Get the value of field \p Primary, if possible. If \p Primary does not226/// exist, get the value of \p Fallback and escape it for rST emission.227std::string getRSTStringWithTextFallback(const Record *R, StringRef Primary,228StringRef Fallback) {229for (auto Field : {Primary, Fallback}) {230if (auto *V = R->getValue(Field)) {231StringRef Value;232if (auto *SV = dyn_cast_or_null<StringInit>(V->getValue()))233Value = SV->getValue();234if (!Value.empty())235return Field == Primary ? Value.str() : escapeRST(Value);236}237}238return std::string(StringRef());239}240241void emitOptionWithArgs(StringRef Prefix, const Record *Option,242ArrayRef<StringRef> Args, raw_ostream &OS) {243OS << Prefix << escapeRST(Option->getValueAsString("Name"));244245std::pair<StringRef, StringRef> Separators =246getSeparatorsForKind(Option->getValueAsDef("Kind"));247248StringRef Separator = Separators.first;249for (auto Arg : Args) {250OS << Separator << escapeRST(Arg);251Separator = Separators.second;252}253}254255constexpr StringLiteral DefaultMetaVarName = "<arg>";256257void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {258// Find the arguments to list after the option.259unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);260bool HasMetaVarName = !Option->isValueUnset("MetaVarName");261262std::vector<std::string> Args;263if (HasMetaVarName)264Args.push_back(std::string(Option->getValueAsString("MetaVarName")));265else if (NumArgs == 1)266Args.push_back(DefaultMetaVarName.str());267268// Fill up arguments if this option didn't provide a meta var name or it269// supports an unlimited number of arguments. We can't see how many arguments270// already are in a meta var name, so assume it has right number. This is271// needed for JoinedAndSeparate options so that there arent't too many272// arguments.273if (!HasMetaVarName || NumArgs == UnlimitedArgs) {274while (Args.size() < NumArgs) {275Args.push_back(("<arg" + Twine(Args.size() + 1) + ">").str());276// Use '--args <arg1> <arg2>...' if any number of args are allowed.277if (Args.size() == 2 && NumArgs == UnlimitedArgs) {278Args.back() += "...";279break;280}281}282}283284emitOptionWithArgs(Prefix, Option, std::vector<StringRef>(Args.begin(), Args.end()), OS);285286auto AliasArgs = Option->getValueAsListOfStrings("AliasArgs");287if (!AliasArgs.empty()) {288Record *Alias = Option->getValueAsDef("Alias");289OS << " (equivalent to ";290emitOptionWithArgs(291Alias->getValueAsListOfStrings("Prefixes").front(), Alias,292AliasArgs, OS);293OS << ")";294}295}296297bool emitOptionNames(const Record *Option, raw_ostream &OS, bool EmittedAny) {298for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes")) {299if (EmittedAny)300OS << ", ";301emitOptionName(Prefix, Option, OS);302EmittedAny = true;303}304return EmittedAny;305}306307template <typename Fn>308void forEachOptionName(const DocumentedOption &Option, const Record *DocInfo,309Fn F) {310F(Option.Option);311312for (auto *Alias : Option.Aliases)313if (isOptionVisible(Alias, DocInfo) &&314canSphinxCopeWithOption(Option.Option))315F(Alias);316}317318void emitOption(const DocumentedOption &Option, const Record *DocInfo,319raw_ostream &OS) {320if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||321Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")322return;323if (!canSphinxCopeWithOption(Option.Option))324return;325326// HACK: Emit a different program name with each option to work around327// sphinx's inability to cope with options that differ only by punctuation328// (eg -ObjC vs -ObjC++, -G vs -G=).329std::vector<std::string> SphinxOptionIDs;330forEachOptionName(Option, DocInfo, [&](const Record *Option) {331for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))332SphinxOptionIDs.push_back(std::string(getSphinxOptionID(333(Prefix + Option->getValueAsString("Name")).str())));334});335assert(!SphinxOptionIDs.empty() && "no flags for option");336static std::map<std::string, int> NextSuffix;337int SphinxWorkaroundSuffix = NextSuffix[*std::max_element(338SphinxOptionIDs.begin(), SphinxOptionIDs.end(),339[&](const std::string &A, const std::string &B) {340return NextSuffix[A] < NextSuffix[B];341})];342for (auto &S : SphinxOptionIDs)343NextSuffix[S] = SphinxWorkaroundSuffix + 1;344345std::string Program = DocInfo->getValueAsString("Program").lower();346if (SphinxWorkaroundSuffix)347OS << ".. program:: " << Program << SphinxWorkaroundSuffix << "\n";348349// Emit the names of the option.350OS << ".. option:: ";351bool EmittedAny = false;352forEachOptionName(Option, DocInfo, [&](const Record *Option) {353EmittedAny = emitOptionNames(Option, OS, EmittedAny);354});355if (SphinxWorkaroundSuffix)356OS << "\n.. program:: " << Program;357OS << "\n\n";358359// Emit the description, if we have one.360const Record *R = Option.Option;361std::string Description;362363// Prefer a program specific help string.364// This is a list of (visibilities, string) pairs.365std::vector<Record *> VisibilitiesHelp =366R->getValueAsListOfDefs("HelpTextsForVariants");367for (Record *VisibilityHelp : VisibilitiesHelp) {368// This is a list of visibilities.369ArrayRef<Init *> Visibilities =370VisibilityHelp->getValueAsListInit("Visibilities")->getValues();371372// See if any of the program's visibilities are in the list.373for (StringRef DocInfoMask :374DocInfo->getValueAsListOfStrings("VisibilityMask")) {375for (Init *Visibility : Visibilities) {376if (Visibility->getAsUnquotedString() == DocInfoMask) {377// Use the first one we find.378Description = escapeRST(VisibilityHelp->getValueAsString("Text"));379break;380}381}382if (!Description.empty())383break;384}385386if (!Description.empty())387break;388}389390// If there's not a program specific string, use the default one.391if (Description.empty())392Description = getRSTStringWithTextFallback(R, "DocBrief", "HelpText");393394if (!isa<UnsetInit>(R->getValueInit("Values"))) {395if (!Description.empty() && Description.back() != '.')396Description.push_back('.');397398StringRef MetaVarName;399if (!isa<UnsetInit>(R->getValueInit("MetaVarName")))400MetaVarName = R->getValueAsString("MetaVarName");401else402MetaVarName = DefaultMetaVarName;403404SmallVector<StringRef> Values;405SplitString(R->getValueAsString("Values"), Values, ",");406Description += (" " + MetaVarName + " must be '").str();407if (Values.size() > 1) {408Description += join(Values.begin(), Values.end() - 1, "', '");409Description += "' or '";410}411Description += (Values.back() + "'.").str();412}413414if (!Description.empty())415OS << Description << "\n\n";416}417418void emitDocumentation(int Depth, const Documentation &Doc,419const Record *DocInfo, raw_ostream &OS);420421void emitGroup(int Depth, const DocumentedGroup &Group, const Record *DocInfo,422raw_ostream &OS) {423emitHeading(Depth,424getRSTStringWithTextFallback(Group.Group, "DocName", "Name"), OS);425426// Emit the description, if we have one.427std::string Description =428getRSTStringWithTextFallback(Group.Group, "DocBrief", "HelpText");429if (!Description.empty())430OS << Description << "\n\n";431432// Emit contained options and groups.433emitDocumentation(Depth + 1, Group, DocInfo, OS);434}435436void emitDocumentation(int Depth, const Documentation &Doc,437const Record *DocInfo, raw_ostream &OS) {438for (auto &O : Doc.Options)439emitOption(O, DocInfo, OS);440for (auto &G : Doc.Groups)441emitGroup(Depth, G, DocInfo, OS);442}443444} // namespace445446void clang::EmitClangOptDocs(RecordKeeper &Records, raw_ostream &OS) {447const Record *DocInfo = Records.getDef("GlobalDocumentation");448if (!DocInfo) {449PrintFatalError("The GlobalDocumentation top-level definition is missing, "450"no documentation will be generated.");451return;452}453OS << DocInfo->getValueAsString("Intro") << "\n";454OS << ".. program:: " << DocInfo->getValueAsString("Program").lower() << "\n";455456emitDocumentation(0, extractDocumentation(Records, DocInfo), DocInfo, OS);457}458459460