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 IgnoreAllWarnings = false;
71 WarningsAsErrors = false;
72 EnableAllWarnings = false;
73 ErrorsAsFatal = false;
74 FatalsAsError = false;
75 SuppressSystemWarnings = false;
76 SuppressAllDiagnostics = false;
78 PrintTemplateTree = false;
80 ShowOverloads = Ovl_All;
81 ExtBehavior = diag::Severity::Ignored;
84 TemplateBacktraceLimit = 0;
85 ConstexprBacktraceLimit = 0;
90 DiagnosticsEngine::~DiagnosticsEngine() {
91 // If we own the diagnostic client, destroy it first so that it can access the
92 // engine from its destructor.
96 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
97 bool ShouldOwnClient) {
98 Owner.reset(ShouldOwnClient ? client : nullptr);
102 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
103 DiagStateOnPushStack.push_back(GetCurDiagState());
106 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
107 if (DiagStateOnPushStack.empty())
110 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
111 // State changed at some point between push/pop.
112 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
114 DiagStateOnPushStack.pop_back();
118 void DiagnosticsEngine::Reset() {
119 ErrorOccurred = false;
120 UncompilableErrorOccurred = false;
121 FatalErrorOccurred = false;
122 UnrecoverableErrorOccurred = false;
126 TrapNumErrorsOccurred = 0;
127 TrapNumUnrecoverableErrorsOccurred = 0;
130 LastDiagLevel = DiagnosticIDs::Ignored;
133 // Clear state related to #pragma diagnostic.
135 DiagStatesByLoc.clear();
136 DiagStateOnPushStack.clear();
138 // Create a DiagState and DiagStatePoint representing diagnostic changes
139 // through command-line.
140 DiagStates.emplace_back();
141 DiagStatesByLoc.appendFirst(&DiagStates.back());
144 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
149 DelayedDiagID = DiagID;
150 DelayedDiagArg1 = Arg1.str();
151 DelayedDiagArg2 = Arg2.str();
154 void DiagnosticsEngine::ReportDelayed() {
155 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
157 DelayedDiagArg1.clear();
158 DelayedDiagArg2.clear();
161 void DiagnosticsEngine::DiagStateMap::appendFirst(
163 assert(Files.empty() && "not first");
164 FirstDiagState = CurDiagState = State;
165 CurDiagStateLoc = SourceLocation();
168 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
171 CurDiagState = State;
172 CurDiagStateLoc = Loc;
174 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
175 unsigned Offset = Decomp.second;
176 for (File *F = getFile(SrcMgr, Decomp.first); F;
177 Offset = F->ParentOffset, F = F->Parent) {
178 F->HasLocalTransitions = true;
179 auto &Last = F->StateTransitions.back();
180 assert(Last.Offset <= Offset && "state transitions added out of order");
182 if (Last.Offset == Offset) {
183 if (Last.State == State)
189 F->StateTransitions.push_back({State, Offset});
193 DiagnosticsEngine::DiagState *
194 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
195 SourceLocation Loc) const {
196 // Common case: we have not seen any diagnostic pragmas.
198 return FirstDiagState;
200 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
201 const File *F = getFile(SrcMgr, Decomp.first);
202 return F->lookup(Decomp.second);
205 DiagnosticsEngine::DiagState *
206 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
207 auto OnePastIt = std::upper_bound(
208 StateTransitions.begin(), StateTransitions.end(), Offset,
209 [](unsigned Offset, const DiagStatePoint &P) {
210 return Offset < P.Offset;
212 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
213 return OnePastIt[-1].State;
216 DiagnosticsEngine::DiagStateMap::File *
217 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
219 // Get or insert the File for this ID.
220 auto Range = Files.equal_range(ID);
221 if (Range.first != Range.second)
222 return &Range.first->second;
223 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
225 // We created a new File; look up the diagnostic state at the start of it and
228 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
229 F.Parent = getFile(SrcMgr, Decomp.first);
230 F.ParentOffset = Decomp.second;
231 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
233 // This is the (imaginary) root file into which we pretend all top-level
234 // files are included; it descends from the initial state.
236 // FIXME: This doesn't guarantee that we use the same ordering as
237 // isBeforeInTranslationUnit in the cases where someone invented another
238 // top-level file and added diagnostic pragmas to it. See the code at the
239 // end of isBeforeInTranslationUnit for the quirks it deals with.
240 F.StateTransitions.push_back({FirstDiagState, 0});
245 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
246 SourceLocation Loc) {
247 assert(Loc.isValid() && "Adding invalid loc point");
248 DiagStatesByLoc.append(*SourceMgr, Loc, State);
251 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
253 assert(Diag < diag::DIAG_UPPER_LIMIT &&
254 "Can only map builtin diagnostics");
255 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
256 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
257 "Cannot map errors into warnings!");
258 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
260 // Don't allow a mapping to a warning override an error/fatal mapping.
261 bool WasUpgradedFromWarning = false;
262 if (Map == diag::Severity::Warning) {
263 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
264 if (Info.getSeverity() == diag::Severity::Error ||
265 Info.getSeverity() == diag::Severity::Fatal) {
266 Map = Info.getSeverity();
267 WasUpgradedFromWarning = true;
270 DiagnosticMapping Mapping = makeUserMapping(Map, L);
271 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
273 // Common case; setting all the diagnostics of a group in one place.
274 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
275 DiagStatesByLoc.getCurDiagState()) {
276 // FIXME: This is theoretically wrong: if the current state is shared with
277 // some other location (via push/pop) we will change the state for that
278 // other location as well. This cannot currently happen, as we can't update
279 // the diagnostic state at the same location at which we pop.
280 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
284 // A diagnostic pragma occurred, create a new DiagState initialized with
285 // the current one and a new DiagStatePoint to record at which location
286 // the new state became active.
287 DiagStates.push_back(*GetCurDiagState());
288 DiagStates.back().setMapping(Diag, Mapping);
289 PushDiagStatePoint(&DiagStates.back(), L);
292 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
293 StringRef Group, diag::Severity Map,
294 SourceLocation Loc) {
295 // Get the diagnostics in this group.
296 SmallVector<diag::kind, 256> GroupDiags;
297 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
301 for (diag::kind Diag : GroupDiags)
302 setSeverity(Diag, Map, Loc);
307 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
309 // If we are enabling this feature, just set the diagnostic mappings to map to
312 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
313 diag::Severity::Error);
315 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
316 // potentially downgrade anything already mapped to be a warning.
318 // Get the diagnostics in this group.
319 SmallVector<diag::kind, 8> GroupDiags;
320 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
324 // Perform the mapping change.
325 for (diag::kind Diag : GroupDiags) {
326 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
328 if (Info.getSeverity() == diag::Severity::Error ||
329 Info.getSeverity() == diag::Severity::Fatal)
330 Info.setSeverity(diag::Severity::Warning);
332 Info.setNoWarningAsError(true);
338 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
340 // If we are enabling this feature, just set the diagnostic mappings to map to
343 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
344 diag::Severity::Fatal);
346 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
347 // potentially downgrade anything already mapped to be an error.
349 // Get the diagnostics in this group.
350 SmallVector<diag::kind, 8> GroupDiags;
351 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
355 // Perform the mapping change.
356 for (diag::kind Diag : GroupDiags) {
357 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
359 if (Info.getSeverity() == diag::Severity::Fatal)
360 Info.setSeverity(diag::Severity::Error);
362 Info.setNoErrorAsFatal(true);
368 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
370 SourceLocation Loc) {
371 // Get all the diagnostics.
372 SmallVector<diag::kind, 64> AllDiags;
373 Diags->getAllDiagnostics(Flavor, AllDiags);
376 for (diag::kind Diag : AllDiags)
377 if (Diags->isBuiltinWarningOrExtension(Diag))
378 setSeverity(Diag, Map, Loc);
381 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
382 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
384 CurDiagLoc = storedDiag.getLocation();
385 CurDiagID = storedDiag.getID();
389 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
391 DiagFixItHints.clear();
392 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
394 assert(Client && "DiagnosticConsumer not set!");
395 Level DiagLevel = storedDiag.getLevel();
396 Diagnostic Info(this, storedDiag.getMessage());
397 Client->HandleDiagnostic(DiagLevel, Info);
398 if (Client->IncludeInDiagnosticCounts()) {
399 if (DiagLevel == DiagnosticsEngine::Warning)
406 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
407 assert(getClient() && "DiagnosticClient not set!");
411 Diagnostic Info(this);
413 // Figure out the diagnostic level of this message.
414 DiagnosticIDs::Level DiagLevel
415 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
417 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
419 // Emit the diagnostic regardless of suppression level.
420 Diags->EmitDiag(*this, DiagLevel);
423 // Process the diagnostic, sending the accumulated information to the
424 // DiagnosticConsumer.
425 Emitted = ProcessDiag();
428 // Clear out the current diagnostic object.
429 unsigned DiagID = CurDiagID;
432 // If there was a delayed diagnostic, emit it now.
433 if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
440 DiagnosticConsumer::~DiagnosticConsumer() {}
442 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
443 const Diagnostic &Info) {
444 if (!IncludeInDiagnosticCounts())
447 if (DiagLevel == DiagnosticsEngine::Warning)
449 else if (DiagLevel >= DiagnosticsEngine::Error)
453 /// ModifierIs - Return true if the specified modifier matches specified string.
454 template <std::size_t StrLen>
455 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
456 const char (&Str)[StrLen]) {
457 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
460 /// ScanForward - Scans forward, looking for the given character, skipping
461 /// nested clauses and escaped characters.
462 static const char *ScanFormat(const char *I, const char *E, char Target) {
465 for ( ; I != E; ++I) {
466 if (Depth == 0 && *I == Target) return I;
467 if (Depth != 0 && *I == '}') Depth--;
473 // Escaped characters get implicitly skipped here.
476 if (!isDigit(*I) && !isPunctuation(*I)) {
477 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
487 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
488 /// like this: %select{foo|bar|baz}2. This means that the integer argument
489 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
490 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
491 /// This is very useful for certain classes of variant diagnostics.
492 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
493 const char *Argument, unsigned ArgumentLen,
494 SmallVectorImpl<char> &OutStr) {
495 const char *ArgumentEnd = Argument+ArgumentLen;
497 // Skip over 'ValNo' |'s.
499 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
500 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
501 " larger than the number of options in the diagnostic string!");
502 Argument = NextVal+1; // Skip this string.
506 // Get the end of the value. This is either the } or the |.
507 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
509 // Recursively format the result of the select clause into the output string.
510 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
513 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
514 /// letter 's' to the string if the value is not 1. This is used in cases like
515 /// this: "you idiot, you have %4 parameter%s4!".
516 static void HandleIntegerSModifier(unsigned ValNo,
517 SmallVectorImpl<char> &OutStr) {
519 OutStr.push_back('s');
522 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
523 /// prints the ordinal form of the given integer, with 1 corresponding
524 /// to the first ordinal. Currently this is hard-coded to use the
526 static void HandleOrdinalModifier(unsigned ValNo,
527 SmallVectorImpl<char> &OutStr) {
528 assert(ValNo != 0 && "ValNo must be strictly positive!");
530 llvm::raw_svector_ostream Out(OutStr);
532 // We could use text forms for the first N ordinals, but the numeric
533 // forms are actually nicer in diagnostics because they stand out.
534 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
538 /// PluralNumber - Parse an unsigned integer and advance Start.
539 static unsigned PluralNumber(const char *&Start, const char *End) {
540 // Programming 101: Parse a decimal number :-)
542 while (Start != End && *Start >= '0' && *Start <= '9') {
550 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
551 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
553 unsigned Ref = PluralNumber(Start, End);
558 unsigned Low = PluralNumber(Start, End);
559 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
561 unsigned High = PluralNumber(Start, End);
562 assert(*Start == ']' && "Bad plural expression syntax: expected )");
564 return Low <= Val && Val <= High;
567 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
568 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
578 unsigned Arg = PluralNumber(Start, End);
579 assert(*Start == '=' && "Bad plural expression syntax: expected =");
581 unsigned ValMod = ValNo % Arg;
582 if (TestPluralRange(ValMod, Start, End))
585 assert((C == '[' || (C >= '0' && C <= '9')) &&
586 "Bad plural expression syntax: unexpected character");
588 if (TestPluralRange(ValNo, Start, End))
592 // Scan for next or-expr part.
593 Start = std::find(Start, End, ',');
601 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
602 /// for complex plural forms, or in languages where all plurals are complex.
603 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
604 /// conditions that are tested in order, the form corresponding to the first
605 /// that applies being emitted. The empty condition is always true, making the
606 /// last form a default case.
607 /// Conditions are simple boolean expressions, where n is the number argument.
608 /// Here are the rules.
609 /// condition := expression | empty
610 /// empty := -> always true
611 /// expression := numeric [',' expression] -> logical or
612 /// numeric := range -> true if n in range
613 /// | '%' number '=' range -> true if n % number in range
615 /// | '[' number ',' number ']' -> ranges are inclusive both ends
617 /// Here are some examples from the GNU gettext manual written in this form:
621 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
623 /// {1:form0|2:form1|:form2}
625 /// {1:form0|0,%100=[1,19]:form1|:form2}
627 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
628 /// Russian (requires repeated form):
629 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
631 /// {1:form0|[2,4]:form1|:form2}
632 /// Polish (requires repeated form):
633 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
634 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
635 const char *Argument, unsigned ArgumentLen,
636 SmallVectorImpl<char> &OutStr) {
637 const char *ArgumentEnd = Argument + ArgumentLen;
639 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
640 const char *ExprEnd = Argument;
641 while (*ExprEnd != ':') {
642 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
645 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
646 Argument = ExprEnd + 1;
647 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
649 // Recursively format the result of the plural clause into the
651 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
654 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
658 /// \brief Returns the friendly description for a token kind that will appear
659 /// without quotes in diagnostic messages. These strings may be translatable in
661 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
663 case tok::identifier:
670 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
671 /// formal arguments into the %0 slots. The result is appended onto the Str
674 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
675 if (!StoredDiagMessage.empty()) {
676 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
681 getDiags()->getDiagnosticIDs()->getDescription(getID());
683 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
687 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
688 SmallVectorImpl<char> &OutStr) const {
690 // When the diagnostic string is only "%0", the entire string is being given
691 // by an outside source. Remove unprintable characters from this string
692 // and skip all the other string processing.
693 if (DiagEnd - DiagStr == 2 &&
694 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
695 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
696 const std::string &S = getArgStdStr(0);
698 if (llvm::sys::locale::isPrint(c) || c == '\t') {
705 /// FormattedArgs - Keep track of all of the arguments formatted by
706 /// ConvertArgToString and pass them into subsequent calls to
707 /// ConvertArgToString, allowing the implementation to avoid redundancies in
709 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
711 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
712 /// compared to see if more information is needed to be printed.
713 SmallVector<intptr_t, 2> QualTypeVals;
714 SmallVector<char, 64> Tree;
716 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
717 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
718 QualTypeVals.push_back(getRawArg(i));
720 while (DiagStr != DiagEnd) {
721 if (DiagStr[0] != '%') {
722 // Append non-%0 substrings to Str if we have one.
723 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
724 OutStr.append(DiagStr, StrEnd);
727 } else if (isPunctuation(DiagStr[1])) {
728 OutStr.push_back(DiagStr[1]); // %% -> %.
736 // This must be a placeholder for a diagnostic argument. The format for a
737 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
738 // The digit is a number from 0-9 indicating which argument this comes from.
739 // The modifier is a string of digits from the set [-a-z]+, arguments is a
740 // brace enclosed string.
741 const char *Modifier = nullptr, *Argument = nullptr;
742 unsigned ModifierLen = 0, ArgumentLen = 0;
744 // Check to see if we have a modifier. If so eat it.
745 if (!isDigit(DiagStr[0])) {
747 while (DiagStr[0] == '-' ||
748 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
750 ModifierLen = DiagStr-Modifier;
752 // If we have an argument, get it next.
753 if (DiagStr[0] == '{') {
754 ++DiagStr; // Skip {.
757 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
758 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
759 ArgumentLen = DiagStr-Argument;
760 ++DiagStr; // Skip }.
764 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
765 unsigned ArgNo = *DiagStr++ - '0';
767 // Only used for type diffing.
768 unsigned ArgNo2 = ArgNo;
770 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
771 if (ModifierIs(Modifier, ModifierLen, "diff")) {
772 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
773 "Invalid format for diff modifier");
775 ArgNo2 = *DiagStr++ - '0';
776 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
777 if (Kind == DiagnosticsEngine::ak_qualtype &&
778 Kind2 == DiagnosticsEngine::ak_qualtype)
779 Kind = DiagnosticsEngine::ak_qualtype_pair;
781 // %diff only supports QualTypes. For other kinds of arguments,
782 // use the default printing. For example, if the modifier is:
783 // "%diff{compare $ to $|other text}1,2"
785 // "compare %1 to %2"
786 const char *ArgumentEnd = Argument + ArgumentLen;
787 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
788 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
789 "Found too many '|'s in a %diff modifier!");
790 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
791 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
792 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
793 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
794 FormatDiagnostic(Argument, FirstDollar, OutStr);
795 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
796 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
797 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
798 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
805 case DiagnosticsEngine::ak_std_string: {
806 const std::string &S = getArgStdStr(ArgNo);
807 assert(ModifierLen == 0 && "No modifiers for strings yet");
808 OutStr.append(S.begin(), S.end());
811 case DiagnosticsEngine::ak_c_string: {
812 const char *S = getArgCStr(ArgNo);
813 assert(ModifierLen == 0 && "No modifiers for strings yet");
815 // Don't crash if get passed a null pointer by accident.
819 OutStr.append(S, S + strlen(S));
822 // ---- INTEGERS ----
823 case DiagnosticsEngine::ak_sint: {
824 int Val = getArgSInt(ArgNo);
826 if (ModifierIs(Modifier, ModifierLen, "select")) {
827 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
829 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
830 HandleIntegerSModifier(Val, OutStr);
831 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
832 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
834 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
835 HandleOrdinalModifier((unsigned)Val, OutStr);
837 assert(ModifierLen == 0 && "Unknown integer modifier");
838 llvm::raw_svector_ostream(OutStr) << Val;
842 case DiagnosticsEngine::ak_uint: {
843 unsigned Val = getArgUInt(ArgNo);
845 if (ModifierIs(Modifier, ModifierLen, "select")) {
846 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
847 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
848 HandleIntegerSModifier(Val, OutStr);
849 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
850 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
852 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
853 HandleOrdinalModifier(Val, OutStr);
855 assert(ModifierLen == 0 && "Unknown integer modifier");
856 llvm::raw_svector_ostream(OutStr) << Val;
860 // ---- TOKEN SPELLINGS ----
861 case DiagnosticsEngine::ak_tokenkind: {
862 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
863 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
865 llvm::raw_svector_ostream Out(OutStr);
866 if (const char *S = tok::getPunctuatorSpelling(Kind))
867 // Quoted token spelling for punctuators.
868 Out << '\'' << S << '\'';
869 else if (const char *S = tok::getKeywordSpelling(Kind))
870 // Unquoted token spelling for keywords.
872 else if (const char *S = getTokenDescForDiagnostic(Kind))
873 // Unquoted translatable token name.
875 else if (const char *S = tok::getTokenName(Kind))
876 // Debug name, shouldn't appear in user-facing diagnostics.
877 Out << '<' << S << '>';
882 // ---- NAMES and TYPES ----
883 case DiagnosticsEngine::ak_identifierinfo: {
884 const IdentifierInfo *II = getArgIdentifier(ArgNo);
885 assert(ModifierLen == 0 && "No modifiers for strings yet");
887 // Don't crash if get passed a null pointer by accident.
889 const char *S = "(null)";
890 OutStr.append(S, S + strlen(S));
894 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
897 case DiagnosticsEngine::ak_qualtype:
898 case DiagnosticsEngine::ak_declarationname:
899 case DiagnosticsEngine::ak_nameddecl:
900 case DiagnosticsEngine::ak_nestednamespec:
901 case DiagnosticsEngine::ak_declcontext:
902 case DiagnosticsEngine::ak_attr:
903 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
904 StringRef(Modifier, ModifierLen),
905 StringRef(Argument, ArgumentLen),
907 OutStr, QualTypeVals);
909 case DiagnosticsEngine::ak_qualtype_pair:
910 // Create a struct with all the info needed for printing.
911 TemplateDiffTypes TDT;
912 TDT.FromType = getRawArg(ArgNo);
913 TDT.ToType = getRawArg(ArgNo2);
914 TDT.ElideType = getDiags()->ElideType;
915 TDT.ShowColors = getDiags()->ShowColors;
916 TDT.TemplateDiffUsed = false;
917 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
919 const char *ArgumentEnd = Argument + ArgumentLen;
920 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
922 // Print the tree. If this diagnostic already has a tree, skip the
924 if (getDiags()->PrintTemplateTree && Tree.empty()) {
925 TDT.PrintFromType = true;
926 TDT.PrintTree = true;
927 getDiags()->ConvertArgToString(Kind, val,
928 StringRef(Modifier, ModifierLen),
929 StringRef(Argument, ArgumentLen),
932 // If there is no tree information, fall back to regular printing.
934 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
939 // Non-tree printing, also the fall-back when tree printing fails.
940 // The fall-back is triggered when the types compared are not templates.
941 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
942 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
944 // Append before text
945 FormatDiagnostic(Argument, FirstDollar, OutStr);
948 TDT.PrintTree = false;
949 TDT.PrintFromType = true;
950 getDiags()->ConvertArgToString(Kind, val,
951 StringRef(Modifier, ModifierLen),
952 StringRef(Argument, ArgumentLen),
954 OutStr, QualTypeVals);
955 if (!TDT.TemplateDiffUsed)
956 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
959 // Append middle text
960 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
962 // Append second type
963 TDT.PrintFromType = false;
964 getDiags()->ConvertArgToString(Kind, val,
965 StringRef(Modifier, ModifierLen),
966 StringRef(Argument, ArgumentLen),
968 OutStr, QualTypeVals);
969 if (!TDT.TemplateDiffUsed)
970 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
974 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
978 // Remember this argument info for subsequent formatting operations. Turn
979 // std::strings into a null terminated string to make it be the same case as
980 // all the other ones.
981 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
983 else if (Kind != DiagnosticsEngine::ak_std_string)
984 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
986 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
987 (intptr_t)getArgStdStr(ArgNo).c_str()));
991 // Append the type tree to the end of the diagnostics.
992 OutStr.append(Tree.begin(), Tree.end());
995 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
997 : ID(ID), Level(Level), Loc(), Message(Message) { }
999 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
1000 const Diagnostic &Info)
1001 : ID(Info.getID()), Level(Level)
1003 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1004 "Valid source location without setting a source manager for diagnostic");
1005 if (Info.getLocation().isValid())
1006 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1007 SmallString<64> Message;
1008 Info.FormatDiagnostic(Message);
1009 this->Message.assign(Message.begin(), Message.end());
1010 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1011 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1014 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1015 StringRef Message, FullSourceLoc Loc,
1016 ArrayRef<CharSourceRange> Ranges,
1017 ArrayRef<FixItHint> FixIts)
1018 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1019 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1023 /// IncludeInDiagnosticCounts - This method (whose default implementation
1024 /// returns true) indicates whether the diagnostics handled by this
1025 /// DiagnosticConsumer should be included in the number of diagnostics
1026 /// reported by DiagnosticsEngine.
1027 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1029 void IgnoringDiagConsumer::anchor() { }
1031 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
1033 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1034 DiagnosticsEngine::Level DiagLevel,
1035 const Diagnostic &Info) {
1036 Target.HandleDiagnostic(DiagLevel, Info);
1039 void ForwardingDiagnosticConsumer::clear() {
1040 DiagnosticConsumer::clear();
1044 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1045 return Target.IncludeInDiagnosticCounts();
1048 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1049 for (unsigned I = 0; I != NumCached; ++I)
1050 FreeList[I] = Cached + I;
1051 NumFreeListEntries = NumCached;
1054 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1055 // Don't assert if we are in a CrashRecovery context, as this invariant may
1056 // be invalidated during a crash.
1057 assert((NumFreeListEntries == NumCached ||
1058 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1059 "A partial is on the lam");