1 //===- Diagnostic.cpp - C Language Family Diagnostic Handling -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Diagnostic-related interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/DiagnosticError.h"
16 #include "clang/Basic/DiagnosticIDs.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TokenKinds.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/CrashRecoveryContext.h"
29 #include "llvm/Support/Locale.h"
30 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
43 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
44 DiagNullabilityKind nullability) {
46 switch (nullability.first) {
47 case NullabilityKind::NonNull:
48 string = nullability.second ? "'nonnull'" : "'_Nonnull'";
51 case NullabilityKind::Nullable:
52 string = nullability.second ? "'nullable'" : "'_Nullable'";
55 case NullabilityKind::Unspecified:
56 string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
64 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
66 DB.AddString(toString(std::move(E)));
70 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
71 StringRef Modifier, StringRef Argument,
72 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
73 SmallVectorImpl<char> &Output,
75 ArrayRef<intptr_t> QualTypeVals) {
76 StringRef Str = "<can't format argument>";
77 Output.append(Str.begin(), Str.end());
80 DiagnosticsEngine::DiagnosticsEngine(
81 IntrusiveRefCntPtr<DiagnosticIDs> diags,
82 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,
84 : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
85 setClient(client, ShouldOwnClient);
86 ArgToStringFn = DummyArgToStringFn;
91 DiagnosticsEngine::~DiagnosticsEngine() {
92 // If we own the diagnostic client, destroy it first so that it can access the
93 // engine from its destructor.
97 void DiagnosticsEngine::dump() const {
98 DiagStatesByLoc.dump(*SourceMgr);
101 void DiagnosticsEngine::dump(StringRef DiagName) const {
102 DiagStatesByLoc.dump(*SourceMgr, DiagName);
105 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
106 bool ShouldOwnClient) {
107 Owner.reset(ShouldOwnClient ? client : nullptr);
111 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
112 DiagStateOnPushStack.push_back(GetCurDiagState());
115 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
116 if (DiagStateOnPushStack.empty())
119 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
120 // State changed at some point between push/pop.
121 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
123 DiagStateOnPushStack.pop_back();
127 void DiagnosticsEngine::Reset() {
128 ErrorOccurred = false;
129 UncompilableErrorOccurred = false;
130 FatalErrorOccurred = false;
131 UnrecoverableErrorOccurred = false;
135 TrapNumErrorsOccurred = 0;
136 TrapNumUnrecoverableErrorsOccurred = 0;
138 CurDiagID = std::numeric_limits<unsigned>::max();
139 LastDiagLevel = DiagnosticIDs::Ignored;
142 // Clear state related to #pragma diagnostic.
144 DiagStatesByLoc.clear();
145 DiagStateOnPushStack.clear();
147 // Create a DiagState and DiagStatePoint representing diagnostic changes
148 // through command-line.
149 DiagStates.emplace_back();
150 DiagStatesByLoc.appendFirst(&DiagStates.back());
153 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
154 StringRef Arg2, StringRef Arg3) {
158 DelayedDiagID = DiagID;
159 DelayedDiagArg1 = Arg1.str();
160 DelayedDiagArg2 = Arg2.str();
161 DelayedDiagArg3 = Arg3.str();
164 void DiagnosticsEngine::ReportDelayed() {
165 unsigned ID = DelayedDiagID;
167 Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
170 void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
171 assert(Files.empty() && "not first");
172 FirstDiagState = CurDiagState = State;
173 CurDiagStateLoc = SourceLocation();
176 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
179 CurDiagState = State;
180 CurDiagStateLoc = Loc;
182 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
183 unsigned Offset = Decomp.second;
184 for (File *F = getFile(SrcMgr, Decomp.first); F;
185 Offset = F->ParentOffset, F = F->Parent) {
186 F->HasLocalTransitions = true;
187 auto &Last = F->StateTransitions.back();
188 assert(Last.Offset <= Offset && "state transitions added out of order");
190 if (Last.Offset == Offset) {
191 if (Last.State == State)
197 F->StateTransitions.push_back({State, Offset});
201 DiagnosticsEngine::DiagState *
202 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
203 SourceLocation Loc) const {
204 // Common case: we have not seen any diagnostic pragmas.
206 return FirstDiagState;
208 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
209 const File *F = getFile(SrcMgr, Decomp.first);
210 return F->lookup(Decomp.second);
213 DiagnosticsEngine::DiagState *
214 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
216 llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
217 return P.Offset <= Offset;
219 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
220 return OnePastIt[-1].State;
223 DiagnosticsEngine::DiagStateMap::File *
224 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
226 // Get or insert the File for this ID.
227 auto Range = Files.equal_range(ID);
228 if (Range.first != Range.second)
229 return &Range.first->second;
230 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
232 // We created a new File; look up the diagnostic state at the start of it and
235 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
236 F.Parent = getFile(SrcMgr, Decomp.first);
237 F.ParentOffset = Decomp.second;
238 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
240 // This is the (imaginary) root file into which we pretend all top-level
241 // files are included; it descends from the initial state.
243 // FIXME: This doesn't guarantee that we use the same ordering as
244 // isBeforeInTranslationUnit in the cases where someone invented another
245 // top-level file and added diagnostic pragmas to it. See the code at the
246 // end of isBeforeInTranslationUnit for the quirks it deals with.
247 F.StateTransitions.push_back({FirstDiagState, 0});
252 void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
253 StringRef DiagName) const {
254 llvm::errs() << "diagnostic state at ";
255 CurDiagStateLoc.print(llvm::errs(), SrcMgr);
256 llvm::errs() << ": " << CurDiagState << "\n";
258 for (auto &F : Files) {
260 File &File = F.second;
262 bool PrintedOuterHeading = false;
263 auto PrintOuterHeading = [&] {
264 if (PrintedOuterHeading) return;
265 PrintedOuterHeading = true;
267 llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
268 << ">: " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
269 if (F.second.Parent) {
270 std::pair<FileID, unsigned> Decomp =
271 SrcMgr.getDecomposedIncludedLoc(ID);
272 assert(File.ParentOffset == Decomp.second);
273 llvm::errs() << " parent " << File.Parent << " <FileID "
274 << Decomp.first.getHashValue() << "> ";
275 SrcMgr.getLocForStartOfFile(Decomp.first)
276 .getLocWithOffset(Decomp.second)
277 .print(llvm::errs(), SrcMgr);
279 if (File.HasLocalTransitions)
280 llvm::errs() << " has_local_transitions";
281 llvm::errs() << "\n";
284 if (DiagName.empty())
287 for (DiagStatePoint &Transition : File.StateTransitions) {
288 bool PrintedInnerHeading = false;
289 auto PrintInnerHeading = [&] {
290 if (PrintedInnerHeading) return;
291 PrintedInnerHeading = true;
295 SrcMgr.getLocForStartOfFile(ID)
296 .getLocWithOffset(Transition.Offset)
297 .print(llvm::errs(), SrcMgr);
298 llvm::errs() << ": state " << Transition.State << ":\n";
301 if (DiagName.empty())
304 for (auto &Mapping : *Transition.State) {
306 DiagnosticIDs::getWarningOptionForDiag(Mapping.first);
307 if (!DiagName.empty() && DiagName != Option)
313 llvm::errs() << "<unknown " << Mapping.first << ">";
315 llvm::errs() << Option;
316 llvm::errs() << ": ";
318 switch (Mapping.second.getSeverity()) {
319 case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
320 case diag::Severity::Remark: llvm::errs() << "remark"; break;
321 case diag::Severity::Warning: llvm::errs() << "warning"; break;
322 case diag::Severity::Error: llvm::errs() << "error"; break;
323 case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
326 if (!Mapping.second.isUser())
327 llvm::errs() << " default";
328 if (Mapping.second.isPragma())
329 llvm::errs() << " pragma";
330 if (Mapping.second.hasNoWarningAsError())
331 llvm::errs() << " no-error";
332 if (Mapping.second.hasNoErrorAsFatal())
333 llvm::errs() << " no-fatal";
334 if (Mapping.second.wasUpgradedFromWarning())
335 llvm::errs() << " overruled";
336 llvm::errs() << "\n";
342 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
343 SourceLocation Loc) {
344 assert(Loc.isValid() && "Adding invalid loc point");
345 DiagStatesByLoc.append(*SourceMgr, Loc, State);
348 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
350 assert(Diag < diag::DIAG_UPPER_LIMIT &&
351 "Can only map builtin diagnostics");
352 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
353 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
354 "Cannot map errors into warnings!");
355 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
357 // Don't allow a mapping to a warning override an error/fatal mapping.
358 bool WasUpgradedFromWarning = false;
359 if (Map == diag::Severity::Warning) {
360 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
361 if (Info.getSeverity() == diag::Severity::Error ||
362 Info.getSeverity() == diag::Severity::Fatal) {
363 Map = Info.getSeverity();
364 WasUpgradedFromWarning = true;
367 DiagnosticMapping Mapping = makeUserMapping(Map, L);
368 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
370 // Common case; setting all the diagnostics of a group in one place.
371 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
372 DiagStatesByLoc.getCurDiagState()) {
373 // FIXME: This is theoretically wrong: if the current state is shared with
374 // some other location (via push/pop) we will change the state for that
375 // other location as well. This cannot currently happen, as we can't update
376 // the diagnostic state at the same location at which we pop.
377 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
381 // A diagnostic pragma occurred, create a new DiagState initialized with
382 // the current one and a new DiagStatePoint to record at which location
383 // the new state became active.
384 DiagStates.push_back(*GetCurDiagState());
385 DiagStates.back().setMapping(Diag, Mapping);
386 PushDiagStatePoint(&DiagStates.back(), L);
389 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
390 StringRef Group, diag::Severity Map,
391 SourceLocation Loc) {
392 // Get the diagnostics in this group.
393 SmallVector<diag::kind, 256> GroupDiags;
394 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
398 for (diag::kind Diag : GroupDiags)
399 setSeverity(Diag, Map, Loc);
404 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
406 // If we are enabling this feature, just set the diagnostic mappings to map to
409 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
410 diag::Severity::Error);
412 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
413 // potentially downgrade anything already mapped to be a warning.
415 // Get the diagnostics in this group.
416 SmallVector<diag::kind, 8> GroupDiags;
417 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
421 // Perform the mapping change.
422 for (diag::kind Diag : GroupDiags) {
423 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
425 if (Info.getSeverity() == diag::Severity::Error ||
426 Info.getSeverity() == diag::Severity::Fatal)
427 Info.setSeverity(diag::Severity::Warning);
429 Info.setNoWarningAsError(true);
435 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
437 // If we are enabling this feature, just set the diagnostic mappings to map to
440 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
441 diag::Severity::Fatal);
443 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
444 // and potentially downgrade anything already mapped to be a fatal error.
446 // Get the diagnostics in this group.
447 SmallVector<diag::kind, 8> GroupDiags;
448 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
452 // Perform the mapping change.
453 for (diag::kind Diag : GroupDiags) {
454 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
456 if (Info.getSeverity() == diag::Severity::Fatal)
457 Info.setSeverity(diag::Severity::Error);
459 Info.setNoErrorAsFatal(true);
465 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
467 SourceLocation Loc) {
468 // Get all the diagnostics.
469 std::vector<diag::kind> AllDiags;
470 DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
473 for (diag::kind Diag : AllDiags)
474 if (Diags->isBuiltinWarningOrExtension(Diag))
475 setSeverity(Diag, Map, Loc);
478 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
479 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
480 "Multiple diagnostics in flight at once!");
482 CurDiagLoc = storedDiag.getLocation();
483 CurDiagID = storedDiag.getID();
487 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
489 DiagFixItHints.clear();
490 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
492 assert(Client && "DiagnosticConsumer not set!");
493 Level DiagLevel = storedDiag.getLevel();
494 Diagnostic Info(this, storedDiag.getMessage());
495 Client->HandleDiagnostic(DiagLevel, Info);
496 if (Client->IncludeInDiagnosticCounts()) {
497 if (DiagLevel == DiagnosticsEngine::Warning)
501 CurDiagID = std::numeric_limits<unsigned>::max();
504 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
505 assert(getClient() && "DiagnosticClient not set!");
509 Diagnostic Info(this);
511 // Figure out the diagnostic level of this message.
512 DiagnosticIDs::Level DiagLevel
513 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
515 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
517 // Emit the diagnostic regardless of suppression level.
518 Diags->EmitDiag(*this, DiagLevel);
521 // Process the diagnostic, sending the accumulated information to the
522 // DiagnosticConsumer.
523 Emitted = ProcessDiag();
526 // Clear out the current diagnostic object.
529 // If there was a delayed diagnostic, emit it now.
530 if (!Force && DelayedDiagID)
536 DiagnosticConsumer::~DiagnosticConsumer() = default;
538 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
539 const Diagnostic &Info) {
540 if (!IncludeInDiagnosticCounts())
543 if (DiagLevel == DiagnosticsEngine::Warning)
545 else if (DiagLevel >= DiagnosticsEngine::Error)
549 /// ModifierIs - Return true if the specified modifier matches specified string.
550 template <std::size_t StrLen>
551 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
552 const char (&Str)[StrLen]) {
553 return StrLen-1 == ModifierLen && memcmp(Modifier, Str, StrLen-1) == 0;
556 /// ScanForward - Scans forward, looking for the given character, skipping
557 /// nested clauses and escaped characters.
558 static const char *ScanFormat(const char *I, const char *E, char Target) {
561 for ( ; I != E; ++I) {
562 if (Depth == 0 && *I == Target) return I;
563 if (Depth != 0 && *I == '}') Depth--;
569 // Escaped characters get implicitly skipped here.
572 if (!isDigit(*I) && !isPunctuation(*I)) {
573 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
583 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
584 /// like this: %select{foo|bar|baz}2. This means that the integer argument
585 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
586 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
587 /// This is very useful for certain classes of variant diagnostics.
588 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
589 const char *Argument, unsigned ArgumentLen,
590 SmallVectorImpl<char> &OutStr) {
591 const char *ArgumentEnd = Argument+ArgumentLen;
593 // Skip over 'ValNo' |'s.
595 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
596 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
597 " larger than the number of options in the diagnostic string!");
598 Argument = NextVal+1; // Skip this string.
602 // Get the end of the value. This is either the } or the |.
603 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
605 // Recursively format the result of the select clause into the output string.
606 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
609 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
610 /// letter 's' to the string if the value is not 1. This is used in cases like
611 /// this: "you idiot, you have %4 parameter%s4!".
612 static void HandleIntegerSModifier(unsigned ValNo,
613 SmallVectorImpl<char> &OutStr) {
615 OutStr.push_back('s');
618 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
619 /// prints the ordinal form of the given integer, with 1 corresponding
620 /// to the first ordinal. Currently this is hard-coded to use the
622 static void HandleOrdinalModifier(unsigned ValNo,
623 SmallVectorImpl<char> &OutStr) {
624 assert(ValNo != 0 && "ValNo must be strictly positive!");
626 llvm::raw_svector_ostream Out(OutStr);
628 // We could use text forms for the first N ordinals, but the numeric
629 // forms are actually nicer in diagnostics because they stand out.
630 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
633 /// PluralNumber - Parse an unsigned integer and advance Start.
634 static unsigned PluralNumber(const char *&Start, const char *End) {
635 // Programming 101: Parse a decimal number :-)
637 while (Start != End && *Start >= '0' && *Start <= '9') {
645 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
646 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
648 unsigned Ref = PluralNumber(Start, End);
653 unsigned Low = PluralNumber(Start, End);
654 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
656 unsigned High = PluralNumber(Start, End);
657 assert(*Start == ']' && "Bad plural expression syntax: expected )");
659 return Low <= Val && Val <= High;
662 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
663 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
673 unsigned Arg = PluralNumber(Start, End);
674 assert(*Start == '=' && "Bad plural expression syntax: expected =");
676 unsigned ValMod = ValNo % Arg;
677 if (TestPluralRange(ValMod, Start, End))
680 assert((C == '[' || (C >= '0' && C <= '9')) &&
681 "Bad plural expression syntax: unexpected character");
683 if (TestPluralRange(ValNo, Start, End))
687 // Scan for next or-expr part.
688 Start = std::find(Start, End, ',');
696 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
697 /// for complex plural forms, or in languages where all plurals are complex.
698 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
699 /// conditions that are tested in order, the form corresponding to the first
700 /// that applies being emitted. The empty condition is always true, making the
701 /// last form a default case.
702 /// Conditions are simple boolean expressions, where n is the number argument.
703 /// Here are the rules.
704 /// condition := expression | empty
705 /// empty := -> always true
706 /// expression := numeric [',' expression] -> logical or
707 /// numeric := range -> true if n in range
708 /// | '%' number '=' range -> true if n % number in range
710 /// | '[' number ',' number ']' -> ranges are inclusive both ends
712 /// Here are some examples from the GNU gettext manual written in this form:
716 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
718 /// {1:form0|2:form1|:form2}
720 /// {1:form0|0,%100=[1,19]:form1|:form2}
722 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
723 /// Russian (requires repeated form):
724 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
726 /// {1:form0|[2,4]:form1|:form2}
727 /// Polish (requires repeated form):
728 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
729 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
730 const char *Argument, unsigned ArgumentLen,
731 SmallVectorImpl<char> &OutStr) {
732 const char *ArgumentEnd = Argument + ArgumentLen;
734 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
735 const char *ExprEnd = Argument;
736 while (*ExprEnd != ':') {
737 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
740 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
741 Argument = ExprEnd + 1;
742 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
744 // Recursively format the result of the plural clause into the
746 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
749 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
753 /// Returns the friendly description for a token kind that will appear
754 /// without quotes in diagnostic messages. These strings may be translatable in
756 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
758 case tok::identifier:
765 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
766 /// formal arguments into the %0 slots. The result is appended onto the Str
769 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
770 if (!StoredDiagMessage.empty()) {
771 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
776 getDiags()->getDiagnosticIDs()->getDescription(getID());
778 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
782 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
783 SmallVectorImpl<char> &OutStr) const {
784 // When the diagnostic string is only "%0", the entire string is being given
785 // by an outside source. Remove unprintable characters from this string
786 // and skip all the other string processing.
787 if (DiagEnd - DiagStr == 2 &&
788 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
789 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
790 const std::string &S = getArgStdStr(0);
792 if (llvm::sys::locale::isPrint(c) || c == '\t') {
799 /// FormattedArgs - Keep track of all of the arguments formatted by
800 /// ConvertArgToString and pass them into subsequent calls to
801 /// ConvertArgToString, allowing the implementation to avoid redundancies in
803 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
805 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
806 /// compared to see if more information is needed to be printed.
807 SmallVector<intptr_t, 2> QualTypeVals;
808 SmallVector<char, 64> Tree;
810 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
811 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
812 QualTypeVals.push_back(getRawArg(i));
814 while (DiagStr != DiagEnd) {
815 if (DiagStr[0] != '%') {
816 // Append non-%0 substrings to Str if we have one.
817 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
818 OutStr.append(DiagStr, StrEnd);
821 } else if (isPunctuation(DiagStr[1])) {
822 OutStr.push_back(DiagStr[1]); // %% -> %.
830 // This must be a placeholder for a diagnostic argument. The format for a
831 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
832 // The digit is a number from 0-9 indicating which argument this comes from.
833 // The modifier is a string of digits from the set [-a-z]+, arguments is a
834 // brace enclosed string.
835 const char *Modifier = nullptr, *Argument = nullptr;
836 unsigned ModifierLen = 0, ArgumentLen = 0;
838 // Check to see if we have a modifier. If so eat it.
839 if (!isDigit(DiagStr[0])) {
841 while (DiagStr[0] == '-' ||
842 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
844 ModifierLen = DiagStr-Modifier;
846 // If we have an argument, get it next.
847 if (DiagStr[0] == '{') {
848 ++DiagStr; // Skip {.
851 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
852 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
853 ArgumentLen = DiagStr-Argument;
854 ++DiagStr; // Skip }.
858 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
859 unsigned ArgNo = *DiagStr++ - '0';
861 // Only used for type diffing.
862 unsigned ArgNo2 = ArgNo;
864 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
865 if (ModifierIs(Modifier, ModifierLen, "diff")) {
866 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
867 "Invalid format for diff modifier");
869 ArgNo2 = *DiagStr++ - '0';
870 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
871 if (Kind == DiagnosticsEngine::ak_qualtype &&
872 Kind2 == DiagnosticsEngine::ak_qualtype)
873 Kind = DiagnosticsEngine::ak_qualtype_pair;
875 // %diff only supports QualTypes. For other kinds of arguments,
876 // use the default printing. For example, if the modifier is:
877 // "%diff{compare $ to $|other text}1,2"
879 // "compare %1 to %2"
880 const char *ArgumentEnd = Argument + ArgumentLen;
881 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
882 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
883 "Found too many '|'s in a %diff modifier!");
884 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
885 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
886 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
887 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
888 FormatDiagnostic(Argument, FirstDollar, OutStr);
889 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
890 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
891 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
892 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
899 case DiagnosticsEngine::ak_std_string: {
900 const std::string &S = getArgStdStr(ArgNo);
901 assert(ModifierLen == 0 && "No modifiers for strings yet");
902 OutStr.append(S.begin(), S.end());
905 case DiagnosticsEngine::ak_c_string: {
906 const char *S = getArgCStr(ArgNo);
907 assert(ModifierLen == 0 && "No modifiers for strings yet");
909 // Don't crash if get passed a null pointer by accident.
913 OutStr.append(S, S + strlen(S));
916 // ---- INTEGERS ----
917 case DiagnosticsEngine::ak_sint: {
918 int Val = getArgSInt(ArgNo);
920 if (ModifierIs(Modifier, ModifierLen, "select")) {
921 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
923 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
924 HandleIntegerSModifier(Val, OutStr);
925 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
926 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
928 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
929 HandleOrdinalModifier((unsigned)Val, OutStr);
931 assert(ModifierLen == 0 && "Unknown integer modifier");
932 llvm::raw_svector_ostream(OutStr) << Val;
936 case DiagnosticsEngine::ak_uint: {
937 unsigned Val = getArgUInt(ArgNo);
939 if (ModifierIs(Modifier, ModifierLen, "select")) {
940 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
941 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
942 HandleIntegerSModifier(Val, OutStr);
943 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
944 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
946 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
947 HandleOrdinalModifier(Val, OutStr);
949 assert(ModifierLen == 0 && "Unknown integer modifier");
950 llvm::raw_svector_ostream(OutStr) << Val;
954 // ---- TOKEN SPELLINGS ----
955 case DiagnosticsEngine::ak_tokenkind: {
956 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
957 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
959 llvm::raw_svector_ostream Out(OutStr);
960 if (const char *S = tok::getPunctuatorSpelling(Kind))
961 // Quoted token spelling for punctuators.
962 Out << '\'' << S << '\'';
963 else if (const char *S = tok::getKeywordSpelling(Kind))
964 // Unquoted token spelling for keywords.
966 else if (const char *S = getTokenDescForDiagnostic(Kind))
967 // Unquoted translatable token name.
969 else if (const char *S = tok::getTokenName(Kind))
970 // Debug name, shouldn't appear in user-facing diagnostics.
971 Out << '<' << S << '>';
976 // ---- NAMES and TYPES ----
977 case DiagnosticsEngine::ak_identifierinfo: {
978 const IdentifierInfo *II = getArgIdentifier(ArgNo);
979 assert(ModifierLen == 0 && "No modifiers for strings yet");
981 // Don't crash if get passed a null pointer by accident.
983 const char *S = "(null)";
984 OutStr.append(S, S + strlen(S));
988 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
991 case DiagnosticsEngine::ak_addrspace:
992 case DiagnosticsEngine::ak_qual:
993 case DiagnosticsEngine::ak_qualtype:
994 case DiagnosticsEngine::ak_declarationname:
995 case DiagnosticsEngine::ak_nameddecl:
996 case DiagnosticsEngine::ak_nestednamespec:
997 case DiagnosticsEngine::ak_declcontext:
998 case DiagnosticsEngine::ak_attr:
999 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
1000 StringRef(Modifier, ModifierLen),
1001 StringRef(Argument, ArgumentLen),
1003 OutStr, QualTypeVals);
1005 case DiagnosticsEngine::ak_qualtype_pair: {
1006 // Create a struct with all the info needed for printing.
1007 TemplateDiffTypes TDT;
1008 TDT.FromType = getRawArg(ArgNo);
1009 TDT.ToType = getRawArg(ArgNo2);
1010 TDT.ElideType = getDiags()->ElideType;
1011 TDT.ShowColors = getDiags()->ShowColors;
1012 TDT.TemplateDiffUsed = false;
1013 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1015 const char *ArgumentEnd = Argument + ArgumentLen;
1016 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1018 // Print the tree. If this diagnostic already has a tree, skip the
1020 if (getDiags()->PrintTemplateTree && Tree.empty()) {
1021 TDT.PrintFromType = true;
1022 TDT.PrintTree = true;
1023 getDiags()->ConvertArgToString(Kind, val,
1024 StringRef(Modifier, ModifierLen),
1025 StringRef(Argument, ArgumentLen),
1027 Tree, QualTypeVals);
1028 // If there is no tree information, fall back to regular printing.
1029 if (!Tree.empty()) {
1030 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1035 // Non-tree printing, also the fall-back when tree printing fails.
1036 // The fall-back is triggered when the types compared are not templates.
1037 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1038 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1040 // Append before text
1041 FormatDiagnostic(Argument, FirstDollar, OutStr);
1043 // Append first type
1044 TDT.PrintTree = false;
1045 TDT.PrintFromType = true;
1046 getDiags()->ConvertArgToString(Kind, val,
1047 StringRef(Modifier, ModifierLen),
1048 StringRef(Argument, ArgumentLen),
1050 OutStr, QualTypeVals);
1051 if (!TDT.TemplateDiffUsed)
1052 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1055 // Append middle text
1056 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1058 // Append second type
1059 TDT.PrintFromType = false;
1060 getDiags()->ConvertArgToString(Kind, val,
1061 StringRef(Modifier, ModifierLen),
1062 StringRef(Argument, ArgumentLen),
1064 OutStr, QualTypeVals);
1065 if (!TDT.TemplateDiffUsed)
1066 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1070 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1075 // Remember this argument info for subsequent formatting operations. Turn
1076 // std::strings into a null terminated string to make it be the same case as
1077 // all the other ones.
1078 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
1080 else if (Kind != DiagnosticsEngine::ak_std_string)
1081 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1083 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
1084 (intptr_t)getArgStdStr(ArgNo).c_str()));
1087 // Append the type tree to the end of the diagnostics.
1088 OutStr.append(Tree.begin(), Tree.end());
1091 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1093 : ID(ID), Level(Level), Message(Message) {}
1095 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
1096 const Diagnostic &Info)
1097 : ID(Info.getID()), Level(Level) {
1098 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1099 "Valid source location without setting a source manager for diagnostic");
1100 if (Info.getLocation().isValid())
1101 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1102 SmallString<64> Message;
1103 Info.FormatDiagnostic(Message);
1104 this->Message.assign(Message.begin(), Message.end());
1105 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1106 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1109 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1110 StringRef Message, FullSourceLoc Loc,
1111 ArrayRef<CharSourceRange> Ranges,
1112 ArrayRef<FixItHint> FixIts)
1113 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1114 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1118 /// IncludeInDiagnosticCounts - This method (whose default implementation
1119 /// returns true) indicates whether the diagnostics handled by this
1120 /// DiagnosticConsumer should be included in the number of diagnostics
1121 /// reported by DiagnosticsEngine.
1122 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1124 void IgnoringDiagConsumer::anchor() {}
1126 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;
1128 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1129 DiagnosticsEngine::Level DiagLevel,
1130 const Diagnostic &Info) {
1131 Target.HandleDiagnostic(DiagLevel, Info);
1134 void ForwardingDiagnosticConsumer::clear() {
1135 DiagnosticConsumer::clear();
1139 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1140 return Target.IncludeInDiagnosticCounts();
1143 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1144 for (unsigned I = 0; I != NumCached; ++I)
1145 FreeList[I] = Cached + I;
1146 NumFreeListEntries = NumCached;
1149 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1150 // Don't assert if we are in a CrashRecovery context, as this invariant may
1151 // be invalidated during a crash.
1152 assert((NumFreeListEntries == NumCached ||
1153 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1154 "A partial is on the lam");
1157 char DiagnosticError::ID;