Path: blob/main/contrib/llvm-project/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
35230 views
//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-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//===----------------------------------------------------------------------===//7//8// These tablegen backends emit Clang diagnostics tables.9//10//===----------------------------------------------------------------------===//1112#include "TableGenBackends.h"13#include "llvm/ADT/DenseSet.h"14#include "llvm/ADT/PointerUnion.h"15#include "llvm/ADT/STLExtras.h"16#include "llvm/ADT/SmallPtrSet.h"17#include "llvm/ADT/SmallString.h"18#include "llvm/ADT/SmallVector.h"19#include "llvm/ADT/StringMap.h"20#include "llvm/ADT/StringSwitch.h"21#include "llvm/ADT/Twine.h"22#include "llvm/Support/Casting.h"23#include "llvm/TableGen/Error.h"24#include "llvm/TableGen/Record.h"25#include "llvm/TableGen/StringToOffsetTable.h"26#include "llvm/TableGen/TableGenBackend.h"27#include <algorithm>28#include <cctype>29#include <functional>30#include <map>31#include <optional>32#include <set>33using namespace llvm;3435//===----------------------------------------------------------------------===//36// Diagnostic category computation code.37//===----------------------------------------------------------------------===//3839namespace {40class DiagGroupParentMap {41RecordKeeper &Records;42std::map<const Record*, std::vector<Record*> > Mapping;43public:44DiagGroupParentMap(RecordKeeper &records) : Records(records) {45std::vector<Record*> DiagGroups46= Records.getAllDerivedDefinitions("DiagGroup");47for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {48std::vector<Record*> SubGroups =49DiagGroups[i]->getValueAsListOfDefs("SubGroups");50for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)51Mapping[SubGroups[j]].push_back(DiagGroups[i]);52}53}5455const std::vector<Record*> &getParents(const Record *Group) {56return Mapping[Group];57}58};59} // end anonymous namespace.6061static std::string62getCategoryFromDiagGroup(const Record *Group,63DiagGroupParentMap &DiagGroupParents) {64// If the DiagGroup has a category, return it.65std::string CatName = std::string(Group->getValueAsString("CategoryName"));66if (!CatName.empty()) return CatName;6768// The diag group may the subgroup of one or more other diagnostic groups,69// check these for a category as well.70const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);71for (unsigned i = 0, e = Parents.size(); i != e; ++i) {72CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);73if (!CatName.empty()) return CatName;74}75return "";76}7778/// getDiagnosticCategory - Return the category that the specified diagnostic79/// lives in.80static std::string getDiagnosticCategory(const Record *R,81DiagGroupParentMap &DiagGroupParents) {82// If the diagnostic is in a group, and that group has a category, use it.83if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {84// Check the diagnostic's diag group for a category.85std::string CatName = getCategoryFromDiagGroup(Group->getDef(),86DiagGroupParents);87if (!CatName.empty()) return CatName;88}8990// If the diagnostic itself has a category, get it.91return std::string(R->getValueAsString("CategoryName"));92}9394namespace {95class DiagCategoryIDMap {96RecordKeeper &Records;97StringMap<unsigned> CategoryIDs;98std::vector<std::string> CategoryStrings;99public:100DiagCategoryIDMap(RecordKeeper &records) : Records(records) {101DiagGroupParentMap ParentInfo(Records);102103// The zero'th category is "".104CategoryStrings.push_back("");105CategoryIDs[""] = 0;106107std::vector<Record*> Diags =108Records.getAllDerivedDefinitions("Diagnostic");109for (unsigned i = 0, e = Diags.size(); i != e; ++i) {110std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);111if (Category.empty()) continue; // Skip diags with no category.112113unsigned &ID = CategoryIDs[Category];114if (ID != 0) continue; // Already seen.115116ID = CategoryStrings.size();117CategoryStrings.push_back(Category);118}119}120121unsigned getID(StringRef CategoryString) {122return CategoryIDs[CategoryString];123}124125typedef std::vector<std::string>::const_iterator const_iterator;126const_iterator begin() const { return CategoryStrings.begin(); }127const_iterator end() const { return CategoryStrings.end(); }128};129130struct GroupInfo {131llvm::StringRef GroupName;132std::vector<const Record*> DiagsInGroup;133std::vector<std::string> SubGroups;134unsigned IDNo = 0;135136llvm::SmallVector<const Record *, 1> Defs;137138GroupInfo() = default;139};140} // end anonymous namespace.141142static bool beforeThanCompare(const Record *LHS, const Record *RHS) {143assert(!LHS->getLoc().empty() && !RHS->getLoc().empty());144return145LHS->getLoc().front().getPointer() < RHS->getLoc().front().getPointer();146}147148static bool diagGroupBeforeByName(const Record *LHS, const Record *RHS) {149return LHS->getValueAsString("GroupName") <150RHS->getValueAsString("GroupName");151}152153/// Invert the 1-[0/1] mapping of diags to group into a one to many154/// mapping of groups to diags in the group.155static void groupDiagnostics(const std::vector<Record*> &Diags,156const std::vector<Record*> &DiagGroups,157std::map<std::string, GroupInfo> &DiagsInGroup) {158159for (unsigned i = 0, e = Diags.size(); i != e; ++i) {160const Record *R = Diags[i];161DefInit *DI = dyn_cast<DefInit>(R->getValueInit("Group"));162if (!DI)163continue;164assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&165"Note can't be in a DiagGroup");166std::string GroupName =167std::string(DI->getDef()->getValueAsString("GroupName"));168DiagsInGroup[GroupName].DiagsInGroup.push_back(R);169}170171// Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty172// groups (these are warnings that GCC supports that clang never produces).173for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {174Record *Group = DiagGroups[i];175GroupInfo &GI =176DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];177GI.GroupName = Group->getName();178GI.Defs.push_back(Group);179180std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");181for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)182GI.SubGroups.push_back(183std::string(SubGroups[j]->getValueAsString("GroupName")));184}185186// Assign unique ID numbers to the groups.187unsigned IDNo = 0;188for (std::map<std::string, GroupInfo>::iterator189I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)190I->second.IDNo = IDNo;191192// Warn if the same group is defined more than once (including implicitly).193for (auto &Group : DiagsInGroup) {194if (Group.second.Defs.size() == 1 &&195(!Group.second.Defs.front()->isAnonymous() ||196Group.second.DiagsInGroup.size() <= 1))197continue;198199bool First = true;200for (const Record *Def : Group.second.Defs) {201// Skip implicit definitions from diagnostics; we'll report those202// separately below.203bool IsImplicit = false;204for (const Record *Diag : Group.second.DiagsInGroup) {205if (cast<DefInit>(Diag->getValueInit("Group"))->getDef() == Def) {206IsImplicit = true;207break;208}209}210if (IsImplicit)211continue;212213llvm::SMLoc Loc = Def->getLoc().front();214if (First) {215SrcMgr.PrintMessage(Loc, SourceMgr::DK_Error,216Twine("group '") + Group.first +217"' is defined more than once");218First = false;219} else {220SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, "also defined here");221}222}223224for (const Record *Diag : Group.second.DiagsInGroup) {225if (!cast<DefInit>(Diag->getValueInit("Group"))->getDef()->isAnonymous())226continue;227228llvm::SMLoc Loc = Diag->getLoc().front();229if (First) {230SrcMgr.PrintMessage(Loc, SourceMgr::DK_Error,231Twine("group '") + Group.first +232"' is implicitly defined more than once");233First = false;234} else {235SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note,236"also implicitly defined here");237}238}239}240}241242//===----------------------------------------------------------------------===//243// Infer members of -Wpedantic.244//===----------------------------------------------------------------------===//245246typedef std::vector<const Record *> RecordVec;247typedef llvm::DenseSet<const Record *> RecordSet;248typedef llvm::PointerUnion<RecordVec*, RecordSet*> VecOrSet;249250namespace {251class InferPedantic {252typedef llvm::DenseMap<const Record *,253std::pair<unsigned, std::optional<unsigned>>>254GMap;255256DiagGroupParentMap &DiagGroupParents;257const std::vector<Record*> &Diags;258const std::vector<Record*> DiagGroups;259std::map<std::string, GroupInfo> &DiagsInGroup;260llvm::DenseSet<const Record*> DiagsSet;261GMap GroupCount;262public:263InferPedantic(DiagGroupParentMap &DiagGroupParents,264const std::vector<Record*> &Diags,265const std::vector<Record*> &DiagGroups,266std::map<std::string, GroupInfo> &DiagsInGroup)267: DiagGroupParents(DiagGroupParents),268Diags(Diags),269DiagGroups(DiagGroups),270DiagsInGroup(DiagsInGroup) {}271272/// Compute the set of diagnostics and groups that are immediately273/// in -Wpedantic.274void compute(VecOrSet DiagsInPedantic,275VecOrSet GroupsInPedantic);276277private:278/// Determine whether a group is a subgroup of another group.279bool isSubGroupOfGroup(const Record *Group,280llvm::StringRef RootGroupName);281282/// Determine if the diagnostic is an extension.283bool isExtension(const Record *Diag);284285/// Determine if the diagnostic is off by default.286bool isOffByDefault(const Record *Diag);287288/// Increment the count for a group, and transitively marked289/// parent groups when appropriate.290void markGroup(const Record *Group);291292/// Return true if the diagnostic is in a pedantic group.293bool groupInPedantic(const Record *Group, bool increment = false);294};295} // end anonymous namespace296297bool InferPedantic::isSubGroupOfGroup(const Record *Group,298llvm::StringRef GName) {299const std::string &GroupName =300std::string(Group->getValueAsString("GroupName"));301if (GName == GroupName)302return true;303304const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);305for (unsigned i = 0, e = Parents.size(); i != e; ++i)306if (isSubGroupOfGroup(Parents[i], GName))307return true;308309return false;310}311312/// Determine if the diagnostic is an extension.313bool InferPedantic::isExtension(const Record *Diag) {314const std::string &ClsName =315std::string(Diag->getValueAsDef("Class")->getName());316return ClsName == "CLASS_EXTENSION";317}318319bool InferPedantic::isOffByDefault(const Record *Diag) {320const std::string &DefSeverity = std::string(321Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));322return DefSeverity == "Ignored";323}324325bool InferPedantic::groupInPedantic(const Record *Group, bool increment) {326GMap::mapped_type &V = GroupCount[Group];327// Lazily compute the threshold value for the group count.328if (!V.second) {329const GroupInfo &GI =330DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];331V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();332}333334if (increment)335++V.first;336337// Consider a group in -Wpendatic IFF if has at least one diagnostic338// or subgroup AND all of those diagnostics and subgroups are covered339// by -Wpedantic via our computation.340return V.first != 0 && V.first == *V.second;341}342343void InferPedantic::markGroup(const Record *Group) {344// If all the diagnostics and subgroups have been marked as being345// covered by -Wpedantic, increment the count of parent groups. Once the346// group's count is equal to the number of subgroups and diagnostics in347// that group, we can safely add this group to -Wpedantic.348if (groupInPedantic(Group, /* increment */ true)) {349const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);350for (unsigned i = 0, e = Parents.size(); i != e; ++i)351markGroup(Parents[i]);352}353}354355void InferPedantic::compute(VecOrSet DiagsInPedantic,356VecOrSet GroupsInPedantic) {357// All extensions that are not on by default are implicitly in the358// "pedantic" group. For those that aren't explicitly included in -Wpedantic,359// mark them for consideration to be included in -Wpedantic directly.360for (unsigned i = 0, e = Diags.size(); i != e; ++i) {361Record *R = Diags[i];362if (isExtension(R) && isOffByDefault(R)) {363DiagsSet.insert(R);364if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {365const Record *GroupRec = Group->getDef();366if (!isSubGroupOfGroup(GroupRec, "pedantic")) {367markGroup(GroupRec);368}369}370}371}372373// Compute the set of diagnostics that are directly in -Wpedantic. We374// march through Diags a second time to ensure the results are emitted375// in deterministic order.376for (unsigned i = 0, e = Diags.size(); i != e; ++i) {377Record *R = Diags[i];378if (!DiagsSet.count(R))379continue;380// Check if the group is implicitly in -Wpedantic. If so,381// the diagnostic should not be directly included in the -Wpedantic382// diagnostic group.383if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group")))384if (groupInPedantic(Group->getDef()))385continue;386387// The diagnostic is not included in a group that is (transitively) in388// -Wpedantic. Include it in -Wpedantic directly.389if (RecordVec *V = DiagsInPedantic.dyn_cast<RecordVec*>())390V->push_back(R);391else {392DiagsInPedantic.get<RecordSet*>()->insert(R);393}394}395396if (!GroupsInPedantic)397return;398399// Compute the set of groups that are directly in -Wpedantic. We400// march through the groups to ensure the results are emitted401/// in a deterministc order.402for (unsigned i = 0, ei = DiagGroups.size(); i != ei; ++i) {403Record *Group = DiagGroups[i];404if (!groupInPedantic(Group))405continue;406407const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);408bool AllParentsInPedantic =409llvm::all_of(Parents, [&](Record *R) { return groupInPedantic(R); });410// If all the parents are in -Wpedantic, this means that this diagnostic411// group will be indirectly included by -Wpedantic already. In that412// case, do not add it directly to -Wpedantic. If the group has no413// parents, obviously it should go into -Wpedantic.414if (Parents.size() > 0 && AllParentsInPedantic)415continue;416417if (RecordVec *V = GroupsInPedantic.dyn_cast<RecordVec*>())418V->push_back(Group);419else {420GroupsInPedantic.get<RecordSet*>()->insert(Group);421}422}423}424425namespace {426enum PieceKind {427MultiPieceClass,428TextPieceClass,429PlaceholderPieceClass,430SelectPieceClass,431PluralPieceClass,432DiffPieceClass,433SubstitutionPieceClass,434};435436enum ModifierType {437MT_Unknown,438MT_Placeholder,439MT_Select,440MT_Sub,441MT_Plural,442MT_Diff,443MT_Ordinal,444MT_S,445MT_Q,446MT_ObjCClass,447MT_ObjCInstance,448};449450static StringRef getModifierName(ModifierType MT) {451switch (MT) {452case MT_Select:453return "select";454case MT_Sub:455return "sub";456case MT_Diff:457return "diff";458case MT_Plural:459return "plural";460case MT_Ordinal:461return "ordinal";462case MT_S:463return "s";464case MT_Q:465return "q";466case MT_Placeholder:467return "";468case MT_ObjCClass:469return "objcclass";470case MT_ObjCInstance:471return "objcinstance";472case MT_Unknown:473llvm_unreachable("invalid modifier type");474}475// Unhandled case476llvm_unreachable("invalid modifier type");477}478479struct Piece {480// This type and its derived classes are move-only.481Piece(PieceKind Kind) : ClassKind(Kind) {}482Piece(Piece const &O) = delete;483Piece &operator=(Piece const &) = delete;484virtual ~Piece() {}485486PieceKind getPieceClass() const { return ClassKind; }487static bool classof(const Piece *) { return true; }488489private:490PieceKind ClassKind;491};492493struct MultiPiece : Piece {494MultiPiece() : Piece(MultiPieceClass) {}495MultiPiece(std::vector<Piece *> Pieces)496: Piece(MultiPieceClass), Pieces(std::move(Pieces)) {}497498std::vector<Piece *> Pieces;499500static bool classof(const Piece *P) {501return P->getPieceClass() == MultiPieceClass;502}503};504505struct TextPiece : Piece {506StringRef Role;507std::string Text;508TextPiece(StringRef Text, StringRef Role = "")509: Piece(TextPieceClass), Role(Role), Text(Text.str()) {}510511static bool classof(const Piece *P) {512return P->getPieceClass() == TextPieceClass;513}514};515516struct PlaceholderPiece : Piece {517ModifierType Kind;518int Index;519PlaceholderPiece(ModifierType Kind, int Index)520: Piece(PlaceholderPieceClass), Kind(Kind), Index(Index) {}521522static bool classof(const Piece *P) {523return P->getPieceClass() == PlaceholderPieceClass;524}525};526527struct SelectPiece : Piece {528protected:529SelectPiece(PieceKind Kind, ModifierType ModKind)530: Piece(Kind), ModKind(ModKind) {}531532public:533SelectPiece(ModifierType ModKind) : SelectPiece(SelectPieceClass, ModKind) {}534535ModifierType ModKind;536std::vector<Piece *> Options;537int Index = 0;538539static bool classof(const Piece *P) {540return P->getPieceClass() == SelectPieceClass ||541P->getPieceClass() == PluralPieceClass;542}543};544545struct PluralPiece : SelectPiece {546PluralPiece() : SelectPiece(PluralPieceClass, MT_Plural) {}547548std::vector<Piece *> OptionPrefixes;549int Index = 0;550551static bool classof(const Piece *P) {552return P->getPieceClass() == PluralPieceClass;553}554};555556struct DiffPiece : Piece {557DiffPiece() : Piece(DiffPieceClass) {}558559Piece *Parts[4] = {};560int Indexes[2] = {};561562static bool classof(const Piece *P) {563return P->getPieceClass() == DiffPieceClass;564}565};566567struct SubstitutionPiece : Piece {568SubstitutionPiece() : Piece(SubstitutionPieceClass) {}569570std::string Name;571std::vector<int> Modifiers;572573static bool classof(const Piece *P) {574return P->getPieceClass() == SubstitutionPieceClass;575}576};577578/// Diagnostic text, parsed into pieces.579580581struct DiagnosticTextBuilder {582DiagnosticTextBuilder(DiagnosticTextBuilder const &) = delete;583DiagnosticTextBuilder &operator=(DiagnosticTextBuilder const &) = delete;584585DiagnosticTextBuilder(RecordKeeper &Records) {586// Build up the list of substitution records.587for (auto *S : Records.getAllDerivedDefinitions("TextSubstitution")) {588EvaluatingRecordGuard Guard(&EvaluatingRecord, S);589Substitutions.try_emplace(590S->getName(), DiagText(*this, S->getValueAsString("Substitution")));591}592593// Check that no diagnostic definitions have the same name as a594// substitution.595for (Record *Diag : Records.getAllDerivedDefinitions("Diagnostic")) {596StringRef Name = Diag->getName();597if (Substitutions.count(Name))598llvm::PrintFatalError(599Diag->getLoc(),600"Diagnostic '" + Name +601"' has same name as TextSubstitution definition");602}603}604605std::vector<std::string> buildForDocumentation(StringRef Role,606const Record *R);607std::string buildForDefinition(const Record *R);608609Piece *getSubstitution(SubstitutionPiece *S) const {610auto It = Substitutions.find(S->Name);611if (It == Substitutions.end())612PrintFatalError("Failed to find substitution with name: " + S->Name);613return It->second.Root;614}615616[[noreturn]] void PrintFatalError(llvm::Twine const &Msg) const {617assert(EvaluatingRecord && "not evaluating a record?");618llvm::PrintFatalError(EvaluatingRecord->getLoc(), Msg);619}620621private:622struct DiagText {623DiagnosticTextBuilder &Builder;624std::vector<Piece *> AllocatedPieces;625Piece *Root = nullptr;626627template <class T, class... Args> T *New(Args &&... args) {628static_assert(std::is_base_of<Piece, T>::value, "must be piece");629T *Mem = new T(std::forward<Args>(args)...);630AllocatedPieces.push_back(Mem);631return Mem;632}633634DiagText(DiagnosticTextBuilder &Builder, StringRef Text)635: Builder(Builder), Root(parseDiagText(Text, StopAt::End)) {}636637enum class StopAt {638// Parse until the end of the string.639End,640// Additionally stop if we hit a non-nested '|' or '}'.641PipeOrCloseBrace,642// Additionally stop if we hit a non-nested '$'.643Dollar,644};645646Piece *parseDiagText(StringRef &Text, StopAt Stop);647int parseModifier(StringRef &) const;648649public:650DiagText(DiagText &&O) noexcept651: Builder(O.Builder), AllocatedPieces(std::move(O.AllocatedPieces)),652Root(O.Root) {653O.Root = nullptr;654}655// The move assignment operator is defined as deleted pending further656// motivation.657DiagText &operator=(DiagText &&) = delete;658659// The copy constrcutor and copy assignment operator is defined as deleted660// pending further motivation.661DiagText(const DiagText &) = delete;662DiagText &operator=(const DiagText &) = delete;663664~DiagText() {665for (Piece *P : AllocatedPieces)666delete P;667}668};669670private:671const Record *EvaluatingRecord = nullptr;672struct EvaluatingRecordGuard {673EvaluatingRecordGuard(const Record **Dest, const Record *New)674: Dest(Dest), Old(*Dest) {675*Dest = New;676}677~EvaluatingRecordGuard() { *Dest = Old; }678const Record **Dest;679const Record *Old;680};681682StringMap<DiagText> Substitutions;683};684685template <class Derived> struct DiagTextVisitor {686using ModifierMappingsType = std::optional<std::vector<int>>;687688private:689Derived &getDerived() { return static_cast<Derived &>(*this); }690691public:692std::vector<int>693getSubstitutionMappings(SubstitutionPiece *P,694const ModifierMappingsType &Mappings) const {695std::vector<int> NewMappings;696for (int Idx : P->Modifiers)697NewMappings.push_back(mapIndex(Idx, Mappings));698return NewMappings;699}700701struct SubstitutionContext {702SubstitutionContext(DiagTextVisitor &Visitor, SubstitutionPiece *P)703: Visitor(Visitor) {704Substitution = Visitor.Builder.getSubstitution(P);705OldMappings = std::move(Visitor.ModifierMappings);706std::vector<int> NewMappings =707Visitor.getSubstitutionMappings(P, OldMappings);708Visitor.ModifierMappings = std::move(NewMappings);709}710711~SubstitutionContext() {712Visitor.ModifierMappings = std::move(OldMappings);713}714715private:716DiagTextVisitor &Visitor;717std::optional<std::vector<int>> OldMappings;718719public:720Piece *Substitution;721};722723public:724DiagTextVisitor(DiagnosticTextBuilder &Builder) : Builder(Builder) {}725726void Visit(Piece *P) {727switch (P->getPieceClass()) {728#define CASE(T) \729case T##PieceClass: \730return getDerived().Visit##T(static_cast<T##Piece *>(P))731CASE(Multi);732CASE(Text);733CASE(Placeholder);734CASE(Select);735CASE(Plural);736CASE(Diff);737CASE(Substitution);738#undef CASE739}740}741742void VisitSubstitution(SubstitutionPiece *P) {743SubstitutionContext Guard(*this, P);744Visit(Guard.Substitution);745}746747int mapIndex(int Idx,748ModifierMappingsType const &ModifierMappings) const {749if (!ModifierMappings)750return Idx;751if (ModifierMappings->size() <= static_cast<unsigned>(Idx))752Builder.PrintFatalError("Modifier value '" + std::to_string(Idx) +753"' is not valid for this mapping (has " +754std::to_string(ModifierMappings->size()) +755" mappings)");756return (*ModifierMappings)[Idx];757}758759int mapIndex(int Idx) const {760return mapIndex(Idx, ModifierMappings);761}762763protected:764DiagnosticTextBuilder &Builder;765ModifierMappingsType ModifierMappings;766};767768void escapeRST(StringRef Str, std::string &Out) {769for (auto K : Str) {770if (StringRef("`*|_[]\\").count(K))771Out.push_back('\\');772Out.push_back(K);773}774}775776template <typename It> void padToSameLength(It Begin, It End) {777size_t Width = 0;778for (It I = Begin; I != End; ++I)779Width = std::max(Width, I->size());780for (It I = Begin; I != End; ++I)781(*I) += std::string(Width - I->size(), ' ');782}783784template <typename It> void makeTableRows(It Begin, It End) {785if (Begin == End)786return;787padToSameLength(Begin, End);788for (It I = Begin; I != End; ++I)789*I = "|" + *I + "|";790}791792void makeRowSeparator(std::string &Str) {793for (char &K : Str)794K = (K == '|' ? '+' : '-');795}796797struct DiagTextDocPrinter : DiagTextVisitor<DiagTextDocPrinter> {798using BaseTy = DiagTextVisitor<DiagTextDocPrinter>;799DiagTextDocPrinter(DiagnosticTextBuilder &Builder,800std::vector<std::string> &RST)801: BaseTy(Builder), RST(RST) {}802803void gatherNodes(804Piece *OrigP, const ModifierMappingsType &CurrentMappings,805std::vector<std::pair<Piece *, ModifierMappingsType>> &Pieces) const {806if (auto *Sub = dyn_cast<SubstitutionPiece>(OrigP)) {807ModifierMappingsType NewMappings =808getSubstitutionMappings(Sub, CurrentMappings);809return gatherNodes(Builder.getSubstitution(Sub), NewMappings, Pieces);810}811if (auto *MD = dyn_cast<MultiPiece>(OrigP)) {812for (Piece *Node : MD->Pieces)813gatherNodes(Node, CurrentMappings, Pieces);814return;815}816Pieces.push_back(std::make_pair(OrigP, CurrentMappings));817}818819void VisitMulti(MultiPiece *P) {820if (P->Pieces.empty()) {821RST.push_back("");822return;823}824825if (P->Pieces.size() == 1)826return Visit(P->Pieces[0]);827828// Flatten the list of nodes, replacing any substitution pieces with the829// recursively flattened substituted node.830std::vector<std::pair<Piece *, ModifierMappingsType>> Pieces;831gatherNodes(P, ModifierMappings, Pieces);832833std::string EmptyLinePrefix;834size_t Start = RST.size();835bool HasMultipleLines = true;836for (const std::pair<Piece *, ModifierMappingsType> &NodePair : Pieces) {837std::vector<std::string> Lines;838DiagTextDocPrinter Visitor{Builder, Lines};839Visitor.ModifierMappings = NodePair.second;840Visitor.Visit(NodePair.first);841842if (Lines.empty())843continue;844845// We need a vertical separator if either this or the previous piece is a846// multi-line piece, or this is the last piece.847const char *Separator = (Lines.size() > 1 || HasMultipleLines) ? "|" : "";848HasMultipleLines = Lines.size() > 1;849850if (Start + Lines.size() > RST.size())851RST.resize(Start + Lines.size(), EmptyLinePrefix);852853padToSameLength(Lines.begin(), Lines.end());854for (size_t I = 0; I != Lines.size(); ++I)855RST[Start + I] += Separator + Lines[I];856std::string Empty(Lines[0].size(), ' ');857for (size_t I = Start + Lines.size(); I != RST.size(); ++I)858RST[I] += Separator + Empty;859EmptyLinePrefix += Separator + Empty;860}861for (size_t I = Start; I != RST.size(); ++I)862RST[I] += "|";863EmptyLinePrefix += "|";864865makeRowSeparator(EmptyLinePrefix);866RST.insert(RST.begin() + Start, EmptyLinePrefix);867RST.insert(RST.end(), EmptyLinePrefix);868}869870void VisitText(TextPiece *P) {871RST.push_back("");872auto &S = RST.back();873874StringRef T = P->Text;875while (T.consume_front(" "))876RST.back() += " |nbsp| ";877878std::string Suffix;879while (T.consume_back(" "))880Suffix += " |nbsp| ";881882if (!T.empty()) {883S += ':';884S += P->Role;885S += ":`";886escapeRST(T, S);887S += '`';888}889890S += Suffix;891}892893void VisitPlaceholder(PlaceholderPiece *P) {894RST.push_back(std::string(":placeholder:`") +895char('A' + mapIndex(P->Index)) + "`");896}897898void VisitSelect(SelectPiece *P) {899std::vector<size_t> SeparatorIndexes;900SeparatorIndexes.push_back(RST.size());901RST.emplace_back();902for (auto *O : P->Options) {903Visit(O);904SeparatorIndexes.push_back(RST.size());905RST.emplace_back();906}907908makeTableRows(RST.begin() + SeparatorIndexes.front(),909RST.begin() + SeparatorIndexes.back() + 1);910for (size_t I : SeparatorIndexes)911makeRowSeparator(RST[I]);912}913914void VisitPlural(PluralPiece *P) { VisitSelect(P); }915916void VisitDiff(DiffPiece *P) {917// Render %diff{a $ b $ c|d}e,f as %select{a %e b %f c|d}.918PlaceholderPiece E(MT_Placeholder, P->Indexes[0]);919PlaceholderPiece F(MT_Placeholder, P->Indexes[1]);920921MultiPiece FirstOption;922FirstOption.Pieces.push_back(P->Parts[0]);923FirstOption.Pieces.push_back(&E);924FirstOption.Pieces.push_back(P->Parts[1]);925FirstOption.Pieces.push_back(&F);926FirstOption.Pieces.push_back(P->Parts[2]);927928SelectPiece Select(MT_Diff);929Select.Options.push_back(&FirstOption);930Select.Options.push_back(P->Parts[3]);931932VisitSelect(&Select);933}934935std::vector<std::string> &RST;936};937938struct DiagTextPrinter : DiagTextVisitor<DiagTextPrinter> {939public:940using BaseTy = DiagTextVisitor<DiagTextPrinter>;941DiagTextPrinter(DiagnosticTextBuilder &Builder, std::string &Result)942: BaseTy(Builder), Result(Result) {}943944void VisitMulti(MultiPiece *P) {945for (auto *Child : P->Pieces)946Visit(Child);947}948void VisitText(TextPiece *P) { Result += P->Text; }949void VisitPlaceholder(PlaceholderPiece *P) {950Result += "%";951Result += getModifierName(P->Kind);952addInt(mapIndex(P->Index));953}954void VisitSelect(SelectPiece *P) {955Result += "%";956Result += getModifierName(P->ModKind);957if (P->ModKind == MT_Select) {958Result += "{";959for (auto *D : P->Options) {960Visit(D);961Result += '|';962}963if (!P->Options.empty())964Result.erase(--Result.end());965Result += '}';966}967addInt(mapIndex(P->Index));968}969970void VisitPlural(PluralPiece *P) {971Result += "%plural{";972assert(P->Options.size() == P->OptionPrefixes.size());973for (unsigned I = 0, End = P->Options.size(); I < End; ++I) {974if (P->OptionPrefixes[I])975Visit(P->OptionPrefixes[I]);976Visit(P->Options[I]);977Result += "|";978}979if (!P->Options.empty())980Result.erase(--Result.end());981Result += '}';982addInt(mapIndex(P->Index));983}984985void VisitDiff(DiffPiece *P) {986Result += "%diff{";987Visit(P->Parts[0]);988Result += "$";989Visit(P->Parts[1]);990Result += "$";991Visit(P->Parts[2]);992Result += "|";993Visit(P->Parts[3]);994Result += "}";995addInt(mapIndex(P->Indexes[0]));996Result += ",";997addInt(mapIndex(P->Indexes[1]));998}9991000void addInt(int Val) { Result += std::to_string(Val); }10011002std::string &Result;1003};10041005int DiagnosticTextBuilder::DiagText::parseModifier(StringRef &Text) const {1006if (Text.empty() || !isdigit(Text[0]))1007Builder.PrintFatalError("expected modifier in diagnostic");1008int Val = 0;1009do {1010Val *= 10;1011Val += Text[0] - '0';1012Text = Text.drop_front();1013} while (!Text.empty() && isdigit(Text[0]));1014return Val;1015}10161017Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,1018StopAt Stop) {1019std::vector<Piece *> Parsed;10201021constexpr llvm::StringLiteral StopSets[] = {"%", "%|}", "%|}$"};1022llvm::StringRef StopSet = StopSets[static_cast<int>(Stop)];10231024while (!Text.empty()) {1025size_t End = (size_t)-2;1026do1027End = Text.find_first_of(StopSet, End + 2);1028while (1029End < Text.size() - 1 && Text[End] == '%' &&1030(Text[End + 1] == '%' || Text[End + 1] == '|' || Text[End + 1] == '$'));10311032if (End) {1033Parsed.push_back(New<TextPiece>(Text.slice(0, End), "diagtext"));1034Text = Text.slice(End, StringRef::npos);1035if (Text.empty())1036break;1037}10381039if (Text[0] == '|' || Text[0] == '}' || Text[0] == '$')1040break;10411042// Drop the '%'.1043Text = Text.drop_front();10441045// Extract the (optional) modifier.1046size_t ModLength = Text.find_first_of("0123456789{");1047StringRef Modifier = Text.slice(0, ModLength);1048Text = Text.slice(ModLength, StringRef::npos);1049ModifierType ModType = llvm::StringSwitch<ModifierType>{Modifier}1050.Case("select", MT_Select)1051.Case("sub", MT_Sub)1052.Case("diff", MT_Diff)1053.Case("plural", MT_Plural)1054.Case("s", MT_S)1055.Case("ordinal", MT_Ordinal)1056.Case("q", MT_Q)1057.Case("objcclass", MT_ObjCClass)1058.Case("objcinstance", MT_ObjCInstance)1059.Case("", MT_Placeholder)1060.Default(MT_Unknown);10611062auto ExpectAndConsume = [&](StringRef Prefix) {1063if (!Text.consume_front(Prefix))1064Builder.PrintFatalError("expected '" + Prefix + "' while parsing %" +1065Modifier);1066};10671068switch (ModType) {1069case MT_Unknown:1070Builder.PrintFatalError("Unknown modifier type: " + Modifier);1071case MT_Select: {1072SelectPiece *Select = New<SelectPiece>(MT_Select);1073do {1074Text = Text.drop_front(); // '{' or '|'1075Select->Options.push_back(1076parseDiagText(Text, StopAt::PipeOrCloseBrace));1077assert(!Text.empty() && "malformed %select");1078} while (Text.front() == '|');1079ExpectAndConsume("}");1080Select->Index = parseModifier(Text);1081Parsed.push_back(Select);1082continue;1083}1084case MT_Plural: {1085PluralPiece *Plural = New<PluralPiece>();1086do {1087Text = Text.drop_front(); // '{' or '|'1088size_t End = Text.find_first_of(':');1089if (End == StringRef::npos)1090Builder.PrintFatalError("expected ':' while parsing %plural");1091++End;1092assert(!Text.empty());1093Plural->OptionPrefixes.push_back(1094New<TextPiece>(Text.slice(0, End), "diagtext"));1095Text = Text.slice(End, StringRef::npos);1096Plural->Options.push_back(1097parseDiagText(Text, StopAt::PipeOrCloseBrace));1098assert(!Text.empty() && "malformed %plural");1099} while (Text.front() == '|');1100ExpectAndConsume("}");1101Plural->Index = parseModifier(Text);1102Parsed.push_back(Plural);1103continue;1104}1105case MT_Sub: {1106SubstitutionPiece *Sub = New<SubstitutionPiece>();1107ExpectAndConsume("{");1108size_t NameSize = Text.find_first_of('}');1109assert(NameSize != size_t(-1) && "failed to find the end of the name");1110assert(NameSize != 0 && "empty name?");1111Sub->Name = Text.substr(0, NameSize).str();1112Text = Text.drop_front(NameSize);1113ExpectAndConsume("}");1114if (!Text.empty()) {1115while (true) {1116if (!isdigit(Text[0]))1117break;1118Sub->Modifiers.push_back(parseModifier(Text));1119if (!Text.consume_front(","))1120break;1121assert(!Text.empty() && isdigit(Text[0]) &&1122"expected another modifier");1123}1124}1125Parsed.push_back(Sub);1126continue;1127}1128case MT_Diff: {1129DiffPiece *Diff = New<DiffPiece>();1130ExpectAndConsume("{");1131Diff->Parts[0] = parseDiagText(Text, StopAt::Dollar);1132ExpectAndConsume("$");1133Diff->Parts[1] = parseDiagText(Text, StopAt::Dollar);1134ExpectAndConsume("$");1135Diff->Parts[2] = parseDiagText(Text, StopAt::PipeOrCloseBrace);1136ExpectAndConsume("|");1137Diff->Parts[3] = parseDiagText(Text, StopAt::PipeOrCloseBrace);1138ExpectAndConsume("}");1139Diff->Indexes[0] = parseModifier(Text);1140ExpectAndConsume(",");1141Diff->Indexes[1] = parseModifier(Text);1142Parsed.push_back(Diff);1143continue;1144}1145case MT_S: {1146SelectPiece *Select = New<SelectPiece>(ModType);1147Select->Options.push_back(New<TextPiece>(""));1148Select->Options.push_back(New<TextPiece>("s", "diagtext"));1149Select->Index = parseModifier(Text);1150Parsed.push_back(Select);1151continue;1152}1153case MT_Q:1154case MT_Placeholder:1155case MT_ObjCClass:1156case MT_ObjCInstance:1157case MT_Ordinal: {1158Parsed.push_back(New<PlaceholderPiece>(ModType, parseModifier(Text)));1159continue;1160}1161}1162}11631164return New<MultiPiece>(Parsed);1165}11661167std::vector<std::string>1168DiagnosticTextBuilder::buildForDocumentation(StringRef Severity,1169const Record *R) {1170EvaluatingRecordGuard Guard(&EvaluatingRecord, R);1171StringRef Text = R->getValueAsString("Summary");11721173DiagText D(*this, Text);1174TextPiece *Prefix = D.New<TextPiece>(Severity, Severity);1175Prefix->Text += ": ";1176auto *MP = dyn_cast<MultiPiece>(D.Root);1177if (!MP) {1178MP = D.New<MultiPiece>();1179MP->Pieces.push_back(D.Root);1180D.Root = MP;1181}1182MP->Pieces.insert(MP->Pieces.begin(), Prefix);1183std::vector<std::string> Result;1184DiagTextDocPrinter{*this, Result}.Visit(D.Root);1185return Result;1186}11871188std::string DiagnosticTextBuilder::buildForDefinition(const Record *R) {1189EvaluatingRecordGuard Guard(&EvaluatingRecord, R);1190StringRef Text = R->getValueAsString("Summary");1191DiagText D(*this, Text);1192std::string Result;1193DiagTextPrinter{*this, Result}.Visit(D.Root);1194return Result;1195}11961197} // namespace11981199//===----------------------------------------------------------------------===//1200// Warning Tables (.inc file) generation.1201//===----------------------------------------------------------------------===//12021203static bool isError(const Record &Diag) {1204const std::string &ClsName =1205std::string(Diag.getValueAsDef("Class")->getName());1206return ClsName == "CLASS_ERROR";1207}12081209static bool isRemark(const Record &Diag) {1210const std::string &ClsName =1211std::string(Diag.getValueAsDef("Class")->getName());1212return ClsName == "CLASS_REMARK";1213}12141215// Presumes the text has been split at the first whitespace or hyphen.1216static bool isExemptAtStart(StringRef Text) {1217// Fast path, the first character is lowercase or not alphanumeric.1218if (Text.empty() || isLower(Text[0]) || !isAlnum(Text[0]))1219return true;12201221// If the text is all uppercase (or numbers, +, or _), then we assume it's an1222// acronym and that's allowed. This covers cases like ISO, C23, C++14, and1223// OBJECT_MODE. However, if there's only a single letter other than "C", we1224// do not exempt it so that we catch a case like "A really bad idea" while1225// still allowing a case like "C does not allow...".1226if (llvm::all_of(Text, [](char C) {1227return isUpper(C) || isDigit(C) || C == '+' || C == '_';1228}))1229return Text.size() > 1 || Text[0] == 'C';12301231// Otherwise, there are a few other exemptions.1232return StringSwitch<bool>(Text)1233.Case("AddressSanitizer", true)1234.Case("CFString", true)1235.Case("Clang", true)1236.Case("Fuchsia", true)1237.Case("GNUstep", true)1238.Case("IBOutletCollection", true)1239.Case("Microsoft", true)1240.Case("Neon", true)1241.StartsWith("NSInvocation", true) // NSInvocation, NSInvocation's1242.Case("Objective", true) // Objective-C (hyphen is a word boundary)1243.Case("OpenACC", true)1244.Case("OpenCL", true)1245.Case("OpenMP", true)1246.Case("Pascal", true)1247.Case("Swift", true)1248.Case("Unicode", true)1249.Case("Vulkan", true)1250.Case("WebAssembly", true)1251.Default(false);1252}12531254// Does not presume the text has been split at all.1255static bool isExemptAtEnd(StringRef Text) {1256// Rather than come up with a list of characters that are allowed, we go the1257// other way and look only for characters that are not allowed.1258switch (Text.back()) {1259default:1260return true;1261case '?':1262// Explicitly allowed to support "; did you mean?".1263return true;1264case '.':1265case '!':1266return false;1267}1268}12691270static void verifyDiagnosticWording(const Record &Diag) {1271StringRef FullDiagText = Diag.getValueAsString("Summary");12721273auto DiagnoseStart = [&](StringRef Text) {1274// Verify that the text does not start with a capital letter, except for1275// special cases that are exempt like ISO and C++. Find the first word1276// by looking for a word breaking character.1277char Separators[] = {' ', '-', ',', '}'};1278auto Iter = std::find_first_of(1279Text.begin(), Text.end(), std::begin(Separators), std::end(Separators));12801281StringRef First = Text.substr(0, Iter - Text.begin());1282if (!isExemptAtStart(First)) {1283PrintError(&Diag,1284"Diagnostics should not start with a capital letter; '" +1285First + "' is invalid");1286}1287};12881289auto DiagnoseEnd = [&](StringRef Text) {1290// Verify that the text does not end with punctuation like '.' or '!'.1291if (!isExemptAtEnd(Text)) {1292PrintError(&Diag, "Diagnostics should not end with punctuation; '" +1293Text.substr(Text.size() - 1, 1) + "' is invalid");1294}1295};12961297// If the diagnostic starts with %select, look through it to see whether any1298// of the options will cause a problem.1299if (FullDiagText.starts_with("%select{")) {1300// Do a balanced delimiter scan from the start of the text to find the1301// closing '}', skipping intermediary {} pairs.13021303size_t BraceCount = 1;1304constexpr size_t PercentSelectBraceLen = sizeof("%select{") - 1;1305auto Iter = FullDiagText.begin() + PercentSelectBraceLen;1306for (auto End = FullDiagText.end(); Iter != End; ++Iter) {1307char Ch = *Iter;1308if (Ch == '{')1309++BraceCount;1310else if (Ch == '}')1311--BraceCount;1312if (!BraceCount)1313break;1314}1315// Defending against a malformed diagnostic string.1316if (BraceCount != 0)1317return;13181319StringRef SelectText =1320FullDiagText.substr(PercentSelectBraceLen, Iter - FullDiagText.begin() -1321PercentSelectBraceLen);1322SmallVector<StringRef, 4> SelectPieces;1323SelectText.split(SelectPieces, '|');13241325// Walk over all of the individual pieces of select text to see if any of1326// them start with an invalid character. If any of the select pieces is1327// empty, we need to look at the first word after the %select to see1328// whether that is invalid or not. If all of the pieces are fine, then we1329// don't need to check anything else about the start of the diagnostic.1330bool CheckSecondWord = false;1331for (StringRef Piece : SelectPieces) {1332if (Piece.empty())1333CheckSecondWord = true;1334else1335DiagnoseStart(Piece);1336}13371338if (CheckSecondWord) {1339// There was an empty select piece, so we need to check the second1340// word. This catches situations like '%select{|fine}0 Not okay'. Add1341// two to account for the closing curly brace and the number after it.1342StringRef AfterSelect =1343FullDiagText.substr(Iter - FullDiagText.begin() + 2).ltrim();1344DiagnoseStart(AfterSelect);1345}1346} else {1347// If the start of the diagnostic is not %select, we can check the first1348// word and be done with it.1349DiagnoseStart(FullDiagText);1350}13511352// If the last character in the diagnostic is a number preceded by a }, scan1353// backwards to see if this is for a %select{...}0. If it is, we need to look1354// at each piece to see whether it ends in punctuation or not.1355bool StillNeedToDiagEnd = true;1356if (isDigit(FullDiagText.back()) && *(FullDiagText.end() - 2) == '}') {1357// Scan backwards to find the opening curly brace.1358size_t BraceCount = 1;1359auto Iter = FullDiagText.end() - sizeof("}0");1360for (auto End = FullDiagText.begin(); Iter != End; --Iter) {1361char Ch = *Iter;1362if (Ch == '}')1363++BraceCount;1364else if (Ch == '{')1365--BraceCount;1366if (!BraceCount)1367break;1368}1369// Defending against a malformed diagnostic string.1370if (BraceCount != 0)1371return;13721373// Continue the backwards scan to find the word before the '{' to see if it1374// is 'select'.1375constexpr size_t SelectLen = sizeof("select") - 1;1376bool IsSelect =1377(FullDiagText.substr(Iter - SelectLen - FullDiagText.begin(),1378SelectLen) == "select");1379if (IsSelect) {1380// Gather the content between the {} for the select in question so we can1381// split it into pieces.1382StillNeedToDiagEnd = false; // No longer need to handle the end.1383StringRef SelectText =1384FullDiagText.substr(Iter - FullDiagText.begin() + /*{*/ 1,1385FullDiagText.end() - Iter - /*pos before }0*/ 3);1386SmallVector<StringRef, 4> SelectPieces;1387SelectText.split(SelectPieces, '|');1388for (StringRef Piece : SelectPieces) {1389// Not worrying about a situation like: "this is bar. %select{foo|}0".1390if (!Piece.empty())1391DiagnoseEnd(Piece);1392}1393}1394}13951396// If we didn't already cover the diagnostic because of a %select, handle it1397// now.1398if (StillNeedToDiagEnd)1399DiagnoseEnd(FullDiagText);14001401// FIXME: This could also be improved by looking for instances of clang or1402// gcc in the diagnostic and recommend Clang or GCC instead. However, this1403// runs into odd situations like [[clang::warn_unused_result]],1404// #pragma clang, or --unwindlib=libgcc.1405}14061407/// ClangDiagsDefsEmitter - The top-level class emits .def files containing1408/// declarations of Clang diagnostics.1409void clang::EmitClangDiagsDefs(RecordKeeper &Records, raw_ostream &OS,1410const std::string &Component) {1411// Write the #if guard1412if (!Component.empty()) {1413std::string ComponentName = StringRef(Component).upper();1414OS << "#ifdef " << ComponentName << "START\n";1415OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName1416<< ",\n";1417OS << "#undef " << ComponentName << "START\n";1418OS << "#endif\n\n";1419}14201421DiagnosticTextBuilder DiagTextBuilder(Records);14221423std::vector<Record *> Diags = Records.getAllDerivedDefinitions("Diagnostic");14241425std::vector<Record*> DiagGroups1426= Records.getAllDerivedDefinitions("DiagGroup");14271428std::map<std::string, GroupInfo> DiagsInGroup;1429groupDiagnostics(Diags, DiagGroups, DiagsInGroup);14301431DiagCategoryIDMap CategoryIDs(Records);1432DiagGroupParentMap DGParentMap(Records);14331434// Compute the set of diagnostics that are in -Wpedantic.1435RecordSet DiagsInPedantic;1436InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);1437inferPedantic.compute(&DiagsInPedantic, (RecordVec*)nullptr);14381439for (unsigned i = 0, e = Diags.size(); i != e; ++i) {1440const Record &R = *Diags[i];14411442// Check if this is an error that is accidentally in a warning1443// group.1444if (isError(R)) {1445if (DefInit *Group = dyn_cast<DefInit>(R.getValueInit("Group"))) {1446const Record *GroupRec = Group->getDef();1447const std::string &GroupName =1448std::string(GroupRec->getValueAsString("GroupName"));1449PrintFatalError(R.getLoc(), "Error " + R.getName() +1450" cannot be in a warning group [" + GroupName + "]");1451}1452}14531454// Check that all remarks have an associated diagnostic group.1455if (isRemark(R)) {1456if (!isa<DefInit>(R.getValueInit("Group"))) {1457PrintFatalError(R.getLoc(), "Error " + R.getName() +1458" not in any diagnostic group");1459}1460}14611462// Filter by component.1463if (!Component.empty() && Component != R.getValueAsString("Component"))1464continue;14651466// Validate diagnostic wording for common issues.1467verifyDiagnosticWording(R);14681469OS << "DIAG(" << R.getName() << ", ";1470OS << R.getValueAsDef("Class")->getName();1471OS << ", (unsigned)diag::Severity::"1472<< R.getValueAsDef("DefaultSeverity")->getValueAsString("Name");14731474// Description string.1475OS << ", \"";1476OS.write_escaped(DiagTextBuilder.buildForDefinition(&R)) << '"';14771478// Warning group associated with the diagnostic. This is stored as an index1479// into the alphabetically sorted warning group table.1480if (DefInit *DI = dyn_cast<DefInit>(R.getValueInit("Group"))) {1481std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.find(1482std::string(DI->getDef()->getValueAsString("GroupName")));1483assert(I != DiagsInGroup.end());1484OS << ", " << I->second.IDNo;1485} else if (DiagsInPedantic.count(&R)) {1486std::map<std::string, GroupInfo>::iterator I =1487DiagsInGroup.find("pedantic");1488assert(I != DiagsInGroup.end() && "pedantic group not defined");1489OS << ", " << I->second.IDNo;1490} else {1491OS << ", 0";1492}14931494// SFINAE response.1495OS << ", " << R.getValueAsDef("SFINAE")->getName();14961497// Default warning has no Werror bit.1498if (R.getValueAsBit("WarningNoWerror"))1499OS << ", true";1500else1501OS << ", false";15021503if (R.getValueAsBit("ShowInSystemHeader"))1504OS << ", true";1505else1506OS << ", false";15071508if (R.getValueAsBit("ShowInSystemMacro"))1509OS << ", true";1510else1511OS << ", false";15121513if (R.getValueAsBit("Deferrable"))1514OS << ", true";1515else1516OS << ", false";15171518// Category number.1519OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));1520OS << ")\n";1521}1522}15231524//===----------------------------------------------------------------------===//1525// Warning Group Tables generation1526//===----------------------------------------------------------------------===//15271528static std::string getDiagCategoryEnum(llvm::StringRef name) {1529if (name.empty())1530return "DiagCat_None";1531SmallString<256> enumName = llvm::StringRef("DiagCat_");1532for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)1533enumName += isalnum(*I) ? *I : '_';1534return std::string(enumName);1535}15361537/// Emit the array of diagnostic subgroups.1538///1539/// The array of diagnostic subgroups contains for each group a list of its1540/// subgroups. The individual lists are separated by '-1'. Groups with no1541/// subgroups are skipped.1542///1543/// \code1544/// static const int16_t DiagSubGroups[] = {1545/// /* Empty */ -1,1546/// /* DiagSubGroup0 */ 142, -1,1547/// /* DiagSubGroup13 */ 265, 322, 399, -11548/// }1549/// \endcode1550///1551static void emitDiagSubGroups(std::map<std::string, GroupInfo> &DiagsInGroup,1552RecordVec &GroupsInPedantic, raw_ostream &OS) {1553OS << "static const int16_t DiagSubGroups[] = {\n"1554<< " /* Empty */ -1,\n";1555for (auto const &I : DiagsInGroup) {1556const bool IsPedantic = I.first == "pedantic";15571558const std::vector<std::string> &SubGroups = I.second.SubGroups;1559if (!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty())) {1560OS << " /* DiagSubGroup" << I.second.IDNo << " */ ";1561for (auto const &SubGroup : SubGroups) {1562std::map<std::string, GroupInfo>::const_iterator RI =1563DiagsInGroup.find(SubGroup);1564assert(RI != DiagsInGroup.end() && "Referenced without existing?");1565OS << RI->second.IDNo << ", ";1566}1567// Emit the groups implicitly in "pedantic".1568if (IsPedantic) {1569for (auto const &Group : GroupsInPedantic) {1570const std::string &GroupName =1571std::string(Group->getValueAsString("GroupName"));1572std::map<std::string, GroupInfo>::const_iterator RI =1573DiagsInGroup.find(GroupName);1574assert(RI != DiagsInGroup.end() && "Referenced without existing?");1575OS << RI->second.IDNo << ", ";1576}1577}15781579OS << "-1,\n";1580}1581}1582OS << "};\n\n";1583}15841585/// Emit the list of diagnostic arrays.1586///1587/// This data structure is a large array that contains itself arrays of varying1588/// size. Each array represents a list of diagnostics. The different arrays are1589/// separated by the value '-1'.1590///1591/// \code1592/// static const int16_t DiagArrays[] = {1593/// /* Empty */ -1,1594/// /* DiagArray1 */ diag::warn_pragma_message,1595/// -1,1596/// /* DiagArray2 */ diag::warn_abs_too_small,1597/// diag::warn_unsigned_abs,1598/// diag::warn_wrong_absolute_value_type,1599/// -11600/// };1601/// \endcode1602///1603static void emitDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,1604RecordVec &DiagsInPedantic, raw_ostream &OS) {1605OS << "static const int16_t DiagArrays[] = {\n"1606<< " /* Empty */ -1,\n";1607for (auto const &I : DiagsInGroup) {1608const bool IsPedantic = I.first == "pedantic";16091610const std::vector<const Record *> &V = I.second.DiagsInGroup;1611if (!V.empty() || (IsPedantic && !DiagsInPedantic.empty())) {1612OS << " /* DiagArray" << I.second.IDNo << " */ ";1613for (auto *Record : V)1614OS << "diag::" << Record->getName() << ", ";1615// Emit the diagnostics implicitly in "pedantic".1616if (IsPedantic) {1617for (auto const &Diag : DiagsInPedantic)1618OS << "diag::" << Diag->getName() << ", ";1619}1620OS << "-1,\n";1621}1622}1623OS << "};\n\n";1624}16251626/// Emit a list of group names.1627///1628/// This creates a long string which by itself contains a list of pascal style1629/// strings, which consist of a length byte directly followed by the string.1630///1631/// \code1632/// static const char DiagGroupNames[] = {1633/// \000\020#pragma-messages\t#warnings\020CFString-literal"1634/// };1635/// \endcode1636static void emitDiagGroupNames(StringToOffsetTable &GroupNames,1637raw_ostream &OS) {1638OS << "static const char DiagGroupNames[] = {\n";1639GroupNames.EmitString(OS);1640OS << "};\n\n";1641}16421643/// Emit diagnostic arrays and related data structures.1644///1645/// This creates the actual diagnostic array, an array of diagnostic subgroups1646/// and an array of subgroup names.1647///1648/// \code1649/// #ifdef GET_DIAG_ARRAYS1650/// static const int16_t DiagArrays[];1651/// static const int16_t DiagSubGroups[];1652/// static const char DiagGroupNames[];1653/// #endif1654/// \endcode1655static void emitAllDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,1656RecordVec &DiagsInPedantic,1657RecordVec &GroupsInPedantic,1658StringToOffsetTable &GroupNames,1659raw_ostream &OS) {1660OS << "\n#ifdef GET_DIAG_ARRAYS\n";1661emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);1662emitDiagSubGroups(DiagsInGroup, GroupsInPedantic, OS);1663emitDiagGroupNames(GroupNames, OS);1664OS << "#endif // GET_DIAG_ARRAYS\n\n";1665}16661667/// Emit diagnostic table.1668///1669/// The table is sorted by the name of the diagnostic group. Each element1670/// consists of the name of the diagnostic group (given as offset in the1671/// group name table), a reference to a list of diagnostics (optional) and a1672/// reference to a set of subgroups (optional).1673///1674/// \code1675/// #ifdef GET_DIAG_TABLE1676/// {/* abi */ 159, /* DiagArray11 */ 19, /* Empty */ 0},1677/// {/* aggregate-return */ 180, /* Empty */ 0, /* Empty */ 0},1678/// {/* all */ 197, /* Empty */ 0, /* DiagSubGroup13 */ 3},1679/// {/* deprecated */ 1981,/* DiagArray1 */ 348, /* DiagSubGroup3 */ 9},1680/// #endif1681/// \endcode1682static void emitDiagTable(std::map<std::string, GroupInfo> &DiagsInGroup,1683RecordVec &DiagsInPedantic,1684RecordVec &GroupsInPedantic,1685StringToOffsetTable &GroupNames, raw_ostream &OS) {1686unsigned MaxLen = 0;16871688for (auto const &I: DiagsInGroup)1689MaxLen = std::max(MaxLen, (unsigned)I.first.size());16901691OS << "\n#ifdef DIAG_ENTRY\n";1692unsigned SubGroupIndex = 1, DiagArrayIndex = 1;1693for (auto const &I: DiagsInGroup) {1694// Group option string.1695OS << "DIAG_ENTRY(";1696OS << I.second.GroupName << " /* ";16971698if (I.first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"1699"ABCDEFGHIJKLMNOPQRSTUVWXYZ"1700"0123456789!@#$%^*-+=:?") !=1701std::string::npos)1702PrintFatalError("Invalid character in diagnostic group '" + I.first +1703"'");1704OS << I.first << " */, ";1705// Store a pascal-style length byte at the beginning of the string.1706std::string Name = char(I.first.size()) + I.first;1707OS << GroupNames.GetOrAddStringOffset(Name, false) << ", ";17081709// Special handling for 'pedantic'.1710const bool IsPedantic = I.first == "pedantic";17111712// Diagnostics in the group.1713const std::vector<const Record *> &V = I.second.DiagsInGroup;1714const bool hasDiags =1715!V.empty() || (IsPedantic && !DiagsInPedantic.empty());1716if (hasDiags) {1717OS << "/* DiagArray" << I.second.IDNo << " */ " << DiagArrayIndex1718<< ", ";1719if (IsPedantic)1720DiagArrayIndex += DiagsInPedantic.size();1721DiagArrayIndex += V.size() + 1;1722} else {1723OS << "0, ";1724}17251726// Subgroups.1727const std::vector<std::string> &SubGroups = I.second.SubGroups;1728const bool hasSubGroups =1729!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty());1730if (hasSubGroups) {1731OS << "/* DiagSubGroup" << I.second.IDNo << " */ " << SubGroupIndex1732<< ", ";1733if (IsPedantic)1734SubGroupIndex += GroupsInPedantic.size();1735SubGroupIndex += SubGroups.size() + 1;1736} else {1737OS << "0, ";1738}17391740std::string Documentation = I.second.Defs.back()1741->getValue("Documentation")1742->getValue()1743->getAsUnquotedString();17441745OS << "R\"(" << StringRef(Documentation).trim() << ")\"";17461747OS << ")\n";1748}1749OS << "#endif // DIAG_ENTRY\n\n";1750}17511752/// Emit the table of diagnostic categories.1753///1754/// The table has the form of macro calls that have two parameters. The1755/// category's name as well as an enum that represents the category. The1756/// table can be used by defining the macro 'CATEGORY' and including this1757/// table right after.1758///1759/// \code1760/// #ifdef GET_CATEGORY_TABLE1761/// CATEGORY("Semantic Issue", DiagCat_Semantic_Issue)1762/// CATEGORY("Lambda Issue", DiagCat_Lambda_Issue)1763/// #endif1764/// \endcode1765static void emitCategoryTable(RecordKeeper &Records, raw_ostream &OS) {1766DiagCategoryIDMap CategoriesByID(Records);1767OS << "\n#ifdef GET_CATEGORY_TABLE\n";1768for (auto const &C : CategoriesByID)1769OS << "CATEGORY(\"" << C << "\", " << getDiagCategoryEnum(C) << ")\n";1770OS << "#endif // GET_CATEGORY_TABLE\n\n";1771}17721773void clang::EmitClangDiagGroups(RecordKeeper &Records, raw_ostream &OS) {1774// Compute a mapping from a DiagGroup to all of its parents.1775DiagGroupParentMap DGParentMap(Records);17761777std::vector<Record *> Diags = Records.getAllDerivedDefinitions("Diagnostic");17781779std::vector<Record *> DiagGroups =1780Records.getAllDerivedDefinitions("DiagGroup");17811782std::map<std::string, GroupInfo> DiagsInGroup;1783groupDiagnostics(Diags, DiagGroups, DiagsInGroup);17841785// All extensions are implicitly in the "pedantic" group. Record the1786// implicit set of groups in the "pedantic" group, and use this information1787// later when emitting the group information for Pedantic.1788RecordVec DiagsInPedantic;1789RecordVec GroupsInPedantic;1790InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);1791inferPedantic.compute(&DiagsInPedantic, &GroupsInPedantic);17921793StringToOffsetTable GroupNames;1794for (std::map<std::string, GroupInfo>::const_iterator1795I = DiagsInGroup.begin(),1796E = DiagsInGroup.end();1797I != E; ++I) {1798// Store a pascal-style length byte at the beginning of the string.1799std::string Name = char(I->first.size()) + I->first;1800GroupNames.GetOrAddStringOffset(Name, false);1801}18021803emitAllDiagArrays(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,1804OS);1805emitDiagTable(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,1806OS);1807emitCategoryTable(Records, OS);1808}18091810//===----------------------------------------------------------------------===//1811// Diagnostic name index generation1812//===----------------------------------------------------------------------===//18131814namespace {1815struct RecordIndexElement1816{1817RecordIndexElement() {}1818explicit RecordIndexElement(Record const &R)1819: Name(std::string(R.getName())) {}18201821std::string Name;1822};1823} // end anonymous namespace.18241825void clang::EmitClangDiagsIndexName(RecordKeeper &Records, raw_ostream &OS) {1826const std::vector<Record*> &Diags =1827Records.getAllDerivedDefinitions("Diagnostic");18281829std::vector<RecordIndexElement> Index;1830Index.reserve(Diags.size());1831for (unsigned i = 0, e = Diags.size(); i != e; ++i) {1832const Record &R = *(Diags[i]);1833Index.push_back(RecordIndexElement(R));1834}18351836llvm::sort(Index,1837[](const RecordIndexElement &Lhs, const RecordIndexElement &Rhs) {1838return Lhs.Name < Rhs.Name;1839});18401841for (unsigned i = 0, e = Index.size(); i != e; ++i) {1842const RecordIndexElement &R = Index[i];18431844OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";1845}1846}18471848//===----------------------------------------------------------------------===//1849// Diagnostic documentation generation1850//===----------------------------------------------------------------------===//18511852namespace docs {1853namespace {18541855bool isRemarkGroup(const Record *DiagGroup,1856const std::map<std::string, GroupInfo> &DiagsInGroup) {1857bool AnyRemarks = false, AnyNonRemarks = false;18581859std::function<void(StringRef)> Visit = [&](StringRef GroupName) {1860auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;1861for (const Record *Diag : GroupInfo.DiagsInGroup)1862(isRemark(*Diag) ? AnyRemarks : AnyNonRemarks) = true;1863for (const auto &Name : GroupInfo.SubGroups)1864Visit(Name);1865};1866Visit(DiagGroup->getValueAsString("GroupName"));18671868if (AnyRemarks && AnyNonRemarks)1869PrintFatalError(1870DiagGroup->getLoc(),1871"Diagnostic group contains both remark and non-remark diagnostics");1872return AnyRemarks;1873}18741875std::string getDefaultSeverity(const Record *Diag) {1876return std::string(1877Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));1878}18791880std::set<std::string>1881getDefaultSeverities(const Record *DiagGroup,1882const std::map<std::string, GroupInfo> &DiagsInGroup) {1883std::set<std::string> States;18841885std::function<void(StringRef)> Visit = [&](StringRef GroupName) {1886auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;1887for (const Record *Diag : GroupInfo.DiagsInGroup)1888States.insert(getDefaultSeverity(Diag));1889for (const auto &Name : GroupInfo.SubGroups)1890Visit(Name);1891};1892Visit(DiagGroup->getValueAsString("GroupName"));1893return States;1894}18951896void writeHeader(StringRef Str, raw_ostream &OS, char Kind = '-') {1897OS << Str << "\n" << std::string(Str.size(), Kind) << "\n";1898}18991900void writeDiagnosticText(DiagnosticTextBuilder &Builder, const Record *R,1901StringRef Role, raw_ostream &OS) {1902StringRef Text = R->getValueAsString("Summary");1903if (Text == "%0")1904OS << "The text of this diagnostic is not controlled by Clang.\n\n";1905else {1906std::vector<std::string> Out = Builder.buildForDocumentation(Role, R);1907for (auto &Line : Out)1908OS << Line << "\n";1909OS << "\n";1910}1911}19121913} // namespace1914} // namespace docs19151916void clang::EmitClangDiagDocs(RecordKeeper &Records, raw_ostream &OS) {1917using namespace docs;19181919// Get the documentation introduction paragraph.1920const Record *Documentation = Records.getDef("GlobalDocumentation");1921if (!Documentation) {1922PrintFatalError("The Documentation top-level definition is missing, "1923"no documentation will be generated.");1924return;1925}19261927OS << Documentation->getValueAsString("Intro") << "\n";19281929DiagnosticTextBuilder Builder(Records);19301931std::vector<Record*> Diags =1932Records.getAllDerivedDefinitions("Diagnostic");19331934std::vector<Record*> DiagGroups =1935Records.getAllDerivedDefinitions("DiagGroup");1936llvm::sort(DiagGroups, diagGroupBeforeByName);19371938DiagGroupParentMap DGParentMap(Records);19391940std::map<std::string, GroupInfo> DiagsInGroup;1941groupDiagnostics(Diags, DiagGroups, DiagsInGroup);19421943// Compute the set of diagnostics that are in -Wpedantic.1944{1945RecordSet DiagsInPedanticSet;1946RecordSet GroupsInPedanticSet;1947InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);1948inferPedantic.compute(&DiagsInPedanticSet, &GroupsInPedanticSet);1949auto &PedDiags = DiagsInGroup["pedantic"];1950// Put the diagnostics into a deterministic order.1951RecordVec DiagsInPedantic(DiagsInPedanticSet.begin(),1952DiagsInPedanticSet.end());1953RecordVec GroupsInPedantic(GroupsInPedanticSet.begin(),1954GroupsInPedanticSet.end());1955llvm::sort(DiagsInPedantic, beforeThanCompare);1956llvm::sort(GroupsInPedantic, beforeThanCompare);1957PedDiags.DiagsInGroup.insert(PedDiags.DiagsInGroup.end(),1958DiagsInPedantic.begin(),1959DiagsInPedantic.end());1960for (auto *Group : GroupsInPedantic)1961PedDiags.SubGroups.push_back(1962std::string(Group->getValueAsString("GroupName")));1963}19641965// FIXME: Write diagnostic categories and link to diagnostic groups in each.19661967// Write out the diagnostic groups.1968for (const Record *G : DiagGroups) {1969bool IsRemarkGroup = isRemarkGroup(G, DiagsInGroup);1970auto &GroupInfo =1971DiagsInGroup[std::string(G->getValueAsString("GroupName"))];1972bool IsSynonym = GroupInfo.DiagsInGroup.empty() &&1973GroupInfo.SubGroups.size() == 1;19741975writeHeader(((IsRemarkGroup ? "-R" : "-W") +1976G->getValueAsString("GroupName")).str(),1977OS);19781979if (!IsSynonym) {1980// FIXME: Ideally, all the diagnostics in a group should have the same1981// default state, but that is not currently the case.1982auto DefaultSeverities = getDefaultSeverities(G, DiagsInGroup);1983if (!DefaultSeverities.empty() && !DefaultSeverities.count("Ignored")) {1984bool AnyNonErrors = DefaultSeverities.count("Warning") ||1985DefaultSeverities.count("Remark");1986if (!AnyNonErrors)1987OS << "This diagnostic is an error by default, but the flag ``-Wno-"1988<< G->getValueAsString("GroupName") << "`` can be used to disable "1989<< "the error.\n\n";1990else1991OS << "This diagnostic is enabled by default.\n\n";1992} else if (DefaultSeverities.size() > 1) {1993OS << "Some of the diagnostics controlled by this flag are enabled "1994<< "by default.\n\n";1995}1996}19971998if (!GroupInfo.SubGroups.empty()) {1999if (IsSynonym)2000OS << "Synonym for ";2001else if (GroupInfo.DiagsInGroup.empty())2002OS << "Controls ";2003else2004OS << "Also controls ";20052006bool First = true;2007llvm::sort(GroupInfo.SubGroups);2008for (const auto &Name : GroupInfo.SubGroups) {2009if (!First) OS << ", ";2010OS << "`" << (IsRemarkGroup ? "-R" : "-W") << Name << "`_";2011First = false;2012}2013OS << ".\n\n";2014}20152016if (!GroupInfo.DiagsInGroup.empty()) {2017OS << "**Diagnostic text:**\n\n";2018for (const Record *D : GroupInfo.DiagsInGroup) {2019auto Severity = getDefaultSeverity(D);2020Severity[0] = tolower(Severity[0]);2021if (Severity == "ignored")2022Severity = IsRemarkGroup ? "remark" : "warning";20232024writeDiagnosticText(Builder, D, Severity, OS);2025}2026}20272028auto Doc = G->getValueAsString("Documentation");2029if (!Doc.empty())2030OS << Doc;2031else if (GroupInfo.SubGroups.empty() && GroupInfo.DiagsInGroup.empty())2032OS << "This diagnostic flag exists for GCC compatibility, and has no "2033"effect in Clang.\n";2034OS << "\n";2035}2036}203720382039