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/DiagnosticOptions.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/PartialDiagnostic.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
24 using namespace clang;
26 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
27 const char *Modifier, unsigned ML,
28 const char *Argument, unsigned ArgLen,
29 const DiagnosticsEngine::ArgumentValue *PrevArgs,
31 SmallVectorImpl<char> &Output,
33 ArrayRef<intptr_t> QualTypeVals) {
34 const char *Str = "<can't format argument>";
35 Output.append(Str, Str+strlen(Str));
39 DiagnosticsEngine::DiagnosticsEngine(
40 const IntrusiveRefCntPtr<DiagnosticIDs> &diags,
41 DiagnosticOptions *DiagOpts,
42 DiagnosticConsumer *client, bool ShouldOwnClient)
43 : Diags(diags), DiagOpts(DiagOpts), Client(client),
44 OwnsDiagClient(ShouldOwnClient), SourceMgr(0) {
45 ArgToStringFn = DummyArgToStringFn;
46 ArgToStringCookie = 0;
48 AllExtensionsSilenced = 0;
49 IgnoreAllWarnings = false;
50 WarningsAsErrors = false;
51 EnableAllWarnings = false;
52 ErrorsAsFatal = false;
53 SuppressSystemWarnings = false;
54 SuppressAllDiagnostics = false;
56 PrintTemplateTree = false;
58 ShowOverloads = Ovl_All;
59 ExtBehavior = Ext_Ignore;
62 TemplateBacktraceLimit = 0;
63 ConstexprBacktraceLimit = 0;
68 DiagnosticsEngine::~DiagnosticsEngine() {
73 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
74 bool ShouldOwnClient) {
75 if (OwnsDiagClient && Client)
79 OwnsDiagClient = ShouldOwnClient;
82 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
83 DiagStateOnPushStack.push_back(GetCurDiagState());
86 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
87 if (DiagStateOnPushStack.empty())
90 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
91 // State changed at some point between push/pop.
92 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
94 DiagStateOnPushStack.pop_back();
98 void DiagnosticsEngine::Reset() {
99 ErrorOccurred = false;
100 FatalErrorOccurred = false;
101 UnrecoverableErrorOccurred = false;
105 NumErrorsSuppressed = 0;
106 TrapNumErrorsOccurred = 0;
107 TrapNumUnrecoverableErrorsOccurred = 0;
110 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
111 // using a DiagnosticsEngine associated to a translation unit that follow
112 // diagnostics from a DiagnosticsEngine associated to anoter t.u. will not be
114 LastDiagLevel = (DiagnosticIDs::Level)-1;
117 // Clear state related to #pragma diagnostic.
119 DiagStatePoints.clear();
120 DiagStateOnPushStack.clear();
122 // Create a DiagState and DiagStatePoint representing diagnostic changes
123 // through command-line.
124 DiagStates.push_back(DiagState());
125 DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
128 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
133 DelayedDiagID = DiagID;
134 DelayedDiagArg1 = Arg1.str();
135 DelayedDiagArg2 = Arg2.str();
138 void DiagnosticsEngine::ReportDelayed() {
139 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
141 DelayedDiagArg1.clear();
142 DelayedDiagArg2.clear();
145 DiagnosticsEngine::DiagStatePointsTy::iterator
146 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
147 assert(!DiagStatePoints.empty());
148 assert(DiagStatePoints.front().Loc.isInvalid() &&
149 "Should have created a DiagStatePoint for command-line");
152 return DiagStatePoints.end() - 1;
154 FullSourceLoc Loc(L, *SourceMgr);
156 return DiagStatePoints.end() - 1;
158 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
159 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
160 if (LastStateChangePos.isValid() &&
161 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
162 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
163 DiagStatePoint(0, Loc));
168 void DiagnosticsEngine::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
170 assert(Diag < diag::DIAG_UPPER_LIMIT &&
171 "Can only map builtin diagnostics");
172 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
173 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
174 "Cannot map errors into warnings!");
175 assert(!DiagStatePoints.empty());
176 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
178 FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc();
179 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
180 // Don't allow a mapping to a warning override an error/fatal mapping.
181 if (Map == diag::MAP_WARNING) {
182 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
183 if (Info.getMapping() == diag::MAP_ERROR ||
184 Info.getMapping() == diag::MAP_FATAL)
185 Map = Info.getMapping();
187 DiagnosticMappingInfo MappingInfo = makeMappingInfo(Map, L);
189 // Common case; setting all the diagnostics of a group in one place.
190 if (Loc.isInvalid() || Loc == LastStateChangePos) {
191 GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
195 // Another common case; modifying diagnostic state in a source location
196 // after the previous one.
197 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
198 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
199 // A diagnostic pragma occurred, create a new DiagState initialized with
200 // the current one and a new DiagStatePoint to record at which location
201 // the new state became active.
202 DiagStates.push_back(*GetCurDiagState());
203 PushDiagStatePoint(&DiagStates.back(), Loc);
204 GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
208 // We allow setting the diagnostic state in random source order for
209 // completeness but it should not be actually happening in normal practice.
211 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
212 assert(Pos != DiagStatePoints.end());
214 // Update all diagnostic states that are active after the given location.
215 for (DiagStatePointsTy::iterator
216 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
217 GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
220 // If the location corresponds to an existing point, just update its state.
221 if (Pos->Loc == Loc) {
222 GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
226 // Create a new state/point and fit it into the vector of DiagStatePoints
227 // so that the vector is always ordered according to location.
228 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
229 DiagStates.push_back(*Pos->State);
230 DiagState *NewState = &DiagStates.back();
231 GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
232 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
233 FullSourceLoc(Loc, *SourceMgr)));
236 bool DiagnosticsEngine::setDiagnosticGroupMapping(
237 StringRef Group, diag::Mapping Map, SourceLocation Loc)
239 // Get the diagnostics in this group.
240 llvm::SmallVector<diag::kind, 8> GroupDiags;
241 if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
245 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i)
246 setDiagnosticMapping(GroupDiags[i], Map, Loc);
251 void DiagnosticsEngine::setDiagnosticWarningAsError(diag::kind Diag,
253 // If we are enabling this feature, just set the diagnostic mappings to map to
256 setDiagnosticMapping(Diag, diag::MAP_ERROR, SourceLocation());
258 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
259 // potentially downgrade anything already mapped to be a warning.
260 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
262 if (Info.getMapping() == diag::MAP_ERROR ||
263 Info.getMapping() == diag::MAP_FATAL)
264 Info.setMapping(diag::MAP_WARNING);
266 Info.setNoWarningAsError(true);
269 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
271 // If we are enabling this feature, just set the diagnostic mappings to map to
274 return setDiagnosticGroupMapping(Group, diag::MAP_ERROR);
276 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
277 // potentially downgrade anything already mapped to be a warning.
279 // Get the diagnostics in this group.
280 llvm::SmallVector<diag::kind, 8> GroupDiags;
281 if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
284 // Perform the mapping change.
285 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
286 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
289 if (Info.getMapping() == diag::MAP_ERROR ||
290 Info.getMapping() == diag::MAP_FATAL)
291 Info.setMapping(diag::MAP_WARNING);
293 Info.setNoWarningAsError(true);
299 void DiagnosticsEngine::setDiagnosticErrorAsFatal(diag::kind Diag,
301 // If we are enabling this feature, just set the diagnostic mappings to map to
304 setDiagnosticMapping(Diag, diag::MAP_FATAL, SourceLocation());
306 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
307 // potentially downgrade anything already mapped to be a warning.
308 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
310 if (Info.getMapping() == diag::MAP_FATAL)
311 Info.setMapping(diag::MAP_ERROR);
313 Info.setNoErrorAsFatal(true);
316 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
318 // If we are enabling this feature, just set the diagnostic mappings to map to
321 return setDiagnosticGroupMapping(Group, diag::MAP_FATAL);
323 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
324 // potentially downgrade anything already mapped to be an error.
326 // Get the diagnostics in this group.
327 llvm::SmallVector<diag::kind, 8> GroupDiags;
328 if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
331 // Perform the mapping change.
332 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
333 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
336 if (Info.getMapping() == diag::MAP_FATAL)
337 Info.setMapping(diag::MAP_ERROR);
339 Info.setNoErrorAsFatal(true);
345 void DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map,
346 SourceLocation Loc) {
347 // Get all the diagnostics.
348 llvm::SmallVector<diag::kind, 64> AllDiags;
349 Diags->getAllDiagnostics(AllDiags);
352 for (unsigned i = 0, e = AllDiags.size(); i != e; ++i)
353 if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
354 setDiagnosticMapping(AllDiags[i], Map, Loc);
357 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
358 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
360 CurDiagLoc = storedDiag.getLocation();
361 CurDiagID = storedDiag.getID();
364 NumDiagRanges = storedDiag.range_size();
365 assert(NumDiagRanges < DiagnosticsEngine::MaxRanges &&
366 "Too many arguments to diagnostic!");
368 for (StoredDiagnostic::range_iterator
369 RI = storedDiag.range_begin(),
370 RE = storedDiag.range_end(); RI != RE; ++RI)
371 DiagRanges[i++] = *RI;
373 assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints &&
374 "Too many arguments to diagnostic!");
375 NumDiagFixItHints = 0;
376 for (StoredDiagnostic::fixit_iterator
377 FI = storedDiag.fixit_begin(),
378 FE = storedDiag.fixit_end(); FI != FE; ++FI)
379 DiagFixItHints[NumDiagFixItHints++] = *FI;
381 assert(Client && "DiagnosticConsumer not set!");
382 Level DiagLevel = storedDiag.getLevel();
383 Diagnostic Info(this, storedDiag.getMessage());
384 Client->HandleDiagnostic(DiagLevel, Info);
385 if (Client->IncludeInDiagnosticCounts()) {
386 if (DiagLevel == DiagnosticsEngine::Warning)
393 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
394 assert(getClient() && "DiagnosticClient not set!");
398 Diagnostic Info(this);
400 // Figure out the diagnostic level of this message.
401 DiagnosticIDs::Level DiagLevel
402 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
404 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
406 // Emit the diagnostic regardless of suppression level.
407 Diags->EmitDiag(*this, DiagLevel);
410 // Process the diagnostic, sending the accumulated information to the
411 // DiagnosticConsumer.
412 Emitted = ProcessDiag();
415 // Clear out the current diagnostic object.
416 unsigned DiagID = CurDiagID;
419 // If there was a delayed diagnostic, emit it now.
420 if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
427 DiagnosticConsumer::~DiagnosticConsumer() {}
429 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
430 const Diagnostic &Info) {
431 if (!IncludeInDiagnosticCounts())
434 if (DiagLevel == DiagnosticsEngine::Warning)
436 else if (DiagLevel >= DiagnosticsEngine::Error)
440 /// ModifierIs - Return true if the specified modifier matches specified string.
441 template <std::size_t StrLen>
442 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
443 const char (&Str)[StrLen]) {
444 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
447 /// ScanForward - Scans forward, looking for the given character, skipping
448 /// nested clauses and escaped characters.
449 static const char *ScanFormat(const char *I, const char *E, char Target) {
452 for ( ; I != E; ++I) {
453 if (Depth == 0 && *I == Target) return I;
454 if (Depth != 0 && *I == '}') Depth--;
460 // Escaped characters get implicitly skipped here.
463 if (!isdigit(*I) && !ispunct(*I)) {
464 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
474 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
475 /// like this: %select{foo|bar|baz}2. This means that the integer argument
476 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
477 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
478 /// This is very useful for certain classes of variant diagnostics.
479 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
480 const char *Argument, unsigned ArgumentLen,
481 SmallVectorImpl<char> &OutStr) {
482 const char *ArgumentEnd = Argument+ArgumentLen;
484 // Skip over 'ValNo' |'s.
486 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
487 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
488 " larger than the number of options in the diagnostic string!");
489 Argument = NextVal+1; // Skip this string.
493 // Get the end of the value. This is either the } or the |.
494 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
496 // Recursively format the result of the select clause into the output string.
497 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
500 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
501 /// letter 's' to the string if the value is not 1. This is used in cases like
502 /// this: "you idiot, you have %4 parameter%s4!".
503 static void HandleIntegerSModifier(unsigned ValNo,
504 SmallVectorImpl<char> &OutStr) {
506 OutStr.push_back('s');
509 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
510 /// prints the ordinal form of the given integer, with 1 corresponding
511 /// to the first ordinal. Currently this is hard-coded to use the
513 static void HandleOrdinalModifier(unsigned ValNo,
514 SmallVectorImpl<char> &OutStr) {
515 assert(ValNo != 0 && "ValNo must be strictly positive!");
517 llvm::raw_svector_ostream Out(OutStr);
519 // We could use text forms for the first N ordinals, but the numeric
520 // forms are actually nicer in diagnostics because they stand out.
521 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
525 /// PluralNumber - Parse an unsigned integer and advance Start.
526 static unsigned PluralNumber(const char *&Start, const char *End) {
527 // Programming 101: Parse a decimal number :-)
529 while (Start != End && *Start >= '0' && *Start <= '9') {
537 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
538 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
540 unsigned Ref = PluralNumber(Start, End);
545 unsigned Low = PluralNumber(Start, End);
546 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
548 unsigned High = PluralNumber(Start, End);
549 assert(*Start == ']' && "Bad plural expression syntax: expected )");
551 return Low <= Val && Val <= High;
554 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
555 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
565 unsigned Arg = PluralNumber(Start, End);
566 assert(*Start == '=' && "Bad plural expression syntax: expected =");
568 unsigned ValMod = ValNo % Arg;
569 if (TestPluralRange(ValMod, Start, End))
572 assert((C == '[' || (C >= '0' && C <= '9')) &&
573 "Bad plural expression syntax: unexpected character");
575 if (TestPluralRange(ValNo, Start, End))
579 // Scan for next or-expr part.
580 Start = std::find(Start, End, ',');
588 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
589 /// for complex plural forms, or in languages where all plurals are complex.
590 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
591 /// conditions that are tested in order, the form corresponding to the first
592 /// that applies being emitted. The empty condition is always true, making the
593 /// last form a default case.
594 /// Conditions are simple boolean expressions, where n is the number argument.
595 /// Here are the rules.
596 /// condition := expression | empty
597 /// empty := -> always true
598 /// expression := numeric [',' expression] -> logical or
599 /// numeric := range -> true if n in range
600 /// | '%' number '=' range -> true if n % number in range
602 /// | '[' number ',' number ']' -> ranges are inclusive both ends
604 /// Here are some examples from the GNU gettext manual written in this form:
608 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
610 /// {1:form0|2:form1|:form2}
612 /// {1:form0|0,%100=[1,19]:form1|:form2}
614 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
615 /// Russian (requires repeated form):
616 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
618 /// {1:form0|[2,4]:form1|:form2}
619 /// Polish (requires repeated form):
620 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
621 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
622 const char *Argument, unsigned ArgumentLen,
623 SmallVectorImpl<char> &OutStr) {
624 const char *ArgumentEnd = Argument + ArgumentLen;
626 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
627 const char *ExprEnd = Argument;
628 while (*ExprEnd != ':') {
629 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
632 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
633 Argument = ExprEnd + 1;
634 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
636 // Recursively format the result of the plural clause into the
638 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
641 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
646 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
647 /// formal arguments into the %0 slots. The result is appended onto the Str
650 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
651 if (!StoredDiagMessage.empty()) {
652 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
657 getDiags()->getDiagnosticIDs()->getDescription(getID());
659 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
663 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
664 SmallVectorImpl<char> &OutStr) const {
666 /// FormattedArgs - Keep track of all of the arguments formatted by
667 /// ConvertArgToString and pass them into subsequent calls to
668 /// ConvertArgToString, allowing the implementation to avoid redundancies in
670 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
672 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
673 /// compared to see if more information is needed to be printed.
674 SmallVector<intptr_t, 2> QualTypeVals;
675 SmallVector<char, 64> Tree;
677 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
678 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
679 QualTypeVals.push_back(getRawArg(i));
681 while (DiagStr != DiagEnd) {
682 if (DiagStr[0] != '%') {
683 // Append non-%0 substrings to Str if we have one.
684 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
685 OutStr.append(DiagStr, StrEnd);
688 } else if (ispunct(DiagStr[1])) {
689 OutStr.push_back(DiagStr[1]); // %% -> %.
697 // This must be a placeholder for a diagnostic argument. The format for a
698 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
699 // The digit is a number from 0-9 indicating which argument this comes from.
700 // The modifier is a string of digits from the set [-a-z]+, arguments is a
701 // brace enclosed string.
702 const char *Modifier = 0, *Argument = 0;
703 unsigned ModifierLen = 0, ArgumentLen = 0;
705 // Check to see if we have a modifier. If so eat it.
706 if (!isdigit(DiagStr[0])) {
708 while (DiagStr[0] == '-' ||
709 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
711 ModifierLen = DiagStr-Modifier;
713 // If we have an argument, get it next.
714 if (DiagStr[0] == '{') {
715 ++DiagStr; // Skip {.
718 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
719 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
720 ArgumentLen = DiagStr-Argument;
721 ++DiagStr; // Skip }.
725 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
726 unsigned ArgNo = *DiagStr++ - '0';
728 // Only used for type diffing.
729 unsigned ArgNo2 = ArgNo;
731 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
732 if (Kind == DiagnosticsEngine::ak_qualtype &&
733 ModifierIs(Modifier, ModifierLen, "diff")) {
734 Kind = DiagnosticsEngine::ak_qualtype_pair;
735 assert(*DiagStr == ',' && isdigit(*(DiagStr + 1)) &&
736 "Invalid format for diff modifier");
738 ArgNo2 = *DiagStr++ - '0';
739 assert(getArgKind(ArgNo2) == DiagnosticsEngine::ak_qualtype &&
740 "Second value of type diff must be a qualtype");
745 case DiagnosticsEngine::ak_std_string: {
746 const std::string &S = getArgStdStr(ArgNo);
747 assert(ModifierLen == 0 && "No modifiers for strings yet");
748 OutStr.append(S.begin(), S.end());
751 case DiagnosticsEngine::ak_c_string: {
752 const char *S = getArgCStr(ArgNo);
753 assert(ModifierLen == 0 && "No modifiers for strings yet");
755 // Don't crash if get passed a null pointer by accident.
759 OutStr.append(S, S + strlen(S));
762 // ---- INTEGERS ----
763 case DiagnosticsEngine::ak_sint: {
764 int Val = getArgSInt(ArgNo);
766 if (ModifierIs(Modifier, ModifierLen, "select")) {
767 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
769 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
770 HandleIntegerSModifier(Val, OutStr);
771 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
772 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
774 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
775 HandleOrdinalModifier((unsigned)Val, OutStr);
777 assert(ModifierLen == 0 && "Unknown integer modifier");
778 llvm::raw_svector_ostream(OutStr) << Val;
782 case DiagnosticsEngine::ak_uint: {
783 unsigned Val = getArgUInt(ArgNo);
785 if (ModifierIs(Modifier, ModifierLen, "select")) {
786 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
787 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
788 HandleIntegerSModifier(Val, OutStr);
789 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
790 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
792 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
793 HandleOrdinalModifier(Val, OutStr);
795 assert(ModifierLen == 0 && "Unknown integer modifier");
796 llvm::raw_svector_ostream(OutStr) << Val;
800 // ---- NAMES and TYPES ----
801 case DiagnosticsEngine::ak_identifierinfo: {
802 const IdentifierInfo *II = getArgIdentifier(ArgNo);
803 assert(ModifierLen == 0 && "No modifiers for strings yet");
805 // Don't crash if get passed a null pointer by accident.
807 const char *S = "(null)";
808 OutStr.append(S, S + strlen(S));
812 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
815 case DiagnosticsEngine::ak_qualtype:
816 case DiagnosticsEngine::ak_declarationname:
817 case DiagnosticsEngine::ak_nameddecl:
818 case DiagnosticsEngine::ak_nestednamespec:
819 case DiagnosticsEngine::ak_declcontext:
820 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
821 Modifier, ModifierLen,
822 Argument, ArgumentLen,
823 FormattedArgs.data(), FormattedArgs.size(),
824 OutStr, QualTypeVals);
826 case DiagnosticsEngine::ak_qualtype_pair:
827 // Create a struct with all the info needed for printing.
828 TemplateDiffTypes TDT;
829 TDT.FromType = getRawArg(ArgNo);
830 TDT.ToType = getRawArg(ArgNo2);
831 TDT.ElideType = getDiags()->ElideType;
832 TDT.ShowColors = getDiags()->ShowColors;
833 TDT.TemplateDiffUsed = false;
834 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
836 const char *ArgumentEnd = Argument + ArgumentLen;
837 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
839 // Print the tree. If this diagnostic already has a tree, skip the
841 if (getDiags()->PrintTemplateTree && Tree.empty()) {
842 TDT.PrintFromType = true;
843 TDT.PrintTree = true;
844 getDiags()->ConvertArgToString(Kind, val,
845 Modifier, ModifierLen,
846 Argument, ArgumentLen,
847 FormattedArgs.data(),
848 FormattedArgs.size(),
850 // If there is no tree information, fall back to regular printing.
852 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
857 // Non-tree printing, also the fall-back when tree printing fails.
858 // The fall-back is triggered when the types compared are not templates.
859 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
860 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
862 // Append before text
863 FormatDiagnostic(Argument, FirstDollar, OutStr);
866 TDT.PrintTree = false;
867 TDT.PrintFromType = true;
868 getDiags()->ConvertArgToString(Kind, val,
869 Modifier, ModifierLen,
870 Argument, ArgumentLen,
871 FormattedArgs.data(), FormattedArgs.size(),
872 OutStr, QualTypeVals);
873 if (!TDT.TemplateDiffUsed)
874 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
877 // Append middle text
878 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
880 // Append second type
881 TDT.PrintFromType = false;
882 getDiags()->ConvertArgToString(Kind, val,
883 Modifier, ModifierLen,
884 Argument, ArgumentLen,
885 FormattedArgs.data(), FormattedArgs.size(),
886 OutStr, QualTypeVals);
887 if (!TDT.TemplateDiffUsed)
888 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
892 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
896 // Remember this argument info for subsequent formatting operations. Turn
897 // std::strings into a null terminated string to make it be the same case as
898 // all the other ones.
899 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
901 else if (Kind != DiagnosticsEngine::ak_std_string)
902 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
904 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
905 (intptr_t)getArgStdStr(ArgNo).c_str()));
909 // Append the type tree to the end of the diagnostics.
910 OutStr.append(Tree.begin(), Tree.end());
913 StoredDiagnostic::StoredDiagnostic() { }
915 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
917 : ID(ID), Level(Level), Loc(), Message(Message) { }
919 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
920 const Diagnostic &Info)
921 : ID(Info.getID()), Level(Level)
923 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
924 "Valid source location without setting a source manager for diagnostic");
925 if (Info.getLocation().isValid())
926 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
927 SmallString<64> Message;
928 Info.FormatDiagnostic(Message);
929 this->Message.assign(Message.begin(), Message.end());
931 Ranges.reserve(Info.getNumRanges());
932 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
933 Ranges.push_back(Info.getRange(I));
935 FixIts.reserve(Info.getNumFixItHints());
936 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
937 FixIts.push_back(Info.getFixItHint(I));
940 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
941 StringRef Message, FullSourceLoc Loc,
942 ArrayRef<CharSourceRange> Ranges,
943 ArrayRef<FixItHint> Fixits)
944 : ID(ID), Level(Level), Loc(Loc), Message(Message)
946 this->Ranges.assign(Ranges.begin(), Ranges.end());
947 this->FixIts.assign(FixIts.begin(), FixIts.end());
950 StoredDiagnostic::~StoredDiagnostic() { }
952 /// IncludeInDiagnosticCounts - This method (whose default implementation
953 /// returns true) indicates whether the diagnostics handled by this
954 /// DiagnosticConsumer should be included in the number of diagnostics
955 /// reported by DiagnosticsEngine.
956 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
958 void IgnoringDiagConsumer::anchor() { }
960 PartialDiagnostic::StorageAllocator::StorageAllocator() {
961 for (unsigned I = 0; I != NumCached; ++I)
962 FreeList[I] = Cached + I;
963 NumFreeListEntries = NumCached;
966 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
967 // Don't assert if we are in a CrashRecovery context, as this invariant may
968 // be invalidated during a crash.
969 assert((NumFreeListEntries == NumCached ||
970 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
971 "A partial is on the lamb");