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/Locale.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
28 DiagNullabilityKind nullability) {
30 switch (nullability.first) {
31 case NullabilityKind::NonNull:
32 string = nullability.second ? "'nonnull'" : "'_Nonnull'";
35 case NullabilityKind::Nullable:
36 string = nullability.second ? "'nullable'" : "'_Nullable'";
39 case NullabilityKind::Unspecified:
40 string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
48 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
49 StringRef Modifier, StringRef Argument,
50 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
51 SmallVectorImpl<char> &Output,
53 ArrayRef<intptr_t> QualTypeVals) {
54 StringRef Str = "<can't format argument>";
55 Output.append(Str.begin(), Str.end());
58 DiagnosticsEngine::DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> diags,
59 DiagnosticOptions *DiagOpts,
60 DiagnosticConsumer *client,
62 : Diags(std::move(diags)), DiagOpts(DiagOpts), Client(nullptr),
64 setClient(client, ShouldOwnClient);
65 ArgToStringFn = DummyArgToStringFn;
66 ArgToStringCookie = nullptr;
68 AllExtensionsSilenced = 0;
69 IgnoreAllWarnings = false;
70 WarningsAsErrors = false;
71 EnableAllWarnings = false;
72 ErrorsAsFatal = false;
73 FatalsAsError = false;
74 SuppressSystemWarnings = false;
75 SuppressAllDiagnostics = false;
77 PrintTemplateTree = false;
79 ShowOverloads = Ovl_All;
80 ExtBehavior = diag::Severity::Ignored;
83 TemplateBacktraceLimit = 0;
84 ConstexprBacktraceLimit = 0;
89 DiagnosticsEngine::~DiagnosticsEngine() {
90 // If we own the diagnostic client, destroy it first so that it can access the
91 // engine from its destructor.
95 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
96 bool ShouldOwnClient) {
97 Owner.reset(ShouldOwnClient ? client : nullptr);
101 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
102 DiagStateOnPushStack.push_back(GetCurDiagState());
105 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
106 if (DiagStateOnPushStack.empty())
109 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
110 // State changed at some point between push/pop.
111 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
113 DiagStateOnPushStack.pop_back();
117 void DiagnosticsEngine::Reset() {
118 ErrorOccurred = false;
119 UncompilableErrorOccurred = false;
120 FatalErrorOccurred = false;
121 UnrecoverableErrorOccurred = false;
125 TrapNumErrorsOccurred = 0;
126 TrapNumUnrecoverableErrorsOccurred = 0;
129 LastDiagLevel = DiagnosticIDs::Ignored;
132 // Clear state related to #pragma diagnostic.
134 DiagStatePoints.clear();
135 DiagStateOnPushStack.clear();
137 // Create a DiagState and DiagStatePoint representing diagnostic changes
138 // through command-line.
139 DiagStates.emplace_back();
140 DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
143 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
148 DelayedDiagID = DiagID;
149 DelayedDiagArg1 = Arg1.str();
150 DelayedDiagArg2 = Arg2.str();
153 void DiagnosticsEngine::ReportDelayed() {
154 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
156 DelayedDiagArg1.clear();
157 DelayedDiagArg2.clear();
160 DiagnosticsEngine::DiagStatePointsTy::iterator
161 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
162 assert(!DiagStatePoints.empty());
163 assert(DiagStatePoints.front().Loc.isInvalid() &&
164 "Should have created a DiagStatePoint for command-line");
167 return DiagStatePoints.end() - 1;
169 FullSourceLoc Loc(L, *SourceMgr);
171 return DiagStatePoints.end() - 1;
173 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
174 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
175 if (LastStateChangePos.isValid() &&
176 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
177 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
178 DiagStatePoint(nullptr, Loc));
183 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
185 assert(Diag < diag::DIAG_UPPER_LIMIT &&
186 "Can only map builtin diagnostics");
187 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
188 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
189 "Cannot map errors into warnings!");
190 assert(!DiagStatePoints.empty());
191 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
193 FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc();
194 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
195 // Don't allow a mapping to a warning override an error/fatal mapping.
196 if (Map == diag::Severity::Warning) {
197 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
198 if (Info.getSeverity() == diag::Severity::Error ||
199 Info.getSeverity() == diag::Severity::Fatal)
200 Map = Info.getSeverity();
202 DiagnosticMapping Mapping = makeUserMapping(Map, L);
204 // Common case; setting all the diagnostics of a group in one place.
205 if (Loc.isInvalid() || Loc == LastStateChangePos) {
206 GetCurDiagState()->setMapping(Diag, Mapping);
210 // Another common case; modifying diagnostic state in a source location
211 // after the previous one.
212 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
213 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
214 // A diagnostic pragma occurred, create a new DiagState initialized with
215 // the current one and a new DiagStatePoint to record at which location
216 // the new state became active.
217 DiagStates.push_back(*GetCurDiagState());
218 PushDiagStatePoint(&DiagStates.back(), Loc);
219 GetCurDiagState()->setMapping(Diag, Mapping);
223 // We allow setting the diagnostic state in random source order for
224 // completeness but it should not be actually happening in normal practice.
226 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
227 assert(Pos != DiagStatePoints.end());
229 // Update all diagnostic states that are active after the given location.
230 for (DiagStatePointsTy::iterator
231 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
232 I->State->setMapping(Diag, Mapping);
235 // If the location corresponds to an existing point, just update its state.
236 if (Pos->Loc == Loc) {
237 Pos->State->setMapping(Diag, Mapping);
241 // Create a new state/point and fit it into the vector of DiagStatePoints
242 // so that the vector is always ordered according to location.
243 assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc));
244 DiagStates.push_back(*Pos->State);
245 DiagState *NewState = &DiagStates.back();
246 NewState->setMapping(Diag, Mapping);
247 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
248 FullSourceLoc(Loc, *SourceMgr)));
251 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
252 StringRef Group, diag::Severity Map,
253 SourceLocation Loc) {
254 // Get the diagnostics in this group.
255 SmallVector<diag::kind, 256> GroupDiags;
256 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
260 for (diag::kind Diag : GroupDiags)
261 setSeverity(Diag, Map, Loc);
266 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
268 // If we are enabling this feature, just set the diagnostic mappings to map to
271 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
272 diag::Severity::Error);
274 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
275 // potentially downgrade anything already mapped to be a warning.
277 // Get the diagnostics in this group.
278 SmallVector<diag::kind, 8> GroupDiags;
279 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
283 // Perform the mapping change.
284 for (diag::kind Diag : GroupDiags) {
285 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
287 if (Info.getSeverity() == diag::Severity::Error ||
288 Info.getSeverity() == diag::Severity::Fatal)
289 Info.setSeverity(diag::Severity::Warning);
291 Info.setNoWarningAsError(true);
297 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
299 // If we are enabling this feature, just set the diagnostic mappings to map to
302 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
303 diag::Severity::Fatal);
305 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
306 // potentially downgrade anything already mapped to be an error.
308 // Get the diagnostics in this group.
309 SmallVector<diag::kind, 8> GroupDiags;
310 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
314 // Perform the mapping change.
315 for (diag::kind Diag : GroupDiags) {
316 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
318 if (Info.getSeverity() == diag::Severity::Fatal)
319 Info.setSeverity(diag::Severity::Error);
321 Info.setNoErrorAsFatal(true);
327 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
329 SourceLocation Loc) {
330 // Get all the diagnostics.
331 SmallVector<diag::kind, 64> AllDiags;
332 Diags->getAllDiagnostics(Flavor, AllDiags);
335 for (diag::kind Diag : AllDiags)
336 if (Diags->isBuiltinWarningOrExtension(Diag))
337 setSeverity(Diag, Map, Loc);
340 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
341 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
343 CurDiagLoc = storedDiag.getLocation();
344 CurDiagID = storedDiag.getID();
348 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
350 DiagFixItHints.clear();
351 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
353 assert(Client && "DiagnosticConsumer not set!");
354 Level DiagLevel = storedDiag.getLevel();
355 Diagnostic Info(this, storedDiag.getMessage());
356 Client->HandleDiagnostic(DiagLevel, Info);
357 if (Client->IncludeInDiagnosticCounts()) {
358 if (DiagLevel == DiagnosticsEngine::Warning)
365 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
366 assert(getClient() && "DiagnosticClient not set!");
370 Diagnostic Info(this);
372 // Figure out the diagnostic level of this message.
373 DiagnosticIDs::Level DiagLevel
374 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
376 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
378 // Emit the diagnostic regardless of suppression level.
379 Diags->EmitDiag(*this, DiagLevel);
382 // Process the diagnostic, sending the accumulated information to the
383 // DiagnosticConsumer.
384 Emitted = ProcessDiag();
387 // Clear out the current diagnostic object.
388 unsigned DiagID = CurDiagID;
391 // If there was a delayed diagnostic, emit it now.
392 if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
399 DiagnosticConsumer::~DiagnosticConsumer() {}
401 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
402 const Diagnostic &Info) {
403 if (!IncludeInDiagnosticCounts())
406 if (DiagLevel == DiagnosticsEngine::Warning)
408 else if (DiagLevel >= DiagnosticsEngine::Error)
412 /// ModifierIs - Return true if the specified modifier matches specified string.
413 template <std::size_t StrLen>
414 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
415 const char (&Str)[StrLen]) {
416 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
419 /// ScanForward - Scans forward, looking for the given character, skipping
420 /// nested clauses and escaped characters.
421 static const char *ScanFormat(const char *I, const char *E, char Target) {
424 for ( ; I != E; ++I) {
425 if (Depth == 0 && *I == Target) return I;
426 if (Depth != 0 && *I == '}') Depth--;
432 // Escaped characters get implicitly skipped here.
435 if (!isDigit(*I) && !isPunctuation(*I)) {
436 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
446 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
447 /// like this: %select{foo|bar|baz}2. This means that the integer argument
448 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
449 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
450 /// This is very useful for certain classes of variant diagnostics.
451 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
452 const char *Argument, unsigned ArgumentLen,
453 SmallVectorImpl<char> &OutStr) {
454 const char *ArgumentEnd = Argument+ArgumentLen;
456 // Skip over 'ValNo' |'s.
458 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
459 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
460 " larger than the number of options in the diagnostic string!");
461 Argument = NextVal+1; // Skip this string.
465 // Get the end of the value. This is either the } or the |.
466 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
468 // Recursively format the result of the select clause into the output string.
469 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
472 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
473 /// letter 's' to the string if the value is not 1. This is used in cases like
474 /// this: "you idiot, you have %4 parameter%s4!".
475 static void HandleIntegerSModifier(unsigned ValNo,
476 SmallVectorImpl<char> &OutStr) {
478 OutStr.push_back('s');
481 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
482 /// prints the ordinal form of the given integer, with 1 corresponding
483 /// to the first ordinal. Currently this is hard-coded to use the
485 static void HandleOrdinalModifier(unsigned ValNo,
486 SmallVectorImpl<char> &OutStr) {
487 assert(ValNo != 0 && "ValNo must be strictly positive!");
489 llvm::raw_svector_ostream Out(OutStr);
491 // We could use text forms for the first N ordinals, but the numeric
492 // forms are actually nicer in diagnostics because they stand out.
493 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
497 /// PluralNumber - Parse an unsigned integer and advance Start.
498 static unsigned PluralNumber(const char *&Start, const char *End) {
499 // Programming 101: Parse a decimal number :-)
501 while (Start != End && *Start >= '0' && *Start <= '9') {
509 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
510 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
512 unsigned Ref = PluralNumber(Start, End);
517 unsigned Low = PluralNumber(Start, End);
518 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
520 unsigned High = PluralNumber(Start, End);
521 assert(*Start == ']' && "Bad plural expression syntax: expected )");
523 return Low <= Val && Val <= High;
526 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
527 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
537 unsigned Arg = PluralNumber(Start, End);
538 assert(*Start == '=' && "Bad plural expression syntax: expected =");
540 unsigned ValMod = ValNo % Arg;
541 if (TestPluralRange(ValMod, Start, End))
544 assert((C == '[' || (C >= '0' && C <= '9')) &&
545 "Bad plural expression syntax: unexpected character");
547 if (TestPluralRange(ValNo, Start, End))
551 // Scan for next or-expr part.
552 Start = std::find(Start, End, ',');
560 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
561 /// for complex plural forms, or in languages where all plurals are complex.
562 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
563 /// conditions that are tested in order, the form corresponding to the first
564 /// that applies being emitted. The empty condition is always true, making the
565 /// last form a default case.
566 /// Conditions are simple boolean expressions, where n is the number argument.
567 /// Here are the rules.
568 /// condition := expression | empty
569 /// empty := -> always true
570 /// expression := numeric [',' expression] -> logical or
571 /// numeric := range -> true if n in range
572 /// | '%' number '=' range -> true if n % number in range
574 /// | '[' number ',' number ']' -> ranges are inclusive both ends
576 /// Here are some examples from the GNU gettext manual written in this form:
580 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
582 /// {1:form0|2:form1|:form2}
584 /// {1:form0|0,%100=[1,19]:form1|:form2}
586 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
587 /// Russian (requires repeated form):
588 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
590 /// {1:form0|[2,4]:form1|:form2}
591 /// Polish (requires repeated form):
592 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
593 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
594 const char *Argument, unsigned ArgumentLen,
595 SmallVectorImpl<char> &OutStr) {
596 const char *ArgumentEnd = Argument + ArgumentLen;
598 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
599 const char *ExprEnd = Argument;
600 while (*ExprEnd != ':') {
601 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
604 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
605 Argument = ExprEnd + 1;
606 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
608 // Recursively format the result of the plural clause into the
610 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
613 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
617 /// \brief Returns the friendly description for a token kind that will appear
618 /// without quotes in diagnostic messages. These strings may be translatable in
620 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
622 case tok::identifier:
629 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
630 /// formal arguments into the %0 slots. The result is appended onto the Str
633 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
634 if (!StoredDiagMessage.empty()) {
635 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
640 getDiags()->getDiagnosticIDs()->getDescription(getID());
642 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
646 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
647 SmallVectorImpl<char> &OutStr) const {
649 // When the diagnostic string is only "%0", the entire string is being given
650 // by an outside source. Remove unprintable characters from this string
651 // and skip all the other string processing.
652 if (DiagEnd - DiagStr == 2 &&
653 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
654 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
655 const std::string &S = getArgStdStr(0);
657 if (llvm::sys::locale::isPrint(c) || c == '\t') {
664 /// FormattedArgs - Keep track of all of the arguments formatted by
665 /// ConvertArgToString and pass them into subsequent calls to
666 /// ConvertArgToString, allowing the implementation to avoid redundancies in
668 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
670 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
671 /// compared to see if more information is needed to be printed.
672 SmallVector<intptr_t, 2> QualTypeVals;
673 SmallVector<char, 64> Tree;
675 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
676 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
677 QualTypeVals.push_back(getRawArg(i));
679 while (DiagStr != DiagEnd) {
680 if (DiagStr[0] != '%') {
681 // Append non-%0 substrings to Str if we have one.
682 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
683 OutStr.append(DiagStr, StrEnd);
686 } else if (isPunctuation(DiagStr[1])) {
687 OutStr.push_back(DiagStr[1]); // %% -> %.
695 // This must be a placeholder for a diagnostic argument. The format for a
696 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
697 // The digit is a number from 0-9 indicating which argument this comes from.
698 // The modifier is a string of digits from the set [-a-z]+, arguments is a
699 // brace enclosed string.
700 const char *Modifier = nullptr, *Argument = nullptr;
701 unsigned ModifierLen = 0, ArgumentLen = 0;
703 // Check to see if we have a modifier. If so eat it.
704 if (!isDigit(DiagStr[0])) {
706 while (DiagStr[0] == '-' ||
707 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
709 ModifierLen = DiagStr-Modifier;
711 // If we have an argument, get it next.
712 if (DiagStr[0] == '{') {
713 ++DiagStr; // Skip {.
716 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
717 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
718 ArgumentLen = DiagStr-Argument;
719 ++DiagStr; // Skip }.
723 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
724 unsigned ArgNo = *DiagStr++ - '0';
726 // Only used for type diffing.
727 unsigned ArgNo2 = ArgNo;
729 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
730 if (ModifierIs(Modifier, ModifierLen, "diff")) {
731 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
732 "Invalid format for diff modifier");
734 ArgNo2 = *DiagStr++ - '0';
735 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
736 if (Kind == DiagnosticsEngine::ak_qualtype &&
737 Kind2 == DiagnosticsEngine::ak_qualtype)
738 Kind = DiagnosticsEngine::ak_qualtype_pair;
740 // %diff only supports QualTypes. For other kinds of arguments,
741 // use the default printing. For example, if the modifier is:
742 // "%diff{compare $ to $|other text}1,2"
744 // "compare %1 to %2"
745 const char *ArgumentEnd = Argument + ArgumentLen;
746 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
747 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
748 "Found too many '|'s in a %diff modifier!");
749 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
750 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
751 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
752 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
753 FormatDiagnostic(Argument, FirstDollar, OutStr);
754 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
755 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
756 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
757 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
764 case DiagnosticsEngine::ak_std_string: {
765 const std::string &S = getArgStdStr(ArgNo);
766 assert(ModifierLen == 0 && "No modifiers for strings yet");
767 OutStr.append(S.begin(), S.end());
770 case DiagnosticsEngine::ak_c_string: {
771 const char *S = getArgCStr(ArgNo);
772 assert(ModifierLen == 0 && "No modifiers for strings yet");
774 // Don't crash if get passed a null pointer by accident.
778 OutStr.append(S, S + strlen(S));
781 // ---- INTEGERS ----
782 case DiagnosticsEngine::ak_sint: {
783 int Val = getArgSInt(ArgNo);
785 if (ModifierIs(Modifier, ModifierLen, "select")) {
786 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
788 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
789 HandleIntegerSModifier(Val, OutStr);
790 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
791 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
793 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
794 HandleOrdinalModifier((unsigned)Val, OutStr);
796 assert(ModifierLen == 0 && "Unknown integer modifier");
797 llvm::raw_svector_ostream(OutStr) << Val;
801 case DiagnosticsEngine::ak_uint: {
802 unsigned Val = getArgUInt(ArgNo);
804 if (ModifierIs(Modifier, ModifierLen, "select")) {
805 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
806 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
807 HandleIntegerSModifier(Val, OutStr);
808 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
809 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
811 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
812 HandleOrdinalModifier(Val, OutStr);
814 assert(ModifierLen == 0 && "Unknown integer modifier");
815 llvm::raw_svector_ostream(OutStr) << Val;
819 // ---- TOKEN SPELLINGS ----
820 case DiagnosticsEngine::ak_tokenkind: {
821 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
822 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
824 llvm::raw_svector_ostream Out(OutStr);
825 if (const char *S = tok::getPunctuatorSpelling(Kind))
826 // Quoted token spelling for punctuators.
827 Out << '\'' << S << '\'';
828 else if (const char *S = tok::getKeywordSpelling(Kind))
829 // Unquoted token spelling for keywords.
831 else if (const char *S = getTokenDescForDiagnostic(Kind))
832 // Unquoted translatable token name.
834 else if (const char *S = tok::getTokenName(Kind))
835 // Debug name, shouldn't appear in user-facing diagnostics.
836 Out << '<' << S << '>';
841 // ---- NAMES and TYPES ----
842 case DiagnosticsEngine::ak_identifierinfo: {
843 const IdentifierInfo *II = getArgIdentifier(ArgNo);
844 assert(ModifierLen == 0 && "No modifiers for strings yet");
846 // Don't crash if get passed a null pointer by accident.
848 const char *S = "(null)";
849 OutStr.append(S, S + strlen(S));
853 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
856 case DiagnosticsEngine::ak_qualtype:
857 case DiagnosticsEngine::ak_declarationname:
858 case DiagnosticsEngine::ak_nameddecl:
859 case DiagnosticsEngine::ak_nestednamespec:
860 case DiagnosticsEngine::ak_declcontext:
861 case DiagnosticsEngine::ak_attr:
862 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
863 StringRef(Modifier, ModifierLen),
864 StringRef(Argument, ArgumentLen),
866 OutStr, QualTypeVals);
868 case DiagnosticsEngine::ak_qualtype_pair:
869 // Create a struct with all the info needed for printing.
870 TemplateDiffTypes TDT;
871 TDT.FromType = getRawArg(ArgNo);
872 TDT.ToType = getRawArg(ArgNo2);
873 TDT.ElideType = getDiags()->ElideType;
874 TDT.ShowColors = getDiags()->ShowColors;
875 TDT.TemplateDiffUsed = false;
876 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
878 const char *ArgumentEnd = Argument + ArgumentLen;
879 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
881 // Print the tree. If this diagnostic already has a tree, skip the
883 if (getDiags()->PrintTemplateTree && Tree.empty()) {
884 TDT.PrintFromType = true;
885 TDT.PrintTree = true;
886 getDiags()->ConvertArgToString(Kind, val,
887 StringRef(Modifier, ModifierLen),
888 StringRef(Argument, ArgumentLen),
891 // If there is no tree information, fall back to regular printing.
893 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
898 // Non-tree printing, also the fall-back when tree printing fails.
899 // The fall-back is triggered when the types compared are not templates.
900 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
901 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
903 // Append before text
904 FormatDiagnostic(Argument, FirstDollar, OutStr);
907 TDT.PrintTree = false;
908 TDT.PrintFromType = true;
909 getDiags()->ConvertArgToString(Kind, val,
910 StringRef(Modifier, ModifierLen),
911 StringRef(Argument, ArgumentLen),
913 OutStr, QualTypeVals);
914 if (!TDT.TemplateDiffUsed)
915 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
918 // Append middle text
919 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
921 // Append second type
922 TDT.PrintFromType = false;
923 getDiags()->ConvertArgToString(Kind, val,
924 StringRef(Modifier, ModifierLen),
925 StringRef(Argument, ArgumentLen),
927 OutStr, QualTypeVals);
928 if (!TDT.TemplateDiffUsed)
929 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
933 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
937 // Remember this argument info for subsequent formatting operations. Turn
938 // std::strings into a null terminated string to make it be the same case as
939 // all the other ones.
940 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
942 else if (Kind != DiagnosticsEngine::ak_std_string)
943 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
945 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
946 (intptr_t)getArgStdStr(ArgNo).c_str()));
950 // Append the type tree to the end of the diagnostics.
951 OutStr.append(Tree.begin(), Tree.end());
954 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
956 : ID(ID), Level(Level), Loc(), Message(Message) { }
958 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
959 const Diagnostic &Info)
960 : ID(Info.getID()), Level(Level)
962 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
963 "Valid source location without setting a source manager for diagnostic");
964 if (Info.getLocation().isValid())
965 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
966 SmallString<64> Message;
967 Info.FormatDiagnostic(Message);
968 this->Message.assign(Message.begin(), Message.end());
969 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
970 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
973 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
974 StringRef Message, FullSourceLoc Loc,
975 ArrayRef<CharSourceRange> Ranges,
976 ArrayRef<FixItHint> FixIts)
977 : ID(ID), Level(Level), Loc(Loc), Message(Message),
978 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
982 /// IncludeInDiagnosticCounts - This method (whose default implementation
983 /// returns true) indicates whether the diagnostics handled by this
984 /// DiagnosticConsumer should be included in the number of diagnostics
985 /// reported by DiagnosticsEngine.
986 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
988 void IgnoringDiagConsumer::anchor() { }
990 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
992 void ForwardingDiagnosticConsumer::HandleDiagnostic(
993 DiagnosticsEngine::Level DiagLevel,
994 const Diagnostic &Info) {
995 Target.HandleDiagnostic(DiagLevel, Info);
998 void ForwardingDiagnosticConsumer::clear() {
999 DiagnosticConsumer::clear();
1003 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1004 return Target.IncludeInDiagnosticCounts();
1007 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1008 for (unsigned I = 0; I != NumCached; ++I)
1009 FreeList[I] = Cached + I;
1010 NumFreeListEntries = NumCached;
1013 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1014 // Don't assert if we are in a CrashRecovery context, as this invariant may
1015 // be invalidated during a crash.
1016 assert((NumFreeListEntries == NumCached ||
1017 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1018 "A partial is on the lam");