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 "clang/Basic/SourceManager.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/CrashRecoveryContext.h"
23 #include "llvm/Support/Locale.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
28 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
29 DiagNullabilityKind nullability) {
31 switch (nullability.first) {
32 case NullabilityKind::NonNull:
33 string = nullability.second ? "'nonnull'" : "'_Nonnull'";
36 case NullabilityKind::Nullable:
37 string = nullability.second ? "'nullable'" : "'_Nullable'";
40 case NullabilityKind::Unspecified:
41 string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
49 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
50 StringRef Modifier, StringRef Argument,
51 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
52 SmallVectorImpl<char> &Output,
54 ArrayRef<intptr_t> QualTypeVals) {
55 StringRef Str = "<can't format argument>";
56 Output.append(Str.begin(), Str.end());
59 DiagnosticsEngine::DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> diags,
60 DiagnosticOptions *DiagOpts,
61 DiagnosticConsumer *client,
63 : Diags(std::move(diags)), DiagOpts(DiagOpts), Client(nullptr),
65 setClient(client, ShouldOwnClient);
66 ArgToStringFn = DummyArgToStringFn;
67 ArgToStringCookie = nullptr;
69 AllExtensionsSilenced = 0;
70 SuppressAfterFatalError = true;
71 SuppressAllDiagnostics = false;
73 PrintTemplateTree = false;
75 ShowOverloads = Ovl_All;
78 TemplateBacktraceLimit = 0;
79 ConstexprBacktraceLimit = 0;
84 DiagnosticsEngine::~DiagnosticsEngine() {
85 // If we own the diagnostic client, destroy it first so that it can access the
86 // engine from its destructor.
90 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
91 bool ShouldOwnClient) {
92 Owner.reset(ShouldOwnClient ? client : nullptr);
96 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
97 DiagStateOnPushStack.push_back(GetCurDiagState());
100 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
101 if (DiagStateOnPushStack.empty())
104 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
105 // State changed at some point between push/pop.
106 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
108 DiagStateOnPushStack.pop_back();
112 void DiagnosticsEngine::Reset() {
113 ErrorOccurred = false;
114 UncompilableErrorOccurred = false;
115 FatalErrorOccurred = false;
116 UnrecoverableErrorOccurred = false;
120 TrapNumErrorsOccurred = 0;
121 TrapNumUnrecoverableErrorsOccurred = 0;
124 LastDiagLevel = DiagnosticIDs::Ignored;
127 // Clear state related to #pragma diagnostic.
129 DiagStatesByLoc.clear();
130 DiagStateOnPushStack.clear();
132 // Create a DiagState and DiagStatePoint representing diagnostic changes
133 // through command-line.
134 DiagStates.emplace_back();
135 DiagStatesByLoc.appendFirst(&DiagStates.back());
138 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
143 DelayedDiagID = DiagID;
144 DelayedDiagArg1 = Arg1.str();
145 DelayedDiagArg2 = Arg2.str();
148 void DiagnosticsEngine::ReportDelayed() {
149 unsigned ID = DelayedDiagID;
151 Report(ID) << DelayedDiagArg1 << DelayedDiagArg2;
154 void DiagnosticsEngine::DiagStateMap::appendFirst(
156 assert(Files.empty() && "not first");
157 FirstDiagState = CurDiagState = State;
158 CurDiagStateLoc = SourceLocation();
161 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
164 CurDiagState = State;
165 CurDiagStateLoc = Loc;
167 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
168 unsigned Offset = Decomp.second;
169 for (File *F = getFile(SrcMgr, Decomp.first); F;
170 Offset = F->ParentOffset, F = F->Parent) {
171 F->HasLocalTransitions = true;
172 auto &Last = F->StateTransitions.back();
173 assert(Last.Offset <= Offset && "state transitions added out of order");
175 if (Last.Offset == Offset) {
176 if (Last.State == State)
182 F->StateTransitions.push_back({State, Offset});
186 DiagnosticsEngine::DiagState *
187 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
188 SourceLocation Loc) const {
189 // Common case: we have not seen any diagnostic pragmas.
191 return FirstDiagState;
193 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
194 const File *F = getFile(SrcMgr, Decomp.first);
195 return F->lookup(Decomp.second);
198 DiagnosticsEngine::DiagState *
199 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
200 auto OnePastIt = std::upper_bound(
201 StateTransitions.begin(), StateTransitions.end(), Offset,
202 [](unsigned Offset, const DiagStatePoint &P) {
203 return Offset < P.Offset;
205 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
206 return OnePastIt[-1].State;
209 DiagnosticsEngine::DiagStateMap::File *
210 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
212 // Get or insert the File for this ID.
213 auto Range = Files.equal_range(ID);
214 if (Range.first != Range.second)
215 return &Range.first->second;
216 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
218 // We created a new File; look up the diagnostic state at the start of it and
221 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
222 F.Parent = getFile(SrcMgr, Decomp.first);
223 F.ParentOffset = Decomp.second;
224 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
226 // This is the (imaginary) root file into which we pretend all top-level
227 // files are included; it descends from the initial state.
229 // FIXME: This doesn't guarantee that we use the same ordering as
230 // isBeforeInTranslationUnit in the cases where someone invented another
231 // top-level file and added diagnostic pragmas to it. See the code at the
232 // end of isBeforeInTranslationUnit for the quirks it deals with.
233 F.StateTransitions.push_back({FirstDiagState, 0});
238 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
239 SourceLocation Loc) {
240 assert(Loc.isValid() && "Adding invalid loc point");
241 DiagStatesByLoc.append(*SourceMgr, Loc, State);
244 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
246 assert(Diag < diag::DIAG_UPPER_LIMIT &&
247 "Can only map builtin diagnostics");
248 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
249 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
250 "Cannot map errors into warnings!");
251 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
253 // Don't allow a mapping to a warning override an error/fatal mapping.
254 bool WasUpgradedFromWarning = false;
255 if (Map == diag::Severity::Warning) {
256 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
257 if (Info.getSeverity() == diag::Severity::Error ||
258 Info.getSeverity() == diag::Severity::Fatal) {
259 Map = Info.getSeverity();
260 WasUpgradedFromWarning = true;
263 DiagnosticMapping Mapping = makeUserMapping(Map, L);
264 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
266 // Common case; setting all the diagnostics of a group in one place.
267 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
268 DiagStatesByLoc.getCurDiagState()) {
269 // FIXME: This is theoretically wrong: if the current state is shared with
270 // some other location (via push/pop) we will change the state for that
271 // other location as well. This cannot currently happen, as we can't update
272 // the diagnostic state at the same location at which we pop.
273 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
277 // A diagnostic pragma occurred, create a new DiagState initialized with
278 // the current one and a new DiagStatePoint to record at which location
279 // the new state became active.
280 DiagStates.push_back(*GetCurDiagState());
281 DiagStates.back().setMapping(Diag, Mapping);
282 PushDiagStatePoint(&DiagStates.back(), L);
285 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
286 StringRef Group, diag::Severity Map,
287 SourceLocation Loc) {
288 // Get the diagnostics in this group.
289 SmallVector<diag::kind, 256> GroupDiags;
290 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
294 for (diag::kind Diag : GroupDiags)
295 setSeverity(Diag, Map, Loc);
300 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
302 // If we are enabling this feature, just set the diagnostic mappings to map to
305 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
306 diag::Severity::Error);
308 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
309 // potentially downgrade anything already mapped to be a warning.
311 // Get the diagnostics in this group.
312 SmallVector<diag::kind, 8> GroupDiags;
313 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
317 // Perform the mapping change.
318 for (diag::kind Diag : GroupDiags) {
319 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
321 if (Info.getSeverity() == diag::Severity::Error ||
322 Info.getSeverity() == diag::Severity::Fatal)
323 Info.setSeverity(diag::Severity::Warning);
325 Info.setNoWarningAsError(true);
331 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
333 // If we are enabling this feature, just set the diagnostic mappings to map to
336 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
337 diag::Severity::Fatal);
339 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
340 // and potentially downgrade anything already mapped to be a fatal error.
342 // Get the diagnostics in this group.
343 SmallVector<diag::kind, 8> GroupDiags;
344 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
348 // Perform the mapping change.
349 for (diag::kind Diag : GroupDiags) {
350 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
352 if (Info.getSeverity() == diag::Severity::Fatal)
353 Info.setSeverity(diag::Severity::Error);
355 Info.setNoErrorAsFatal(true);
361 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
363 SourceLocation Loc) {
364 // Get all the diagnostics.
365 SmallVector<diag::kind, 64> AllDiags;
366 Diags->getAllDiagnostics(Flavor, AllDiags);
369 for (diag::kind Diag : AllDiags)
370 if (Diags->isBuiltinWarningOrExtension(Diag))
371 setSeverity(Diag, Map, Loc);
374 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
375 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
377 CurDiagLoc = storedDiag.getLocation();
378 CurDiagID = storedDiag.getID();
382 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
384 DiagFixItHints.clear();
385 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
387 assert(Client && "DiagnosticConsumer not set!");
388 Level DiagLevel = storedDiag.getLevel();
389 Diagnostic Info(this, storedDiag.getMessage());
390 Client->HandleDiagnostic(DiagLevel, Info);
391 if (Client->IncludeInDiagnosticCounts()) {
392 if (DiagLevel == DiagnosticsEngine::Warning)
399 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
400 assert(getClient() && "DiagnosticClient not set!");
404 Diagnostic Info(this);
406 // Figure out the diagnostic level of this message.
407 DiagnosticIDs::Level DiagLevel
408 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
410 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
412 // Emit the diagnostic regardless of suppression level.
413 Diags->EmitDiag(*this, DiagLevel);
416 // Process the diagnostic, sending the accumulated information to the
417 // DiagnosticConsumer.
418 Emitted = ProcessDiag();
421 // Clear out the current diagnostic object.
424 // If there was a delayed diagnostic, emit it now.
425 if (!Force && DelayedDiagID)
432 DiagnosticConsumer::~DiagnosticConsumer() {}
434 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
435 const Diagnostic &Info) {
436 if (!IncludeInDiagnosticCounts())
439 if (DiagLevel == DiagnosticsEngine::Warning)
441 else if (DiagLevel >= DiagnosticsEngine::Error)
445 /// ModifierIs - Return true if the specified modifier matches specified string.
446 template <std::size_t StrLen>
447 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
448 const char (&Str)[StrLen]) {
449 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
452 /// ScanForward - Scans forward, looking for the given character, skipping
453 /// nested clauses and escaped characters.
454 static const char *ScanFormat(const char *I, const char *E, char Target) {
457 for ( ; I != E; ++I) {
458 if (Depth == 0 && *I == Target) return I;
459 if (Depth != 0 && *I == '}') Depth--;
465 // Escaped characters get implicitly skipped here.
468 if (!isDigit(*I) && !isPunctuation(*I)) {
469 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
479 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
480 /// like this: %select{foo|bar|baz}2. This means that the integer argument
481 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
482 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
483 /// This is very useful for certain classes of variant diagnostics.
484 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
485 const char *Argument, unsigned ArgumentLen,
486 SmallVectorImpl<char> &OutStr) {
487 const char *ArgumentEnd = Argument+ArgumentLen;
489 // Skip over 'ValNo' |'s.
491 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
492 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
493 " larger than the number of options in the diagnostic string!");
494 Argument = NextVal+1; // Skip this string.
498 // Get the end of the value. This is either the } or the |.
499 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
501 // Recursively format the result of the select clause into the output string.
502 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
505 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
506 /// letter 's' to the string if the value is not 1. This is used in cases like
507 /// this: "you idiot, you have %4 parameter%s4!".
508 static void HandleIntegerSModifier(unsigned ValNo,
509 SmallVectorImpl<char> &OutStr) {
511 OutStr.push_back('s');
514 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
515 /// prints the ordinal form of the given integer, with 1 corresponding
516 /// to the first ordinal. Currently this is hard-coded to use the
518 static void HandleOrdinalModifier(unsigned ValNo,
519 SmallVectorImpl<char> &OutStr) {
520 assert(ValNo != 0 && "ValNo must be strictly positive!");
522 llvm::raw_svector_ostream Out(OutStr);
524 // We could use text forms for the first N ordinals, but the numeric
525 // forms are actually nicer in diagnostics because they stand out.
526 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
530 /// PluralNumber - Parse an unsigned integer and advance Start.
531 static unsigned PluralNumber(const char *&Start, const char *End) {
532 // Programming 101: Parse a decimal number :-)
534 while (Start != End && *Start >= '0' && *Start <= '9') {
542 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
543 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
545 unsigned Ref = PluralNumber(Start, End);
550 unsigned Low = PluralNumber(Start, End);
551 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
553 unsigned High = PluralNumber(Start, End);
554 assert(*Start == ']' && "Bad plural expression syntax: expected )");
556 return Low <= Val && Val <= High;
559 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
560 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
570 unsigned Arg = PluralNumber(Start, End);
571 assert(*Start == '=' && "Bad plural expression syntax: expected =");
573 unsigned ValMod = ValNo % Arg;
574 if (TestPluralRange(ValMod, Start, End))
577 assert((C == '[' || (C >= '0' && C <= '9')) &&
578 "Bad plural expression syntax: unexpected character");
580 if (TestPluralRange(ValNo, Start, End))
584 // Scan for next or-expr part.
585 Start = std::find(Start, End, ',');
593 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
594 /// for complex plural forms, or in languages where all plurals are complex.
595 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
596 /// conditions that are tested in order, the form corresponding to the first
597 /// that applies being emitted. The empty condition is always true, making the
598 /// last form a default case.
599 /// Conditions are simple boolean expressions, where n is the number argument.
600 /// Here are the rules.
601 /// condition := expression | empty
602 /// empty := -> always true
603 /// expression := numeric [',' expression] -> logical or
604 /// numeric := range -> true if n in range
605 /// | '%' number '=' range -> true if n % number in range
607 /// | '[' number ',' number ']' -> ranges are inclusive both ends
609 /// Here are some examples from the GNU gettext manual written in this form:
613 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
615 /// {1:form0|2:form1|:form2}
617 /// {1:form0|0,%100=[1,19]:form1|:form2}
619 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
620 /// Russian (requires repeated form):
621 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
623 /// {1:form0|[2,4]:form1|:form2}
624 /// Polish (requires repeated form):
625 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
626 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
627 const char *Argument, unsigned ArgumentLen,
628 SmallVectorImpl<char> &OutStr) {
629 const char *ArgumentEnd = Argument + ArgumentLen;
631 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
632 const char *ExprEnd = Argument;
633 while (*ExprEnd != ':') {
634 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
637 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
638 Argument = ExprEnd + 1;
639 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
641 // Recursively format the result of the plural clause into the
643 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
646 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
650 /// \brief Returns the friendly description for a token kind that will appear
651 /// without quotes in diagnostic messages. These strings may be translatable in
653 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
655 case tok::identifier:
662 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
663 /// formal arguments into the %0 slots. The result is appended onto the Str
666 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
667 if (!StoredDiagMessage.empty()) {
668 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
673 getDiags()->getDiagnosticIDs()->getDescription(getID());
675 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
679 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
680 SmallVectorImpl<char> &OutStr) const {
682 // When the diagnostic string is only "%0", the entire string is being given
683 // by an outside source. Remove unprintable characters from this string
684 // and skip all the other string processing.
685 if (DiagEnd - DiagStr == 2 &&
686 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
687 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
688 const std::string &S = getArgStdStr(0);
690 if (llvm::sys::locale::isPrint(c) || c == '\t') {
697 /// FormattedArgs - Keep track of all of the arguments formatted by
698 /// ConvertArgToString and pass them into subsequent calls to
699 /// ConvertArgToString, allowing the implementation to avoid redundancies in
701 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
703 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
704 /// compared to see if more information is needed to be printed.
705 SmallVector<intptr_t, 2> QualTypeVals;
706 SmallVector<char, 64> Tree;
708 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
709 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
710 QualTypeVals.push_back(getRawArg(i));
712 while (DiagStr != DiagEnd) {
713 if (DiagStr[0] != '%') {
714 // Append non-%0 substrings to Str if we have one.
715 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
716 OutStr.append(DiagStr, StrEnd);
719 } else if (isPunctuation(DiagStr[1])) {
720 OutStr.push_back(DiagStr[1]); // %% -> %.
728 // This must be a placeholder for a diagnostic argument. The format for a
729 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
730 // The digit is a number from 0-9 indicating which argument this comes from.
731 // The modifier is a string of digits from the set [-a-z]+, arguments is a
732 // brace enclosed string.
733 const char *Modifier = nullptr, *Argument = nullptr;
734 unsigned ModifierLen = 0, ArgumentLen = 0;
736 // Check to see if we have a modifier. If so eat it.
737 if (!isDigit(DiagStr[0])) {
739 while (DiagStr[0] == '-' ||
740 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
742 ModifierLen = DiagStr-Modifier;
744 // If we have an argument, get it next.
745 if (DiagStr[0] == '{') {
746 ++DiagStr; // Skip {.
749 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
750 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
751 ArgumentLen = DiagStr-Argument;
752 ++DiagStr; // Skip }.
756 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
757 unsigned ArgNo = *DiagStr++ - '0';
759 // Only used for type diffing.
760 unsigned ArgNo2 = ArgNo;
762 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
763 if (ModifierIs(Modifier, ModifierLen, "diff")) {
764 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
765 "Invalid format for diff modifier");
767 ArgNo2 = *DiagStr++ - '0';
768 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
769 if (Kind == DiagnosticsEngine::ak_qualtype &&
770 Kind2 == DiagnosticsEngine::ak_qualtype)
771 Kind = DiagnosticsEngine::ak_qualtype_pair;
773 // %diff only supports QualTypes. For other kinds of arguments,
774 // use the default printing. For example, if the modifier is:
775 // "%diff{compare $ to $|other text}1,2"
777 // "compare %1 to %2"
778 const char *ArgumentEnd = Argument + ArgumentLen;
779 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
780 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
781 "Found too many '|'s in a %diff modifier!");
782 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
783 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
784 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
785 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
786 FormatDiagnostic(Argument, FirstDollar, OutStr);
787 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
788 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
789 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
790 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
797 case DiagnosticsEngine::ak_std_string: {
798 const std::string &S = getArgStdStr(ArgNo);
799 assert(ModifierLen == 0 && "No modifiers for strings yet");
800 OutStr.append(S.begin(), S.end());
803 case DiagnosticsEngine::ak_c_string: {
804 const char *S = getArgCStr(ArgNo);
805 assert(ModifierLen == 0 && "No modifiers for strings yet");
807 // Don't crash if get passed a null pointer by accident.
811 OutStr.append(S, S + strlen(S));
814 // ---- INTEGERS ----
815 case DiagnosticsEngine::ak_sint: {
816 int Val = getArgSInt(ArgNo);
818 if (ModifierIs(Modifier, ModifierLen, "select")) {
819 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
821 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
822 HandleIntegerSModifier(Val, OutStr);
823 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
824 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
826 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
827 HandleOrdinalModifier((unsigned)Val, OutStr);
829 assert(ModifierLen == 0 && "Unknown integer modifier");
830 llvm::raw_svector_ostream(OutStr) << Val;
834 case DiagnosticsEngine::ak_uint: {
835 unsigned Val = getArgUInt(ArgNo);
837 if (ModifierIs(Modifier, ModifierLen, "select")) {
838 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
839 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
840 HandleIntegerSModifier(Val, OutStr);
841 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
842 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
844 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
845 HandleOrdinalModifier(Val, OutStr);
847 assert(ModifierLen == 0 && "Unknown integer modifier");
848 llvm::raw_svector_ostream(OutStr) << Val;
852 // ---- TOKEN SPELLINGS ----
853 case DiagnosticsEngine::ak_tokenkind: {
854 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
855 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
857 llvm::raw_svector_ostream Out(OutStr);
858 if (const char *S = tok::getPunctuatorSpelling(Kind))
859 // Quoted token spelling for punctuators.
860 Out << '\'' << S << '\'';
861 else if (const char *S = tok::getKeywordSpelling(Kind))
862 // Unquoted token spelling for keywords.
864 else if (const char *S = getTokenDescForDiagnostic(Kind))
865 // Unquoted translatable token name.
867 else if (const char *S = tok::getTokenName(Kind))
868 // Debug name, shouldn't appear in user-facing diagnostics.
869 Out << '<' << S << '>';
874 // ---- NAMES and TYPES ----
875 case DiagnosticsEngine::ak_identifierinfo: {
876 const IdentifierInfo *II = getArgIdentifier(ArgNo);
877 assert(ModifierLen == 0 && "No modifiers for strings yet");
879 // Don't crash if get passed a null pointer by accident.
881 const char *S = "(null)";
882 OutStr.append(S, S + strlen(S));
886 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
889 case DiagnosticsEngine::ak_qualtype:
890 case DiagnosticsEngine::ak_declarationname:
891 case DiagnosticsEngine::ak_nameddecl:
892 case DiagnosticsEngine::ak_nestednamespec:
893 case DiagnosticsEngine::ak_declcontext:
894 case DiagnosticsEngine::ak_attr:
895 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
896 StringRef(Modifier, ModifierLen),
897 StringRef(Argument, ArgumentLen),
899 OutStr, QualTypeVals);
901 case DiagnosticsEngine::ak_qualtype_pair:
902 // Create a struct with all the info needed for printing.
903 TemplateDiffTypes TDT;
904 TDT.FromType = getRawArg(ArgNo);
905 TDT.ToType = getRawArg(ArgNo2);
906 TDT.ElideType = getDiags()->ElideType;
907 TDT.ShowColors = getDiags()->ShowColors;
908 TDT.TemplateDiffUsed = false;
909 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
911 const char *ArgumentEnd = Argument + ArgumentLen;
912 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
914 // Print the tree. If this diagnostic already has a tree, skip the
916 if (getDiags()->PrintTemplateTree && Tree.empty()) {
917 TDT.PrintFromType = true;
918 TDT.PrintTree = true;
919 getDiags()->ConvertArgToString(Kind, val,
920 StringRef(Modifier, ModifierLen),
921 StringRef(Argument, ArgumentLen),
924 // If there is no tree information, fall back to regular printing.
926 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
931 // Non-tree printing, also the fall-back when tree printing fails.
932 // The fall-back is triggered when the types compared are not templates.
933 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
934 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
936 // Append before text
937 FormatDiagnostic(Argument, FirstDollar, OutStr);
940 TDT.PrintTree = false;
941 TDT.PrintFromType = true;
942 getDiags()->ConvertArgToString(Kind, val,
943 StringRef(Modifier, ModifierLen),
944 StringRef(Argument, ArgumentLen),
946 OutStr, QualTypeVals);
947 if (!TDT.TemplateDiffUsed)
948 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
951 // Append middle text
952 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
954 // Append second type
955 TDT.PrintFromType = false;
956 getDiags()->ConvertArgToString(Kind, val,
957 StringRef(Modifier, ModifierLen),
958 StringRef(Argument, ArgumentLen),
960 OutStr, QualTypeVals);
961 if (!TDT.TemplateDiffUsed)
962 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
966 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
970 // Remember this argument info for subsequent formatting operations. Turn
971 // std::strings into a null terminated string to make it be the same case as
972 // all the other ones.
973 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
975 else if (Kind != DiagnosticsEngine::ak_std_string)
976 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
978 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
979 (intptr_t)getArgStdStr(ArgNo).c_str()));
983 // Append the type tree to the end of the diagnostics.
984 OutStr.append(Tree.begin(), Tree.end());
987 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
989 : ID(ID), Level(Level), Loc(), Message(Message) { }
991 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
992 const Diagnostic &Info)
993 : ID(Info.getID()), Level(Level)
995 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
996 "Valid source location without setting a source manager for diagnostic");
997 if (Info.getLocation().isValid())
998 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
999 SmallString<64> Message;
1000 Info.FormatDiagnostic(Message);
1001 this->Message.assign(Message.begin(), Message.end());
1002 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1003 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1006 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1007 StringRef Message, FullSourceLoc Loc,
1008 ArrayRef<CharSourceRange> Ranges,
1009 ArrayRef<FixItHint> FixIts)
1010 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1011 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1015 /// IncludeInDiagnosticCounts - This method (whose default implementation
1016 /// returns true) indicates whether the diagnostics handled by this
1017 /// DiagnosticConsumer should be included in the number of diagnostics
1018 /// reported by DiagnosticsEngine.
1019 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1021 void IgnoringDiagConsumer::anchor() { }
1023 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
1025 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1026 DiagnosticsEngine::Level DiagLevel,
1027 const Diagnostic &Info) {
1028 Target.HandleDiagnostic(DiagLevel, Info);
1031 void ForwardingDiagnosticConsumer::clear() {
1032 DiagnosticConsumer::clear();
1036 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1037 return Target.IncludeInDiagnosticCounts();
1040 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1041 for (unsigned I = 0; I != NumCached; ++I)
1042 FreeList[I] = Cached + I;
1043 NumFreeListEntries = NumCached;
1046 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1047 // Don't assert if we are in a CrashRecovery context, as this invariant may
1048 // be invalidated during a crash.
1049 assert((NumFreeListEntries == NumCached ||
1050 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1051 "A partial is on the lam");