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/AST/ASTDiagnostic.h"
15 #include "clang/Analysis/AnalysisDiagnostic.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Driver/DriverDiagnostic.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "clang/Parse/ParseDiagnostic.h"
26 #include "clang/Sema/SemaDiagnostic.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
35 using namespace clang;
37 //===----------------------------------------------------------------------===//
38 // Builtin Diagnostic information
39 //===----------------------------------------------------------------------===//
43 // Diagnostic classes.
47 CLASS_EXTENSION = 0x03,
51 struct StaticDiagInfoRec {
52 unsigned short DiagID;
56 unsigned Category : 5;
58 const char *Description;
59 const char *OptionGroup;
61 bool operator<(const StaticDiagInfoRec &RHS) const {
62 return DiagID < RHS.DiagID;
68 static const StaticDiagInfoRec StaticDiagInfo[] = {
69 #define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY) \
70 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP },
71 #include "clang/Basic/DiagnosticCommonKinds.inc"
72 #include "clang/Basic/DiagnosticDriverKinds.inc"
73 #include "clang/Basic/DiagnosticFrontendKinds.inc"
74 #include "clang/Basic/DiagnosticLexKinds.inc"
75 #include "clang/Basic/DiagnosticParseKinds.inc"
76 #include "clang/Basic/DiagnosticASTKinds.inc"
77 #include "clang/Basic/DiagnosticSemaKinds.inc"
78 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
79 { 0, 0, 0, 0, 0, 0, 0}
83 /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
84 /// or null if the ID is invalid.
85 static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
86 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
88 // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
90 static bool IsFirst = true;
92 for (unsigned i = 1; i != NumDiagEntries; ++i) {
93 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
94 "Diag ID conflict, the enums at the start of clang::diag (in "
95 "Diagnostic.h) probably need to be increased");
97 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
98 "Improperly sorted diag info");
104 // Search the diagnostic table with a binary search.
105 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 };
107 const StaticDiagInfoRec *Found =
108 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
109 if (Found == StaticDiagInfo + NumDiagEntries ||
110 Found->DiagID != DiagID)
116 static unsigned GetDefaultDiagMapping(unsigned DiagID) {
117 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
118 return Info->Mapping;
119 return diag::MAP_FATAL;
122 /// getWarningOptionForDiag - Return the lowest-level warning option that
123 /// enables the specified diagnostic. If there is no -Wfoo flag that controls
124 /// the diagnostic, this returns null.
125 const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
126 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
127 return Info->OptionGroup;
131 /// getWarningOptionForDiag - Return the category number that a specified
132 /// DiagID belongs to, or 0 if no category.
133 unsigned Diagnostic::getCategoryNumberForDiag(unsigned DiagID) {
134 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
135 return Info->Category;
139 /// getCategoryNameFromID - Given a category ID, return the name of the
140 /// category, an empty string if CategoryID is zero, or null if CategoryID is
142 const char *Diagnostic::getCategoryNameFromID(unsigned CategoryID) {
143 // Second the table of options, sorted by name for fast binary lookup.
144 static const char *CategoryNameTable[] = {
145 #define GET_CATEGORY_TABLE
146 #define CATEGORY(X) X,
147 #include "clang/Basic/DiagnosticGroups.inc"
148 #undef GET_CATEGORY_TABLE
151 static const size_t CategoryNameTableSize =
152 sizeof(CategoryNameTable) / sizeof(CategoryNameTable[0])-1;
154 if (CategoryID >= CategoryNameTableSize) return 0;
155 return CategoryNameTable[CategoryID];
160 Diagnostic::SFINAEResponse
161 Diagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) {
162 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) {
164 return SFINAE_Report;
166 if (Info->Class == CLASS_ERROR)
167 return SFINAE_SubstitutionFailure;
169 // Suppress notes, warnings, and extensions;
170 return SFINAE_Suppress;
173 return SFINAE_Report;
176 /// getDiagClass - Return the class field of the diagnostic.
178 static unsigned getBuiltinDiagClass(unsigned DiagID) {
179 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
184 //===----------------------------------------------------------------------===//
185 // Custom Diagnostic information
186 //===----------------------------------------------------------------------===//
190 class CustomDiagInfo {
191 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
192 std::vector<DiagDesc> DiagInfo;
193 std::map<DiagDesc, unsigned> DiagIDs;
196 /// getDescription - Return the description of the specified custom
198 const char *getDescription(unsigned DiagID) const {
199 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
200 "Invalid diagnosic ID");
201 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
204 /// getLevel - Return the level of the specified custom diagnostic.
205 Diagnostic::Level getLevel(unsigned DiagID) const {
206 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
207 "Invalid diagnosic ID");
208 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
211 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
213 DiagDesc D(L, Message);
214 // Check to see if it already exists.
215 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
216 if (I != DiagIDs.end() && I->first == D)
219 // If not, assign a new ID.
220 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
221 DiagIDs.insert(std::make_pair(D, ID));
222 DiagInfo.push_back(D);
227 } // end diag namespace
228 } // end clang namespace
231 //===----------------------------------------------------------------------===//
232 // Common Diagnostic implementation
233 //===----------------------------------------------------------------------===//
235 static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
236 const char *Modifier, unsigned ML,
237 const char *Argument, unsigned ArgLen,
238 const Diagnostic::ArgumentValue *PrevArgs,
239 unsigned NumPrevArgs,
240 llvm::SmallVectorImpl<char> &Output,
242 const char *Str = "<can't format argument>";
243 Output.append(Str, Str+strlen(Str));
247 Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
248 ArgToStringFn = DummyArgToStringFn;
249 ArgToStringCookie = 0;
251 AllExtensionsSilenced = 0;
252 IgnoreAllWarnings = false;
253 WarningsAsErrors = false;
254 ErrorsAsFatal = false;
255 SuppressSystemWarnings = false;
256 SuppressAllDiagnostics = false;
257 ShowOverloads = Ovl_All;
258 ExtBehavior = Ext_Ignore;
261 TemplateBacktraceLimit = 0;
264 // Set all mappings to 'unset'.
265 DiagMappingsStack.clear();
266 DiagMappingsStack.push_back(DiagMappings());
271 Diagnostic::~Diagnostic() {
272 delete CustomDiagInfo;
276 void Diagnostic::pushMappings() {
277 // Avoids undefined behavior when the stack has to resize.
278 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
279 DiagMappingsStack.push_back(DiagMappingsStack.back());
282 bool Diagnostic::popMappings() {
283 if (DiagMappingsStack.size() == 1)
286 DiagMappingsStack.pop_back();
290 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
291 /// and level. If this is the first request for this diagnosic, it is
292 /// registered and created, otherwise the existing ID is returned.
293 unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
294 if (CustomDiagInfo == 0)
295 CustomDiagInfo = new diag::CustomDiagInfo();
296 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
300 /// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
301 /// level of the specified diagnostic ID is a Warning or Extension.
302 /// This only works on builtin diagnostics, not custom ones, and is not legal to
304 bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
305 return DiagID < diag::DIAG_UPPER_LIMIT &&
306 getBuiltinDiagClass(DiagID) != CLASS_ERROR;
309 /// \brief Determine whether the given built-in diagnostic ID is a
311 bool Diagnostic::isBuiltinNote(unsigned DiagID) {
312 return DiagID < diag::DIAG_UPPER_LIMIT &&
313 getBuiltinDiagClass(DiagID) == CLASS_NOTE;
316 /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
317 /// ID is for an extension of some sort. This also returns EnabledByDefault,
318 /// which is set to indicate whether the diagnostic is ignored by default (in
319 /// which case -pedantic enables it) or treated as a warning/error by default.
321 bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID,
322 bool &EnabledByDefault) {
323 if (DiagID >= diag::DIAG_UPPER_LIMIT ||
324 getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
327 EnabledByDefault = GetDefaultDiagMapping(DiagID) != diag::MAP_IGNORE;
331 void Diagnostic::Reset() {
332 ErrorOccurred = false;
333 FatalErrorOccurred = false;
337 NumErrorsSuppressed = 0;
339 LastDiagLevel = Ignored;
343 /// getDescription - Given a diagnostic ID, return a description of the
345 const char *Diagnostic::getDescription(unsigned DiagID) const {
346 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
347 return Info->Description;
348 return CustomDiagInfo->getDescription(DiagID);
351 void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
352 llvm::StringRef Arg2) {
356 DelayedDiagID = DiagID;
357 DelayedDiagArg1 = Arg1.str();
358 DelayedDiagArg2 = Arg2.str();
361 void Diagnostic::ReportDelayed() {
362 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
364 DelayedDiagArg1.clear();
365 DelayedDiagArg2.clear();
368 /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
369 /// object, classify the specified diagnostic ID into a Level, consumable by
370 /// the DiagnosticClient.
371 Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
372 // Handle custom diagnostics, which cannot be mapped.
373 if (DiagID >= diag::DIAG_UPPER_LIMIT)
374 return CustomDiagInfo->getLevel(DiagID);
376 unsigned DiagClass = getBuiltinDiagClass(DiagID);
377 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
378 return getDiagnosticLevel(DiagID, DiagClass);
381 /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
382 /// object, classify the specified diagnostic ID into a Level, consumable by
383 /// the DiagnosticClient.
385 Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
386 // Specific non-error diagnostics may be mapped to various levels from ignored
387 // to error. Errors can only be mapped to fatal.
388 Diagnostic::Level Result = Diagnostic::Fatal;
390 // Get the mapping information, if unset, compute it lazily.
391 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
392 if (MappingInfo == 0) {
393 MappingInfo = GetDefaultDiagMapping(DiagID);
394 setDiagnosticMappingInternal(DiagID, MappingInfo, false);
397 switch (MappingInfo & 7) {
398 default: assert(0 && "Unknown mapping!");
399 case diag::MAP_IGNORE:
400 // Ignore this, unless this is an extension diagnostic and we're mapping
401 // them onto warnings or errors.
402 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension
403 ExtBehavior == Ext_Ignore || // Extensions ignored anyway
404 (MappingInfo & 8) != 0) // User explicitly mapped it.
405 return Diagnostic::Ignored;
406 Result = Diagnostic::Warning;
407 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
408 if (Result == Diagnostic::Error && ErrorsAsFatal)
409 Result = Diagnostic::Fatal;
411 case diag::MAP_ERROR:
412 Result = Diagnostic::Error;
414 Result = Diagnostic::Fatal;
416 case diag::MAP_FATAL:
417 Result = Diagnostic::Fatal;
419 case diag::MAP_WARNING:
420 // If warnings are globally mapped to ignore or error, do it.
421 if (IgnoreAllWarnings)
422 return Diagnostic::Ignored;
424 Result = Diagnostic::Warning;
426 // If this is an extension diagnostic and we're in -pedantic-error mode, and
427 // if the user didn't explicitly map it, upgrade to an error.
428 if (ExtBehavior == Ext_Error &&
429 (MappingInfo & 8) == 0 &&
430 isBuiltinExtensionDiag(DiagID))
431 Result = Diagnostic::Error;
433 if (WarningsAsErrors)
434 Result = Diagnostic::Error;
435 if (Result == Diagnostic::Error && ErrorsAsFatal)
436 Result = Diagnostic::Fatal;
439 case diag::MAP_WARNING_NO_WERROR:
440 // Diagnostics specified with -Wno-error=foo should be set to warnings, but
441 // not be adjusted by -Werror or -pedantic-errors.
442 Result = Diagnostic::Warning;
444 // If warnings are globally mapped to ignore or error, do it.
445 if (IgnoreAllWarnings)
446 return Diagnostic::Ignored;
450 case diag::MAP_ERROR_NO_WFATAL:
451 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
452 // unaffected by -Wfatal-errors.
453 Result = Diagnostic::Error;
457 // Okay, we're about to return this as a "diagnostic to emit" one last check:
458 // if this is any sort of extension warning, and if we're in an __extension__
459 // block, silence it.
460 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
461 return Diagnostic::Ignored;
466 struct WarningOption {
468 const short *Members;
469 const short *SubGroups;
472 #define GET_DIAG_ARRAYS
473 #include "clang/Basic/DiagnosticGroups.inc"
474 #undef GET_DIAG_ARRAYS
476 // Second the table of options, sorted by name for fast binary lookup.
477 static const WarningOption OptionTable[] = {
478 #define GET_DIAG_TABLE
479 #include "clang/Basic/DiagnosticGroups.inc"
480 #undef GET_DIAG_TABLE
482 static const size_t OptionTableSize =
483 sizeof(OptionTable) / sizeof(OptionTable[0]);
485 static bool WarningOptionCompare(const WarningOption &LHS,
486 const WarningOption &RHS) {
487 return strcmp(LHS.Name, RHS.Name) < 0;
490 static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
492 // Option exists, poke all the members of its diagnostic set.
493 if (const short *Member = Group->Members) {
494 for (; *Member != -1; ++Member)
495 Diags.setDiagnosticMapping(*Member, Mapping);
498 // Enable/disable all subgroups along with this one.
499 if (const short *SubGroups = Group->SubGroups) {
500 for (; *SubGroups != (short)-1; ++SubGroups)
501 MapGroupMembers(&OptionTable[(short)*SubGroups], Mapping, Diags);
505 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
506 /// "unknown-pragmas" to have the specified mapping. This returns true and
507 /// ignores the request if "Group" was unknown, false otherwise.
508 bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
511 WarningOption Key = { Group, 0, 0 };
512 const WarningOption *Found =
513 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
514 WarningOptionCompare);
515 if (Found == OptionTable + OptionTableSize ||
516 strcmp(Found->Name, Group) != 0)
517 return true; // Option not found.
519 MapGroupMembers(Found, Map, *this);
524 /// ProcessDiag - This is the method used to report a diagnostic that is
525 /// finally fully formed.
526 bool Diagnostic::ProcessDiag() {
527 DiagnosticInfo Info(this);
529 if (SuppressAllDiagnostics)
532 // Figure out the diagnostic level of this message.
533 Diagnostic::Level DiagLevel;
534 unsigned DiagID = Info.getID();
536 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
537 // in a system header.
538 bool ShouldEmitInSystemHeader;
540 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
541 // Handle custom diagnostics, which cannot be mapped.
542 DiagLevel = CustomDiagInfo->getLevel(DiagID);
544 // Custom diagnostics always are emitted in system headers.
545 ShouldEmitInSystemHeader = true;
547 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
548 // the diagnostic level was for the previous diagnostic so that it is
549 // filtered the same as the previous diagnostic.
550 unsigned DiagClass = getBuiltinDiagClass(DiagID);
551 if (DiagClass == CLASS_NOTE) {
552 DiagLevel = Diagnostic::Note;
553 ShouldEmitInSystemHeader = false; // extra consideration is needed
555 // If this is not an error and we are in a system header, we ignore it.
556 // Check the original Diag ID here, because we also want to ignore
557 // extensions and warnings in -Werror and -pedantic-errors modes, which
558 // *map* warnings/extensions to errors.
559 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
561 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
565 if (DiagLevel != Diagnostic::Note) {
566 // Record that a fatal error occurred only when we see a second
567 // non-note diagnostic. This allows notes to be attached to the
568 // fatal error, but suppresses any diagnostics that follow those
570 if (LastDiagLevel == Diagnostic::Fatal)
571 FatalErrorOccurred = true;
573 LastDiagLevel = DiagLevel;
576 // If a fatal error has already been emitted, silence all subsequent
578 if (FatalErrorOccurred) {
579 if (DiagLevel >= Diagnostic::Error && Client->IncludeInDiagnosticCounts()) {
581 ++NumErrorsSuppressed;
587 // If the client doesn't care about this message, don't issue it. If this is
588 // a note and the last real diagnostic was ignored, ignore it too.
589 if (DiagLevel == Diagnostic::Ignored ||
590 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
593 // If this diagnostic is in a system header and is not a clang error, suppress
595 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
596 Info.getLocation().isValid() &&
597 Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
598 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
599 LastDiagLevel = Diagnostic::Ignored;
603 if (DiagLevel >= Diagnostic::Error) {
604 if (Client->IncludeInDiagnosticCounts()) {
605 ErrorOccurred = true;
609 // If we've emitted a lot of errors, emit a fatal error after it to stop a
610 // flood of bogus errors.
611 if (ErrorLimit && NumErrors >= ErrorLimit &&
612 DiagLevel == Diagnostic::Error)
613 SetDelayedDiagnostic(diag::fatal_too_many_errors);
616 // Finally, report it.
617 Client->HandleDiagnostic(DiagLevel, Info);
618 if (Client->IncludeInDiagnosticCounts()) {
619 if (DiagLevel == Diagnostic::Warning)
628 bool DiagnosticBuilder::Emit() {
629 // If DiagObj is null, then its soul was stolen by the copy ctor
630 // or the user called Emit().
631 if (DiagObj == 0) return false;
633 // When emitting diagnostics, we set the final argument count into
634 // the Diagnostic object.
635 DiagObj->NumDiagArgs = NumArgs;
636 DiagObj->NumDiagRanges = NumRanges;
637 DiagObj->NumFixItHints = NumFixItHints;
639 // Process the diagnostic, sending the accumulated information to the
641 bool Emitted = DiagObj->ProcessDiag();
643 // Clear out the current diagnostic object.
644 unsigned DiagID = DiagObj->CurDiagID;
647 // If there was a delayed diagnostic, emit it now.
648 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
649 DiagObj->ReportDelayed();
651 // This diagnostic is dead.
658 DiagnosticClient::~DiagnosticClient() {}
661 /// ModifierIs - Return true if the specified modifier matches specified string.
662 template <std::size_t StrLen>
663 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
664 const char (&Str)[StrLen]) {
665 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
668 /// ScanForward - Scans forward, looking for the given character, skipping
669 /// nested clauses and escaped characters.
670 static const char *ScanFormat(const char *I, const char *E, char Target) {
673 for ( ; I != E; ++I) {
674 if (Depth == 0 && *I == Target) return I;
675 if (Depth != 0 && *I == '}') Depth--;
681 // Escaped characters get implicitly skipped here.
684 if (!isdigit(*I) && !ispunct(*I)) {
685 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
695 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
696 /// like this: %select{foo|bar|baz}2. This means that the integer argument
697 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
698 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
699 /// This is very useful for certain classes of variant diagnostics.
700 static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
701 const char *Argument, unsigned ArgumentLen,
702 llvm::SmallVectorImpl<char> &OutStr) {
703 const char *ArgumentEnd = Argument+ArgumentLen;
705 // Skip over 'ValNo' |'s.
707 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
708 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
709 " larger than the number of options in the diagnostic string!");
710 Argument = NextVal+1; // Skip this string.
714 // Get the end of the value. This is either the } or the |.
715 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
717 // Recursively format the result of the select clause into the output string.
718 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
721 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
722 /// letter 's' to the string if the value is not 1. This is used in cases like
723 /// this: "you idiot, you have %4 parameter%s4!".
724 static void HandleIntegerSModifier(unsigned ValNo,
725 llvm::SmallVectorImpl<char> &OutStr) {
727 OutStr.push_back('s');
730 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
731 /// prints the ordinal form of the given integer, with 1 corresponding
732 /// to the first ordinal. Currently this is hard-coded to use the
734 static void HandleOrdinalModifier(unsigned ValNo,
735 llvm::SmallVectorImpl<char> &OutStr) {
736 assert(ValNo != 0 && "ValNo must be strictly positive!");
738 llvm::raw_svector_ostream Out(OutStr);
740 // We could use text forms for the first N ordinals, but the numeric
741 // forms are actually nicer in diagnostics because they stand out.
744 // It is critically important that we do this perfectly for
745 // user-written sequences with over 100 elements.
746 switch (ValNo % 100) {
752 switch (ValNo % 10) {
753 case 1: Out << "st"; return;
754 case 2: Out << "nd"; return;
755 case 3: Out << "rd"; return;
756 default: Out << "th"; return;
762 /// PluralNumber - Parse an unsigned integer and advance Start.
763 static unsigned PluralNumber(const char *&Start, const char *End) {
764 // Programming 101: Parse a decimal number :-)
766 while (Start != End && *Start >= '0' && *Start <= '9') {
774 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
775 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
777 unsigned Ref = PluralNumber(Start, End);
782 unsigned Low = PluralNumber(Start, End);
783 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
785 unsigned High = PluralNumber(Start, End);
786 assert(*Start == ']' && "Bad plural expression syntax: expected )");
788 return Low <= Val && Val <= High;
791 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
792 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
802 unsigned Arg = PluralNumber(Start, End);
803 assert(*Start == '=' && "Bad plural expression syntax: expected =");
805 unsigned ValMod = ValNo % Arg;
806 if (TestPluralRange(ValMod, Start, End))
809 assert((C == '[' || (C >= '0' && C <= '9')) &&
810 "Bad plural expression syntax: unexpected character");
812 if (TestPluralRange(ValNo, Start, End))
816 // Scan for next or-expr part.
817 Start = std::find(Start, End, ',');
825 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
826 /// for complex plural forms, or in languages where all plurals are complex.
827 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
828 /// conditions that are tested in order, the form corresponding to the first
829 /// that applies being emitted. The empty condition is always true, making the
830 /// last form a default case.
831 /// Conditions are simple boolean expressions, where n is the number argument.
832 /// Here are the rules.
833 /// condition := expression | empty
834 /// empty := -> always true
835 /// expression := numeric [',' expression] -> logical or
836 /// numeric := range -> true if n in range
837 /// | '%' number '=' range -> true if n % number in range
839 /// | '[' number ',' number ']' -> ranges are inclusive both ends
841 /// Here are some examples from the GNU gettext manual written in this form:
845 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
847 /// {1:form0|2:form1|:form2}
849 /// {1:form0|0,%100=[1,19]:form1|:form2}
851 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
852 /// Russian (requires repeated form):
853 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
855 /// {1:form0|[2,4]:form1|:form2}
856 /// Polish (requires repeated form):
857 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
858 static void HandlePluralModifier(unsigned ValNo,
859 const char *Argument, unsigned ArgumentLen,
860 llvm::SmallVectorImpl<char> &OutStr) {
861 const char *ArgumentEnd = Argument + ArgumentLen;
863 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
864 const char *ExprEnd = Argument;
865 while (*ExprEnd != ':') {
866 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
869 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
870 Argument = ExprEnd + 1;
871 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
872 OutStr.append(Argument, ExprEnd);
875 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
880 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
881 /// formal arguments into the %0 slots. The result is appended onto the Str
883 void DiagnosticInfo::
884 FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
885 const char *DiagStr = getDiags()->getDescription(getID());
886 const char *DiagEnd = DiagStr+strlen(DiagStr);
888 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
891 void DiagnosticInfo::
892 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
893 llvm::SmallVectorImpl<char> &OutStr) const {
895 /// FormattedArgs - Keep track of all of the arguments formatted by
896 /// ConvertArgToString and pass them into subsequent calls to
897 /// ConvertArgToString, allowing the implementation to avoid redundancies in
899 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
901 while (DiagStr != DiagEnd) {
902 if (DiagStr[0] != '%') {
903 // Append non-%0 substrings to Str if we have one.
904 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
905 OutStr.append(DiagStr, StrEnd);
908 } else if (ispunct(DiagStr[1])) {
909 OutStr.push_back(DiagStr[1]); // %% -> %.
917 // This must be a placeholder for a diagnostic argument. The format for a
918 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
919 // The digit is a number from 0-9 indicating which argument this comes from.
920 // The modifier is a string of digits from the set [-a-z]+, arguments is a
921 // brace enclosed string.
922 const char *Modifier = 0, *Argument = 0;
923 unsigned ModifierLen = 0, ArgumentLen = 0;
925 // Check to see if we have a modifier. If so eat it.
926 if (!isdigit(DiagStr[0])) {
928 while (DiagStr[0] == '-' ||
929 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
931 ModifierLen = DiagStr-Modifier;
933 // If we have an argument, get it next.
934 if (DiagStr[0] == '{') {
935 ++DiagStr; // Skip {.
938 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
939 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
940 ArgumentLen = DiagStr-Argument;
941 ++DiagStr; // Skip }.
945 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
946 unsigned ArgNo = *DiagStr++ - '0';
948 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
952 case Diagnostic::ak_std_string: {
953 const std::string &S = getArgStdStr(ArgNo);
954 assert(ModifierLen == 0 && "No modifiers for strings yet");
955 OutStr.append(S.begin(), S.end());
958 case Diagnostic::ak_c_string: {
959 const char *S = getArgCStr(ArgNo);
960 assert(ModifierLen == 0 && "No modifiers for strings yet");
962 // Don't crash if get passed a null pointer by accident.
966 OutStr.append(S, S + strlen(S));
969 // ---- INTEGERS ----
970 case Diagnostic::ak_sint: {
971 int Val = getArgSInt(ArgNo);
973 if (ModifierIs(Modifier, ModifierLen, "select")) {
974 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
975 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
976 HandleIntegerSModifier(Val, OutStr);
977 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
978 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
979 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
980 HandleOrdinalModifier((unsigned)Val, OutStr);
982 assert(ModifierLen == 0 && "Unknown integer modifier");
983 llvm::raw_svector_ostream(OutStr) << Val;
987 case Diagnostic::ak_uint: {
988 unsigned Val = getArgUInt(ArgNo);
990 if (ModifierIs(Modifier, ModifierLen, "select")) {
991 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
992 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
993 HandleIntegerSModifier(Val, OutStr);
994 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
995 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
996 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
997 HandleOrdinalModifier(Val, OutStr);
999 assert(ModifierLen == 0 && "Unknown integer modifier");
1000 llvm::raw_svector_ostream(OutStr) << Val;
1004 // ---- NAMES and TYPES ----
1005 case Diagnostic::ak_identifierinfo: {
1006 const IdentifierInfo *II = getArgIdentifier(ArgNo);
1007 assert(ModifierLen == 0 && "No modifiers for strings yet");
1009 // Don't crash if get passed a null pointer by accident.
1011 const char *S = "(null)";
1012 OutStr.append(S, S + strlen(S));
1016 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
1019 case Diagnostic::ak_qualtype:
1020 case Diagnostic::ak_declarationname:
1021 case Diagnostic::ak_nameddecl:
1022 case Diagnostic::ak_nestednamespec:
1023 case Diagnostic::ak_declcontext:
1024 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
1025 Modifier, ModifierLen,
1026 Argument, ArgumentLen,
1027 FormattedArgs.data(), FormattedArgs.size(),
1032 // Remember this argument info for subsequent formatting operations. Turn
1033 // std::strings into a null terminated string to make it be the same case as
1034 // all the other ones.
1035 if (Kind != Diagnostic::ak_std_string)
1036 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1038 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1039 (intptr_t)getArgStdStr(ArgNo).c_str()));
1044 StoredDiagnostic::StoredDiagnostic() { }
1046 StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1047 llvm::StringRef Message)
1048 : Level(Level), Loc(), Message(Message) { }
1050 StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1051 const DiagnosticInfo &Info)
1052 : Level(Level), Loc(Info.getLocation()) {
1053 llvm::SmallString<64> Message;
1054 Info.FormatDiagnostic(Message);
1055 this->Message.assign(Message.begin(), Message.end());
1057 Ranges.reserve(Info.getNumRanges());
1058 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
1059 Ranges.push_back(Info.getRange(I));
1061 FixIts.reserve(Info.getNumFixItHints());
1062 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
1063 FixIts.push_back(Info.getFixItHint(I));
1066 StoredDiagnostic::~StoredDiagnostic() { }
1068 static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1069 OS.write((const char *)&Value, sizeof(unsigned));
1072 static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1073 WriteUnsigned(OS, String.size());
1074 OS.write(String.data(), String.size());
1077 static void WriteSourceLocation(llvm::raw_ostream &OS,
1079 SourceLocation Location) {
1080 if (!SM || Location.isInvalid()) {
1081 // If we don't have a source manager or this location is invalid,
1082 // just write an invalid location.
1083 WriteUnsigned(OS, 0);
1084 WriteUnsigned(OS, 0);
1085 WriteUnsigned(OS, 0);
1089 Location = SM->getInstantiationLoc(Location);
1090 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
1092 const FileEntry *FE = SM->getFileEntryForID(Decomposed.first);
1094 WriteString(OS, FE->getName());
1096 // Fallback to using the buffer name when there is no entry.
1097 WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier());
1100 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1101 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1104 void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
1105 SourceManager *SM = 0;
1106 if (getLocation().isValid())
1107 SM = &const_cast<SourceManager &>(getLocation().getManager());
1109 // Write a short header to help identify diagnostics.
1110 OS << (char)0x06 << (char)0x07;
1112 // Write the diagnostic level and location.
1113 WriteUnsigned(OS, (unsigned)Level);
1114 WriteSourceLocation(OS, SM, getLocation());
1116 // Write the diagnostic message.
1117 llvm::SmallString<64> Message;
1118 WriteString(OS, getMessage());
1120 // Count the number of ranges that don't point into macros, since
1121 // only simple file ranges serialize well.
1122 unsigned NumNonMacroRanges = 0;
1123 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1124 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1127 ++NumNonMacroRanges;
1130 // Write the ranges.
1131 WriteUnsigned(OS, NumNonMacroRanges);
1132 if (NumNonMacroRanges) {
1133 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1134 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1137 WriteSourceLocation(OS, SM, R->getBegin());
1138 WriteSourceLocation(OS, SM, R->getEnd());
1139 WriteUnsigned(OS, R->isTokenRange());
1143 // Determine if all of the fix-its involve rewrites with simple file
1144 // locations (not in macro instantiations). If so, we can write
1145 // fix-it information.
1146 unsigned NumFixIts = 0;
1147 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1148 if (F->RemoveRange.isValid() &&
1149 (F->RemoveRange.getBegin().isMacroID() ||
1150 F->RemoveRange.getEnd().isMacroID())) {
1158 // Write the fix-its.
1159 WriteUnsigned(OS, NumFixIts);
1160 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1161 WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1162 WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
1163 WriteUnsigned(OS, F->RemoveRange.isTokenRange());
1164 WriteString(OS, F->CodeToInsert);
1168 static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1170 if (Memory + sizeof(unsigned) > MemoryEnd)
1173 memmove(&Value, Memory, sizeof(unsigned));
1174 Memory += sizeof(unsigned);
1178 static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1179 const char *&Memory, const char *MemoryEnd,
1180 SourceLocation &Location) {
1181 // Read the filename.
1182 unsigned FileNameLen = 0;
1183 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1184 Memory + FileNameLen > MemoryEnd)
1187 llvm::StringRef FileName(Memory, FileNameLen);
1188 Memory += FileNameLen;
1190 // Read the line, column.
1191 unsigned Line = 0, Column = 0;
1192 if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1193 ReadUnsigned(Memory, MemoryEnd, Column))
1196 if (FileName.empty()) {
1197 Location = SourceLocation();
1201 const FileEntry *File = FM.getFile(FileName);
1205 // Make sure that this file has an entry in the source manager.
1206 if (!SM.hasFileInfo(File))
1207 SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1209 Location = SM.getLocation(File, Line, Column);
1214 StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1215 const char *&Memory, const char *MemoryEnd) {
1217 if (Memory == MemoryEnd)
1218 return StoredDiagnostic();
1220 if (*Memory != 0x06) {
1226 if (Memory == MemoryEnd)
1227 return StoredDiagnostic();
1229 if (*Memory != 0x07) {
1234 // We found the header. We're done.
1239 // Read the severity level.
1241 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1242 return StoredDiagnostic();
1244 // Read the source location.
1245 SourceLocation Location;
1246 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1247 return StoredDiagnostic();
1249 // Read the diagnostic text.
1250 if (Memory == MemoryEnd)
1251 return StoredDiagnostic();
1253 unsigned MessageLen = 0;
1254 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1255 Memory + MessageLen > MemoryEnd)
1256 return StoredDiagnostic();
1258 llvm::StringRef Message(Memory, MessageLen);
1259 Memory += MessageLen;
1262 // At this point, we have enough information to form a diagnostic. Do so.
1263 StoredDiagnostic Diag;
1264 Diag.Level = (Diagnostic::Level)Level;
1265 Diag.Loc = FullSourceLoc(Location, SM);
1266 Diag.Message = Message;
1267 if (Memory == MemoryEnd)
1270 // Read the source ranges.
1271 unsigned NumSourceRanges = 0;
1272 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1274 for (unsigned I = 0; I != NumSourceRanges; ++I) {
1275 SourceLocation Begin, End;
1276 unsigned IsTokenRange;
1277 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
1278 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End) ||
1279 ReadUnsigned(Memory, MemoryEnd, IsTokenRange))
1282 Diag.Ranges.push_back(CharSourceRange(SourceRange(Begin, End),
1286 // Read the fix-it hints.
1287 unsigned NumFixIts = 0;
1288 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1290 for (unsigned I = 0; I != NumFixIts; ++I) {
1291 SourceLocation RemoveBegin, RemoveEnd;
1292 unsigned InsertLen = 0, RemoveIsTokenRange;
1293 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1294 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
1295 ReadUnsigned(Memory, MemoryEnd, RemoveIsTokenRange) ||
1296 ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1297 Memory + InsertLen > MemoryEnd) {
1298 Diag.FixIts.clear();
1303 Hint.RemoveRange = CharSourceRange(SourceRange(RemoveBegin, RemoveEnd),
1304 RemoveIsTokenRange);
1305 Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1306 Memory += InsertLen;
1307 Diag.FixIts.push_back(Hint);
1313 /// IncludeInDiagnosticCounts - This method (whose default implementation
1314 /// returns true) indicates whether the diagnostics handled by this
1315 /// DiagnosticClient should be included in the number of diagnostics
1316 /// reported by Diagnostic.
1317 bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
1319 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1320 for (unsigned I = 0; I != NumCached; ++I)
1321 FreeList[I] = Cached + I;
1322 NumFreeListEntries = NumCached;
1325 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1326 assert(NumFreeListEntries == NumCached && "A partial is on the lamb");