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 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
65 StringRef Modifier, StringRef Argument,
66 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
67 SmallVectorImpl<char> &Output,
69 ArrayRef<intptr_t> QualTypeVals) {
70 StringRef Str = "<can't format argument>";
71 Output.append(Str.begin(), Str.end());
74 DiagnosticsEngine::DiagnosticsEngine(
75 IntrusiveRefCntPtr<DiagnosticIDs> diags,
76 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,
78 : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
79 setClient(client, ShouldOwnClient);
80 ArgToStringFn = DummyArgToStringFn;
85 DiagnosticsEngine::~DiagnosticsEngine() {
86 // If we own the diagnostic client, destroy it first so that it can access the
87 // engine from its destructor.
91 void DiagnosticsEngine::dump() const {
92 DiagStatesByLoc.dump(*SourceMgr);
95 void DiagnosticsEngine::dump(StringRef DiagName) const {
96 DiagStatesByLoc.dump(*SourceMgr, DiagName);
99 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
100 bool ShouldOwnClient) {
101 Owner.reset(ShouldOwnClient ? client : nullptr);
105 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
106 DiagStateOnPushStack.push_back(GetCurDiagState());
109 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
110 if (DiagStateOnPushStack.empty())
113 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
114 // State changed at some point between push/pop.
115 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
117 DiagStateOnPushStack.pop_back();
121 void DiagnosticsEngine::Reset() {
122 ErrorOccurred = false;
123 UncompilableErrorOccurred = false;
124 FatalErrorOccurred = false;
125 UnrecoverableErrorOccurred = false;
129 TrapNumErrorsOccurred = 0;
130 TrapNumUnrecoverableErrorsOccurred = 0;
132 CurDiagID = std::numeric_limits<unsigned>::max();
133 LastDiagLevel = DiagnosticIDs::Ignored;
136 // Clear state related to #pragma diagnostic.
138 DiagStatesByLoc.clear();
139 DiagStateOnPushStack.clear();
141 // Create a DiagState and DiagStatePoint representing diagnostic changes
142 // through command-line.
143 DiagStates.emplace_back();
144 DiagStatesByLoc.appendFirst(&DiagStates.back());
147 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
148 StringRef Arg2, StringRef Arg3) {
152 DelayedDiagID = DiagID;
153 DelayedDiagArg1 = Arg1.str();
154 DelayedDiagArg2 = Arg2.str();
155 DelayedDiagArg3 = Arg3.str();
158 void DiagnosticsEngine::ReportDelayed() {
159 unsigned ID = DelayedDiagID;
161 Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
164 void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
165 assert(Files.empty() && "not first");
166 FirstDiagState = CurDiagState = State;
167 CurDiagStateLoc = SourceLocation();
170 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
173 CurDiagState = State;
174 CurDiagStateLoc = Loc;
176 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
177 unsigned Offset = Decomp.second;
178 for (File *F = getFile(SrcMgr, Decomp.first); F;
179 Offset = F->ParentOffset, F = F->Parent) {
180 F->HasLocalTransitions = true;
181 auto &Last = F->StateTransitions.back();
182 assert(Last.Offset <= Offset && "state transitions added out of order");
184 if (Last.Offset == Offset) {
185 if (Last.State == State)
191 F->StateTransitions.push_back({State, Offset});
195 DiagnosticsEngine::DiagState *
196 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
197 SourceLocation Loc) const {
198 // Common case: we have not seen any diagnostic pragmas.
200 return FirstDiagState;
202 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
203 const File *F = getFile(SrcMgr, Decomp.first);
204 return F->lookup(Decomp.second);
207 DiagnosticsEngine::DiagState *
208 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
210 llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
211 return P.Offset <= Offset;
213 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
214 return OnePastIt[-1].State;
217 DiagnosticsEngine::DiagStateMap::File *
218 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
220 // Get or insert the File for this ID.
221 auto Range = Files.equal_range(ID);
222 if (Range.first != Range.second)
223 return &Range.first->second;
224 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
226 // We created a new File; look up the diagnostic state at the start of it and
229 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
230 F.Parent = getFile(SrcMgr, Decomp.first);
231 F.ParentOffset = Decomp.second;
232 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
234 // This is the (imaginary) root file into which we pretend all top-level
235 // files are included; it descends from the initial state.
237 // FIXME: This doesn't guarantee that we use the same ordering as
238 // isBeforeInTranslationUnit in the cases where someone invented another
239 // top-level file and added diagnostic pragmas to it. See the code at the
240 // end of isBeforeInTranslationUnit for the quirks it deals with.
241 F.StateTransitions.push_back({FirstDiagState, 0});
246 void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
247 StringRef DiagName) const {
248 llvm::errs() << "diagnostic state at ";
249 CurDiagStateLoc.print(llvm::errs(), SrcMgr);
250 llvm::errs() << ": " << CurDiagState << "\n";
252 for (auto &F : Files) {
254 File &File = F.second;
256 bool PrintedOuterHeading = false;
257 auto PrintOuterHeading = [&] {
258 if (PrintedOuterHeading) return;
259 PrintedOuterHeading = true;
261 llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
262 << ">: " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
263 if (F.second.Parent) {
264 std::pair<FileID, unsigned> Decomp =
265 SrcMgr.getDecomposedIncludedLoc(ID);
266 assert(File.ParentOffset == Decomp.second);
267 llvm::errs() << " parent " << File.Parent << " <FileID "
268 << Decomp.first.getHashValue() << "> ";
269 SrcMgr.getLocForStartOfFile(Decomp.first)
270 .getLocWithOffset(Decomp.second)
271 .print(llvm::errs(), SrcMgr);
273 if (File.HasLocalTransitions)
274 llvm::errs() << " has_local_transitions";
275 llvm::errs() << "\n";
278 if (DiagName.empty())
281 for (DiagStatePoint &Transition : File.StateTransitions) {
282 bool PrintedInnerHeading = false;
283 auto PrintInnerHeading = [&] {
284 if (PrintedInnerHeading) return;
285 PrintedInnerHeading = true;
289 SrcMgr.getLocForStartOfFile(ID)
290 .getLocWithOffset(Transition.Offset)
291 .print(llvm::errs(), SrcMgr);
292 llvm::errs() << ": state " << Transition.State << ":\n";
295 if (DiagName.empty())
298 for (auto &Mapping : *Transition.State) {
300 DiagnosticIDs::getWarningOptionForDiag(Mapping.first);
301 if (!DiagName.empty() && DiagName != Option)
307 llvm::errs() << "<unknown " << Mapping.first << ">";
309 llvm::errs() << Option;
310 llvm::errs() << ": ";
312 switch (Mapping.second.getSeverity()) {
313 case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
314 case diag::Severity::Remark: llvm::errs() << "remark"; break;
315 case diag::Severity::Warning: llvm::errs() << "warning"; break;
316 case diag::Severity::Error: llvm::errs() << "error"; break;
317 case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
320 if (!Mapping.second.isUser())
321 llvm::errs() << " default";
322 if (Mapping.second.isPragma())
323 llvm::errs() << " pragma";
324 if (Mapping.second.hasNoWarningAsError())
325 llvm::errs() << " no-error";
326 if (Mapping.second.hasNoErrorAsFatal())
327 llvm::errs() << " no-fatal";
328 if (Mapping.second.wasUpgradedFromWarning())
329 llvm::errs() << " overruled";
330 llvm::errs() << "\n";
336 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
337 SourceLocation Loc) {
338 assert(Loc.isValid() && "Adding invalid loc point");
339 DiagStatesByLoc.append(*SourceMgr, Loc, State);
342 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
344 assert(Diag < diag::DIAG_UPPER_LIMIT &&
345 "Can only map builtin diagnostics");
346 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
347 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
348 "Cannot map errors into warnings!");
349 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
351 // Don't allow a mapping to a warning override an error/fatal mapping.
352 bool WasUpgradedFromWarning = false;
353 if (Map == diag::Severity::Warning) {
354 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
355 if (Info.getSeverity() == diag::Severity::Error ||
356 Info.getSeverity() == diag::Severity::Fatal) {
357 Map = Info.getSeverity();
358 WasUpgradedFromWarning = true;
361 DiagnosticMapping Mapping = makeUserMapping(Map, L);
362 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
364 // Common case; setting all the diagnostics of a group in one place.
365 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
366 DiagStatesByLoc.getCurDiagState()) {
367 // FIXME: This is theoretically wrong: if the current state is shared with
368 // some other location (via push/pop) we will change the state for that
369 // other location as well. This cannot currently happen, as we can't update
370 // the diagnostic state at the same location at which we pop.
371 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
375 // A diagnostic pragma occurred, create a new DiagState initialized with
376 // the current one and a new DiagStatePoint to record at which location
377 // the new state became active.
378 DiagStates.push_back(*GetCurDiagState());
379 DiagStates.back().setMapping(Diag, Mapping);
380 PushDiagStatePoint(&DiagStates.back(), L);
383 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
384 StringRef Group, diag::Severity Map,
385 SourceLocation Loc) {
386 // Get the diagnostics in this group.
387 SmallVector<diag::kind, 256> GroupDiags;
388 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
392 for (diag::kind Diag : GroupDiags)
393 setSeverity(Diag, Map, Loc);
398 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
400 // If we are enabling this feature, just set the diagnostic mappings to map to
403 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
404 diag::Severity::Error);
406 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
407 // potentially downgrade anything already mapped to be a warning.
409 // Get the diagnostics in this group.
410 SmallVector<diag::kind, 8> GroupDiags;
411 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
415 // Perform the mapping change.
416 for (diag::kind Diag : GroupDiags) {
417 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
419 if (Info.getSeverity() == diag::Severity::Error ||
420 Info.getSeverity() == diag::Severity::Fatal)
421 Info.setSeverity(diag::Severity::Warning);
423 Info.setNoWarningAsError(true);
429 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
431 // If we are enabling this feature, just set the diagnostic mappings to map to
434 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
435 diag::Severity::Fatal);
437 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
438 // and potentially downgrade anything already mapped to be a fatal error.
440 // Get the diagnostics in this group.
441 SmallVector<diag::kind, 8> GroupDiags;
442 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
446 // Perform the mapping change.
447 for (diag::kind Diag : GroupDiags) {
448 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
450 if (Info.getSeverity() == diag::Severity::Fatal)
451 Info.setSeverity(diag::Severity::Error);
453 Info.setNoErrorAsFatal(true);
459 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
461 SourceLocation Loc) {
462 // Get all the diagnostics.
463 std::vector<diag::kind> AllDiags;
464 DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
467 for (diag::kind Diag : AllDiags)
468 if (Diags->isBuiltinWarningOrExtension(Diag))
469 setSeverity(Diag, Map, Loc);
472 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
473 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
474 "Multiple diagnostics in flight at once!");
476 CurDiagLoc = storedDiag.getLocation();
477 CurDiagID = storedDiag.getID();
481 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
483 DiagFixItHints.clear();
484 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
486 assert(Client && "DiagnosticConsumer not set!");
487 Level DiagLevel = storedDiag.getLevel();
488 Diagnostic Info(this, storedDiag.getMessage());
489 Client->HandleDiagnostic(DiagLevel, Info);
490 if (Client->IncludeInDiagnosticCounts()) {
491 if (DiagLevel == DiagnosticsEngine::Warning)
495 CurDiagID = std::numeric_limits<unsigned>::max();
498 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
499 assert(getClient() && "DiagnosticClient not set!");
503 Diagnostic Info(this);
505 // Figure out the diagnostic level of this message.
506 DiagnosticIDs::Level DiagLevel
507 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
509 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
511 // Emit the diagnostic regardless of suppression level.
512 Diags->EmitDiag(*this, DiagLevel);
515 // Process the diagnostic, sending the accumulated information to the
516 // DiagnosticConsumer.
517 Emitted = ProcessDiag();
520 // Clear out the current diagnostic object.
523 // If there was a delayed diagnostic, emit it now.
524 if (!Force && DelayedDiagID)
530 DiagnosticConsumer::~DiagnosticConsumer() = default;
532 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
533 const Diagnostic &Info) {
534 if (!IncludeInDiagnosticCounts())
537 if (DiagLevel == DiagnosticsEngine::Warning)
539 else if (DiagLevel >= DiagnosticsEngine::Error)
543 /// ModifierIs - Return true if the specified modifier matches specified string.
544 template <std::size_t StrLen>
545 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
546 const char (&Str)[StrLen]) {
547 return StrLen-1 == ModifierLen && memcmp(Modifier, Str, StrLen-1) == 0;
550 /// ScanForward - Scans forward, looking for the given character, skipping
551 /// nested clauses and escaped characters.
552 static const char *ScanFormat(const char *I, const char *E, char Target) {
555 for ( ; I != E; ++I) {
556 if (Depth == 0 && *I == Target) return I;
557 if (Depth != 0 && *I == '}') Depth--;
563 // Escaped characters get implicitly skipped here.
566 if (!isDigit(*I) && !isPunctuation(*I)) {
567 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
577 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
578 /// like this: %select{foo|bar|baz}2. This means that the integer argument
579 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
580 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
581 /// This is very useful for certain classes of variant diagnostics.
582 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
583 const char *Argument, unsigned ArgumentLen,
584 SmallVectorImpl<char> &OutStr) {
585 const char *ArgumentEnd = Argument+ArgumentLen;
587 // Skip over 'ValNo' |'s.
589 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
590 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
591 " larger than the number of options in the diagnostic string!");
592 Argument = NextVal+1; // Skip this string.
596 // Get the end of the value. This is either the } or the |.
597 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
599 // Recursively format the result of the select clause into the output string.
600 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
603 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
604 /// letter 's' to the string if the value is not 1. This is used in cases like
605 /// this: "you idiot, you have %4 parameter%s4!".
606 static void HandleIntegerSModifier(unsigned ValNo,
607 SmallVectorImpl<char> &OutStr) {
609 OutStr.push_back('s');
612 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
613 /// prints the ordinal form of the given integer, with 1 corresponding
614 /// to the first ordinal. Currently this is hard-coded to use the
616 static void HandleOrdinalModifier(unsigned ValNo,
617 SmallVectorImpl<char> &OutStr) {
618 assert(ValNo != 0 && "ValNo must be strictly positive!");
620 llvm::raw_svector_ostream Out(OutStr);
622 // We could use text forms for the first N ordinals, but the numeric
623 // forms are actually nicer in diagnostics because they stand out.
624 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
627 /// PluralNumber - Parse an unsigned integer and advance Start.
628 static unsigned PluralNumber(const char *&Start, const char *End) {
629 // Programming 101: Parse a decimal number :-)
631 while (Start != End && *Start >= '0' && *Start <= '9') {
639 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
640 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
642 unsigned Ref = PluralNumber(Start, End);
647 unsigned Low = PluralNumber(Start, End);
648 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
650 unsigned High = PluralNumber(Start, End);
651 assert(*Start == ']' && "Bad plural expression syntax: expected )");
653 return Low <= Val && Val <= High;
656 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
657 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
667 unsigned Arg = PluralNumber(Start, End);
668 assert(*Start == '=' && "Bad plural expression syntax: expected =");
670 unsigned ValMod = ValNo % Arg;
671 if (TestPluralRange(ValMod, Start, End))
674 assert((C == '[' || (C >= '0' && C <= '9')) &&
675 "Bad plural expression syntax: unexpected character");
677 if (TestPluralRange(ValNo, Start, End))
681 // Scan for next or-expr part.
682 Start = std::find(Start, End, ',');
690 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
691 /// for complex plural forms, or in languages where all plurals are complex.
692 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
693 /// conditions that are tested in order, the form corresponding to the first
694 /// that applies being emitted. The empty condition is always true, making the
695 /// last form a default case.
696 /// Conditions are simple boolean expressions, where n is the number argument.
697 /// Here are the rules.
698 /// condition := expression | empty
699 /// empty := -> always true
700 /// expression := numeric [',' expression] -> logical or
701 /// numeric := range -> true if n in range
702 /// | '%' number '=' range -> true if n % number in range
704 /// | '[' number ',' number ']' -> ranges are inclusive both ends
706 /// Here are some examples from the GNU gettext manual written in this form:
710 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
712 /// {1:form0|2:form1|:form2}
714 /// {1:form0|0,%100=[1,19]:form1|:form2}
716 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
717 /// Russian (requires repeated form):
718 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
720 /// {1:form0|[2,4]:form1|:form2}
721 /// Polish (requires repeated form):
722 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
723 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
724 const char *Argument, unsigned ArgumentLen,
725 SmallVectorImpl<char> &OutStr) {
726 const char *ArgumentEnd = Argument + ArgumentLen;
728 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
729 const char *ExprEnd = Argument;
730 while (*ExprEnd != ':') {
731 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
734 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
735 Argument = ExprEnd + 1;
736 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
738 // Recursively format the result of the plural clause into the
740 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
743 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
747 /// Returns the friendly description for a token kind that will appear
748 /// without quotes in diagnostic messages. These strings may be translatable in
750 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
752 case tok::identifier:
759 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
760 /// formal arguments into the %0 slots. The result is appended onto the Str
763 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
764 if (!StoredDiagMessage.empty()) {
765 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
770 getDiags()->getDiagnosticIDs()->getDescription(getID());
772 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
776 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
777 SmallVectorImpl<char> &OutStr) const {
778 // When the diagnostic string is only "%0", the entire string is being given
779 // by an outside source. Remove unprintable characters from this string
780 // and skip all the other string processing.
781 if (DiagEnd - DiagStr == 2 &&
782 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
783 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
784 const std::string &S = getArgStdStr(0);
786 if (llvm::sys::locale::isPrint(c) || c == '\t') {
793 /// FormattedArgs - Keep track of all of the arguments formatted by
794 /// ConvertArgToString and pass them into subsequent calls to
795 /// ConvertArgToString, allowing the implementation to avoid redundancies in
797 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
799 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
800 /// compared to see if more information is needed to be printed.
801 SmallVector<intptr_t, 2> QualTypeVals;
802 SmallVector<char, 64> Tree;
804 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
805 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
806 QualTypeVals.push_back(getRawArg(i));
808 while (DiagStr != DiagEnd) {
809 if (DiagStr[0] != '%') {
810 // Append non-%0 substrings to Str if we have one.
811 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
812 OutStr.append(DiagStr, StrEnd);
815 } else if (isPunctuation(DiagStr[1])) {
816 OutStr.push_back(DiagStr[1]); // %% -> %.
824 // This must be a placeholder for a diagnostic argument. The format for a
825 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
826 // The digit is a number from 0-9 indicating which argument this comes from.
827 // The modifier is a string of digits from the set [-a-z]+, arguments is a
828 // brace enclosed string.
829 const char *Modifier = nullptr, *Argument = nullptr;
830 unsigned ModifierLen = 0, ArgumentLen = 0;
832 // Check to see if we have a modifier. If so eat it.
833 if (!isDigit(DiagStr[0])) {
835 while (DiagStr[0] == '-' ||
836 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
838 ModifierLen = DiagStr-Modifier;
840 // If we have an argument, get it next.
841 if (DiagStr[0] == '{') {
842 ++DiagStr; // Skip {.
845 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
846 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
847 ArgumentLen = DiagStr-Argument;
848 ++DiagStr; // Skip }.
852 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
853 unsigned ArgNo = *DiagStr++ - '0';
855 // Only used for type diffing.
856 unsigned ArgNo2 = ArgNo;
858 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
859 if (ModifierIs(Modifier, ModifierLen, "diff")) {
860 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
861 "Invalid format for diff modifier");
863 ArgNo2 = *DiagStr++ - '0';
864 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
865 if (Kind == DiagnosticsEngine::ak_qualtype &&
866 Kind2 == DiagnosticsEngine::ak_qualtype)
867 Kind = DiagnosticsEngine::ak_qualtype_pair;
869 // %diff only supports QualTypes. For other kinds of arguments,
870 // use the default printing. For example, if the modifier is:
871 // "%diff{compare $ to $|other text}1,2"
873 // "compare %1 to %2"
874 const char *ArgumentEnd = Argument + ArgumentLen;
875 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
876 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
877 "Found too many '|'s in a %diff modifier!");
878 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
879 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
880 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
881 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
882 FormatDiagnostic(Argument, FirstDollar, OutStr);
883 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
884 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
885 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
886 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
893 case DiagnosticsEngine::ak_std_string: {
894 const std::string &S = getArgStdStr(ArgNo);
895 assert(ModifierLen == 0 && "No modifiers for strings yet");
896 OutStr.append(S.begin(), S.end());
899 case DiagnosticsEngine::ak_c_string: {
900 const char *S = getArgCStr(ArgNo);
901 assert(ModifierLen == 0 && "No modifiers for strings yet");
903 // Don't crash if get passed a null pointer by accident.
907 OutStr.append(S, S + strlen(S));
910 // ---- INTEGERS ----
911 case DiagnosticsEngine::ak_sint: {
912 int Val = getArgSInt(ArgNo);
914 if (ModifierIs(Modifier, ModifierLen, "select")) {
915 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
917 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
918 HandleIntegerSModifier(Val, OutStr);
919 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
920 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
922 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
923 HandleOrdinalModifier((unsigned)Val, OutStr);
925 assert(ModifierLen == 0 && "Unknown integer modifier");
926 llvm::raw_svector_ostream(OutStr) << Val;
930 case DiagnosticsEngine::ak_uint: {
931 unsigned Val = getArgUInt(ArgNo);
933 if (ModifierIs(Modifier, ModifierLen, "select")) {
934 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
935 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
936 HandleIntegerSModifier(Val, OutStr);
937 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
938 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
940 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
941 HandleOrdinalModifier(Val, OutStr);
943 assert(ModifierLen == 0 && "Unknown integer modifier");
944 llvm::raw_svector_ostream(OutStr) << Val;
948 // ---- TOKEN SPELLINGS ----
949 case DiagnosticsEngine::ak_tokenkind: {
950 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
951 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
953 llvm::raw_svector_ostream Out(OutStr);
954 if (const char *S = tok::getPunctuatorSpelling(Kind))
955 // Quoted token spelling for punctuators.
956 Out << '\'' << S << '\'';
957 else if (const char *S = tok::getKeywordSpelling(Kind))
958 // Unquoted token spelling for keywords.
960 else if (const char *S = getTokenDescForDiagnostic(Kind))
961 // Unquoted translatable token name.
963 else if (const char *S = tok::getTokenName(Kind))
964 // Debug name, shouldn't appear in user-facing diagnostics.
965 Out << '<' << S << '>';
970 // ---- NAMES and TYPES ----
971 case DiagnosticsEngine::ak_identifierinfo: {
972 const IdentifierInfo *II = getArgIdentifier(ArgNo);
973 assert(ModifierLen == 0 && "No modifiers for strings yet");
975 // Don't crash if get passed a null pointer by accident.
977 const char *S = "(null)";
978 OutStr.append(S, S + strlen(S));
982 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
985 case DiagnosticsEngine::ak_addrspace:
986 case DiagnosticsEngine::ak_qual:
987 case DiagnosticsEngine::ak_qualtype:
988 case DiagnosticsEngine::ak_declarationname:
989 case DiagnosticsEngine::ak_nameddecl:
990 case DiagnosticsEngine::ak_nestednamespec:
991 case DiagnosticsEngine::ak_declcontext:
992 case DiagnosticsEngine::ak_attr:
993 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
994 StringRef(Modifier, ModifierLen),
995 StringRef(Argument, ArgumentLen),
997 OutStr, QualTypeVals);
999 case DiagnosticsEngine::ak_qualtype_pair: {
1000 // Create a struct with all the info needed for printing.
1001 TemplateDiffTypes TDT;
1002 TDT.FromType = getRawArg(ArgNo);
1003 TDT.ToType = getRawArg(ArgNo2);
1004 TDT.ElideType = getDiags()->ElideType;
1005 TDT.ShowColors = getDiags()->ShowColors;
1006 TDT.TemplateDiffUsed = false;
1007 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1009 const char *ArgumentEnd = Argument + ArgumentLen;
1010 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1012 // Print the tree. If this diagnostic already has a tree, skip the
1014 if (getDiags()->PrintTemplateTree && Tree.empty()) {
1015 TDT.PrintFromType = true;
1016 TDT.PrintTree = true;
1017 getDiags()->ConvertArgToString(Kind, val,
1018 StringRef(Modifier, ModifierLen),
1019 StringRef(Argument, ArgumentLen),
1021 Tree, QualTypeVals);
1022 // If there is no tree information, fall back to regular printing.
1023 if (!Tree.empty()) {
1024 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1029 // Non-tree printing, also the fall-back when tree printing fails.
1030 // The fall-back is triggered when the types compared are not templates.
1031 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1032 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1034 // Append before text
1035 FormatDiagnostic(Argument, FirstDollar, OutStr);
1037 // Append first type
1038 TDT.PrintTree = false;
1039 TDT.PrintFromType = true;
1040 getDiags()->ConvertArgToString(Kind, val,
1041 StringRef(Modifier, ModifierLen),
1042 StringRef(Argument, ArgumentLen),
1044 OutStr, QualTypeVals);
1045 if (!TDT.TemplateDiffUsed)
1046 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1049 // Append middle text
1050 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1052 // Append second type
1053 TDT.PrintFromType = false;
1054 getDiags()->ConvertArgToString(Kind, val,
1055 StringRef(Modifier, ModifierLen),
1056 StringRef(Argument, ArgumentLen),
1058 OutStr, QualTypeVals);
1059 if (!TDT.TemplateDiffUsed)
1060 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1064 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1069 // Remember this argument info for subsequent formatting operations. Turn
1070 // std::strings into a null terminated string to make it be the same case as
1071 // all the other ones.
1072 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
1074 else if (Kind != DiagnosticsEngine::ak_std_string)
1075 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1077 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
1078 (intptr_t)getArgStdStr(ArgNo).c_str()));
1081 // Append the type tree to the end of the diagnostics.
1082 OutStr.append(Tree.begin(), Tree.end());
1085 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1087 : ID(ID), Level(Level), Message(Message) {}
1089 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
1090 const Diagnostic &Info)
1091 : ID(Info.getID()), Level(Level) {
1092 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1093 "Valid source location without setting a source manager for diagnostic");
1094 if (Info.getLocation().isValid())
1095 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1096 SmallString<64> Message;
1097 Info.FormatDiagnostic(Message);
1098 this->Message.assign(Message.begin(), Message.end());
1099 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1100 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1103 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1104 StringRef Message, FullSourceLoc Loc,
1105 ArrayRef<CharSourceRange> Ranges,
1106 ArrayRef<FixItHint> FixIts)
1107 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1108 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1112 /// IncludeInDiagnosticCounts - This method (whose default implementation
1113 /// returns true) indicates whether the diagnostics handled by this
1114 /// DiagnosticConsumer should be included in the number of diagnostics
1115 /// reported by DiagnosticsEngine.
1116 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1118 void IgnoringDiagConsumer::anchor() {}
1120 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;
1122 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1123 DiagnosticsEngine::Level DiagLevel,
1124 const Diagnostic &Info) {
1125 Target.HandleDiagnostic(DiagLevel, Info);
1128 void ForwardingDiagnosticConsumer::clear() {
1129 DiagnosticConsumer::clear();
1133 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1134 return Target.IncludeInDiagnosticCounts();
1137 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1138 for (unsigned I = 0; I != NumCached; ++I)
1139 FreeList[I] = Cached + I;
1140 NumFreeListEntries = NumCached;
1143 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1144 // Don't assert if we are in a CrashRecovery context, as this invariant may
1145 // be invalidated during a crash.
1146 assert((NumFreeListEntries == NumCached ||
1147 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1148 "A partial is on the lam");
1151 char DiagnosticError::ID;