1 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Diagnostic-related interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/PartialDiagnostic.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
26 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
27 StringRef Modifier, StringRef Argument,
28 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
29 SmallVectorImpl<char> &Output,
31 ArrayRef<intptr_t> QualTypeVals) {
32 StringRef Str = "<can't format argument>";
33 Output.append(Str.begin(), Str.end());
37 DiagnosticsEngine::DiagnosticsEngine(
38 const IntrusiveRefCntPtr<DiagnosticIDs> &diags,
39 DiagnosticOptions *DiagOpts,
40 DiagnosticConsumer *client, bool ShouldOwnClient)
41 : Diags(diags), DiagOpts(DiagOpts), Client(client),
42 OwnsDiagClient(ShouldOwnClient), SourceMgr(nullptr) {
43 ArgToStringFn = DummyArgToStringFn;
44 ArgToStringCookie = nullptr;
46 AllExtensionsSilenced = 0;
47 IgnoreAllWarnings = false;
48 WarningsAsErrors = false;
49 EnableAllWarnings = false;
50 ErrorsAsFatal = false;
51 SuppressSystemWarnings = false;
52 SuppressAllDiagnostics = false;
54 PrintTemplateTree = false;
56 ShowOverloads = Ovl_All;
57 ExtBehavior = diag::Severity::Ignored;
60 TemplateBacktraceLimit = 0;
61 ConstexprBacktraceLimit = 0;
66 DiagnosticsEngine::~DiagnosticsEngine() {
71 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
72 bool ShouldOwnClient) {
73 if (OwnsDiagClient && Client)
77 OwnsDiagClient = ShouldOwnClient;
80 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
81 DiagStateOnPushStack.push_back(GetCurDiagState());
84 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
85 if (DiagStateOnPushStack.empty())
88 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
89 // State changed at some point between push/pop.
90 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
92 DiagStateOnPushStack.pop_back();
96 void DiagnosticsEngine::Reset() {
97 ErrorOccurred = false;
98 UncompilableErrorOccurred = false;
99 FatalErrorOccurred = false;
100 UnrecoverableErrorOccurred = false;
104 NumErrorsSuppressed = 0;
105 TrapNumErrorsOccurred = 0;
106 TrapNumUnrecoverableErrorsOccurred = 0;
109 LastDiagLevel = DiagnosticIDs::Ignored;
112 // Clear state related to #pragma diagnostic.
114 DiagStatePoints.clear();
115 DiagStateOnPushStack.clear();
117 // Create a DiagState and DiagStatePoint representing diagnostic changes
118 // through command-line.
119 DiagStates.push_back(DiagState());
120 DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
123 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
128 DelayedDiagID = DiagID;
129 DelayedDiagArg1 = Arg1.str();
130 DelayedDiagArg2 = Arg2.str();
133 void DiagnosticsEngine::ReportDelayed() {
134 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
136 DelayedDiagArg1.clear();
137 DelayedDiagArg2.clear();
140 DiagnosticsEngine::DiagStatePointsTy::iterator
141 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
142 assert(!DiagStatePoints.empty());
143 assert(DiagStatePoints.front().Loc.isInvalid() &&
144 "Should have created a DiagStatePoint for command-line");
147 return DiagStatePoints.end() - 1;
149 FullSourceLoc Loc(L, *SourceMgr);
151 return DiagStatePoints.end() - 1;
153 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
154 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
155 if (LastStateChangePos.isValid() &&
156 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
157 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
158 DiagStatePoint(nullptr, Loc));
163 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
165 assert(Diag < diag::DIAG_UPPER_LIMIT &&
166 "Can only map builtin diagnostics");
167 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
168 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
169 "Cannot map errors into warnings!");
170 assert(!DiagStatePoints.empty());
171 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
173 FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc();
174 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
175 // Don't allow a mapping to a warning override an error/fatal mapping.
176 if (Map == diag::Severity::Warning) {
177 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
178 if (Info.getSeverity() == diag::Severity::Error ||
179 Info.getSeverity() == diag::Severity::Fatal)
180 Map = Info.getSeverity();
182 DiagnosticMapping Mapping = makeUserMapping(Map, L);
184 // Common case; setting all the diagnostics of a group in one place.
185 if (Loc.isInvalid() || Loc == LastStateChangePos) {
186 GetCurDiagState()->setMapping(Diag, Mapping);
190 // Another common case; modifying diagnostic state in a source location
191 // after the previous one.
192 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
193 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
194 // A diagnostic pragma occurred, create a new DiagState initialized with
195 // the current one and a new DiagStatePoint to record at which location
196 // the new state became active.
197 DiagStates.push_back(*GetCurDiagState());
198 PushDiagStatePoint(&DiagStates.back(), Loc);
199 GetCurDiagState()->setMapping(Diag, Mapping);
203 // We allow setting the diagnostic state in random source order for
204 // completeness but it should not be actually happening in normal practice.
206 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
207 assert(Pos != DiagStatePoints.end());
209 // Update all diagnostic states that are active after the given location.
210 for (DiagStatePointsTy::iterator
211 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
212 GetCurDiagState()->setMapping(Diag, Mapping);
215 // If the location corresponds to an existing point, just update its state.
216 if (Pos->Loc == Loc) {
217 GetCurDiagState()->setMapping(Diag, Mapping);
221 // Create a new state/point and fit it into the vector of DiagStatePoints
222 // so that the vector is always ordered according to location.
223 assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc));
224 DiagStates.push_back(*Pos->State);
225 DiagState *NewState = &DiagStates.back();
226 GetCurDiagState()->setMapping(Diag, Mapping);
227 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
228 FullSourceLoc(Loc, *SourceMgr)));
231 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
232 StringRef Group, diag::Severity Map,
233 SourceLocation Loc) {
234 // Get the diagnostics in this group.
235 SmallVector<diag::kind, 8> GroupDiags;
236 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
240 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i)
241 setSeverity(GroupDiags[i], Map, Loc);
246 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
248 // If we are enabling this feature, just set the diagnostic mappings to map to
251 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
252 diag::Severity::Error);
254 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
255 // potentially downgrade anything already mapped to be a warning.
257 // Get the diagnostics in this group.
258 SmallVector<diag::kind, 8> GroupDiags;
259 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
263 // Perform the mapping change.
264 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
265 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]);
267 if (Info.getSeverity() == diag::Severity::Error ||
268 Info.getSeverity() == diag::Severity::Fatal)
269 Info.setSeverity(diag::Severity::Warning);
271 Info.setNoWarningAsError(true);
277 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
279 // If we are enabling this feature, just set the diagnostic mappings to map to
282 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
283 diag::Severity::Fatal);
285 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
286 // potentially downgrade anything already mapped to be an error.
288 // Get the diagnostics in this group.
289 SmallVector<diag::kind, 8> GroupDiags;
290 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
294 // Perform the mapping change.
295 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
296 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]);
298 if (Info.getSeverity() == diag::Severity::Fatal)
299 Info.setSeverity(diag::Severity::Error);
301 Info.setNoErrorAsFatal(true);
307 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
309 SourceLocation Loc) {
310 // Get all the diagnostics.
311 SmallVector<diag::kind, 64> AllDiags;
312 Diags->getAllDiagnostics(Flavor, AllDiags);
315 for (unsigned i = 0, e = AllDiags.size(); i != e; ++i)
316 if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
317 setSeverity(AllDiags[i], Map, Loc);
320 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
321 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
323 CurDiagLoc = storedDiag.getLocation();
324 CurDiagID = storedDiag.getID();
328 DiagRanges.reserve(storedDiag.range_size());
329 for (StoredDiagnostic::range_iterator
330 RI = storedDiag.range_begin(),
331 RE = storedDiag.range_end(); RI != RE; ++RI)
332 DiagRanges.push_back(*RI);
334 DiagFixItHints.clear();
335 DiagFixItHints.reserve(storedDiag.fixit_size());
336 for (StoredDiagnostic::fixit_iterator
337 FI = storedDiag.fixit_begin(),
338 FE = storedDiag.fixit_end(); FI != FE; ++FI)
339 DiagFixItHints.push_back(*FI);
341 assert(Client && "DiagnosticConsumer not set!");
342 Level DiagLevel = storedDiag.getLevel();
343 Diagnostic Info(this, storedDiag.getMessage());
344 Client->HandleDiagnostic(DiagLevel, Info);
345 if (Client->IncludeInDiagnosticCounts()) {
346 if (DiagLevel == DiagnosticsEngine::Warning)
353 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
354 assert(getClient() && "DiagnosticClient not set!");
358 Diagnostic Info(this);
360 // Figure out the diagnostic level of this message.
361 DiagnosticIDs::Level DiagLevel
362 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
364 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
366 // Emit the diagnostic regardless of suppression level.
367 Diags->EmitDiag(*this, DiagLevel);
370 // Process the diagnostic, sending the accumulated information to the
371 // DiagnosticConsumer.
372 Emitted = ProcessDiag();
375 // Clear out the current diagnostic object.
376 unsigned DiagID = CurDiagID;
379 // If there was a delayed diagnostic, emit it now.
380 if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
387 DiagnosticConsumer::~DiagnosticConsumer() {}
389 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
390 const Diagnostic &Info) {
391 if (!IncludeInDiagnosticCounts())
394 if (DiagLevel == DiagnosticsEngine::Warning)
396 else if (DiagLevel >= DiagnosticsEngine::Error)
400 /// ModifierIs - Return true if the specified modifier matches specified string.
401 template <std::size_t StrLen>
402 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
403 const char (&Str)[StrLen]) {
404 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
407 /// ScanForward - Scans forward, looking for the given character, skipping
408 /// nested clauses and escaped characters.
409 static const char *ScanFormat(const char *I, const char *E, char Target) {
412 for ( ; I != E; ++I) {
413 if (Depth == 0 && *I == Target) return I;
414 if (Depth != 0 && *I == '}') Depth--;
420 // Escaped characters get implicitly skipped here.
423 if (!isDigit(*I) && !isPunctuation(*I)) {
424 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
434 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
435 /// like this: %select{foo|bar|baz}2. This means that the integer argument
436 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
437 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
438 /// This is very useful for certain classes of variant diagnostics.
439 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
440 const char *Argument, unsigned ArgumentLen,
441 SmallVectorImpl<char> &OutStr) {
442 const char *ArgumentEnd = Argument+ArgumentLen;
444 // Skip over 'ValNo' |'s.
446 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
447 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
448 " larger than the number of options in the diagnostic string!");
449 Argument = NextVal+1; // Skip this string.
453 // Get the end of the value. This is either the } or the |.
454 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
456 // Recursively format the result of the select clause into the output string.
457 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
460 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
461 /// letter 's' to the string if the value is not 1. This is used in cases like
462 /// this: "you idiot, you have %4 parameter%s4!".
463 static void HandleIntegerSModifier(unsigned ValNo,
464 SmallVectorImpl<char> &OutStr) {
466 OutStr.push_back('s');
469 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
470 /// prints the ordinal form of the given integer, with 1 corresponding
471 /// to the first ordinal. Currently this is hard-coded to use the
473 static void HandleOrdinalModifier(unsigned ValNo,
474 SmallVectorImpl<char> &OutStr) {
475 assert(ValNo != 0 && "ValNo must be strictly positive!");
477 llvm::raw_svector_ostream Out(OutStr);
479 // We could use text forms for the first N ordinals, but the numeric
480 // forms are actually nicer in diagnostics because they stand out.
481 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
485 /// PluralNumber - Parse an unsigned integer and advance Start.
486 static unsigned PluralNumber(const char *&Start, const char *End) {
487 // Programming 101: Parse a decimal number :-)
489 while (Start != End && *Start >= '0' && *Start <= '9') {
497 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
498 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
500 unsigned Ref = PluralNumber(Start, End);
505 unsigned Low = PluralNumber(Start, End);
506 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
508 unsigned High = PluralNumber(Start, End);
509 assert(*Start == ']' && "Bad plural expression syntax: expected )");
511 return Low <= Val && Val <= High;
514 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
515 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
525 unsigned Arg = PluralNumber(Start, End);
526 assert(*Start == '=' && "Bad plural expression syntax: expected =");
528 unsigned ValMod = ValNo % Arg;
529 if (TestPluralRange(ValMod, Start, End))
532 assert((C == '[' || (C >= '0' && C <= '9')) &&
533 "Bad plural expression syntax: unexpected character");
535 if (TestPluralRange(ValNo, Start, End))
539 // Scan for next or-expr part.
540 Start = std::find(Start, End, ',');
548 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
549 /// for complex plural forms, or in languages where all plurals are complex.
550 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
551 /// conditions that are tested in order, the form corresponding to the first
552 /// that applies being emitted. The empty condition is always true, making the
553 /// last form a default case.
554 /// Conditions are simple boolean expressions, where n is the number argument.
555 /// Here are the rules.
556 /// condition := expression | empty
557 /// empty := -> always true
558 /// expression := numeric [',' expression] -> logical or
559 /// numeric := range -> true if n in range
560 /// | '%' number '=' range -> true if n % number in range
562 /// | '[' number ',' number ']' -> ranges are inclusive both ends
564 /// Here are some examples from the GNU gettext manual written in this form:
568 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
570 /// {1:form0|2:form1|:form2}
572 /// {1:form0|0,%100=[1,19]:form1|:form2}
574 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
575 /// Russian (requires repeated form):
576 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
578 /// {1:form0|[2,4]:form1|:form2}
579 /// Polish (requires repeated form):
580 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
581 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
582 const char *Argument, unsigned ArgumentLen,
583 SmallVectorImpl<char> &OutStr) {
584 const char *ArgumentEnd = Argument + ArgumentLen;
586 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
587 const char *ExprEnd = Argument;
588 while (*ExprEnd != ':') {
589 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
592 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
593 Argument = ExprEnd + 1;
594 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
596 // Recursively format the result of the plural clause into the
598 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
601 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
605 /// \brief Returns the friendly description for a token kind that will appear
606 /// without quotes in diagnostic messages. These strings may be translatable in
608 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
610 case tok::identifier:
617 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
618 /// formal arguments into the %0 slots. The result is appended onto the Str
621 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
622 if (!StoredDiagMessage.empty()) {
623 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
628 getDiags()->getDiagnosticIDs()->getDescription(getID());
630 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
634 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
635 SmallVectorImpl<char> &OutStr) const {
637 /// FormattedArgs - Keep track of all of the arguments formatted by
638 /// ConvertArgToString and pass them into subsequent calls to
639 /// ConvertArgToString, allowing the implementation to avoid redundancies in
641 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
643 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
644 /// compared to see if more information is needed to be printed.
645 SmallVector<intptr_t, 2> QualTypeVals;
646 SmallVector<char, 64> Tree;
648 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
649 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
650 QualTypeVals.push_back(getRawArg(i));
652 while (DiagStr != DiagEnd) {
653 if (DiagStr[0] != '%') {
654 // Append non-%0 substrings to Str if we have one.
655 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
656 OutStr.append(DiagStr, StrEnd);
659 } else if (isPunctuation(DiagStr[1])) {
660 OutStr.push_back(DiagStr[1]); // %% -> %.
668 // This must be a placeholder for a diagnostic argument. The format for a
669 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
670 // The digit is a number from 0-9 indicating which argument this comes from.
671 // The modifier is a string of digits from the set [-a-z]+, arguments is a
672 // brace enclosed string.
673 const char *Modifier = nullptr, *Argument = nullptr;
674 unsigned ModifierLen = 0, ArgumentLen = 0;
676 // Check to see if we have a modifier. If so eat it.
677 if (!isDigit(DiagStr[0])) {
679 while (DiagStr[0] == '-' ||
680 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
682 ModifierLen = DiagStr-Modifier;
684 // If we have an argument, get it next.
685 if (DiagStr[0] == '{') {
686 ++DiagStr; // Skip {.
689 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
690 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
691 ArgumentLen = DiagStr-Argument;
692 ++DiagStr; // Skip }.
696 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
697 unsigned ArgNo = *DiagStr++ - '0';
699 // Only used for type diffing.
700 unsigned ArgNo2 = ArgNo;
702 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
703 if (ModifierIs(Modifier, ModifierLen, "diff")) {
704 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
705 "Invalid format for diff modifier");
707 ArgNo2 = *DiagStr++ - '0';
708 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
709 if (Kind == DiagnosticsEngine::ak_qualtype &&
710 Kind2 == DiagnosticsEngine::ak_qualtype)
711 Kind = DiagnosticsEngine::ak_qualtype_pair;
713 // %diff only supports QualTypes. For other kinds of arguments,
714 // use the default printing. For example, if the modifier is:
715 // "%diff{compare $ to $|other text}1,2"
717 // "compare %1 to %2"
718 const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|');
719 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
720 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
721 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
722 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
723 FormatDiagnostic(Argument, FirstDollar, OutStr);
724 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
725 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
726 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
727 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
734 case DiagnosticsEngine::ak_std_string: {
735 const std::string &S = getArgStdStr(ArgNo);
736 assert(ModifierLen == 0 && "No modifiers for strings yet");
737 OutStr.append(S.begin(), S.end());
740 case DiagnosticsEngine::ak_c_string: {
741 const char *S = getArgCStr(ArgNo);
742 assert(ModifierLen == 0 && "No modifiers for strings yet");
744 // Don't crash if get passed a null pointer by accident.
748 OutStr.append(S, S + strlen(S));
751 // ---- INTEGERS ----
752 case DiagnosticsEngine::ak_sint: {
753 int Val = getArgSInt(ArgNo);
755 if (ModifierIs(Modifier, ModifierLen, "select")) {
756 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
758 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
759 HandleIntegerSModifier(Val, OutStr);
760 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
761 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
763 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
764 HandleOrdinalModifier((unsigned)Val, OutStr);
766 assert(ModifierLen == 0 && "Unknown integer modifier");
767 llvm::raw_svector_ostream(OutStr) << Val;
771 case DiagnosticsEngine::ak_uint: {
772 unsigned Val = getArgUInt(ArgNo);
774 if (ModifierIs(Modifier, ModifierLen, "select")) {
775 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
776 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
777 HandleIntegerSModifier(Val, OutStr);
778 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
779 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
781 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
782 HandleOrdinalModifier(Val, OutStr);
784 assert(ModifierLen == 0 && "Unknown integer modifier");
785 llvm::raw_svector_ostream(OutStr) << Val;
789 // ---- TOKEN SPELLINGS ----
790 case DiagnosticsEngine::ak_tokenkind: {
791 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
792 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
794 llvm::raw_svector_ostream Out(OutStr);
795 if (const char *S = tok::getPunctuatorSpelling(Kind))
796 // Quoted token spelling for punctuators.
797 Out << '\'' << S << '\'';
798 else if (const char *S = tok::getKeywordSpelling(Kind))
799 // Unquoted token spelling for keywords.
801 else if (const char *S = getTokenDescForDiagnostic(Kind))
802 // Unquoted translatable token name.
804 else if (const char *S = tok::getTokenName(Kind))
805 // Debug name, shouldn't appear in user-facing diagnostics.
806 Out << '<' << S << '>';
811 // ---- NAMES and TYPES ----
812 case DiagnosticsEngine::ak_identifierinfo: {
813 const IdentifierInfo *II = getArgIdentifier(ArgNo);
814 assert(ModifierLen == 0 && "No modifiers for strings yet");
816 // Don't crash if get passed a null pointer by accident.
818 const char *S = "(null)";
819 OutStr.append(S, S + strlen(S));
823 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
826 case DiagnosticsEngine::ak_qualtype:
827 case DiagnosticsEngine::ak_declarationname:
828 case DiagnosticsEngine::ak_nameddecl:
829 case DiagnosticsEngine::ak_nestednamespec:
830 case DiagnosticsEngine::ak_declcontext:
831 case DiagnosticsEngine::ak_attr:
832 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
833 StringRef(Modifier, ModifierLen),
834 StringRef(Argument, ArgumentLen),
836 OutStr, QualTypeVals);
838 case DiagnosticsEngine::ak_qualtype_pair:
839 // Create a struct with all the info needed for printing.
840 TemplateDiffTypes TDT;
841 TDT.FromType = getRawArg(ArgNo);
842 TDT.ToType = getRawArg(ArgNo2);
843 TDT.ElideType = getDiags()->ElideType;
844 TDT.ShowColors = getDiags()->ShowColors;
845 TDT.TemplateDiffUsed = false;
846 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
848 const char *ArgumentEnd = Argument + ArgumentLen;
849 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
851 // Print the tree. If this diagnostic already has a tree, skip the
853 if (getDiags()->PrintTemplateTree && Tree.empty()) {
854 TDT.PrintFromType = true;
855 TDT.PrintTree = true;
856 getDiags()->ConvertArgToString(Kind, val,
857 StringRef(Modifier, ModifierLen),
858 StringRef(Argument, ArgumentLen),
861 // If there is no tree information, fall back to regular printing.
863 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
868 // Non-tree printing, also the fall-back when tree printing fails.
869 // The fall-back is triggered when the types compared are not templates.
870 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
871 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
873 // Append before text
874 FormatDiagnostic(Argument, FirstDollar, OutStr);
877 TDT.PrintTree = false;
878 TDT.PrintFromType = true;
879 getDiags()->ConvertArgToString(Kind, val,
880 StringRef(Modifier, ModifierLen),
881 StringRef(Argument, ArgumentLen),
883 OutStr, QualTypeVals);
884 if (!TDT.TemplateDiffUsed)
885 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
888 // Append middle text
889 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
891 // Append second type
892 TDT.PrintFromType = false;
893 getDiags()->ConvertArgToString(Kind, val,
894 StringRef(Modifier, ModifierLen),
895 StringRef(Argument, ArgumentLen),
897 OutStr, QualTypeVals);
898 if (!TDT.TemplateDiffUsed)
899 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
903 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
907 // Remember this argument info for subsequent formatting operations. Turn
908 // std::strings into a null terminated string to make it be the same case as
909 // all the other ones.
910 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
912 else if (Kind != DiagnosticsEngine::ak_std_string)
913 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
915 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
916 (intptr_t)getArgStdStr(ArgNo).c_str()));
920 // Append the type tree to the end of the diagnostics.
921 OutStr.append(Tree.begin(), Tree.end());
924 StoredDiagnostic::StoredDiagnostic() { }
926 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
928 : ID(ID), Level(Level), Loc(), Message(Message) { }
930 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
931 const Diagnostic &Info)
932 : ID(Info.getID()), Level(Level)
934 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
935 "Valid source location without setting a source manager for diagnostic");
936 if (Info.getLocation().isValid())
937 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
938 SmallString<64> Message;
939 Info.FormatDiagnostic(Message);
940 this->Message.assign(Message.begin(), Message.end());
942 Ranges.reserve(Info.getNumRanges());
943 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
944 Ranges.push_back(Info.getRange(I));
946 FixIts.reserve(Info.getNumFixItHints());
947 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
948 FixIts.push_back(Info.getFixItHint(I));
951 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
952 StringRef Message, FullSourceLoc Loc,
953 ArrayRef<CharSourceRange> Ranges,
954 ArrayRef<FixItHint> FixIts)
955 : ID(ID), Level(Level), Loc(Loc), Message(Message),
956 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
960 StoredDiagnostic::~StoredDiagnostic() { }
962 /// IncludeInDiagnosticCounts - This method (whose default implementation
963 /// returns true) indicates whether the diagnostics handled by this
964 /// DiagnosticConsumer should be included in the number of diagnostics
965 /// reported by DiagnosticsEngine.
966 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
968 void IgnoringDiagConsumer::anchor() { }
970 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
972 void ForwardingDiagnosticConsumer::HandleDiagnostic(
973 DiagnosticsEngine::Level DiagLevel,
974 const Diagnostic &Info) {
975 Target.HandleDiagnostic(DiagLevel, Info);
978 void ForwardingDiagnosticConsumer::clear() {
979 DiagnosticConsumer::clear();
983 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
984 return Target.IncludeInDiagnosticCounts();
987 PartialDiagnostic::StorageAllocator::StorageAllocator() {
988 for (unsigned I = 0; I != NumCached; ++I)
989 FreeList[I] = Cached + I;
990 NumFreeListEntries = NumCached;
993 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
994 // Don't assert if we are in a CrashRecovery context, as this invariant may
995 // be invalidated during a crash.
996 assert((NumFreeListEntries == NumCached ||
997 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
998 "A partial is on the lamb");