1//===-- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// These tablegen backends emit Clang diagnostics tables.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TableGenBackends.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/PointerUnion.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/Format.h"
25#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
27#include "llvm/TableGen/StringToOffsetTable.h"
28#include "llvm/TableGen/TableGenBackend.h"
29#include <algorithm>
30#include <cctype>
31#include <functional>
32#include <map>
33#include <optional>
34#include <set>
35using namespace llvm;
36
37//===----------------------------------------------------------------------===//
38// Diagnostic category computation code.
39//===----------------------------------------------------------------------===//
40
41namespace {
42class DiagGroupParentMap {
43 const RecordKeeper &Records;
44 std::map<const Record *, std::vector<const Record *>> Mapping;
45
46public:
47 DiagGroupParentMap(const RecordKeeper &records) : Records(records) {
48 for (const Record *Group : Records.getAllDerivedDefinitions(ClassName: "DiagGroup"))
49 for (const Record *SubGroup : Group->getValueAsListOfDefs(FieldName: "SubGroups"))
50 Mapping[SubGroup].push_back(x: Group);
51 }
52
53 ArrayRef<const Record *> getParents(const Record *Group) {
54 return Mapping[Group];
55 }
56};
57} // end anonymous namespace.
58
59static StringRef
60getCategoryFromDiagGroup(const Record *Group,
61 DiagGroupParentMap &DiagGroupParents) {
62 // If the DiagGroup has a category, return it.
63 StringRef CatName = Group->getValueAsString(FieldName: "CategoryName");
64 if (!CatName.empty()) return CatName;
65
66 // The diag group may the subgroup of one or more other diagnostic groups,
67 // check these for a category as well.
68 for (const Record *Parent : DiagGroupParents.getParents(Group)) {
69 CatName = getCategoryFromDiagGroup(Group: Parent, DiagGroupParents);
70 if (!CatName.empty()) return CatName;
71 }
72 return "";
73}
74
75/// getDiagnosticCategory - Return the category that the specified diagnostic
76/// lives in.
77static StringRef getDiagnosticCategory(const Record *R,
78 DiagGroupParentMap &DiagGroupParents) {
79 // If the diagnostic is in a group, and that group has a category, use it.
80 if (const auto *Group = dyn_cast<DefInit>(Val: R->getValueInit(FieldName: "Group"))) {
81 // Check the diagnostic's diag group for a category.
82 StringRef CatName =
83 getCategoryFromDiagGroup(Group: Group->getDef(), DiagGroupParents);
84 if (!CatName.empty()) return CatName;
85 }
86
87 // If the diagnostic itself has a category, get it.
88 return R->getValueAsString(FieldName: "CategoryName");
89}
90
91namespace {
92 class DiagCategoryIDMap {
93 const RecordKeeper &Records;
94 StringMap<unsigned> CategoryIDs;
95 std::vector<StringRef> CategoryStrings;
96
97 public:
98 DiagCategoryIDMap(const RecordKeeper &records) : Records(records) {
99 DiagGroupParentMap ParentInfo(Records);
100
101 // The zero'th category is "".
102 CategoryStrings.push_back(x: "");
103 CategoryIDs[""] = 0;
104
105 for (const Record *Diag :
106 Records.getAllDerivedDefinitions(ClassName: "Diagnostic")) {
107 StringRef Category = getDiagnosticCategory(R: Diag, DiagGroupParents&: ParentInfo);
108 if (Category.empty()) continue; // Skip diags with no category.
109
110 unsigned &ID = CategoryIDs[Category];
111 if (ID != 0) continue; // Already seen.
112
113 ID = CategoryStrings.size();
114 CategoryStrings.push_back(x: Category);
115 }
116 }
117
118 unsigned getID(StringRef CategoryString) {
119 return CategoryIDs[CategoryString];
120 }
121
122 typedef std::vector<StringRef>::const_iterator const_iterator;
123 const_iterator begin() const { return CategoryStrings.begin(); }
124 const_iterator end() const { return CategoryStrings.end(); }
125 };
126
127 struct GroupInfo {
128 StringRef GroupName;
129 std::vector<const Record*> DiagsInGroup;
130 std::vector<StringRef> SubGroups;
131 unsigned IDNo = 0;
132
133 SmallVector<const Record *, 1> Defs;
134
135 GroupInfo() = default;
136 };
137} // end anonymous namespace.
138
139static bool diagGroupBeforeByName(const Record *LHS, const Record *RHS) {
140 return LHS->getValueAsString(FieldName: "GroupName") <
141 RHS->getValueAsString(FieldName: "GroupName");
142}
143
144using DiagsInGroupTy = std::map<StringRef, GroupInfo>;
145
146/// Invert the 1-[0/1] mapping of diags to group into a one to many
147/// mapping of groups to diags in the group.
148static void groupDiagnostics(ArrayRef<const Record *> Diags,
149 ArrayRef<const Record *> DiagGroups,
150 DiagsInGroupTy &DiagsInGroup) {
151 for (const Record *R : Diags) {
152 const auto *DI = dyn_cast<DefInit>(Val: R->getValueInit(FieldName: "Group"));
153 if (!DI)
154 continue;
155 assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&
156 "Note can't be in a DiagGroup");
157 StringRef GroupName = DI->getDef()->getValueAsString(FieldName: "GroupName");
158 DiagsInGroup[GroupName].DiagsInGroup.push_back(x: R);
159 }
160
161 // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
162 // groups (these are warnings that GCC supports that clang never produces).
163 for (const Record *Group : DiagGroups) {
164 GroupInfo &GI = DiagsInGroup[Group->getValueAsString(FieldName: "GroupName")];
165 GI.GroupName = Group->getName();
166 GI.Defs.push_back(Elt: Group);
167
168 for (const Record *SubGroup : Group->getValueAsListOfDefs(FieldName: "SubGroups"))
169 GI.SubGroups.push_back(x: SubGroup->getValueAsString(FieldName: "GroupName"));
170 }
171
172 // Assign unique ID numbers to the groups.
173 for (auto [IdNo, Iter] : enumerate(First&: DiagsInGroup))
174 Iter.second.IDNo = IdNo;
175
176 // Warn if the same group is defined more than once (including implicitly).
177 for (auto &Group : DiagsInGroup) {
178 if (Group.second.Defs.size() == 1 &&
179 (!Group.second.Defs.front()->isAnonymous() ||
180 Group.second.DiagsInGroup.size() <= 1))
181 continue;
182
183 bool First = true;
184 for (const Record *Def : Group.second.Defs) {
185 // Skip implicit definitions from diagnostics; we'll report those
186 // separately below.
187 bool IsImplicit = false;
188 for (const Record *Diag : Group.second.DiagsInGroup) {
189 if (cast<DefInit>(Val: Diag->getValueInit(FieldName: "Group"))->getDef() == Def) {
190 IsImplicit = true;
191 break;
192 }
193 }
194 if (IsImplicit)
195 continue;
196
197 SMLoc Loc = Def->getLoc().front();
198 if (First) {
199 PrintError(ErrorLoc: Loc, Msg: Twine("group '") + Group.first +
200 "' is defined more than once");
201 First = false;
202 } else {
203 SrcMgr.PrintMessage(Loc, Kind: SourceMgr::DK_Note, Msg: "also defined here");
204 }
205 }
206
207 for (const Record *Diag : Group.second.DiagsInGroup) {
208 if (!cast<DefInit>(Val: Diag->getValueInit(FieldName: "Group"))->getDef()->isAnonymous())
209 continue;
210
211 SMLoc Loc = Diag->getLoc().front();
212 if (First) {
213 PrintError(ErrorLoc: Loc, Msg: Twine("group '") + Group.first +
214 "' is implicitly defined more than once");
215 First = false;
216 } else {
217 SrcMgr.PrintMessage(Loc, Kind: SourceMgr::DK_Note,
218 Msg: "also implicitly defined here");
219 }
220 }
221 }
222}
223
224//===----------------------------------------------------------------------===//
225// Infer members of -Wpedantic.
226//===----------------------------------------------------------------------===//
227
228typedef std::vector<const Record *> RecordVec;
229typedef DenseSet<const Record *> RecordSet;
230typedef PointerUnion<RecordVec *, RecordSet *> VecOrSet;
231
232namespace {
233class InferPedantic {
234 typedef DenseMap<const Record *, std::pair<unsigned, std::optional<unsigned>>>
235 GMap;
236
237 DiagGroupParentMap &DiagGroupParents;
238 ArrayRef<const Record *> Diags;
239 const std::vector<const Record *> DiagGroups;
240 DiagsInGroupTy &DiagsInGroup;
241 DenseSet<const Record *> DiagsSet;
242 GMap GroupCount;
243public:
244 InferPedantic(DiagGroupParentMap &DiagGroupParents,
245 ArrayRef<const Record *> Diags,
246 ArrayRef<const Record *> DiagGroups,
247 DiagsInGroupTy &DiagsInGroup)
248 : DiagGroupParents(DiagGroupParents), Diags(Diags),
249 DiagGroups(DiagGroups), DiagsInGroup(DiagsInGroup) {}
250
251 /// Compute the set of diagnostics and groups that are immediately
252 /// in -Wpedantic.
253 void compute(VecOrSet DiagsInPedantic,
254 VecOrSet GroupsInPedantic);
255
256private:
257 /// Determine whether a group is a subgroup of another group.
258 bool isSubGroupOfGroup(const Record *Group, StringRef RootGroupName);
259
260 /// Determine if the diagnostic is an extension.
261 bool isExtension(const Record *Diag);
262
263 /// Determine if the diagnostic is off by default.
264 bool isOffByDefault(const Record *Diag);
265
266 /// Increment the count for a group, and transitively marked
267 /// parent groups when appropriate.
268 void markGroup(const Record *Group);
269
270 /// Return true if the diagnostic is in a pedantic group.
271 bool groupInPedantic(const Record *Group, bool increment = false);
272};
273} // end anonymous namespace
274
275bool InferPedantic::isSubGroupOfGroup(const Record *Group, StringRef GName) {
276 StringRef GroupName = Group->getValueAsString(FieldName: "GroupName");
277 if (GName == GroupName)
278 return true;
279
280 for (const Record *Parent : DiagGroupParents.getParents(Group))
281 if (isSubGroupOfGroup(Group: Parent, GName))
282 return true;
283
284 return false;
285}
286
287/// Determine if the diagnostic is an extension.
288bool InferPedantic::isExtension(const Record *Diag) {
289 return Diag->getValueAsDef(FieldName: "Class")->getName() == "CLASS_EXTENSION";
290}
291
292bool InferPedantic::isOffByDefault(const Record *Diag) {
293 return Diag->getValueAsDef(FieldName: "DefaultSeverity")->getValueAsString(FieldName: "Name") ==
294 "Ignored";
295}
296
297bool InferPedantic::groupInPedantic(const Record *Group, bool increment) {
298 GMap::mapped_type &V = GroupCount[Group];
299 // Lazily compute the threshold value for the group count.
300 if (!V.second) {
301 const GroupInfo &GI = DiagsInGroup[Group->getValueAsString(FieldName: "GroupName")];
302 V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();
303 }
304
305 if (increment)
306 ++V.first;
307
308 // Consider a group in -Wpendatic IFF if has at least one diagnostic
309 // or subgroup AND all of those diagnostics and subgroups are covered
310 // by -Wpedantic via our computation.
311 return V.first != 0 && V.first == *V.second;
312}
313
314void InferPedantic::markGroup(const Record *Group) {
315 // If all the diagnostics and subgroups have been marked as being
316 // covered by -Wpedantic, increment the count of parent groups. Once the
317 // group's count is equal to the number of subgroups and diagnostics in
318 // that group, we can safely add this group to -Wpedantic.
319 if (groupInPedantic(Group, /* increment */ true))
320 for (const Record *Parent : DiagGroupParents.getParents(Group))
321 markGroup(Group: Parent);
322}
323
324void InferPedantic::compute(VecOrSet DiagsInPedantic,
325 VecOrSet GroupsInPedantic) {
326 // All extensions that are not on by default are implicitly in the
327 // "pedantic" group. For those that aren't explicitly included in -Wpedantic,
328 // mark them for consideration to be included in -Wpedantic directly.
329 for (const Record *R : Diags) {
330 if (!isExtension(Diag: R) || !isOffByDefault(Diag: R))
331 continue;
332 DiagsSet.insert(V: R);
333 if (const auto *Group = dyn_cast<DefInit>(Val: R->getValueInit(FieldName: "Group"))) {
334 const Record *GroupRec = Group->getDef();
335 if (!isSubGroupOfGroup(Group: GroupRec, GName: "pedantic")) {
336 markGroup(Group: GroupRec);
337 }
338 }
339 }
340
341 // Compute the set of diagnostics that are directly in -Wpedantic. We
342 // march through Diags a second time to ensure the results are emitted
343 // in deterministic order.
344 for (const Record *R : Diags) {
345 if (!DiagsSet.count(V: R))
346 continue;
347 // Check if the group is implicitly in -Wpedantic. If so,
348 // the diagnostic should not be directly included in the -Wpedantic
349 // diagnostic group.
350 if (const auto *Group = dyn_cast<DefInit>(Val: R->getValueInit(FieldName: "Group")))
351 if (groupInPedantic(Group: Group->getDef()))
352 continue;
353
354 // The diagnostic is not included in a group that is (transitively) in
355 // -Wpedantic. Include it in -Wpedantic directly.
356 if (auto *V = dyn_cast<RecordVec *>(Val&: DiagsInPedantic))
357 V->push_back(x: R);
358 else
359 cast<RecordSet *>(Val&: DiagsInPedantic)->insert(V: R);
360 }
361
362 if (!GroupsInPedantic)
363 return;
364
365 // Compute the set of groups that are directly in -Wpedantic. We
366 // march through the groups to ensure the results are emitted
367 /// in a deterministc order.
368 for (const Record *Group : DiagGroups) {
369 if (!groupInPedantic(Group))
370 continue;
371
372 const std::vector<const Record *> &Parents =
373 DiagGroupParents.getParents(Group);
374 bool AllParentsInPedantic =
375 all_of(Range: Parents, P: [&](const Record *R) { return groupInPedantic(Group: R); });
376 // If all the parents are in -Wpedantic, this means that this diagnostic
377 // group will be indirectly included by -Wpedantic already. In that
378 // case, do not add it directly to -Wpedantic. If the group has no
379 // parents, obviously it should go into -Wpedantic.
380 if (Parents.size() > 0 && AllParentsInPedantic)
381 continue;
382
383 if (auto *V = dyn_cast<RecordVec *>(Val&: GroupsInPedantic))
384 V->push_back(x: Group);
385 else
386 cast<RecordSet *>(Val&: GroupsInPedantic)->insert(V: Group);
387 }
388}
389
390namespace {
391enum PieceKind {
392 MultiPieceClass,
393 TextPieceClass,
394 PlaceholderPieceClass,
395 SelectPieceClass,
396 EnumSelectPieceClass,
397 PluralPieceClass,
398 DiffPieceClass,
399 SubstitutionPieceClass,
400};
401
402enum ModifierType {
403 MT_Unknown,
404 MT_Placeholder,
405 MT_Select,
406 MT_EnumSelect,
407 MT_Sub,
408 MT_Plural,
409 MT_Diff,
410 MT_Ordinal,
411 MT_Human,
412 MT_S,
413 MT_Q,
414 MT_ObjCClass,
415 MT_ObjCInstance,
416 MT_Quoted,
417};
418
419static StringRef getModifierName(ModifierType MT) {
420 switch (MT) {
421 case MT_EnumSelect:
422 case MT_Select:
423 return "select";
424 case MT_Sub:
425 return "sub";
426 case MT_Diff:
427 return "diff";
428 case MT_Plural:
429 return "plural";
430 case MT_Ordinal:
431 return "ordinal";
432 case MT_Human:
433 return "human";
434 case MT_S:
435 return "s";
436 case MT_Q:
437 return "q";
438 case MT_Placeholder:
439 return "";
440 case MT_ObjCClass:
441 return "objcclass";
442 case MT_ObjCInstance:
443 return "objcinstance";
444 case MT_Quoted:
445 return "quoted";
446 case MT_Unknown:
447 llvm_unreachable("invalid modifier type");
448 }
449 // Unhandled case
450 llvm_unreachable("invalid modifier type");
451}
452
453struct Piece {
454 // This type and its derived classes are move-only.
455 Piece(PieceKind Kind) : ClassKind(Kind) {}
456 Piece(Piece const &O) = delete;
457 Piece &operator=(Piece const &) = delete;
458 virtual ~Piece() {}
459
460 PieceKind getPieceClass() const { return ClassKind; }
461 static bool classof(const Piece *) { return true; }
462
463private:
464 PieceKind ClassKind;
465};
466
467struct MultiPiece : Piece {
468 MultiPiece() : Piece(MultiPieceClass) {}
469 MultiPiece(std::vector<Piece *> Pieces)
470 : Piece(MultiPieceClass), Pieces(std::move(Pieces)) {}
471
472 std::vector<Piece *> Pieces;
473
474 static bool classof(const Piece *P) {
475 return P->getPieceClass() == MultiPieceClass;
476 }
477};
478
479struct TextPiece : Piece {
480 StringRef Role;
481 std::string Text;
482 TextPiece(StringRef Text, StringRef Role = "")
483 : Piece(TextPieceClass), Role(Role), Text(Text.str()) {}
484
485 static bool classof(const Piece *P) {
486 return P->getPieceClass() == TextPieceClass;
487 }
488};
489
490struct PlaceholderPiece : Piece {
491 ModifierType Kind;
492 int Index;
493 PlaceholderPiece(ModifierType Kind, int Index)
494 : Piece(PlaceholderPieceClass), Kind(Kind), Index(Index) {}
495
496 static bool classof(const Piece *P) {
497 return P->getPieceClass() == PlaceholderPieceClass;
498 }
499};
500
501struct SelectPiece : Piece {
502protected:
503 SelectPiece(PieceKind Kind, ModifierType ModKind)
504 : Piece(Kind), ModKind(ModKind) {}
505
506public:
507 SelectPiece(ModifierType ModKind) : SelectPiece(SelectPieceClass, ModKind) {}
508
509 ModifierType ModKind;
510 std::vector<Piece *> Options;
511 int Index = 0;
512
513 static bool classof(const Piece *P) {
514 return P->getPieceClass() == SelectPieceClass ||
515 P->getPieceClass() == EnumSelectPieceClass ||
516 P->getPieceClass() == PluralPieceClass;
517 }
518};
519
520struct EnumSelectPiece : SelectPiece {
521 EnumSelectPiece() : SelectPiece(EnumSelectPieceClass, MT_EnumSelect) {}
522
523 StringRef EnumName;
524 std::vector<StringRef> OptionEnumNames;
525
526 static bool classof(const Piece *P) {
527 return P->getPieceClass() == EnumSelectPieceClass;
528 }
529};
530
531struct EnumValuePiece : Piece {
532 ModifierType Kind;
533};
534
535struct PluralPiece : SelectPiece {
536 PluralPiece() : SelectPiece(PluralPieceClass, MT_Plural) {}
537
538 std::vector<Piece *> OptionPrefixes;
539 int Index = 0;
540
541 static bool classof(const Piece *P) {
542 return P->getPieceClass() == PluralPieceClass;
543 }
544};
545
546struct DiffPiece : Piece {
547 DiffPiece() : Piece(DiffPieceClass) {}
548
549 Piece *Parts[4] = {};
550 int Indexes[2] = {};
551
552 static bool classof(const Piece *P) {
553 return P->getPieceClass() == DiffPieceClass;
554 }
555};
556
557struct SubstitutionPiece : Piece {
558 SubstitutionPiece() : Piece(SubstitutionPieceClass) {}
559
560 std::string Name;
561 std::vector<int> Modifiers;
562
563 static bool classof(const Piece *P) {
564 return P->getPieceClass() == SubstitutionPieceClass;
565 }
566};
567
568/// Diagnostic text, parsed into pieces.
569
570
571struct DiagnosticTextBuilder {
572 DiagnosticTextBuilder(DiagnosticTextBuilder const &) = delete;
573 DiagnosticTextBuilder &operator=(DiagnosticTextBuilder const &) = delete;
574
575 DiagnosticTextBuilder(const RecordKeeper &Records) {
576 // Build up the list of substitution records.
577 for (auto *S : Records.getAllDerivedDefinitions(ClassName: "TextSubstitution")) {
578 EvaluatingRecordGuard Guard(&EvaluatingRecord, S);
579 Substitutions.try_emplace(
580 Key: S->getName(), Args: DiagText(*this, S->getValueAsString(FieldName: "Substitution")));
581 }
582
583 // Check that no diagnostic definitions have the same name as a
584 // substitution.
585 for (const Record *Diag : Records.getAllDerivedDefinitions(ClassName: "Diagnostic")) {
586 StringRef Name = Diag->getName();
587 if (Substitutions.count(Key: Name))
588 llvm::PrintFatalError(
589 ErrorLoc: Diag->getLoc(),
590 Msg: "Diagnostic '" + Name +
591 "' has same name as TextSubstitution definition");
592 }
593 }
594
595 std::string buildForDocumentation(StringRef Role, const Record *R);
596 std::string buildForDefinition(const Record *R);
597 llvm::SmallVector<std::pair<
598 std::string, llvm::SmallVector<std::pair<unsigned, std::string>>>>
599 buildForEnum(const Record *R);
600
601 Piece *getSubstitution(SubstitutionPiece *S) const {
602 auto It = Substitutions.find(Key: S->Name);
603 if (It == Substitutions.end())
604 llvm::PrintFatalError(Msg: "Failed to find substitution with name: " +
605 S->Name);
606 return It->second.Root;
607 }
608
609 [[noreturn]] void PrintFatalError(Twine const &Msg) const {
610 assert(EvaluatingRecord && "not evaluating a record?");
611 llvm::PrintFatalError(ErrorLoc: EvaluatingRecord->getLoc(), Msg);
612 }
613
614private:
615 struct DiagText {
616 DiagnosticTextBuilder &Builder;
617 std::vector<Piece *> AllocatedPieces;
618 Piece *Root = nullptr;
619
620 template <class T, class... Args> T *New(Args &&... args) {
621 static_assert(std::is_base_of<Piece, T>::value, "must be piece");
622 T *Mem = new T(std::forward<Args>(args)...);
623 AllocatedPieces.push_back(Mem);
624 return Mem;
625 }
626
627 DiagText(DiagnosticTextBuilder &Builder, StringRef Text)
628 : Builder(Builder), Root(parseDiagText(Text, Stop: StopAt::End)) {}
629
630 enum class StopAt {
631 // Parse until the end of the string.
632 End,
633 // Additionally stop if we hit a non-nested '|' or '}'.
634 PipeOrCloseBrace,
635 // Additionally stop if we hit a non-nested '$'.
636 Dollar,
637 };
638
639 Piece *parseDiagText(StringRef &Text, StopAt Stop);
640 int parseModifier(StringRef &) const;
641
642 public:
643 DiagText(DiagText &&O) noexcept
644 : Builder(O.Builder), AllocatedPieces(std::move(O.AllocatedPieces)),
645 Root(O.Root) {
646 O.Root = nullptr;
647 }
648 // The move assignment operator is defined as deleted pending further
649 // motivation.
650 DiagText &operator=(DiagText &&) = delete;
651
652 // The copy constrcutor and copy assignment operator is defined as deleted
653 // pending further motivation.
654 DiagText(const DiagText &) = delete;
655 DiagText &operator=(const DiagText &) = delete;
656
657 ~DiagText() {
658 for (Piece *P : AllocatedPieces)
659 delete P;
660 }
661 };
662
663private:
664 const Record *EvaluatingRecord = nullptr;
665 struct EvaluatingRecordGuard {
666 EvaluatingRecordGuard(const Record **Dest, const Record *New)
667 : Dest(Dest), Old(*Dest) {
668 *Dest = New;
669 }
670 ~EvaluatingRecordGuard() { *Dest = Old; }
671 const Record **Dest;
672 const Record *Old;
673 };
674
675 StringMap<DiagText> Substitutions;
676};
677
678template <class Derived> struct DiagTextVisitor {
679 using ModifierMappingsType = std::optional<std::vector<int>>;
680
681private:
682 Derived &getDerived() { return static_cast<Derived &>(*this); }
683
684public:
685 std::vector<int>
686 getSubstitutionMappings(SubstitutionPiece *P,
687 const ModifierMappingsType &Mappings) const {
688 std::vector<int> NewMappings;
689 for (int Idx : P->Modifiers)
690 NewMappings.push_back(mapIndex(Idx, Mappings));
691 return NewMappings;
692 }
693
694 struct SubstitutionContext {
695 SubstitutionContext(DiagTextVisitor &Visitor, SubstitutionPiece *P)
696 : Visitor(Visitor) {
697 Substitution = Visitor.Builder.getSubstitution(S: P);
698 OldMappings = std::move(Visitor.ModifierMappings);
699 std::vector<int> NewMappings =
700 Visitor.getSubstitutionMappings(P, Mappings: OldMappings);
701 Visitor.ModifierMappings = std::move(NewMappings);
702 }
703
704 ~SubstitutionContext() {
705 Visitor.ModifierMappings = std::move(OldMappings);
706 }
707
708 private:
709 DiagTextVisitor &Visitor;
710 std::optional<std::vector<int>> OldMappings;
711
712 public:
713 Piece *Substitution;
714 };
715
716public:
717 DiagTextVisitor(DiagnosticTextBuilder &Builder) : Builder(Builder) {}
718
719 void Visit(Piece *P) {
720 switch (P->getPieceClass()) {
721#define CASE(T) \
722 case T##PieceClass: \
723 return getDerived().Visit##T(static_cast<T##Piece *>(P))
724 CASE(Multi);
725 CASE(Text);
726 CASE(Placeholder);
727 CASE(Select);
728 CASE(EnumSelect);
729 CASE(Plural);
730 CASE(Diff);
731 CASE(Substitution);
732#undef CASE
733 }
734 }
735
736 void VisitSubstitution(SubstitutionPiece *P) {
737 SubstitutionContext Guard(*this, P);
738 Visit(P: Guard.Substitution);
739 }
740
741 int mapIndex(int Idx,
742 ModifierMappingsType const &ModifierMappings) const {
743 if (!ModifierMappings)
744 return Idx;
745 if (ModifierMappings->size() <= static_cast<unsigned>(Idx))
746 Builder.PrintFatalError(Msg: "Modifier value '" + std::to_string(val: Idx) +
747 "' is not valid for this mapping (has " +
748 std::to_string(val: ModifierMappings->size()) +
749 " mappings)");
750 return (*ModifierMappings)[Idx];
751 }
752
753 int mapIndex(int Idx) const {
754 return mapIndex(Idx, ModifierMappings);
755 }
756
757protected:
758 DiagnosticTextBuilder &Builder;
759 ModifierMappingsType ModifierMappings;
760};
761
762/// Markers written in front of a table cell. Nested tables are distinguished
763/// by indentation rather than by fence length: openCell indents the
764/// continuation lines of a cell by the width of the marker written here, which
765/// puts an inner fence exactly one marker to the right of its parent's. The
766/// two markers must therefore stay the same width.
767constexpr StringRef RowMarker = "* - ";
768constexpr StringRef ColumnMarker = " - ";
769static_assert(RowMarker.size() == ColumnMarker.size());
770
771struct DiagTextDocPrinter : DiagTextVisitor<DiagTextDocPrinter> {
772 using BaseTy = DiagTextVisitor<DiagTextDocPrinter>;
773 DiagTextDocPrinter(DiagnosticTextBuilder &Builder, std::string &Result)
774 : BaseTy(Builder), Result(Result) {}
775
776 bool containsTablePiece(Piece *P) const {
777 if (isa<SelectPiece, DiffPiece>(Val: P))
778 return true;
779 if (auto *Multi = dyn_cast<MultiPiece>(Val: P))
780 return any_of(Range&: Multi->Pieces,
781 P: [this](Piece *Child) { return containsTablePiece(P: Child); });
782 if (auto *Substitution = dyn_cast<SubstitutionPiece>(Val: P))
783 return containsTablePiece(P: Builder.getSubstitution(S: Substitution));
784 return false;
785 }
786
787 /// Append \p P without letting it open a table of its own: a MultiPiece is
788 /// spliced in piece by piece and a substitution is replaced by its
789 /// expansion. Only pieces that contain no table belong here.
790 void appendInline(Piece *P) {
791 assert(!containsTablePiece(P));
792 if (auto *Multi = dyn_cast<MultiPiece>(Val: P)) {
793 for (Piece *Child : Multi->Pieces)
794 appendInline(P: Child);
795 } else if (auto *Substitution = dyn_cast<SubstitutionPiece>(Val: P)) {
796 SubstitutionContext Guard(*this, Substitution);
797 appendInline(P: Guard.Substitution);
798 } else {
799 Visit(P);
800 }
801 }
802
803 /// Append \p P as the body of a cell, using a table for it only if it needs
804 /// one.
805 void appendCellBody(Piece *P) {
806 if (containsTablePiece(P))
807 Visit(P);
808 else
809 appendInline(P);
810 }
811
812 void VisitSubstitution(SubstitutionPiece *P) {
813 SubstitutionContext Guard(*this, P);
814 appendCellBody(P: Guard.Substitution);
815 }
816
817 /// Start a new line, indenting it to the depth of the enclosing cells. A
818 /// blank line is left blank rather than padded out with spaces.
819 void newLine(bool Blank = false) {
820 Result += '\n';
821 if (!Blank)
822 Result.append(n: Indent, c: ' ');
823 }
824
825 /// The cells of the table currently being written. Cells are written
826 /// straight into \p Result, so the only state a table needs is how many
827 /// cells it has so far and, while a cell is open, where in \p Result that
828 /// cell began.
829 struct TableState {
830 /// Whether every cell starts a row of its own, rather than the first cell
831 /// starting a row that the rest extend.
832 bool OnePiecePerRow;
833 unsigned NumCells = 0;
834 bool CellOpen = false;
835 /// Offsets of the open cell's marker and of the body following it.
836 size_t MarkerStart = 0;
837 size_t BodyStart = 0;
838 };
839
840 void startTable() {
841 Result += ":::{list-table}";
842 newLine();
843 Result += ":widths: auto";
844 newLine(/*Blank=*/true);
845 }
846
847 void endTable() {
848 newLine();
849 Result += ":::";
850 }
851
852 /// Open a cell, unless one is already open, by writing its marker. The
853 /// body's continuation lines line up just past the marker.
854 void openCell(TableState &T) {
855 if (T.CellOpen)
856 return;
857 T.MarkerStart = Result.size();
858 newLine();
859 Result += (T.OnePiecePerRow || T.NumCells == 0) ? RowMarker : ColumnMarker;
860 T.BodyStart = Result.size();
861 T.CellOpen = true;
862 Indent += RowMarker.size();
863 }
864
865 /// Close the open cell. A cell whose body turned out to be empty is dropped
866 /// entirely when \p DropIfEmpty, and otherwise keeps its marker, minus the
867 /// trailing space that would be left dangling.
868 void closeCell(TableState &T, bool DropIfEmpty) {
869 assert(T.CellOpen);
870 T.CellOpen = false;
871 Indent -= RowMarker.size();
872 if (Result.size() != T.BodyStart) {
873 ++T.NumCells;
874 } else if (DropIfEmpty) {
875 Result.resize(n: T.MarkerStart);
876 } else {
877 Result.pop_back();
878 ++T.NumCells;
879 }
880 }
881
882 /// Distribute \p Pieces over the cells of the table \p T is writing. A cell
883 /// is either inline text or a nested table, never a mixture, so inline
884 /// pieces extend the open cell while a piece that needs a table of its own
885 /// closes it and takes a cell to itself.
886 void appendPiecesToCells(ArrayRef<Piece *> Pieces, TableState &T) {
887 for (Piece *Child : Pieces) {
888 if (auto *Substitution = dyn_cast<SubstitutionPiece>(Val: Child);
889 Substitution &&
890 isa<MultiPiece>(Val: Builder.getSubstitution(S: Substitution))) {
891 SubstitutionContext Guard(*this, Substitution);
892 appendPiecesToCells(Pieces: cast<MultiPiece>(Val: Guard.Substitution)->Pieces, T);
893 continue;
894 }
895 if (!containsTablePiece(P: Child)) {
896 openCell(T);
897 appendInline(P: Child);
898 continue;
899 }
900 if (T.CellOpen)
901 closeCell(T, /*DropIfEmpty=*/true);
902 openCell(T);
903 Visit(P: Child);
904 closeCell(T, /*DropIfEmpty=*/true);
905 }
906 }
907
908 void VisitMulti(MultiPiece *P) {
909 if (P->Pieces.empty())
910 return;
911 if (P->Pieces.size() == 1 && containsTablePiece(P: P->Pieces.front())) {
912 Visit(P: P->Pieces.front());
913 return;
914 }
915
916 startTable();
917 TableState T{/*OnePiecePerRow=*/false};
918 appendPiecesToCells(Pieces: P->Pieces, T);
919 if (T.CellOpen)
920 closeCell(T, /*DropIfEmpty=*/true);
921 endTable();
922 }
923
924 void VisitText(TextPiece *P) {
925 StringRef Text = P->Text;
926 while (Text.consume_front(Prefix: " "))
927 Result += "&nbsp;";
928
929 unsigned TrailingSpaces = 0;
930 while (Text.consume_back(Suffix: " "))
931 ++TrailingSpaces;
932
933 bool HasText = !Text.empty();
934 if (HasText && !P->Role.empty()) {
935 Result += "{";
936 Result += P->Role;
937 Result += "}`";
938 }
939 for (char C : Text) {
940 if (C == '`')
941 Result += "&#96;";
942 else {
943 if (C == '\\')
944 Result += '\\';
945 Result += C;
946 }
947 }
948 if (HasText && !P->Role.empty())
949 Result += '`';
950 for (unsigned I = 0; I != TrailingSpaces; ++I)
951 Result += "&nbsp;";
952 }
953
954 void VisitPlaceholder(PlaceholderPiece *P) {
955 // Use a role rather than plain `*A*` emphasis: two adjacent placeholders
956 // would render as `*A**B*`, which CommonMark parses as a single emphasis
957 // run containing literal asterisks.
958 Result += "{placeholder}`";
959 Result += char('A' + mapIndex(Idx: P->Index));
960 Result += '`';
961 }
962
963 void VisitSelect(SelectPiece *P) {
964 startTable();
965 TableState T{/*OnePiecePerRow=*/true};
966 for (Piece *Option : P->Options) {
967 openCell(T);
968 appendCellBody(P: Option);
969 closeCell(T, /*DropIfEmpty=*/false);
970 }
971 endTable();
972 }
973
974 void VisitEnumSelect(EnumSelectPiece *P) {
975 // Document this as if it were a 'select', which properly prints all of the
976 // options correctly in a readable/reasonable manner. There isn't really
977 // anything valuable we could add to readers here.
978 VisitSelect(P);
979 }
980
981 void VisitPlural(PluralPiece *P) { VisitSelect(P); }
982
983 void VisitDiff(DiffPiece *P) {
984 // Render %diff{a $ b $ c|d}e,f as %select{a %e b %f c|d}.
985 PlaceholderPiece E(MT_Placeholder, P->Indexes[0]);
986 PlaceholderPiece F(MT_Placeholder, P->Indexes[1]);
987
988 MultiPiece FirstOption;
989 FirstOption.Pieces.push_back(x: P->Parts[0]);
990 FirstOption.Pieces.push_back(x: &E);
991 FirstOption.Pieces.push_back(x: P->Parts[1]);
992 FirstOption.Pieces.push_back(x: &F);
993 FirstOption.Pieces.push_back(x: P->Parts[2]);
994
995 SelectPiece Select(MT_Diff);
996 Select.Options.push_back(x: &FirstOption);
997 Select.Options.push_back(x: P->Parts[3]);
998
999 VisitSelect(P: &Select);
1000 }
1001
1002 std::string &Result;
1003 /// Number of spaces every new line is indented by, one marker per enclosing
1004 /// cell.
1005 unsigned Indent = 0;
1006};
1007
1008struct DiagEnumPrinter : DiagTextVisitor<DiagEnumPrinter> {
1009public:
1010 using BaseTy = DiagTextVisitor<DiagEnumPrinter>;
1011 using EnumeratorItem = std::pair<unsigned, std::string>;
1012 using EnumeratorList = llvm::SmallVector<EnumeratorItem>;
1013 using ResultTy = llvm::SmallVector<std::pair<std::string, EnumeratorList>>;
1014
1015 DiagEnumPrinter(DiagnosticTextBuilder &Builder, ResultTy &Result)
1016 : BaseTy(Builder), Result(Result) {}
1017
1018 ResultTy &Result;
1019
1020 void VisitMulti(MultiPiece *P) {
1021 for (auto *Child : P->Pieces)
1022 Visit(P: Child);
1023 }
1024 void VisitText(TextPiece *P) {}
1025 void VisitPlaceholder(PlaceholderPiece *P) {}
1026 void VisitDiff(DiffPiece *P) {}
1027 void VisitSelect(SelectPiece *P) {
1028 for (auto *D : P->Options)
1029 Visit(P: D);
1030 }
1031 void VisitPlural(PluralPiece *P) { VisitSelect(P); }
1032 void VisitEnumSelect(EnumSelectPiece *P) {
1033 assert(P->Options.size() == P->OptionEnumNames.size());
1034
1035 if (!P->EnumName.empty()) {
1036 EnumeratorList List;
1037
1038 for (const auto &Tup : llvm::enumerate(First&: P->OptionEnumNames))
1039 if (!Tup.value().empty())
1040 List.emplace_back(Args: Tup.index(), Args&: Tup.value());
1041
1042 Result.emplace_back(Args&: P->EnumName, Args&: List);
1043 }
1044
1045 VisitSelect(P);
1046 }
1047};
1048
1049struct DiagTextPrinter : DiagTextVisitor<DiagTextPrinter> {
1050public:
1051 using BaseTy = DiagTextVisitor<DiagTextPrinter>;
1052 DiagTextPrinter(DiagnosticTextBuilder &Builder, std::string &Result)
1053 : BaseTy(Builder), Result(Result) {}
1054
1055 void VisitMulti(MultiPiece *P) {
1056 for (auto *Child : P->Pieces)
1057 Visit(P: Child);
1058 }
1059 void VisitText(TextPiece *P) { Result += P->Text; }
1060 void VisitPlaceholder(PlaceholderPiece *P) {
1061 Result += "%";
1062 Result += getModifierName(MT: P->Kind);
1063 addInt(Val: mapIndex(Idx: P->Index));
1064 }
1065 void VisitSelect(SelectPiece *P) {
1066 Result += "%";
1067 Result += getModifierName(MT: P->ModKind);
1068 if (P->ModKind == MT_Select || P->ModKind == MT_EnumSelect) {
1069 Result += "{";
1070 for (auto *D : P->Options) {
1071 Visit(P: D);
1072 Result += '|';
1073 }
1074 if (!P->Options.empty())
1075 Result.erase(position: --Result.end());
1076 Result += '}';
1077 }
1078 addInt(Val: mapIndex(Idx: P->Index));
1079 }
1080
1081 void VisitPlural(PluralPiece *P) {
1082 Result += "%plural{";
1083 assert(P->Options.size() == P->OptionPrefixes.size());
1084 for (const auto [Prefix, Option] :
1085 zip_equal(t&: P->OptionPrefixes, u&: P->Options)) {
1086 if (Prefix)
1087 Visit(P: Prefix);
1088 Visit(P: Option);
1089 Result += "|";
1090 }
1091 if (!P->Options.empty())
1092 Result.erase(position: --Result.end());
1093 Result += '}';
1094 addInt(Val: mapIndex(Idx: P->Index));
1095 }
1096
1097 void VisitEnumSelect(EnumSelectPiece *P) {
1098 // Print as if we are a 'select', which will result in the compiler just
1099 // treating this like a normal select. This way we don't have to do any
1100 // special work for the compiler to consume these.
1101 VisitSelect(P);
1102 }
1103
1104 void VisitDiff(DiffPiece *P) {
1105 Result += "%diff{";
1106 Visit(P: P->Parts[0]);
1107 Result += "$";
1108 Visit(P: P->Parts[1]);
1109 Result += "$";
1110 Visit(P: P->Parts[2]);
1111 Result += "|";
1112 Visit(P: P->Parts[3]);
1113 Result += "}";
1114 addInt(Val: mapIndex(Idx: P->Indexes[0]));
1115 Result += ",";
1116 addInt(Val: mapIndex(Idx: P->Indexes[1]));
1117 }
1118
1119 void addInt(int Val) { Result += std::to_string(val: Val); }
1120
1121 std::string &Result;
1122};
1123
1124int DiagnosticTextBuilder::DiagText::parseModifier(StringRef &Text) const {
1125 if (Text.empty() || !isdigit(Text[0]))
1126 Builder.PrintFatalError(Msg: "expected modifier in diagnostic");
1127 int Val = 0;
1128 do {
1129 Val *= 10;
1130 Val += Text[0] - '0';
1131 Text = Text.drop_front();
1132 } while (!Text.empty() && isdigit(Text[0]));
1133 return Val;
1134}
1135
1136Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,
1137 StopAt Stop) {
1138 std::vector<Piece *> Parsed;
1139
1140 constexpr StringLiteral StopSets[] = {"%", "%|}", "%|}$"};
1141 StringRef StopSet = StopSets[static_cast<int>(Stop)];
1142
1143 while (!Text.empty()) {
1144 size_t End = (size_t)-2;
1145 do
1146 End = Text.find_first_of(Chars: StopSet, From: End + 2);
1147 while (
1148 End < Text.size() - 1 && Text[End] == '%' &&
1149 (Text[End + 1] == '%' || Text[End + 1] == '|' || Text[End + 1] == '$'));
1150
1151 if (End) {
1152 Parsed.push_back(x: New<TextPiece>(args: Text.slice(Start: 0, End), args: "diagtext"));
1153 Text = Text.substr(Start: End);
1154 if (Text.empty())
1155 break;
1156 }
1157
1158 if (Text[0] == '|' || Text[0] == '}' || Text[0] == '$')
1159 break;
1160
1161 // Drop the '%'.
1162 Text = Text.drop_front();
1163
1164 // Extract the (optional) modifier.
1165 size_t ModLength = Text.find_first_of(Chars: "0123456789<{");
1166 StringRef Modifier = Text.slice(Start: 0, End: ModLength);
1167 Text = Text.substr(Start: ModLength);
1168 ModifierType ModType = StringSwitch<ModifierType>{Modifier}
1169 .Case(S: "select", Value: MT_Select)
1170 .Case(S: "enum_select", Value: MT_EnumSelect)
1171 .Case(S: "sub", Value: MT_Sub)
1172 .Case(S: "diff", Value: MT_Diff)
1173 .Case(S: "plural", Value: MT_Plural)
1174 .Case(S: "s", Value: MT_S)
1175 .Case(S: "ordinal", Value: MT_Ordinal)
1176 .Case(S: "human", Value: MT_Human)
1177 .Case(S: "q", Value: MT_Q)
1178 .Case(S: "objcclass", Value: MT_ObjCClass)
1179 .Case(S: "objcinstance", Value: MT_ObjCInstance)
1180 .Case(S: "quoted", Value: MT_Quoted)
1181 .Case(S: "", Value: MT_Placeholder)
1182 .Default(Value: MT_Unknown);
1183
1184 auto ExpectAndConsume = [&](StringRef Prefix) {
1185 if (!Text.consume_front(Prefix))
1186 Builder.PrintFatalError(Msg: "expected '" + Prefix + "' while parsing %" +
1187 Modifier);
1188 };
1189
1190 if (ModType != MT_EnumSelect && Text[0] == '<')
1191 Builder.PrintFatalError(Msg: "modifier '<' syntax not valid with %" +
1192 Modifier);
1193
1194 switch (ModType) {
1195 case MT_Unknown:
1196 Builder.PrintFatalError(Msg: "Unknown modifier type: " + Modifier);
1197 case MT_Select: {
1198 SelectPiece *Select = New<SelectPiece>(args: MT_Select);
1199 do {
1200 Text = Text.drop_front(); // '{' or '|'
1201 Select->Options.push_back(
1202 x: parseDiagText(Text, Stop: StopAt::PipeOrCloseBrace));
1203 assert(!Text.empty() && "malformed %select");
1204 } while (Text.front() == '|');
1205 ExpectAndConsume("}");
1206 Select->Index = parseModifier(Text);
1207 Parsed.push_back(x: Select);
1208 continue;
1209 }
1210 case MT_EnumSelect: {
1211 EnumSelectPiece *EnumSelect = New<EnumSelectPiece>();
1212 if (Text[0] != '<')
1213 Builder.PrintFatalError(Msg: "expected '<' after " + Modifier);
1214
1215 Text = Text.drop_front(); // Drop '<'
1216 size_t EnumNameLen = Text.find_first_of(C: '>');
1217 EnumSelect->EnumName = Text.slice(Start: 0, End: EnumNameLen);
1218 Text = Text.substr(Start: EnumNameLen);
1219 ExpectAndConsume(">");
1220
1221 if (Text[0] != '{')
1222 Builder.PrintFatalError(Msg: "expected '{' after " + Modifier);
1223
1224 do {
1225 Text = Text.drop_front(); // '{' or '|'
1226
1227 bool BracketsRequired = false;
1228 if (Text[0] == '%') {
1229 BracketsRequired = true;
1230 Text = Text.drop_front(); // '%'
1231 size_t OptionNameLen = Text.find_first_of(Chars: "{");
1232 EnumSelect->OptionEnumNames.push_back(x: Text.slice(Start: 0, End: OptionNameLen));
1233 Text = Text.substr(Start: OptionNameLen);
1234 } else {
1235 EnumSelect->OptionEnumNames.push_back(x: {});
1236 }
1237
1238 if (BracketsRequired)
1239 ExpectAndConsume("{");
1240 else if (Text.front() == '{') {
1241 Text = Text.drop_front();
1242 BracketsRequired = true;
1243 }
1244
1245 EnumSelect->Options.push_back(
1246 x: parseDiagText(Text, Stop: StopAt::PipeOrCloseBrace));
1247
1248 if (BracketsRequired)
1249 ExpectAndConsume("}");
1250
1251 assert(!Text.empty() && "malformed %select");
1252 } while (Text.front() == '|');
1253
1254 ExpectAndConsume("}");
1255 EnumSelect->Index = parseModifier(Text);
1256 Parsed.push_back(x: EnumSelect);
1257 continue;
1258 }
1259 case MT_Plural: {
1260 PluralPiece *Plural = New<PluralPiece>();
1261 do {
1262 Text = Text.drop_front(); // '{' or '|'
1263 size_t End = Text.find_first_of(C: ':');
1264 if (End == StringRef::npos)
1265 Builder.PrintFatalError(Msg: "expected ':' while parsing %plural");
1266 ++End;
1267 assert(!Text.empty());
1268 Plural->OptionPrefixes.push_back(
1269 x: New<TextPiece>(args: Text.slice(Start: 0, End), args: "diagtext"));
1270 Text = Text.substr(Start: End);
1271 Plural->Options.push_back(
1272 x: parseDiagText(Text, Stop: StopAt::PipeOrCloseBrace));
1273 assert(!Text.empty() && "malformed %plural");
1274 } while (Text.front() == '|');
1275 ExpectAndConsume("}");
1276 Plural->Index = parseModifier(Text);
1277 Parsed.push_back(x: Plural);
1278 continue;
1279 }
1280 case MT_Sub: {
1281 SubstitutionPiece *Sub = New<SubstitutionPiece>();
1282 ExpectAndConsume("{");
1283 size_t NameSize = Text.find_first_of(C: '}');
1284 assert(NameSize != size_t(-1) && "failed to find the end of the name");
1285 assert(NameSize != 0 && "empty name?");
1286 Sub->Name = Text.substr(Start: 0, N: NameSize).str();
1287 Text = Text.drop_front(N: NameSize);
1288 ExpectAndConsume("}");
1289 if (!Text.empty()) {
1290 while (true) {
1291 if (!isdigit(Text[0]))
1292 break;
1293 Sub->Modifiers.push_back(x: parseModifier(Text));
1294 if (!Text.consume_front(Prefix: ","))
1295 break;
1296 assert(!Text.empty() && isdigit(Text[0]) &&
1297 "expected another modifier");
1298 }
1299 }
1300 Parsed.push_back(x: Sub);
1301 continue;
1302 }
1303 case MT_Diff: {
1304 DiffPiece *Diff = New<DiffPiece>();
1305 ExpectAndConsume("{");
1306 Diff->Parts[0] = parseDiagText(Text, Stop: StopAt::Dollar);
1307 ExpectAndConsume("$");
1308 Diff->Parts[1] = parseDiagText(Text, Stop: StopAt::Dollar);
1309 ExpectAndConsume("$");
1310 Diff->Parts[2] = parseDiagText(Text, Stop: StopAt::PipeOrCloseBrace);
1311 ExpectAndConsume("|");
1312 Diff->Parts[3] = parseDiagText(Text, Stop: StopAt::PipeOrCloseBrace);
1313 ExpectAndConsume("}");
1314 Diff->Indexes[0] = parseModifier(Text);
1315 ExpectAndConsume(",");
1316 Diff->Indexes[1] = parseModifier(Text);
1317 Parsed.push_back(x: Diff);
1318 continue;
1319 }
1320 case MT_S: {
1321 SelectPiece *Select = New<SelectPiece>(args&: ModType);
1322 Select->Options.push_back(x: New<TextPiece>(args: ""));
1323 Select->Options.push_back(x: New<TextPiece>(args: "s", args: "diagtext"));
1324 Select->Index = parseModifier(Text);
1325 Parsed.push_back(x: Select);
1326 continue;
1327 }
1328 case MT_Q:
1329 case MT_Placeholder:
1330 case MT_ObjCClass:
1331 case MT_ObjCInstance:
1332 case MT_Quoted:
1333 case MT_Ordinal:
1334 case MT_Human: {
1335 Parsed.push_back(x: New<PlaceholderPiece>(args&: ModType, args: parseModifier(Text)));
1336 continue;
1337 }
1338 }
1339 }
1340
1341 return New<MultiPiece>(args&: Parsed);
1342}
1343
1344std::string DiagnosticTextBuilder::buildForDocumentation(StringRef Severity,
1345 const Record *R) {
1346 EvaluatingRecordGuard Guard(&EvaluatingRecord, R);
1347 StringRef Text = R->getValueAsString(FieldName: "Summary");
1348
1349 DiagText D(*this, Text);
1350 TextPiece *Prefix = D.New<TextPiece>(args&: Severity, args&: Severity);
1351 Prefix->Text += ": ";
1352 auto *MP = dyn_cast<MultiPiece>(Val: D.Root);
1353 if (!MP) {
1354 MP = D.New<MultiPiece>();
1355 MP->Pieces.push_back(x: D.Root);
1356 D.Root = MP;
1357 }
1358 MP->Pieces.insert(position: MP->Pieces.begin(), x: Prefix);
1359 std::string Result;
1360 DiagTextDocPrinter{*this, Result}.Visit(P: D.Root);
1361 // The printer indents the line it is on rather than the line it just wrote,
1362 // so it leaves the last line unterminated.
1363 Result += '\n';
1364 return Result;
1365}
1366
1367DiagEnumPrinter::ResultTy DiagnosticTextBuilder::buildForEnum(const Record *R) {
1368 EvaluatingRecordGuard Guard(&EvaluatingRecord, R);
1369 StringRef Text = R->getValueAsString(FieldName: "Summary");
1370 DiagText D(*this, Text);
1371 DiagEnumPrinter::ResultTy Result;
1372 DiagEnumPrinter{*this, Result}.Visit(P: D.Root);
1373 return Result;
1374}
1375
1376std::string DiagnosticTextBuilder::buildForDefinition(const Record *R) {
1377 EvaluatingRecordGuard Guard(&EvaluatingRecord, R);
1378 StringRef Text = R->getValueAsString(FieldName: "Summary");
1379 DiagText D(*this, Text);
1380 std::string Result;
1381 DiagTextPrinter{*this, Result}.Visit(P: D.Root);
1382 return Result;
1383}
1384
1385} // namespace
1386
1387//===----------------------------------------------------------------------===//
1388// Warning Tables (.inc file) generation.
1389//===----------------------------------------------------------------------===//
1390
1391static bool isError(const Record &Diag) {
1392 return Diag.getValueAsDef(FieldName: "Class")->getName() == "CLASS_ERROR";
1393}
1394
1395static bool isRemark(const Record &Diag) {
1396 return Diag.getValueAsDef(FieldName: "Class")->getName() == "CLASS_REMARK";
1397}
1398
1399// Presumes the text has been split at the first whitespace or hyphen.
1400static bool isExemptAtStart(StringRef Text) {
1401 // Fast path, the first character is lowercase or not alphanumeric.
1402 if (Text.empty() || isLower(C: Text[0]) || !isAlnum(C: Text[0]))
1403 return true;
1404
1405 // If the text is all uppercase (or numbers, +, or _), then we assume it's an
1406 // acronym and that's allowed. This covers cases like ISO, C23, C++14, and
1407 // OBJECT_MODE. However, if there's only a single letter other than "C", we
1408 // do not exempt it so that we catch a case like "A really bad idea" while
1409 // still allowing a case like "C does not allow...".
1410 if (all_of(Range&: Text, P: [](char C) {
1411 return isUpper(C) || isDigit(C) || C == '+' || C == '_';
1412 }))
1413 return Text.size() > 1 || Text[0] == 'C';
1414
1415 // Otherwise, there are a few other exemptions.
1416 return StringSwitch<bool>(Text)
1417 .Case(S: "AddressSanitizer", Value: true)
1418 .Case(S: "CFString", Value: true)
1419 .Case(S: "Clang", Value: true)
1420 .Case(S: "Fuchsia", Value: true)
1421 .Case(S: "GNUstep", Value: true)
1422 .Case(S: "IBOutletCollection", Value: true)
1423 .Case(S: "Itanium", Value: true)
1424 .Case(S: "Microsoft", Value: true)
1425 .Case(S: "Neon", Value: true)
1426 .StartsWith(S: "NSInvocation", Value: true) // NSInvocation, NSInvocation's
1427 .Case(S: "Objective", Value: true) // Objective-C (hyphen is a word boundary)
1428 .Case(S: "OpenACC", Value: true)
1429 .Case(S: "OpenCL", Value: true)
1430 .Case(S: "OpenMP", Value: true)
1431 .Case(S: "Pascal", Value: true)
1432 .Case(S: "Swift", Value: true)
1433 .Case(S: "Unicode", Value: true)
1434 .Case(S: "Vulkan", Value: true)
1435 .Case(S: "WebAssembly", Value: true)
1436 .Default(Value: false);
1437}
1438
1439// Does not presume the text has been split at all.
1440static bool isExemptAtEnd(StringRef Text) {
1441 // Rather than come up with a list of characters that are allowed, we go the
1442 // other way and look only for characters that are not allowed.
1443 switch (Text.back()) {
1444 default:
1445 return true;
1446 case '?':
1447 // Explicitly allowed to support "; did you mean?".
1448 return true;
1449 case '.':
1450 case '!':
1451 return false;
1452 }
1453}
1454
1455static void verifyDiagnosticWording(const Record &Diag) {
1456 StringRef FullDiagText = Diag.getValueAsString(FieldName: "Summary");
1457
1458 auto DiagnoseStart = [&](StringRef Text) {
1459 // Verify that the text does not start with a capital letter, except for
1460 // special cases that are exempt like ISO and C++. Find the first word
1461 // by looking for a word breaking character.
1462 char Separators[] = {' ', '-', ',', '}'};
1463 auto Iter = std::find_first_of(
1464 first1: Text.begin(), last1: Text.end(), first2: std::begin(arr&: Separators), last2: std::end(arr&: Separators));
1465
1466 StringRef First = Text.substr(Start: 0, N: Iter - Text.begin());
1467 if (!isExemptAtStart(Text: First)) {
1468 PrintError(Rec: &Diag,
1469 Msg: "Diagnostics should not start with a capital letter; '" +
1470 First + "' is invalid");
1471 }
1472 };
1473
1474 auto DiagnoseEnd = [&](StringRef Text) {
1475 // Verify that the text does not end with punctuation like '.' or '!'.
1476 if (!isExemptAtEnd(Text)) {
1477 PrintError(Rec: &Diag, Msg: "Diagnostics should not end with punctuation; '" +
1478 Text.substr(Start: Text.size() - 1, N: 1) + "' is invalid");
1479 }
1480 };
1481
1482 // If the diagnostic starts with %select, look through it to see whether any
1483 // of the options will cause a problem.
1484 if (FullDiagText.starts_with(Prefix: "%select{")) {
1485 // Do a balanced delimiter scan from the start of the text to find the
1486 // closing '}', skipping intermediary {} pairs.
1487
1488 size_t BraceCount = 1;
1489 constexpr size_t PercentSelectBraceLen = sizeof("%select{") - 1;
1490 auto Iter = FullDiagText.begin() + PercentSelectBraceLen;
1491 for (auto End = FullDiagText.end(); Iter != End; ++Iter) {
1492 char Ch = *Iter;
1493 if (Ch == '{')
1494 ++BraceCount;
1495 else if (Ch == '}')
1496 --BraceCount;
1497 if (!BraceCount)
1498 break;
1499 }
1500 // Defending against a malformed diagnostic string.
1501 if (BraceCount != 0)
1502 return;
1503
1504 StringRef SelectText =
1505 FullDiagText.substr(Start: PercentSelectBraceLen, N: Iter - FullDiagText.begin() -
1506 PercentSelectBraceLen);
1507 SmallVector<StringRef, 4> SelectPieces;
1508 SelectText.split(A&: SelectPieces, Separator: '|');
1509
1510 // Walk over all of the individual pieces of select text to see if any of
1511 // them start with an invalid character. If any of the select pieces is
1512 // empty, we need to look at the first word after the %select to see
1513 // whether that is invalid or not. If all of the pieces are fine, then we
1514 // don't need to check anything else about the start of the diagnostic.
1515 bool CheckSecondWord = false;
1516 for (StringRef Piece : SelectPieces) {
1517 if (Piece.empty())
1518 CheckSecondWord = true;
1519 else
1520 DiagnoseStart(Piece);
1521 }
1522
1523 if (CheckSecondWord) {
1524 // There was an empty select piece, so we need to check the second
1525 // word. This catches situations like '%select{|fine}0 Not okay'. Add
1526 // two to account for the closing curly brace and the number after it.
1527 StringRef AfterSelect =
1528 FullDiagText.substr(Start: Iter - FullDiagText.begin() + 2).ltrim();
1529 DiagnoseStart(AfterSelect);
1530 }
1531 } else {
1532 // If the start of the diagnostic is not %select, we can check the first
1533 // word and be done with it.
1534 DiagnoseStart(FullDiagText);
1535 }
1536
1537 // If the last character in the diagnostic is a number preceded by a }, scan
1538 // backwards to see if this is for a %select{...}0. If it is, we need to look
1539 // at each piece to see whether it ends in punctuation or not.
1540 bool StillNeedToDiagEnd = true;
1541 if (isDigit(C: FullDiagText.back()) && *(FullDiagText.end() - 2) == '}') {
1542 // Scan backwards to find the opening curly brace.
1543 size_t BraceCount = 1;
1544 auto Iter = FullDiagText.end() - sizeof("}0");
1545 for (auto End = FullDiagText.begin(); Iter != End; --Iter) {
1546 char Ch = *Iter;
1547 if (Ch == '}')
1548 ++BraceCount;
1549 else if (Ch == '{')
1550 --BraceCount;
1551 if (!BraceCount)
1552 break;
1553 }
1554 // Defending against a malformed diagnostic string.
1555 if (BraceCount != 0)
1556 return;
1557
1558 // Continue the backwards scan to find the word before the '{' to see if it
1559 // is 'select'.
1560 constexpr size_t SelectLen = sizeof("select") - 1;
1561 bool IsSelect =
1562 (FullDiagText.substr(Start: Iter - SelectLen - FullDiagText.begin(),
1563 N: SelectLen) == "select");
1564 if (IsSelect) {
1565 // Gather the content between the {} for the select in question so we can
1566 // split it into pieces.
1567 StillNeedToDiagEnd = false; // No longer need to handle the end.
1568 StringRef SelectText =
1569 FullDiagText.substr(Start: Iter - FullDiagText.begin() + /*{*/ 1,
1570 N: FullDiagText.end() - Iter - /*pos before }0*/ 3);
1571 SmallVector<StringRef, 4> SelectPieces;
1572 SelectText.split(A&: SelectPieces, Separator: '|');
1573 for (StringRef Piece : SelectPieces) {
1574 // Not worrying about a situation like: "this is bar. %select{foo|}0".
1575 if (!Piece.empty())
1576 DiagnoseEnd(Piece);
1577 }
1578 }
1579 }
1580
1581 // If we didn't already cover the diagnostic because of a %select, handle it
1582 // now.
1583 if (StillNeedToDiagEnd)
1584 DiagnoseEnd(FullDiagText);
1585
1586 // FIXME: This could also be improved by looking for instances of clang or
1587 // gcc in the diagnostic and recommend Clang or GCC instead. However, this
1588 // runs into odd situations like [[clang::warn_unused_result]],
1589 // #pragma clang, or --unwindlib=libgcc.
1590}
1591
1592/// ClangDiagsCompatIDsEmitter - Emit a set of 'compatibility diagnostic ids'
1593/// that map to a set of 2 regular diagnostic ids each and which are used to
1594/// simplify emitting compatibility warnings.
1595void clang::EmitClangDiagsCompatIDs(const llvm::RecordKeeper &Records,
1596 llvm::raw_ostream &OS,
1597 const std::string &Component) {
1598 ArrayRef<const Record *> Ids =
1599 Records.getAllDerivedDefinitions(ClassName: "CompatWarningId");
1600
1601 StringRef PrevComponent = "";
1602 for (auto [I, R] : enumerate(First: make_pointee_range(Range&: Ids))) {
1603 StringRef DiagComponent = R.getValueAsString(FieldName: "Component");
1604 if (!Component.empty() && Component != DiagComponent)
1605 continue;
1606
1607 StringRef CompatDiagName = R.getValueAsString(FieldName: "Name");
1608 StringRef Diag = R.getValueAsString(FieldName: "Diag");
1609 StringRef DiagPre = R.getValueAsString(FieldName: "DiagPre");
1610 int64_t CXXStdVer = R.getValueAsInt(FieldName: "Std");
1611
1612 // We don't want to create empty enums since some compilers (including
1613 // Clang) warn about that, so these macros are used to avoid having to
1614 // unconditionally write 'enum {' and '};' in the headers.
1615 if (PrevComponent != DiagComponent) {
1616 if (!PrevComponent.empty())
1617 OS << "DIAG_COMPAT_IDS_END()\n";
1618 OS << "DIAG_COMPAT_IDS_BEGIN()\n";
1619 PrevComponent = DiagComponent;
1620 }
1621
1622 // FIXME: We sometimes define multiple compat diagnostics with the same
1623 // name, e.g. 'constexpr_body_invalid_stmt' exists for C++14/20/23. It would
1624 // be nice if we could combine all of them into a single compatibility diag
1625 // id.
1626 OS << "DIAG_COMPAT_ID(" << I << ",";
1627 OS << CompatDiagName << "," << CXXStdVer << "," << Diag << "," << DiagPre;
1628 OS << ")\n";
1629 }
1630
1631 if (!PrevComponent.empty())
1632 OS << "DIAG_COMPAT_IDS_END()\n";
1633}
1634
1635/// ClangDiagsIntefaceEmitter - Emit the diagnostics interface header for
1636/// a Clang component.
1637void clang::EmitClangDiagsInterface(llvm::raw_ostream &OS,
1638 const std::string &Component) {
1639 if (Component.empty())
1640 PrintFatalError(Msg: "'-gen-clang-diags-iface' requires a component name");
1641
1642 std::string ComponentUpper = StringRef(Component).upper();
1643 const char *Comp = Component.c_str();
1644 const char *Upper = ComponentUpper.c_str();
1645
1646 OS << llvm::format(Fmt: R"c++(
1647namespace clang {
1648namespace diag {
1649enum {
1650#define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, NOWERROR, \
1651 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY, STABLE_ID, \
1652 LEGACY_STABLE_IDS) \
1653 ENUM,
1654#define %sSTART
1655#include "clang/Basic/Diagnostic%sKinds.inc"
1656#undef DIAG
1657 NUM_BUILTIN_%s_DIAGNOSTICS
1658};
1659
1660#define DIAG_ENUM(ENUM_NAME) \
1661 namespace ENUM_NAME { \
1662 enum {
1663#define DIAG_ENUM_ITEM(IDX, NAME) NAME = IDX,
1664#define DIAG_ENUM_END() \
1665 } \
1666 ; \
1667 }
1668#include "clang/Basic/Diagnostic%sEnums.inc"
1669#undef DIAG_ENUM_END
1670#undef DIAG_ENUM_ITEM
1671#undef DIAG_ENUM
1672} // end namespace diag
1673
1674namespace diag_compat {
1675#define DIAG_COMPAT_IDS_BEGIN() enum {
1676#define DIAG_COMPAT_IDS_END() \
1677 } \
1678 ;
1679#define DIAG_COMPAT_ID(IDX, NAME, ...) NAME = IDX,
1680#include "clang/Basic/Diagnostic%sCompatIDs.inc"
1681#undef DIAG_COMPAT_ID
1682#undef DIAG_COMPAT_IDS_BEGIN
1683#undef DIAG_COMPAT_IDS_END
1684} // end namespace diag_compat
1685} // end namespace clang
1686)c++",
1687 Vals: Upper, Vals: Comp, Vals: Upper, Vals: Comp, Vals: Comp);
1688}
1689
1690/// ClangDiagsEnumsEmitter - The top-level class emits .def files containing
1691/// declarations of Clang diagnostic enums for selects.
1692void clang::EmitClangDiagsEnums(const RecordKeeper &Records, raw_ostream &OS,
1693 const std::string &Component) {
1694 DiagnosticTextBuilder DiagTextBuilder(Records);
1695 ArrayRef<const Record *> Diags =
1696 Records.getAllDerivedDefinitions(ClassName: "Diagnostic");
1697
1698 llvm::SmallVector<std::pair<const Record *, std::string>> EnumerationNames;
1699
1700 for (const Record &R : make_pointee_range(Range&: Diags)) {
1701 DiagEnumPrinter::ResultTy Enums = DiagTextBuilder.buildForEnum(R: &R);
1702
1703 for (auto &Enumeration : Enums) {
1704 bool ShouldPrint =
1705 Component.empty() || Component == R.getValueAsString(FieldName: "Component");
1706
1707 auto PreviousByName = llvm::find_if(Range&: EnumerationNames, P: [&](auto &Prev) {
1708 return Prev.second == Enumeration.first;
1709 });
1710
1711 if (PreviousByName != EnumerationNames.end()) {
1712 PrintError(Rec: &R,
1713 Msg: "Duplicate enumeration name '" + Enumeration.first + "'");
1714 PrintNote(NoteLoc: PreviousByName->first->getLoc(),
1715 Msg: "Previous diagnostic is here");
1716 }
1717
1718 EnumerationNames.emplace_back(Args: &R, Args&: Enumeration.first);
1719
1720 if (ShouldPrint)
1721 OS << "DIAG_ENUM(" << Enumeration.first << ")\n";
1722
1723 llvm::SmallVector<std::string> EnumeratorNames;
1724 for (auto &Enumerator : Enumeration.second) {
1725 if (llvm::is_contained(Range&: EnumeratorNames, Element: Enumerator.second))
1726 PrintError(Rec: &R,
1727 Msg: "Duplicate enumerator name '" + Enumerator.second + "'");
1728 EnumeratorNames.push_back(Elt: Enumerator.second);
1729
1730 if (ShouldPrint)
1731 OS << "DIAG_ENUM_ITEM(" << Enumerator.first << ", "
1732 << Enumerator.second << ")\n";
1733 }
1734 if (ShouldPrint)
1735 OS << "DIAG_ENUM_END()\n";
1736 }
1737 }
1738}
1739
1740//===----------------------------------------------------------------------===//
1741// Stable ID Tables generation
1742//===----------------------------------------------------------------------===//
1743
1744namespace {
1745
1746/// Holds the string table for all Stable IDs, plus the arrays of legacy Stable
1747/// IDs for renamed diagnostics.
1748class DiagStableIDsMap {
1749 StringToOffsetTable StableIDs;
1750 std::vector<uint32_t> LegacyStableIDs;
1751 llvm::StringMap<uint32_t> LegacyStableIDsStartOffsets;
1752
1753public:
1754 DiagStableIDsMap(const RecordKeeper &Records) {
1755 LegacyStableIDs.push_back(x: 0); // Empty array at offset 0
1756
1757 for (const Record *Diag : Records.getAllDerivedDefinitions(ClassName: "Diagnostic")) {
1758 StringRef StableID = getStableID(R: *Diag);
1759 // Memoize the Stable ID
1760 StableIDs.GetOrAddStringOffset(Str: StableID);
1761
1762 auto LegacyIDList = Diag->getValueAsListOfStrings(FieldName: "LegacyStableIds");
1763 if (!LegacyIDList.empty()) {
1764 // Memoize any Legacy Stable IDs, and list their offsets in an array.
1765 size_t StartOffset = LegacyStableIDs.size();
1766 LegacyStableIDsStartOffsets.insert(
1767 KV: std::make_pair(x: Diag->getName(), y&: StartOffset));
1768 for (const auto LegacyID : LegacyIDList) {
1769 unsigned Offset = StableIDs.GetOrAddStringOffset(Str: LegacyID);
1770 LegacyStableIDs.push_back(x: Offset);
1771 }
1772 LegacyStableIDs.push_back(x: 0); // Terminate the array.
1773 }
1774 }
1775 }
1776
1777 /// Gets the string table offset of the Stable ID for the specified Diagnostic
1778 /// record.
1779 uint32_t getStableIDOffset(const Record &R) const {
1780 return StableIDs.GetStringOffset(Str: getStableID(R)).value();
1781 }
1782
1783 /// Gets the offset in the DiagLegacyStableIDs array of the first element of
1784 /// the diagnostic's list of legacy Stable IDs.
1785 uint32_t getLegacyStableIDsStartOffset(StringRef Name) const {
1786 // `lookup()` will return zero if not found, which is exactly what we want
1787 // anyway.
1788 return LegacyStableIDsStartOffsets.lookup(Key: Name);
1789 }
1790
1791 /// Emit diagnostic stable ID arrays and related data structures.
1792 ///
1793 /// This creates the table of stable IDs, plus the array of arrays of old
1794 /// stable IDs.
1795 ///
1796 /// \code
1797 /// #ifdef GET_DIAG_STABLE_ID_ARRAYS
1798 /// static const int32_t DiagOldStableIds[];
1799 /// static constexpr llvm::StringTable DiagStableIds;
1800 /// #endif
1801 /// \endcode
1802 void emit(raw_ostream &OS, const RecordKeeper &Records) const {
1803 OS << "\n#ifdef GET_DIAG_STABLE_ID_ARRAYS\n";
1804 emitStableIDs(OS);
1805 emitLegacyStableIDs(OS);
1806 emitDescriptions(OS, Records);
1807 OS << "#endif // GET_DIAG_STABLE_ID_ARRAYS\n\n";
1808 }
1809
1810private:
1811 /// Gets the Stable ID for the specified Diagnostic record.
1812 /// The Stable ID can be explicitly specified via the "StableId"
1813 /// property. If not specified explicitly, the Stable ID defaults
1814 /// to the name of the diagnostic.
1815 static StringRef getStableID(const Record &R) {
1816 StringRef StableID = R.getValueAsString(FieldName: "StableId");
1817 return StableID.empty() ? R.getName() : StableID;
1818 }
1819
1820 /// Emit a list of stable IDs, used by both the "StableId" and
1821 /// "LegacyStableIds" properties.
1822 ///
1823 /// This creates an `llvm::StringTable` of all the stable ids in use.
1824 void emitStableIDs(raw_ostream &OS) const {
1825 StableIDs.EmitStringTableDef(OS, Name: "DiagStableIDs");
1826 OS << "\n";
1827 }
1828
1829 /// Emit the array of legacy stable IDs for diagnostics.
1830 ///
1831 /// The array of stable IDs contains for each diagnostic a list of its legacy
1832 /// stable IDs. The individual lists are separated by '0'. Diagnostics with
1833 /// no legacy stable IDs are skipped.
1834 ///
1835 /// \code
1836 /// static const uint16_t DiagOldStableIds[] = {
1837 /// /* Empty */ 0,
1838 /// /* Diag0 */ 142, 0,
1839 /// /* Diag13 */ 265, 322, 399, 0
1840 /// }
1841 /// \endcode
1842 ///
1843 void emitLegacyStableIDs(raw_ostream &OS) const {
1844 OS << "static const uint32_t DiagLegacyStableIDs[] = {\n";
1845
1846 bool StartOfLine = true;
1847 for (auto Offset : LegacyStableIDs) {
1848 if (StartOfLine) {
1849 OS << " ";
1850 StartOfLine = false;
1851 }
1852 OS << Offset << ",";
1853 if (Offset > 0) {
1854 OS << " ";
1855 } else {
1856 OS << "\n";
1857 StartOfLine = true;
1858 }
1859 }
1860 OS << "};\n\n";
1861 }
1862
1863 static void emitDescriptions(raw_ostream &OS, const RecordKeeper &Records) {
1864 DiagnosticTextBuilder DiagTextBuilder(Records);
1865 StringToOffsetTable Descriptions;
1866
1867 OS << "enum {\n";
1868 for (const Record &R :
1869 make_pointee_range(Range: Records.getAllDerivedDefinitions(ClassName: "Diagnostic"))) {
1870 std::string Description = DiagTextBuilder.buildForDefinition(R: &R);
1871 if (Description.size() >= (1U << 12))
1872 PrintFatalError(ErrorLoc: R.getLoc(),
1873 Msg: "diagnostic description exceeds 12-bit length limit");
1874
1875 unsigned Offset = Descriptions.GetOrAddStringOffset(Str: Description);
1876 OS << " DIAG_DESC_OFFSET_" << R.getName() << " = " << Offset << ",\n";
1877 }
1878 OS << "};\n\n";
1879
1880 if (Descriptions.size() >= (1U << 20))
1881 PrintFatalError(Msg: "diagnostic descriptions exceed 20-bit offset limit");
1882 Descriptions.EmitStringTableStorageDef(OS, Name: "StaticDiagInfoDescriptions");
1883 }
1884};
1885} // namespace
1886
1887/// Emit the definitions of the Stable ID and old Stable ID tables.
1888void clang::EmitClangDiagsStableIDs(const RecordKeeper &Records,
1889 raw_ostream &OS) {
1890 DiagStableIDsMap StableIDs(Records);
1891 StableIDs.emit(OS, Records);
1892}
1893
1894/// ClangDiagsDefsEmitter - The top-level class emits .def files containing
1895/// declarations of Clang diagnostics.
1896void clang::EmitClangDiagsDefs(const RecordKeeper &Records, raw_ostream &OS,
1897 const std::string &Component) {
1898 // Write the #if guard
1899 if (!Component.empty()) {
1900 std::string ComponentName = StringRef(Component).upper();
1901 OS << "#ifdef " << ComponentName << "START\n";
1902 OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
1903 << ",\n";
1904 OS << "#undef " << ComponentName << "START\n";
1905 OS << "#endif\n\n";
1906 }
1907
1908 DiagnosticTextBuilder DiagTextBuilder(Records);
1909
1910 ArrayRef<const Record *> Diags =
1911 Records.getAllDerivedDefinitions(ClassName: "Diagnostic");
1912
1913 ArrayRef<const Record *> DiagGroups =
1914 Records.getAllDerivedDefinitions(ClassName: "DiagGroup");
1915
1916 DiagsInGroupTy DiagsInGroup;
1917 groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
1918
1919 DiagCategoryIDMap CategoryIDs(Records);
1920 DiagGroupParentMap DGParentMap(Records);
1921 DiagStableIDsMap StableIDs(Records);
1922
1923 // Compute the set of diagnostics that are in -Wpedantic.
1924 RecordSet DiagsInPedantic;
1925 InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
1926 inferPedantic.compute(DiagsInPedantic: &DiagsInPedantic, GroupsInPedantic: (RecordVec*)nullptr);
1927
1928 for (const Record &R : make_pointee_range(Range&: Diags)) {
1929 // Check if this is an error that is accidentally in a warning
1930 // group.
1931 if (isError(Diag: R)) {
1932 if (const auto *Group = dyn_cast<DefInit>(Val: R.getValueInit(FieldName: "Group"))) {
1933 const Record *GroupRec = Group->getDef();
1934 StringRef GroupName = GroupRec->getValueAsString(FieldName: "GroupName");
1935 PrintFatalError(ErrorLoc: R.getLoc(), Msg: "Error " + R.getName() +
1936 " cannot be in a warning group [" + GroupName + "]");
1937 }
1938 }
1939
1940 // Check that all remarks have an associated diagnostic group.
1941 if (isRemark(Diag: R)) {
1942 if (!isa<DefInit>(Val: R.getValueInit(FieldName: "Group"))) {
1943 PrintFatalError(ErrorLoc: R.getLoc(), Msg: "Error " + R.getName() +
1944 " not in any diagnostic group");
1945 }
1946 }
1947
1948 // Filter by component.
1949 if (!Component.empty() && Component != R.getValueAsString(FieldName: "Component"))
1950 continue;
1951
1952 // Validate diagnostic wording for common issues.
1953 verifyDiagnosticWording(Diag: R);
1954
1955 OS << "DIAG(" << R.getName() << ", ";
1956 OS << R.getValueAsDef(FieldName: "Class")->getName();
1957 OS << ", (unsigned)diag::Severity::"
1958 << R.getValueAsDef(FieldName: "DefaultSeverity")->getValueAsString(FieldName: "Name");
1959
1960 // Description string.
1961 OS << ", \"";
1962 OS.write_escaped(Str: DiagTextBuilder.buildForDefinition(R: &R)) << '"';
1963
1964 // Warning group associated with the diagnostic. This is stored as an index
1965 // into the alphabetically sorted warning group table.
1966 if (const auto *DI = dyn_cast<DefInit>(Val: R.getValueInit(FieldName: "Group"))) {
1967 auto I = DiagsInGroup.find(x: DI->getDef()->getValueAsString(FieldName: "GroupName"));
1968 assert(I != DiagsInGroup.end());
1969 OS << ", " << I->second.IDNo;
1970 } else if (DiagsInPedantic.count(V: &R)) {
1971 auto I = DiagsInGroup.find(x: "pedantic");
1972 assert(I != DiagsInGroup.end() && "pedantic group not defined");
1973 OS << ", " << I->second.IDNo;
1974 } else {
1975 OS << ", 0";
1976 }
1977
1978 // SFINAE response.
1979 OS << ", " << R.getValueAsDef(FieldName: "SFINAE")->getName();
1980
1981 // Default warning has no Werror bit.
1982 if (R.getValueAsBit(FieldName: "WarningNoWerror"))
1983 OS << ", true";
1984 else
1985 OS << ", false";
1986
1987 if (R.getValueAsBit(FieldName: "ShowInSystemHeader"))
1988 OS << ", true";
1989 else
1990 OS << ", false";
1991
1992 if (R.getValueAsBit(FieldName: "ShowInSystemMacro"))
1993 OS << ", true";
1994 else
1995 OS << ", false";
1996
1997 if (R.getValueAsBit(FieldName: "Deferrable"))
1998 OS << ", true";
1999 else
2000 OS << ", false";
2001
2002 // Category number.
2003 OS << ", " << CategoryIDs.getID(CategoryString: getDiagnosticCategory(R: &R, DiagGroupParents&: DGParentMap));
2004
2005 // Stable ID.
2006 uint32_t StableIDOffset = StableIDs.getStableIDOffset(R);
2007 OS << ", " << StableIDOffset;
2008
2009 // Previous Stable IDs.
2010 uint32_t LegacyStableIDsStartOffset =
2011 StableIDs.getLegacyStableIDsStartOffset(Name: R.getName());
2012 OS << ", " << LegacyStableIDsStartOffset;
2013
2014 OS << ")\n";
2015 }
2016}
2017
2018//===----------------------------------------------------------------------===//
2019// Warning Group Tables generation
2020//===----------------------------------------------------------------------===//
2021
2022static std::string getDiagCategoryEnum(StringRef name) {
2023 if (name.empty())
2024 return "DiagCat_None";
2025 SmallString<256> enumName = StringRef("DiagCat_");
2026 for (char C : name)
2027 enumName += isalnum(C) ? C : '_';
2028 return std::string(enumName);
2029}
2030
2031/// Emit the array of diagnostic subgroups.
2032///
2033/// The array of diagnostic subgroups contains for each group a list of its
2034/// subgroups. The individual lists are separated by '-1'. Groups with no
2035/// subgroups are skipped.
2036///
2037/// \code
2038/// static const int16_t DiagSubGroups[] = {
2039/// /* Empty */ -1,
2040/// /* DiagSubGroup0 */ 142, -1,
2041/// /* DiagSubGroup13 */ 265, 322, 399, -1
2042/// }
2043/// \endcode
2044///
2045static void emitDiagSubGroups(DiagsInGroupTy &DiagsInGroup,
2046 RecordVec &GroupsInPedantic, raw_ostream &OS) {
2047 OS << "static const int16_t DiagSubGroups[] = {\n"
2048 << " /* Empty */ -1,\n";
2049 for (auto const &[Name, Group] : DiagsInGroup) {
2050 const bool IsPedantic = Name == "pedantic";
2051 const std::vector<StringRef> &SubGroups = Group.SubGroups;
2052 if (!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty())) {
2053 OS << " /* DiagSubGroup" << Group.IDNo << " */ ";
2054 for (StringRef SubGroup : SubGroups) {
2055 auto RI = DiagsInGroup.find(x: SubGroup);
2056 assert(RI != DiagsInGroup.end() && "Referenced without existing?");
2057 OS << RI->second.IDNo << ", ";
2058 }
2059 // Emit the groups implicitly in "pedantic".
2060 if (IsPedantic) {
2061 for (auto const &Group : GroupsInPedantic) {
2062 StringRef GroupName = Group->getValueAsString(FieldName: "GroupName");
2063 auto RI = DiagsInGroup.find(x: GroupName);
2064 assert(RI != DiagsInGroup.end() && "Referenced without existing?");
2065 OS << RI->second.IDNo << ", ";
2066 }
2067 }
2068
2069 OS << "-1,\n";
2070 }
2071 }
2072 OS << "};\n\n";
2073}
2074
2075/// Emit the list of diagnostic arrays.
2076///
2077/// This data structure is a large array that contains itself arrays of varying
2078/// size. Each array represents a list of diagnostics. The different arrays are
2079/// separated by the value '-1'.
2080///
2081/// \code
2082/// static const int16_t DiagArrays[] = {
2083/// /* Empty */ -1,
2084/// /* DiagArray1 */ diag::warn_pragma_message,
2085/// -1,
2086/// /* DiagArray2 */ diag::warn_abs_too_small,
2087/// diag::warn_unsigned_abs,
2088/// diag::warn_wrong_absolute_value_type,
2089/// -1
2090/// };
2091/// \endcode
2092///
2093static void emitDiagArrays(DiagsInGroupTy &DiagsInGroup,
2094 RecordVec &DiagsInPedantic, raw_ostream &OS) {
2095 OS << "static const int16_t DiagArrays[] = {\n"
2096 << " /* Empty */ -1,\n";
2097 for (const auto &[Name, Group] : DiagsInGroup) {
2098 const bool IsPedantic = Name == "pedantic";
2099
2100 const std::vector<const Record *> &V = Group.DiagsInGroup;
2101 if (!V.empty() || (IsPedantic && !DiagsInPedantic.empty())) {
2102 OS << " /* DiagArray" << Group.IDNo << " */ ";
2103 for (auto *Record : V)
2104 OS << "diag::" << Record->getName() << ", ";
2105 // Emit the diagnostics implicitly in "pedantic".
2106 if (IsPedantic) {
2107 for (auto const &Diag : DiagsInPedantic)
2108 OS << "diag::" << Diag->getName() << ", ";
2109 }
2110 OS << "-1,\n";
2111 }
2112 }
2113 OS << "};\n\n";
2114}
2115
2116/// Emit a list of group names.
2117///
2118/// This creates an `llvm::StringTable` of all the diagnostic group names.
2119static void emitDiagGroupNames(const StringToOffsetTable &GroupNames,
2120 raw_ostream &OS) {
2121 GroupNames.EmitStringTableDef(OS, Name: "DiagGroupNames");
2122 OS << "\n";
2123}
2124
2125/// Emit diagnostic arrays and related data structures.
2126///
2127/// This creates the actual diagnostic array, an array of diagnostic subgroups
2128/// and an array of subgroup names.
2129///
2130/// \code
2131/// #ifdef GET_DIAG_ARRAYS
2132/// static const int16_t DiagArrays[];
2133/// static const int16_t DiagSubGroups[];
2134/// static constexpr llvm::StringTable DiagGroupNames;
2135/// #endif
2136/// \endcode
2137static void emitAllDiagArrays(DiagsInGroupTy &DiagsInGroup,
2138 RecordVec &DiagsInPedantic,
2139 RecordVec &GroupsInPedantic,
2140 const StringToOffsetTable &GroupNames,
2141 raw_ostream &OS) {
2142 OS << "\n#ifdef GET_DIAG_ARRAYS\n";
2143 emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);
2144 emitDiagSubGroups(DiagsInGroup, GroupsInPedantic, OS);
2145 emitDiagGroupNames(GroupNames, OS);
2146 OS << "#endif // GET_DIAG_ARRAYS\n\n";
2147}
2148
2149/// Emit diagnostic table.
2150///
2151/// The table is sorted by the name of the diagnostic group. Each element
2152/// consists of the name of the diagnostic group (given as offset in the
2153/// group name table), a reference to a list of diagnostics (optional) and a
2154/// reference to a set of subgroups (optional).
2155///
2156/// \code
2157/// #ifdef GET_DIAG_TABLE
2158/// {/* abi */ 159, /* DiagArray11 */ 19, /* Empty */ 0},
2159/// {/* aggregate-return */ 180, /* Empty */ 0, /* Empty */ 0},
2160/// {/* all */ 197, /* Empty */ 0, /* DiagSubGroup13 */ 3},
2161/// {/* deprecated */ 1981,/* DiagArray1 */ 348, /* DiagSubGroup3 */ 9},
2162/// #endif
2163/// \endcode
2164static void emitDiagTable(DiagsInGroupTy &DiagsInGroup,
2165 RecordVec &DiagsInPedantic,
2166 RecordVec &GroupsInPedantic,
2167 const StringToOffsetTable &GroupNames,
2168 raw_ostream &OS) {
2169 unsigned MaxLen = 0;
2170
2171 for (auto const &I: DiagsInGroup)
2172 MaxLen = std::max(a: MaxLen, b: (unsigned)I.first.size());
2173
2174 OS << "\n#ifdef DIAG_ENTRY\n";
2175 unsigned SubGroupIndex = 1, DiagArrayIndex = 1;
2176 for (auto const &[Name, GroupInfo] : DiagsInGroup) {
2177 // Group option string.
2178 OS << "DIAG_ENTRY(";
2179 OS << GroupInfo.GroupName << " /* ";
2180
2181 if (Name.find_first_not_of(Chars: "abcdefghijklmnopqrstuvwxyz"
2182 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2183 "0123456789!@#$%^*-+=:?") != std::string::npos)
2184 PrintFatalError(Msg: "Invalid character in diagnostic group '" + Name + "'");
2185 OS << Name << " */, ";
2186 OS << *GroupNames.GetStringOffset(Str: Name) << ", ";
2187
2188 // Special handling for 'pedantic'.
2189 const bool IsPedantic = Name == "pedantic";
2190
2191 // Diagnostics in the group.
2192 const std::vector<const Record *> &V = GroupInfo.DiagsInGroup;
2193 const bool hasDiags =
2194 !V.empty() || (IsPedantic && !DiagsInPedantic.empty());
2195 if (hasDiags) {
2196 OS << "/* DiagArray" << GroupInfo.IDNo << " */ " << DiagArrayIndex
2197 << ", ";
2198 if (IsPedantic)
2199 DiagArrayIndex += DiagsInPedantic.size();
2200 DiagArrayIndex += V.size() + 1;
2201 } else {
2202 OS << "0, ";
2203 }
2204
2205 // Subgroups.
2206 const std::vector<StringRef> &SubGroups = GroupInfo.SubGroups;
2207 const bool hasSubGroups =
2208 !SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty());
2209 if (hasSubGroups) {
2210 OS << "/* DiagSubGroup" << GroupInfo.IDNo << " */ " << SubGroupIndex
2211 << ", ";
2212 if (IsPedantic)
2213 SubGroupIndex += GroupsInPedantic.size();
2214 SubGroupIndex += SubGroups.size() + 1;
2215 } else {
2216 OS << "0, ";
2217 }
2218
2219 std::string Documentation = GroupInfo.Defs.back()
2220 ->getValue(Name: "Documentation")
2221 ->getValue()
2222 ->getAsUnquotedString();
2223
2224 OS << "R\"(" << StringRef(Documentation).trim() << ")\"";
2225
2226 OS << ")\n";
2227 }
2228 OS << "#endif // DIAG_ENTRY\n\n";
2229}
2230
2231/// Emit the table of diagnostic categories.
2232///
2233/// The table has the form of macro calls that have two parameters. The
2234/// category's name as well as an enum that represents the category. The
2235/// table can be used by defining the macro 'CATEGORY' and including this
2236/// table right after.
2237///
2238/// \code
2239/// #ifdef GET_CATEGORY_TABLE
2240/// CATEGORY("Semantic Issue", DiagCat_Semantic_Issue)
2241/// CATEGORY("Lambda Issue", DiagCat_Lambda_Issue)
2242/// #endif
2243/// \endcode
2244static void emitCategoryTable(const RecordKeeper &Records, raw_ostream &OS) {
2245 DiagCategoryIDMap CategoriesByID(Records);
2246 OS << "\n#ifdef GET_CATEGORY_TABLE\n";
2247 for (auto const &C : CategoriesByID)
2248 OS << "CATEGORY(\"" << C << "\", " << getDiagCategoryEnum(name: C) << ")\n";
2249 OS << "#endif // GET_CATEGORY_TABLE\n\n";
2250}
2251
2252void clang::EmitClangDiagGroups(const RecordKeeper &Records, raw_ostream &OS) {
2253 // Compute a mapping from a DiagGroup to all of its parents.
2254 DiagGroupParentMap DGParentMap(Records);
2255
2256 ArrayRef<const Record *> Diags =
2257 Records.getAllDerivedDefinitions(ClassName: "Diagnostic");
2258
2259 ArrayRef<const Record *> DiagGroups =
2260 Records.getAllDerivedDefinitions(ClassName: "DiagGroup");
2261
2262 DiagsInGroupTy DiagsInGroup;
2263 groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
2264
2265 // All extensions are implicitly in the "pedantic" group. Record the
2266 // implicit set of groups in the "pedantic" group, and use this information
2267 // later when emitting the group information for Pedantic.
2268 RecordVec DiagsInPedantic;
2269 RecordVec GroupsInPedantic;
2270 InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
2271 inferPedantic.compute(DiagsInPedantic: &DiagsInPedantic, GroupsInPedantic: &GroupsInPedantic);
2272
2273 StringToOffsetTable GroupNames;
2274 for (const auto &[Name, Group] : DiagsInGroup) {
2275 GroupNames.GetOrAddStringOffset(Str: Name);
2276 }
2277
2278 emitAllDiagArrays(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
2279 OS);
2280 emitDiagTable(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
2281 OS);
2282 emitCategoryTable(Records, OS);
2283}
2284
2285//===----------------------------------------------------------------------===//
2286// Diagnostic name index generation
2287//===----------------------------------------------------------------------===//
2288
2289void clang::EmitClangDiagsIndexName(const RecordKeeper &Records,
2290 raw_ostream &OS) {
2291 std::vector<const Record *> Diags =
2292 Records.getAllDerivedDefinitions(ClassName: "Diagnostic");
2293
2294 sort(C&: Diags, Comp: [](const Record *LHS, const Record *RHS) {
2295 return LHS->getName() < RHS->getName();
2296 });
2297
2298 for (const Record *Elem : Diags)
2299 OS << "DIAG_NAME_INDEX(" << Elem->getName() << ")\n";
2300}
2301
2302//===----------------------------------------------------------------------===//
2303// Diagnostic documentation generation
2304//===----------------------------------------------------------------------===//
2305
2306namespace docs {
2307namespace {
2308
2309bool isRemarkGroup(const Record *DiagGroup,
2310 const DiagsInGroupTy &DiagsInGroup) {
2311 bool AnyRemarks = false, AnyNonRemarks = false;
2312
2313 std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
2314 auto &GroupInfo = DiagsInGroup.find(x: GroupName)->second;
2315 for (const Record *Diag : GroupInfo.DiagsInGroup)
2316 (isRemark(Diag: *Diag) ? AnyRemarks : AnyNonRemarks) = true;
2317 for (StringRef Name : GroupInfo.SubGroups)
2318 Visit(Name);
2319 };
2320 Visit(DiagGroup->getValueAsString(FieldName: "GroupName"));
2321
2322 if (AnyRemarks && AnyNonRemarks)
2323 PrintFatalError(
2324 ErrorLoc: DiagGroup->getLoc(),
2325 Msg: "Diagnostic group contains both remark and non-remark diagnostics");
2326 return AnyRemarks;
2327}
2328
2329std::string getDefaultSeverity(const Record *Diag) {
2330 return std::string(
2331 Diag->getValueAsDef(FieldName: "DefaultSeverity")->getValueAsString(FieldName: "Name"));
2332}
2333
2334std::set<std::string> getDefaultSeverities(const Record *DiagGroup,
2335 const DiagsInGroupTy &DiagsInGroup) {
2336 std::set<std::string> States;
2337
2338 std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
2339 auto &GroupInfo = DiagsInGroup.find(x: GroupName)->second;
2340 for (const Record *Diag : GroupInfo.DiagsInGroup)
2341 States.insert(x: getDefaultSeverity(Diag));
2342 for (const auto &Name : GroupInfo.SubGroups)
2343 Visit(Name);
2344 };
2345 Visit(DiagGroup->getValueAsString(FieldName: "GroupName"));
2346 return States;
2347}
2348
2349/// Write the heading for a diagnostic flag, preceded by an explicit
2350/// cross-reference target. Naming the target keeps intra-page links working
2351/// without depending on how Sphinx slugifies heading text, which is a docutils
2352/// implementation detail that LLVM additionally overrides via
2353/// `myst_heading_slug_func`.
2354void writeHeader(StringRef Prefix, StringRef GroupName, raw_ostream &OS) {
2355 OS << "(" << Prefix << GroupName << ")=\n\n### " << Prefix << GroupName
2356 << "\n\n";
2357}
2358
2359void writeDiagnosticText(DiagnosticTextBuilder &Builder, const Record *R,
2360 StringRef Role, raw_ostream &OS) {
2361 StringRef Text = R->getValueAsString(FieldName: "Summary");
2362 if (Text == "%0")
2363 OS << "The text of this diagnostic is not controlled by Clang.\n\n";
2364 else
2365 OS << Builder.buildForDocumentation(Severity: Role, R) << '\n';
2366}
2367
2368void writeDocumentation(StringRef Documentation, raw_ostream &OS) {
2369 SmallVector<StringRef> Lines;
2370 Documentation.trim(Chars: "\n").split(A&: Lines, Separator: '\n');
2371
2372 size_t Indent = StringRef::npos;
2373 for (StringRef Line : Lines)
2374 if (size_t I = Line.find_first_not_of(Chars: " \t"); I != StringRef::npos)
2375 Indent = std::min(a: Indent, b: I);
2376
2377 for (StringRef Line : Lines)
2378 OS << Line.drop_front(N: std::min(a: Indent, b: Line.size())) << '\n';
2379}
2380
2381} // namespace
2382} // namespace docs
2383
2384void clang::EmitClangDiagDocs(const RecordKeeper &Records, raw_ostream &OS) {
2385 using namespace docs;
2386
2387 // Get the documentation introduction paragraph.
2388 const Record *Documentation = Records.getDef(Name: "GlobalDocumentation");
2389 if (!Documentation) {
2390 PrintFatalError(Msg: "The Documentation top-level definition is missing, "
2391 "no documentation will be generated.");
2392 return;
2393 }
2394
2395 OS << Documentation->getValueAsString(FieldName: "Intro") << "\n";
2396
2397 DiagnosticTextBuilder Builder(Records);
2398
2399 ArrayRef<const Record *> Diags =
2400 Records.getAllDerivedDefinitions(ClassName: "Diagnostic");
2401
2402 std::vector<const Record *> DiagGroups =
2403 Records.getAllDerivedDefinitions(ClassName: "DiagGroup");
2404 sort(C&: DiagGroups, Comp: diagGroupBeforeByName);
2405
2406 DiagGroupParentMap DGParentMap(Records);
2407
2408 DiagsInGroupTy DiagsInGroup;
2409 groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
2410
2411 // Compute the set of diagnostics that are in -Wpedantic.
2412 {
2413 // Collect into vectors rather than sets: InferPedantic fills a vector by
2414 // marching the records in source order, so the result is deterministic
2415 // without a sort. A set would have to be sorted back into order, and
2416 // source location alone is not a total order because every record from a
2417 // multiclass reports the location of the `def` inside it.
2418 RecordVec DiagsInPedantic;
2419 RecordVec GroupsInPedantic;
2420 InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
2421 inferPedantic.compute(DiagsInPedantic: &DiagsInPedantic, GroupsInPedantic: &GroupsInPedantic);
2422 auto &PedDiags = DiagsInGroup["pedantic"];
2423 PedDiags.DiagsInGroup.insert(position: PedDiags.DiagsInGroup.end(),
2424 first: DiagsInPedantic.begin(),
2425 last: DiagsInPedantic.end());
2426 for (auto *Group : GroupsInPedantic)
2427 PedDiags.SubGroups.push_back(x: Group->getValueAsString(FieldName: "GroupName"));
2428 }
2429
2430 // FIXME: Write diagnostic categories and link to diagnostic groups in each.
2431
2432 // Write out the diagnostic groups.
2433 for (const Record *G : DiagGroups) {
2434 bool IsRemarkGroup = isRemarkGroup(DiagGroup: G, DiagsInGroup);
2435 StringRef GroupName = G->getValueAsString(FieldName: "GroupName");
2436 StringRef Prefix = IsRemarkGroup ? "-R" : "-W";
2437 auto &GroupInfo = DiagsInGroup[GroupName];
2438 bool IsSynonym =
2439 GroupInfo.DiagsInGroup.empty() && GroupInfo.SubGroups.size() == 1;
2440
2441 writeHeader(Prefix, GroupName, OS);
2442
2443 if (!IsSynonym) {
2444 // FIXME: Ideally, all the diagnostics in a group should have the same
2445 // default state, but that is not currently the case.
2446 auto DefaultSeverities = getDefaultSeverities(DiagGroup: G, DiagsInGroup);
2447 if (!DefaultSeverities.empty() && !DefaultSeverities.count(x: "Ignored")) {
2448 bool AnyNonErrors = DefaultSeverities.count(x: "Warning") ||
2449 DefaultSeverities.count(x: "Remark");
2450 if (!AnyNonErrors)
2451 OS << "This diagnostic is an error by default, but the flag `-Wno-"
2452 << GroupName << "` can be used to disable the error.\n\n";
2453 else
2454 OS << "This diagnostic is enabled by default.\n\n";
2455 } else if (DefaultSeverities.size() > 1) {
2456 OS << "Some of the diagnostics controlled by this flag are enabled "
2457 << "by default.\n\n";
2458 }
2459 }
2460
2461 if (!GroupInfo.SubGroups.empty()) {
2462 if (IsSynonym)
2463 OS << "Synonym for ";
2464 else if (GroupInfo.DiagsInGroup.empty())
2465 OS << "Controls ";
2466 else
2467 OS << "Also controls ";
2468
2469 sort(C&: GroupInfo.SubGroups);
2470 ListSeparator LS;
2471 // writeHeader emits an explicit target named after the flag, so a `{ref}`
2472 // with no explicit title links to it and renders as the flag name.
2473 for (StringRef Name : GroupInfo.SubGroups)
2474 OS << LS << "{ref}`" << Prefix << Name << "`";
2475 OS << ".\n\n";
2476 }
2477
2478 if (!GroupInfo.DiagsInGroup.empty()) {
2479 OS << "**Diagnostic text:**\n\n";
2480 for (const Record *D : GroupInfo.DiagsInGroup) {
2481 auto Severity = getDefaultSeverity(Diag: D);
2482 Severity[0] = tolower(c: Severity[0]);
2483 if (Severity == "ignored")
2484 Severity = IsRemarkGroup ? "remark" : "warning";
2485
2486 writeDiagnosticText(Builder, R: D, Role: Severity, OS);
2487 }
2488 }
2489
2490 auto Doc = G->getValueAsString(FieldName: "Documentation");
2491 if (!Doc.empty())
2492 writeDocumentation(Documentation: Doc, OS);
2493 else if (GroupInfo.SubGroups.empty() && GroupInfo.DiagsInGroup.empty())
2494 OS << "This diagnostic flag exists for GCC compatibility, and has no "
2495 "effect in Clang.\n";
2496 OS << "\n";
2497 }
2498}
2499