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/Diagnostic.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/DiagnosticError.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/Locale.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
29 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
30 DiagNullabilityKind nullability) {
32 switch (nullability.first) {
33 case NullabilityKind::NonNull:
34 string = nullability.second ? "'nonnull'" : "'_Nonnull'";
37 case NullabilityKind::Nullable:
38 string = nullability.second ? "'nullable'" : "'_Nullable'";
41 case NullabilityKind::Unspecified:
42 string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
50 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
51 StringRef Modifier, StringRef Argument,
52 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
53 SmallVectorImpl<char> &Output,
55 ArrayRef<intptr_t> QualTypeVals) {
56 StringRef Str = "<can't format argument>";
57 Output.append(Str.begin(), Str.end());
60 DiagnosticsEngine::DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> diags,
61 DiagnosticOptions *DiagOpts,
62 DiagnosticConsumer *client,
64 : Diags(std::move(diags)), DiagOpts(DiagOpts), Client(nullptr),
66 setClient(client, ShouldOwnClient);
67 ArgToStringFn = DummyArgToStringFn;
68 ArgToStringCookie = nullptr;
70 AllExtensionsSilenced = 0;
71 SuppressAfterFatalError = true;
72 SuppressAllDiagnostics = false;
74 PrintTemplateTree = false;
76 ShowOverloads = Ovl_All;
79 TemplateBacktraceLimit = 0;
80 ConstexprBacktraceLimit = 0;
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::setClient(DiagnosticConsumer *client,
92 bool ShouldOwnClient) {
93 Owner.reset(ShouldOwnClient ? client : nullptr);
97 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
98 DiagStateOnPushStack.push_back(GetCurDiagState());
101 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
102 if (DiagStateOnPushStack.empty())
105 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
106 // State changed at some point between push/pop.
107 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
109 DiagStateOnPushStack.pop_back();
113 void DiagnosticsEngine::Reset() {
114 ErrorOccurred = false;
115 UncompilableErrorOccurred = false;
116 FatalErrorOccurred = false;
117 UnrecoverableErrorOccurred = false;
121 TrapNumErrorsOccurred = 0;
122 TrapNumUnrecoverableErrorsOccurred = 0;
125 LastDiagLevel = DiagnosticIDs::Ignored;
128 // Clear state related to #pragma diagnostic.
130 DiagStatesByLoc.clear();
131 DiagStateOnPushStack.clear();
133 // Create a DiagState and DiagStatePoint representing diagnostic changes
134 // through command-line.
135 DiagStates.emplace_back();
136 DiagStatesByLoc.appendFirst(&DiagStates.back());
139 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
144 DelayedDiagID = DiagID;
145 DelayedDiagArg1 = Arg1.str();
146 DelayedDiagArg2 = Arg2.str();
149 void DiagnosticsEngine::ReportDelayed() {
150 unsigned ID = DelayedDiagID;
152 Report(ID) << DelayedDiagArg1 << DelayedDiagArg2;
155 void DiagnosticsEngine::DiagStateMap::appendFirst(
157 assert(Files.empty() && "not first");
158 FirstDiagState = CurDiagState = State;
159 CurDiagStateLoc = SourceLocation();
162 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
165 CurDiagState = State;
166 CurDiagStateLoc = Loc;
168 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
169 unsigned Offset = Decomp.second;
170 for (File *F = getFile(SrcMgr, Decomp.first); F;
171 Offset = F->ParentOffset, F = F->Parent) {
172 F->HasLocalTransitions = true;
173 auto &Last = F->StateTransitions.back();
174 assert(Last.Offset <= Offset && "state transitions added out of order");
176 if (Last.Offset == Offset) {
177 if (Last.State == State)
183 F->StateTransitions.push_back({State, Offset});
187 DiagnosticsEngine::DiagState *
188 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
189 SourceLocation Loc) const {
190 // Common case: we have not seen any diagnostic pragmas.
192 return FirstDiagState;
194 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
195 const File *F = getFile(SrcMgr, Decomp.first);
196 return F->lookup(Decomp.second);
199 DiagnosticsEngine::DiagState *
200 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
201 auto OnePastIt = std::upper_bound(
202 StateTransitions.begin(), StateTransitions.end(), Offset,
203 [](unsigned Offset, const DiagStatePoint &P) {
204 return Offset < P.Offset;
206 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
207 return OnePastIt[-1].State;
210 DiagnosticsEngine::DiagStateMap::File *
211 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
213 // Get or insert the File for this ID.
214 auto Range = Files.equal_range(ID);
215 if (Range.first != Range.second)
216 return &Range.first->second;
217 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
219 // We created a new File; look up the diagnostic state at the start of it and
222 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
223 F.Parent = getFile(SrcMgr, Decomp.first);
224 F.ParentOffset = Decomp.second;
225 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
227 // This is the (imaginary) root file into which we pretend all top-level
228 // files are included; it descends from the initial state.
230 // FIXME: This doesn't guarantee that we use the same ordering as
231 // isBeforeInTranslationUnit in the cases where someone invented another
232 // top-level file and added diagnostic pragmas to it. See the code at the
233 // end of isBeforeInTranslationUnit for the quirks it deals with.
234 F.StateTransitions.push_back({FirstDiagState, 0});
239 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
240 SourceLocation Loc) {
241 assert(Loc.isValid() && "Adding invalid loc point");
242 DiagStatesByLoc.append(*SourceMgr, Loc, State);
245 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
247 assert(Diag < diag::DIAG_UPPER_LIMIT &&
248 "Can only map builtin diagnostics");
249 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
250 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
251 "Cannot map errors into warnings!");
252 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
254 // Don't allow a mapping to a warning override an error/fatal mapping.
255 bool WasUpgradedFromWarning = false;
256 if (Map == diag::Severity::Warning) {
257 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
258 if (Info.getSeverity() == diag::Severity::Error ||
259 Info.getSeverity() == diag::Severity::Fatal) {
260 Map = Info.getSeverity();
261 WasUpgradedFromWarning = true;
264 DiagnosticMapping Mapping = makeUserMapping(Map, L);
265 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
267 // Common case; setting all the diagnostics of a group in one place.
268 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
269 DiagStatesByLoc.getCurDiagState()) {
270 // FIXME: This is theoretically wrong: if the current state is shared with
271 // some other location (via push/pop) we will change the state for that
272 // other location as well. This cannot currently happen, as we can't update
273 // the diagnostic state at the same location at which we pop.
274 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
278 // A diagnostic pragma occurred, create a new DiagState initialized with
279 // the current one and a new DiagStatePoint to record at which location
280 // the new state became active.
281 DiagStates.push_back(*GetCurDiagState());
282 DiagStates.back().setMapping(Diag, Mapping);
283 PushDiagStatePoint(&DiagStates.back(), L);
286 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
287 StringRef Group, diag::Severity Map,
288 SourceLocation Loc) {
289 // Get the diagnostics in this group.
290 SmallVector<diag::kind, 256> GroupDiags;
291 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
295 for (diag::kind Diag : GroupDiags)
296 setSeverity(Diag, Map, Loc);
301 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
303 // If we are enabling this feature, just set the diagnostic mappings to map to
306 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
307 diag::Severity::Error);
309 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
310 // potentially downgrade anything already mapped to be a warning.
312 // Get the diagnostics in this group.
313 SmallVector<diag::kind, 8> GroupDiags;
314 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
318 // Perform the mapping change.
319 for (diag::kind Diag : GroupDiags) {
320 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
322 if (Info.getSeverity() == diag::Severity::Error ||
323 Info.getSeverity() == diag::Severity::Fatal)
324 Info.setSeverity(diag::Severity::Warning);
326 Info.setNoWarningAsError(true);
332 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
334 // If we are enabling this feature, just set the diagnostic mappings to map to
337 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
338 diag::Severity::Fatal);
340 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
341 // and potentially downgrade anything already mapped to be a fatal error.
343 // Get the diagnostics in this group.
344 SmallVector<diag::kind, 8> GroupDiags;
345 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
349 // Perform the mapping change.
350 for (diag::kind Diag : GroupDiags) {
351 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
353 if (Info.getSeverity() == diag::Severity::Fatal)
354 Info.setSeverity(diag::Severity::Error);
356 Info.setNoErrorAsFatal(true);
362 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
364 SourceLocation Loc) {
365 // Get all the diagnostics.
366 std::vector<diag::kind> AllDiags;
367 DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
370 for (diag::kind Diag : AllDiags)
371 if (Diags->isBuiltinWarningOrExtension(Diag))
372 setSeverity(Diag, Map, Loc);
375 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
376 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
378 CurDiagLoc = storedDiag.getLocation();
379 CurDiagID = storedDiag.getID();
383 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
385 DiagFixItHints.clear();
386 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
388 assert(Client && "DiagnosticConsumer not set!");
389 Level DiagLevel = storedDiag.getLevel();
390 Diagnostic Info(this, storedDiag.getMessage());
391 Client->HandleDiagnostic(DiagLevel, Info);
392 if (Client->IncludeInDiagnosticCounts()) {
393 if (DiagLevel == DiagnosticsEngine::Warning)
400 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
401 assert(getClient() && "DiagnosticClient not set!");
405 Diagnostic Info(this);
407 // Figure out the diagnostic level of this message.
408 DiagnosticIDs::Level DiagLevel
409 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
411 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
413 // Emit the diagnostic regardless of suppression level.
414 Diags->EmitDiag(*this, DiagLevel);
417 // Process the diagnostic, sending the accumulated information to the
418 // DiagnosticConsumer.
419 Emitted = ProcessDiag();
422 // Clear out the current diagnostic object.
425 // If there was a delayed diagnostic, emit it now.
426 if (!Force && DelayedDiagID)
433 DiagnosticConsumer::~DiagnosticConsumer() {}
435 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
436 const Diagnostic &Info) {
437 if (!IncludeInDiagnosticCounts())
440 if (DiagLevel == DiagnosticsEngine::Warning)
442 else if (DiagLevel >= DiagnosticsEngine::Error)
446 /// ModifierIs - Return true if the specified modifier matches specified string.
447 template <std::size_t StrLen>
448 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
449 const char (&Str)[StrLen]) {
450 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
453 /// ScanForward - Scans forward, looking for the given character, skipping
454 /// nested clauses and escaped characters.
455 static const char *ScanFormat(const char *I, const char *E, char Target) {
458 for ( ; I != E; ++I) {
459 if (Depth == 0 && *I == Target) return I;
460 if (Depth != 0 && *I == '}') Depth--;
466 // Escaped characters get implicitly skipped here.
469 if (!isDigit(*I) && !isPunctuation(*I)) {
470 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
480 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
481 /// like this: %select{foo|bar|baz}2. This means that the integer argument
482 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
483 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
484 /// This is very useful for certain classes of variant diagnostics.
485 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
486 const char *Argument, unsigned ArgumentLen,
487 SmallVectorImpl<char> &OutStr) {
488 const char *ArgumentEnd = Argument+ArgumentLen;
490 // Skip over 'ValNo' |'s.
492 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
493 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
494 " larger than the number of options in the diagnostic string!");
495 Argument = NextVal+1; // Skip this string.
499 // Get the end of the value. This is either the } or the |.
500 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
502 // Recursively format the result of the select clause into the output string.
503 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
506 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
507 /// letter 's' to the string if the value is not 1. This is used in cases like
508 /// this: "you idiot, you have %4 parameter%s4!".
509 static void HandleIntegerSModifier(unsigned ValNo,
510 SmallVectorImpl<char> &OutStr) {
512 OutStr.push_back('s');
515 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
516 /// prints the ordinal form of the given integer, with 1 corresponding
517 /// to the first ordinal. Currently this is hard-coded to use the
519 static void HandleOrdinalModifier(unsigned ValNo,
520 SmallVectorImpl<char> &OutStr) {
521 assert(ValNo != 0 && "ValNo must be strictly positive!");
523 llvm::raw_svector_ostream Out(OutStr);
525 // We could use text forms for the first N ordinals, but the numeric
526 // forms are actually nicer in diagnostics because they stand out.
527 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
531 /// PluralNumber - Parse an unsigned integer and advance Start.
532 static unsigned PluralNumber(const char *&Start, const char *End) {
533 // Programming 101: Parse a decimal number :-)
535 while (Start != End && *Start >= '0' && *Start <= '9') {
543 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
544 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
546 unsigned Ref = PluralNumber(Start, End);
551 unsigned Low = PluralNumber(Start, End);
552 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
554 unsigned High = PluralNumber(Start, End);
555 assert(*Start == ']' && "Bad plural expression syntax: expected )");
557 return Low <= Val && Val <= High;
560 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
561 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
571 unsigned Arg = PluralNumber(Start, End);
572 assert(*Start == '=' && "Bad plural expression syntax: expected =");
574 unsigned ValMod = ValNo % Arg;
575 if (TestPluralRange(ValMod, Start, End))
578 assert((C == '[' || (C >= '0' && C <= '9')) &&
579 "Bad plural expression syntax: unexpected character");
581 if (TestPluralRange(ValNo, Start, End))
585 // Scan for next or-expr part.
586 Start = std::find(Start, End, ',');
594 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
595 /// for complex plural forms, or in languages where all plurals are complex.
596 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
597 /// conditions that are tested in order, the form corresponding to the first
598 /// that applies being emitted. The empty condition is always true, making the
599 /// last form a default case.
600 /// Conditions are simple boolean expressions, where n is the number argument.
601 /// Here are the rules.
602 /// condition := expression | empty
603 /// empty := -> always true
604 /// expression := numeric [',' expression] -> logical or
605 /// numeric := range -> true if n in range
606 /// | '%' number '=' range -> true if n % number in range
608 /// | '[' number ',' number ']' -> ranges are inclusive both ends
610 /// Here are some examples from the GNU gettext manual written in this form:
614 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
616 /// {1:form0|2:form1|:form2}
618 /// {1:form0|0,%100=[1,19]:form1|:form2}
620 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
621 /// Russian (requires repeated form):
622 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
624 /// {1:form0|[2,4]:form1|:form2}
625 /// Polish (requires repeated form):
626 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
627 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
628 const char *Argument, unsigned ArgumentLen,
629 SmallVectorImpl<char> &OutStr) {
630 const char *ArgumentEnd = Argument + ArgumentLen;
632 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
633 const char *ExprEnd = Argument;
634 while (*ExprEnd != ':') {
635 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
638 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
639 Argument = ExprEnd + 1;
640 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
642 // Recursively format the result of the plural clause into the
644 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
647 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
651 /// \brief Returns the friendly description for a token kind that will appear
652 /// without quotes in diagnostic messages. These strings may be translatable in
654 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
656 case tok::identifier:
663 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
664 /// formal arguments into the %0 slots. The result is appended onto the Str
667 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
668 if (!StoredDiagMessage.empty()) {
669 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
674 getDiags()->getDiagnosticIDs()->getDescription(getID());
676 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
680 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
681 SmallVectorImpl<char> &OutStr) const {
683 // When the diagnostic string is only "%0", the entire string is being given
684 // by an outside source. Remove unprintable characters from this string
685 // and skip all the other string processing.
686 if (DiagEnd - DiagStr == 2 &&
687 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
688 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
689 const std::string &S = getArgStdStr(0);
691 if (llvm::sys::locale::isPrint(c) || c == '\t') {
698 /// FormattedArgs - Keep track of all of the arguments formatted by
699 /// ConvertArgToString and pass them into subsequent calls to
700 /// ConvertArgToString, allowing the implementation to avoid redundancies in
702 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
704 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
705 /// compared to see if more information is needed to be printed.
706 SmallVector<intptr_t, 2> QualTypeVals;
707 SmallVector<char, 64> Tree;
709 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
710 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
711 QualTypeVals.push_back(getRawArg(i));
713 while (DiagStr != DiagEnd) {
714 if (DiagStr[0] != '%') {
715 // Append non-%0 substrings to Str if we have one.
716 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
717 OutStr.append(DiagStr, StrEnd);
720 } else if (isPunctuation(DiagStr[1])) {
721 OutStr.push_back(DiagStr[1]); // %% -> %.
729 // This must be a placeholder for a diagnostic argument. The format for a
730 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
731 // The digit is a number from 0-9 indicating which argument this comes from.
732 // The modifier is a string of digits from the set [-a-z]+, arguments is a
733 // brace enclosed string.
734 const char *Modifier = nullptr, *Argument = nullptr;
735 unsigned ModifierLen = 0, ArgumentLen = 0;
737 // Check to see if we have a modifier. If so eat it.
738 if (!isDigit(DiagStr[0])) {
740 while (DiagStr[0] == '-' ||
741 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
743 ModifierLen = DiagStr-Modifier;
745 // If we have an argument, get it next.
746 if (DiagStr[0] == '{') {
747 ++DiagStr; // Skip {.
750 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
751 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
752 ArgumentLen = DiagStr-Argument;
753 ++DiagStr; // Skip }.
757 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
758 unsigned ArgNo = *DiagStr++ - '0';
760 // Only used for type diffing.
761 unsigned ArgNo2 = ArgNo;
763 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
764 if (ModifierIs(Modifier, ModifierLen, "diff")) {
765 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
766 "Invalid format for diff modifier");
768 ArgNo2 = *DiagStr++ - '0';
769 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
770 if (Kind == DiagnosticsEngine::ak_qualtype &&
771 Kind2 == DiagnosticsEngine::ak_qualtype)
772 Kind = DiagnosticsEngine::ak_qualtype_pair;
774 // %diff only supports QualTypes. For other kinds of arguments,
775 // use the default printing. For example, if the modifier is:
776 // "%diff{compare $ to $|other text}1,2"
778 // "compare %1 to %2"
779 const char *ArgumentEnd = Argument + ArgumentLen;
780 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
781 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
782 "Found too many '|'s in a %diff modifier!");
783 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
784 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
785 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
786 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
787 FormatDiagnostic(Argument, FirstDollar, OutStr);
788 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
789 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
790 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
791 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
798 case DiagnosticsEngine::ak_std_string: {
799 const std::string &S = getArgStdStr(ArgNo);
800 assert(ModifierLen == 0 && "No modifiers for strings yet");
801 OutStr.append(S.begin(), S.end());
804 case DiagnosticsEngine::ak_c_string: {
805 const char *S = getArgCStr(ArgNo);
806 assert(ModifierLen == 0 && "No modifiers for strings yet");
808 // Don't crash if get passed a null pointer by accident.
812 OutStr.append(S, S + strlen(S));
815 // ---- INTEGERS ----
816 case DiagnosticsEngine::ak_sint: {
817 int Val = getArgSInt(ArgNo);
819 if (ModifierIs(Modifier, ModifierLen, "select")) {
820 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
822 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
823 HandleIntegerSModifier(Val, OutStr);
824 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
825 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
827 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
828 HandleOrdinalModifier((unsigned)Val, OutStr);
830 assert(ModifierLen == 0 && "Unknown integer modifier");
831 llvm::raw_svector_ostream(OutStr) << Val;
835 case DiagnosticsEngine::ak_uint: {
836 unsigned Val = getArgUInt(ArgNo);
838 if (ModifierIs(Modifier, ModifierLen, "select")) {
839 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
840 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
841 HandleIntegerSModifier(Val, OutStr);
842 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
843 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
845 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
846 HandleOrdinalModifier(Val, OutStr);
848 assert(ModifierLen == 0 && "Unknown integer modifier");
849 llvm::raw_svector_ostream(OutStr) << Val;
853 // ---- TOKEN SPELLINGS ----
854 case DiagnosticsEngine::ak_tokenkind: {
855 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
856 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
858 llvm::raw_svector_ostream Out(OutStr);
859 if (const char *S = tok::getPunctuatorSpelling(Kind))
860 // Quoted token spelling for punctuators.
861 Out << '\'' << S << '\'';
862 else if (const char *S = tok::getKeywordSpelling(Kind))
863 // Unquoted token spelling for keywords.
865 else if (const char *S = getTokenDescForDiagnostic(Kind))
866 // Unquoted translatable token name.
868 else if (const char *S = tok::getTokenName(Kind))
869 // Debug name, shouldn't appear in user-facing diagnostics.
870 Out << '<' << S << '>';
875 // ---- NAMES and TYPES ----
876 case DiagnosticsEngine::ak_identifierinfo: {
877 const IdentifierInfo *II = getArgIdentifier(ArgNo);
878 assert(ModifierLen == 0 && "No modifiers for strings yet");
880 // Don't crash if get passed a null pointer by accident.
882 const char *S = "(null)";
883 OutStr.append(S, S + strlen(S));
887 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
890 case DiagnosticsEngine::ak_qualtype:
891 case DiagnosticsEngine::ak_declarationname:
892 case DiagnosticsEngine::ak_nameddecl:
893 case DiagnosticsEngine::ak_nestednamespec:
894 case DiagnosticsEngine::ak_declcontext:
895 case DiagnosticsEngine::ak_attr:
896 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
897 StringRef(Modifier, ModifierLen),
898 StringRef(Argument, ArgumentLen),
900 OutStr, QualTypeVals);
902 case DiagnosticsEngine::ak_qualtype_pair:
903 // Create a struct with all the info needed for printing.
904 TemplateDiffTypes TDT;
905 TDT.FromType = getRawArg(ArgNo);
906 TDT.ToType = getRawArg(ArgNo2);
907 TDT.ElideType = getDiags()->ElideType;
908 TDT.ShowColors = getDiags()->ShowColors;
909 TDT.TemplateDiffUsed = false;
910 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
912 const char *ArgumentEnd = Argument + ArgumentLen;
913 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
915 // Print the tree. If this diagnostic already has a tree, skip the
917 if (getDiags()->PrintTemplateTree && Tree.empty()) {
918 TDT.PrintFromType = true;
919 TDT.PrintTree = true;
920 getDiags()->ConvertArgToString(Kind, val,
921 StringRef(Modifier, ModifierLen),
922 StringRef(Argument, ArgumentLen),
925 // If there is no tree information, fall back to regular printing.
927 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
932 // Non-tree printing, also the fall-back when tree printing fails.
933 // The fall-back is triggered when the types compared are not templates.
934 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
935 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
937 // Append before text
938 FormatDiagnostic(Argument, FirstDollar, OutStr);
941 TDT.PrintTree = false;
942 TDT.PrintFromType = true;
943 getDiags()->ConvertArgToString(Kind, val,
944 StringRef(Modifier, ModifierLen),
945 StringRef(Argument, ArgumentLen),
947 OutStr, QualTypeVals);
948 if (!TDT.TemplateDiffUsed)
949 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
952 // Append middle text
953 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
955 // Append second type
956 TDT.PrintFromType = false;
957 getDiags()->ConvertArgToString(Kind, val,
958 StringRef(Modifier, ModifierLen),
959 StringRef(Argument, ArgumentLen),
961 OutStr, QualTypeVals);
962 if (!TDT.TemplateDiffUsed)
963 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
967 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
971 // Remember this argument info for subsequent formatting operations. Turn
972 // std::strings into a null terminated string to make it be the same case as
973 // all the other ones.
974 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
976 else if (Kind != DiagnosticsEngine::ak_std_string)
977 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
979 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
980 (intptr_t)getArgStdStr(ArgNo).c_str()));
984 // Append the type tree to the end of the diagnostics.
985 OutStr.append(Tree.begin(), Tree.end());
988 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
990 : ID(ID), Level(Level), Loc(), Message(Message) { }
992 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
993 const Diagnostic &Info)
994 : ID(Info.getID()), Level(Level)
996 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
997 "Valid source location without setting a source manager for diagnostic");
998 if (Info.getLocation().isValid())
999 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1000 SmallString<64> Message;
1001 Info.FormatDiagnostic(Message);
1002 this->Message.assign(Message.begin(), Message.end());
1003 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1004 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1007 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1008 StringRef Message, FullSourceLoc Loc,
1009 ArrayRef<CharSourceRange> Ranges,
1010 ArrayRef<FixItHint> FixIts)
1011 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1012 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1016 /// IncludeInDiagnosticCounts - This method (whose default implementation
1017 /// returns true) indicates whether the diagnostics handled by this
1018 /// DiagnosticConsumer should be included in the number of diagnostics
1019 /// reported by DiagnosticsEngine.
1020 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1022 void IgnoringDiagConsumer::anchor() { }
1024 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
1026 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1027 DiagnosticsEngine::Level DiagLevel,
1028 const Diagnostic &Info) {
1029 Target.HandleDiagnostic(DiagLevel, Info);
1032 void ForwardingDiagnosticConsumer::clear() {
1033 DiagnosticConsumer::clear();
1037 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1038 return Target.IncludeInDiagnosticCounts();
1041 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1042 for (unsigned I = 0; I != NumCached; ++I)
1043 FreeList[I] = Cached + I;
1044 NumFreeListEntries = NumCached;
1047 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1048 // Don't assert if we are in a CrashRecovery context, as this invariant may
1049 // be invalidated during a crash.
1050 assert((NumFreeListEntries == NumCached ||
1051 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1052 "A partial is on the lam");
1055 char DiagnosticError::ID;