blob: f7ec873e4c156e06d1b20936563faf60e32fe889 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/Diagnostic.h"
Chris Lattner27ceb9d2009-04-15 07:01:18 +000015
16#include "clang/Lex/LexDiagnostic.h"
17#include "clang/Parse/ParseDiagnostic.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/Sema/SemaDiagnostic.h"
20#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Analysis/AnalysisDiagnostic.h"
22#include "clang/Driver/DriverDiagnostic.h"
23
Douglas Gregord93256e2010-01-28 06:00:51 +000024#include "clang/Basic/FileManager.h"
Chris Lattner43b628c2008-11-19 07:32:16 +000025#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/SourceLocation.h"
Douglas Gregord93256e2010-01-28 06:00:51 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000028#include "llvm/ADT/SmallVector.h"
Chris Lattner30bc9652008-11-19 07:22:31 +000029#include "llvm/ADT/StringExtras.h"
Daniel Dunbar23e47c62009-10-17 18:12:14 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner182745a2007-12-02 01:09:57 +000031#include <vector>
32#include <map>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000033#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattner182745a2007-12-02 01:09:57 +000036//===----------------------------------------------------------------------===//
37// Builtin Diagnostic information
38//===----------------------------------------------------------------------===//
39
Chris Lattner121f60c2009-04-16 06:07:15 +000040// Diagnostic classes.
41enum {
42 CLASS_NOTE = 0x01,
43 CLASS_WARNING = 0x02,
44 CLASS_EXTENSION = 0x03,
45 CLASS_ERROR = 0x04
46};
Chris Lattner27ceb9d2009-04-15 07:01:18 +000047
Chris Lattner33dd2822009-04-16 06:00:24 +000048struct StaticDiagInfoRec {
Chris Lattner121f60c2009-04-16 06:07:15 +000049 unsigned short DiagID;
50 unsigned Mapping : 3;
51 unsigned Class : 3;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000052 bool SFINAE : 1;
Chris Lattner121f60c2009-04-16 06:07:15 +000053 const char *Description;
Chris Lattner33dd2822009-04-16 06:00:24 +000054 const char *OptionGroup;
Mike Stump1eb44332009-09-09 15:08:12 +000055
Chris Lattner87d854e2009-04-16 06:13:46 +000056 bool operator<(const StaticDiagInfoRec &RHS) const {
57 return DiagID < RHS.DiagID;
58 }
59 bool operator>(const StaticDiagInfoRec &RHS) const {
60 return DiagID > RHS.DiagID;
61 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +000062};
63
Chris Lattner33dd2822009-04-16 06:00:24 +000064static const StaticDiagInfoRec StaticDiagInfo[] = {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000065#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) \
66 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, DESC, GROUP },
Chris Lattner27ceb9d2009-04-15 07:01:18 +000067#include "clang/Basic/DiagnosticCommonKinds.inc"
68#include "clang/Basic/DiagnosticDriverKinds.inc"
69#include "clang/Basic/DiagnosticFrontendKinds.inc"
70#include "clang/Basic/DiagnosticLexKinds.inc"
71#include "clang/Basic/DiagnosticParseKinds.inc"
72#include "clang/Basic/DiagnosticASTKinds.inc"
73#include "clang/Basic/DiagnosticSemaKinds.inc"
74#include "clang/Basic/DiagnosticAnalysisKinds.inc"
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000075 { 0, 0, 0, 0, 0, 0}
Chris Lattner27ceb9d2009-04-15 07:01:18 +000076};
Chris Lattner8a941e02009-04-15 16:56:26 +000077#undef DIAG
Chris Lattner27ceb9d2009-04-15 07:01:18 +000078
Chris Lattner87d854e2009-04-16 06:13:46 +000079/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
80/// or null if the ID is invalid.
Chris Lattner33dd2822009-04-16 06:00:24 +000081static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
Chris Lattner87d854e2009-04-16 06:13:46 +000082 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
83
84 // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
85#ifndef NDEBUG
86 static bool IsFirst = true;
87 if (IsFirst) {
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000088 for (unsigned i = 1; i != NumDiagEntries; ++i) {
89 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
90 "Diag ID conflict, the enums at the start of clang::diag (in "
91 "Diagnostic.h) probably need to be increased");
92
Chris Lattner87d854e2009-04-16 06:13:46 +000093 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
94 "Improperly sorted diag info");
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000095 }
Chris Lattner87d854e2009-04-16 06:13:46 +000096 IsFirst = false;
97 }
98#endif
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner87d854e2009-04-16 06:13:46 +0000100 // Search the diagnostic table with a binary search.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000101 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 };
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner87d854e2009-04-16 06:13:46 +0000103 const StaticDiagInfoRec *Found =
104 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
105 if (Found == StaticDiagInfo + NumDiagEntries ||
106 Found->DiagID != DiagID)
107 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner87d854e2009-04-16 06:13:46 +0000109 return Found;
Chris Lattner33dd2822009-04-16 06:00:24 +0000110}
111
112static unsigned GetDefaultDiagMapping(unsigned DiagID) {
113 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Chris Lattner121f60c2009-04-16 06:07:15 +0000114 return Info->Mapping;
Chris Lattner691f1ae2009-04-16 04:12:40 +0000115 return diag::MAP_FATAL;
116}
117
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000118/// getWarningOptionForDiag - Return the lowest-level warning option that
119/// enables the specified diagnostic. If there is no -Wfoo flag that controls
120/// the diagnostic, this returns null.
121const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
Chris Lattner33dd2822009-04-16 06:00:24 +0000122 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
123 return Info->OptionGroup;
124 return 0;
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000125}
126
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000127bool Diagnostic::isBuiltinSFINAEDiag(unsigned DiagID) {
128 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Douglas Gregor8439fac2009-06-15 16:52:15 +0000129 return Info->SFINAE && Info->Class == CLASS_ERROR;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000130 return false;
131}
132
Reid Spencer5f016e22007-07-11 17:01:13 +0000133/// getDiagClass - Return the class field of the diagnostic.
134///
Chris Lattner07506182007-11-30 22:53:43 +0000135static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner121f60c2009-04-16 06:07:15 +0000136 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
137 return Info->Class;
138 return ~0U;
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
Chris Lattner182745a2007-12-02 01:09:57 +0000141//===----------------------------------------------------------------------===//
142// Custom Diagnostic information
143//===----------------------------------------------------------------------===//
144
145namespace clang {
146 namespace diag {
147 class CustomDiagInfo {
148 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
149 std::vector<DiagDesc> DiagInfo;
150 std::map<DiagDesc, unsigned> DiagIDs;
151 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Chris Lattner182745a2007-12-02 01:09:57 +0000153 /// getDescription - Return the description of the specified custom
154 /// diagnostic.
155 const char *getDescription(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000156 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000157 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000158 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner182745a2007-12-02 01:09:57 +0000159 }
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner182745a2007-12-02 01:09:57 +0000161 /// getLevel - Return the level of the specified custom diagnostic.
162 Diagnostic::Level getLevel(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000163 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000164 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000165 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner182745a2007-12-02 01:09:57 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000168 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000169 Diagnostic &Diags) {
Chris Lattner182745a2007-12-02 01:09:57 +0000170 DiagDesc D(L, Message);
171 // Check to see if it already exists.
172 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
173 if (I != DiagIDs.end() && I->first == D)
174 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattner182745a2007-12-02 01:09:57 +0000176 // If not, assign a new ID.
Chris Lattner88eccaf2009-01-29 06:55:46 +0000177 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner182745a2007-12-02 01:09:57 +0000178 DiagIDs.insert(std::make_pair(D, ID));
179 DiagInfo.push_back(D);
180 return ID;
181 }
182 };
Mike Stump1eb44332009-09-09 15:08:12 +0000183
184 } // end diag namespace
185} // end clang namespace
Chris Lattner182745a2007-12-02 01:09:57 +0000186
187
188//===----------------------------------------------------------------------===//
189// Common Diagnostic implementation
190//===----------------------------------------------------------------------===//
191
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000192static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
193 const char *Modifier, unsigned ML,
194 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000195 const Diagnostic::ArgumentValue *PrevArgs,
196 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +0000197 llvm::SmallVectorImpl<char> &Output,
198 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000199 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +0000200 Output.append(Str, Str+strlen(Str));
201}
202
203
Ted Kremenekb4398aa2008-08-07 17:49:57 +0000204Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000205 AllExtensionsSilenced = 0;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000206 IgnoreAllWarnings = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 WarningsAsErrors = false;
Chris Lattnere663c722009-12-22 23:12:53 +0000208 ErrorsAsFatal = false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000209 SuppressSystemWarnings = false;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000210 SuppressAllDiagnostics = false;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000211 ExtBehavior = Ext_Ignore;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 ErrorOccurred = false;
Chris Lattner15221422009-02-06 04:16:02 +0000214 FatalErrorOccurred = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 NumDiagnostics = 0;
Steve Naroffe0c4d892009-12-05 02:14:08 +0000216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 NumErrors = 0;
Chris Lattner182745a2007-12-02 01:09:57 +0000218 CustomDiagInfo = 0;
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000219 CurDiagID = ~0U;
Douglas Gregor525c4b02009-03-19 18:55:06 +0000220 LastDiagLevel = Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000222 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +0000223 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner691f1ae2009-04-16 04:12:40 +0000225 // Set all mappings to 'unset'.
Chris Lattner04ae2df2009-07-12 21:18:45 +0000226 DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
227 DiagMappingsStack.push_back(BlankDiags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000228}
229
Chris Lattner182745a2007-12-02 01:09:57 +0000230Diagnostic::~Diagnostic() {
231 delete CustomDiagInfo;
232}
233
Chris Lattner04ae2df2009-07-12 21:18:45 +0000234
235void Diagnostic::pushMappings() {
John Thompsonca2c3e22009-10-23 02:21:17 +0000236 // Avoids undefined behavior when the stack has to resize.
237 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000238 DiagMappingsStack.push_back(DiagMappingsStack.back());
239}
240
241bool Diagnostic::popMappings() {
242 if (DiagMappingsStack.size() == 1)
243 return false;
244
245 DiagMappingsStack.pop_back();
246 return true;
247}
248
Chris Lattner182745a2007-12-02 01:09:57 +0000249/// getCustomDiagID - Return an ID for a diagnostic with the specified message
250/// and level. If this is the first request for this diagnosic, it is
251/// registered and created, otherwise the existing ID is returned.
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000252unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
Mike Stump1eb44332009-09-09 15:08:12 +0000253 if (CustomDiagInfo == 0)
Chris Lattner182745a2007-12-02 01:09:57 +0000254 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000255 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner182745a2007-12-02 01:09:57 +0000256}
257
258
Chris Lattnerf5d23282009-02-17 06:49:55 +0000259/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
260/// level of the specified diagnostic ID is a Warning or Extension.
261/// This only works on builtin diagnostics, not custom ones, and is not legal to
262/// call on NOTEs.
263bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000264 return DiagID < diag::DIAG_UPPER_LIMIT &&
265 getBuiltinDiagClass(DiagID) != CLASS_ERROR;
Reid Spencer5f016e22007-07-11 17:01:13 +0000266}
267
Douglas Gregoree1828a2009-03-10 18:03:33 +0000268/// \brief Determine whether the given built-in diagnostic ID is a
269/// Note.
270bool Diagnostic::isBuiltinNote(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000271 return DiagID < diag::DIAG_UPPER_LIMIT &&
272 getBuiltinDiagClass(DiagID) == CLASS_NOTE;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000273}
274
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000275/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
276/// ID is for an extension of some sort.
277///
278bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000279 return DiagID < diag::DIAG_UPPER_LIMIT &&
280 getBuiltinDiagClass(DiagID) == CLASS_EXTENSION;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000281}
282
Reid Spencer5f016e22007-07-11 17:01:13 +0000283
284/// getDescription - Given a diagnostic ID, return a description of the
285/// issue.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000286const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattner121f60c2009-04-16 06:07:15 +0000287 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
288 return Info->Description;
Chris Lattner20c6b3b2009-01-27 18:30:58 +0000289 return CustomDiagInfo->getDescription(DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000290}
291
292/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
293/// object, classify the specified diagnostic ID into a Level, consumable by
294/// the DiagnosticClient.
295Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner182745a2007-12-02 01:09:57 +0000296 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000297 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner182745a2007-12-02 01:09:57 +0000298 return CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattner07506182007-11-30 22:53:43 +0000300 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000301 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
Chris Lattnerf5d23282009-02-17 06:49:55 +0000302 return getDiagnosticLevel(DiagID, DiagClass);
303}
304
305/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
306/// object, classify the specified diagnostic ID into a Level, consumable by
307/// the DiagnosticClient.
308Diagnostic::Level
309Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattnerf5d23282009-02-17 06:49:55 +0000311 // to error. Errors can only be mapped to fatal.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000312 Diagnostic::Level Result = Diagnostic::Fatal;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner691f1ae2009-04-16 04:12:40 +0000314 // Get the mapping information, if unset, compute it lazily.
315 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
316 if (MappingInfo == 0) {
317 MappingInfo = GetDefaultDiagMapping(DiagID);
318 setDiagnosticMappingInternal(DiagID, MappingInfo, false);
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner691f1ae2009-04-16 04:12:40 +0000321 switch (MappingInfo & 7) {
322 default: assert(0 && "Unknown mapping!");
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000323 case diag::MAP_IGNORE:
Chris Lattnerb54b2762009-04-16 05:04:32 +0000324 // Ignore this, unless this is an extension diagnostic and we're mapping
325 // them onto warnings or errors.
326 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension
327 ExtBehavior == Ext_Ignore || // Extensions ignored anyway
328 (MappingInfo & 8) != 0) // User explicitly mapped it.
329 return Diagnostic::Ignored;
330 Result = Diagnostic::Warning;
331 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000332 if (Result == Diagnostic::Error && ErrorsAsFatal)
333 Result = Diagnostic::Fatal;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000334 break;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000335 case diag::MAP_ERROR:
336 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000337 if (ErrorsAsFatal)
338 Result = Diagnostic::Fatal;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000339 break;
340 case diag::MAP_FATAL:
341 Result = Diagnostic::Fatal;
342 break;
343 case diag::MAP_WARNING:
344 // If warnings are globally mapped to ignore or error, do it.
Chris Lattner5b4681c2008-05-29 15:36:45 +0000345 if (IgnoreAllWarnings)
346 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000348 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattnerb54b2762009-04-16 05:04:32 +0000350 // If this is an extension diagnostic and we're in -pedantic-error mode, and
351 // if the user didn't explicitly map it, upgrade to an error.
352 if (ExtBehavior == Ext_Error &&
353 (MappingInfo & 8) == 0 &&
354 isBuiltinExtensionDiag(DiagID))
355 Result = Diagnostic::Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000357 if (WarningsAsErrors)
358 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000359 if (Result == Diagnostic::Error && ErrorsAsFatal)
360 Result = Diagnostic::Fatal;
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000361 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000363 case diag::MAP_WARNING_NO_WERROR:
364 // Diagnostics specified with -Wno-error=foo should be set to warnings, but
365 // not be adjusted by -Werror or -pedantic-errors.
366 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000368 // If warnings are globally mapped to ignore or error, do it.
369 if (IgnoreAllWarnings)
370 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000372 break;
Chris Lattnere663c722009-12-22 23:12:53 +0000373
374 case diag::MAP_ERROR_NO_WFATAL:
375 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
376 // unaffected by -Wfatal-errors.
377 Result = Diagnostic::Error;
378 break;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000379 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000380
381 // Okay, we're about to return this as a "diagnostic to emit" one last check:
382 // if this is any sort of extension warning, and if we're in an __extension__
383 // block, silence it.
384 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
385 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000387 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Chris Lattner3bc172b2009-04-19 22:34:23 +0000390struct WarningOption {
391 const char *Name;
392 const short *Members;
393 const char *SubGroups;
394};
395
396#define GET_DIAG_ARRAYS
397#include "clang/Basic/DiagnosticGroups.inc"
398#undef GET_DIAG_ARRAYS
399
400// Second the table of options, sorted by name for fast binary lookup.
401static const WarningOption OptionTable[] = {
402#define GET_DIAG_TABLE
403#include "clang/Basic/DiagnosticGroups.inc"
404#undef GET_DIAG_TABLE
405};
406static const size_t OptionTableSize =
407sizeof(OptionTable) / sizeof(OptionTable[0]);
408
409static bool WarningOptionCompare(const WarningOption &LHS,
410 const WarningOption &RHS) {
411 return strcmp(LHS.Name, RHS.Name) < 0;
412}
413
414static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
415 Diagnostic &Diags) {
416 // Option exists, poke all the members of its diagnostic set.
417 if (const short *Member = Group->Members) {
418 for (; *Member != -1; ++Member)
419 Diags.setDiagnosticMapping(*Member, Mapping);
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner3bc172b2009-04-19 22:34:23 +0000422 // Enable/disable all subgroups along with this one.
423 if (const char *SubGroups = Group->SubGroups) {
424 for (; *SubGroups != (char)-1; ++SubGroups)
425 MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
426 }
427}
428
429/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
430/// "unknown-pragmas" to have the specified mapping. This returns true and
431/// ignores the request if "Group" was unknown, false otherwise.
432bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
433 diag::Mapping Map) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner3bc172b2009-04-19 22:34:23 +0000435 WarningOption Key = { Group, 0, 0 };
436 const WarningOption *Found =
437 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
438 WarningOptionCompare);
439 if (Found == OptionTable + OptionTableSize ||
440 strcmp(Found->Name, Group) != 0)
441 return true; // Option not found.
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattner3bc172b2009-04-19 22:34:23 +0000443 MapGroupMembers(Found, Map, *this);
444 return false;
445}
446
447
Chris Lattner0a14eee2008-11-18 07:04:44 +0000448/// ProcessDiag - This is the method used to report a diagnostic that is
449/// finally fully formed.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000450bool Diagnostic::ProcessDiag() {
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000451 DiagnosticInfo Info(this);
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Douglas Gregor81b747b2009-09-17 21:32:03 +0000453 if (SuppressAllDiagnostics)
454 return false;
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // Figure out the diagnostic level of this message.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000457 Diagnostic::Level DiagLevel;
458 unsigned DiagID = Info.getID();
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Chris Lattnerf5d23282009-02-17 06:49:55 +0000460 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
461 // in a system header.
462 bool ShouldEmitInSystemHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattnerf5d23282009-02-17 06:49:55 +0000464 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
465 // Handle custom diagnostics, which cannot be mapped.
466 DiagLevel = CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattnerf5d23282009-02-17 06:49:55 +0000468 // Custom diagnostics always are emitted in system headers.
469 ShouldEmitInSystemHeader = true;
470 } else {
471 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
472 // the diagnostic level was for the previous diagnostic so that it is
473 // filtered the same as the previous diagnostic.
474 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000475 if (DiagClass == CLASS_NOTE) {
Chris Lattnerf5d23282009-02-17 06:49:55 +0000476 DiagLevel = Diagnostic::Note;
477 ShouldEmitInSystemHeader = false; // extra consideration is needed
478 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000479 // If this is not an error and we are in a system header, we ignore it.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000480 // Check the original Diag ID here, because we also want to ignore
481 // extensions and warnings in -Werror and -pedantic-errors modes, which
482 // *map* warnings/extensions to errors.
Chris Lattner8a941e02009-04-15 16:56:26 +0000483 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnerf5d23282009-02-17 06:49:55 +0000485 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
486 }
487 }
488
Douglas Gregor525c4b02009-03-19 18:55:06 +0000489 if (DiagLevel != Diagnostic::Note) {
490 // Record that a fatal error occurred only when we see a second
491 // non-note diagnostic. This allows notes to be attached to the
492 // fatal error, but suppresses any diagnostics that follow those
493 // notes.
494 if (LastDiagLevel == Diagnostic::Fatal)
495 FatalErrorOccurred = true;
496
Chris Lattnerf5d23282009-02-17 06:49:55 +0000497 LastDiagLevel = DiagLevel;
Mike Stump1eb44332009-09-09 15:08:12 +0000498 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000499
500 // If a fatal error has already been emitted, silence all subsequent
501 // diagnostics.
502 if (FatalErrorOccurred)
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000503 return false;
Douglas Gregor525c4b02009-03-19 18:55:06 +0000504
Chris Lattnerf5d23282009-02-17 06:49:55 +0000505 // If the client doesn't care about this message, don't issue it. If this is
506 // a note and the last real diagnostic was ignored, ignore it too.
507 if (DiagLevel == Diagnostic::Ignored ||
508 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000509 return false;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000510
Chris Lattnerf5d23282009-02-17 06:49:55 +0000511 // If this diagnostic is in a system header and is not a clang error, suppress
512 // it.
513 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner0a14eee2008-11-18 07:04:44 +0000514 Info.getLocation().isValid() &&
John McCall779cf422010-02-11 10:04:29 +0000515 Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
Chris Lattner336f26b2009-02-17 06:52:20 +0000516 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
517 LastDiagLevel = Diagnostic::Ignored;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000518 return false;
Chris Lattner336f26b2009-02-17 06:52:20 +0000519 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000520
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 if (DiagLevel >= Diagnostic::Error) {
522 ErrorOccurred = true;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000523 ++NumErrors;
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 // Finally, report it.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000527 Client->HandleDiagnostic(DiagLevel, Info);
Ted Kremenekcabe6682009-01-23 20:28:53 +0000528 if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000529
Douglas Gregoree1828a2009-03-10 18:03:33 +0000530 CurDiagID = ~0U;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000531
532 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000533}
534
Nico Weber7bfaaae2008-08-10 19:59:06 +0000535
Reid Spencer5f016e22007-07-11 17:01:13 +0000536DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000537
Chris Lattnerf4c83962008-11-19 06:51:40 +0000538
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000539/// ModifierIs - Return true if the specified modifier matches specified string.
540template <std::size_t StrLen>
541static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
542 const char (&Str)[StrLen]) {
543 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
544}
545
John McCall909c1822010-01-14 20:11:39 +0000546/// ScanForward - Scans forward, looking for the given character, skipping
547/// nested clauses and escaped characters.
548static const char *ScanFormat(const char *I, const char *E, char Target) {
549 unsigned Depth = 0;
550
551 for ( ; I != E; ++I) {
552 if (Depth == 0 && *I == Target) return I;
553 if (Depth != 0 && *I == '}') Depth--;
554
555 if (*I == '%') {
556 I++;
557 if (I == E) break;
558
559 // Escaped characters get implicitly skipped here.
560
561 // Format specifier.
562 if (!isdigit(*I) && !ispunct(*I)) {
563 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
564 if (I == E) break;
565 if (*I == '{')
566 Depth++;
567 }
568 }
569 }
570 return E;
571}
572
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000573/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
574/// like this: %select{foo|bar|baz}2. This means that the integer argument
575/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
576/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
577/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000578static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000579 const char *Argument, unsigned ArgumentLen,
580 llvm::SmallVectorImpl<char> &OutStr) {
581 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000583 // Skip over 'ValNo' |'s.
584 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000585 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000586 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
587 " larger than the number of options in the diagnostic string!");
588 Argument = NextVal+1; // Skip this string.
589 --ValNo;
590 }
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000592 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000593 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000594
595 // Recursively format the result of the select clause into the output string.
596 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000597}
598
599/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
600/// letter 's' to the string if the value is not 1. This is used in cases like
601/// this: "you idiot, you have %4 parameter%s4!".
602static void HandleIntegerSModifier(unsigned ValNo,
603 llvm::SmallVectorImpl<char> &OutStr) {
604 if (ValNo != 1)
605 OutStr.push_back('s');
606}
607
John McCall3be16b72010-01-14 00:50:32 +0000608/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
609/// prints the ordinal form of the given integer, with 1 corresponding
610/// to the first ordinal. Currently this is hard-coded to use the
611/// English form.
612static void HandleOrdinalModifier(unsigned ValNo,
613 llvm::SmallVectorImpl<char> &OutStr) {
614 assert(ValNo != 0 && "ValNo must be strictly positive!");
615
616 llvm::raw_svector_ostream Out(OutStr);
617
618 // We could use text forms for the first N ordinals, but the numeric
619 // forms are actually nicer in diagnostics because they stand out.
620 Out << ValNo;
621
622 // It is critically important that we do this perfectly for
623 // user-written sequences with over 100 elements.
624 switch (ValNo % 100) {
625 case 11:
626 case 12:
627 case 13:
628 Out << "th"; return;
629 default:
630 switch (ValNo % 10) {
631 case 1: Out << "st"; return;
632 case 2: Out << "nd"; return;
633 case 3: Out << "rd"; return;
634 default: Out << "th"; return;
635 }
636 }
637}
638
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000639
Sebastian Redle4c452c2008-11-22 13:44:36 +0000640/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000641static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000642 // Programming 101: Parse a decimal number :-)
643 unsigned Val = 0;
644 while (Start != End && *Start >= '0' && *Start <= '9') {
645 Val *= 10;
646 Val += *Start - '0';
647 ++Start;
648 }
649 return Val;
650}
651
652/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000653static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000654 if (*Start != '[') {
655 unsigned Ref = PluralNumber(Start, End);
656 return Ref == Val;
657 }
658
659 ++Start;
660 unsigned Low = PluralNumber(Start, End);
661 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
662 ++Start;
663 unsigned High = PluralNumber(Start, End);
664 assert(*Start == ']' && "Bad plural expression syntax: expected )");
665 ++Start;
666 return Low <= Val && Val <= High;
667}
668
669/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000670static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000671 // Empty condition?
672 if (*Start == ':')
673 return true;
674
675 while (1) {
676 char C = *Start;
677 if (C == '%') {
678 // Modulo expression
679 ++Start;
680 unsigned Arg = PluralNumber(Start, End);
681 assert(*Start == '=' && "Bad plural expression syntax: expected =");
682 ++Start;
683 unsigned ValMod = ValNo % Arg;
684 if (TestPluralRange(ValMod, Start, End))
685 return true;
686 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000687 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000688 "Bad plural expression syntax: unexpected character");
689 // Range expression
690 if (TestPluralRange(ValNo, Start, End))
691 return true;
692 }
693
694 // Scan for next or-expr part.
695 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000696 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000697 break;
698 ++Start;
699 }
700 return false;
701}
702
703/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
704/// for complex plural forms, or in languages where all plurals are complex.
705/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
706/// conditions that are tested in order, the form corresponding to the first
707/// that applies being emitted. The empty condition is always true, making the
708/// last form a default case.
709/// Conditions are simple boolean expressions, where n is the number argument.
710/// Here are the rules.
711/// condition := expression | empty
712/// empty := -> always true
713/// expression := numeric [',' expression] -> logical or
714/// numeric := range -> true if n in range
715/// | '%' number '=' range -> true if n % number in range
716/// range := number
717/// | '[' number ',' number ']' -> ranges are inclusive both ends
718///
719/// Here are some examples from the GNU gettext manual written in this form:
720/// English:
721/// {1:form0|:form1}
722/// Latvian:
723/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
724/// Gaeilge:
725/// {1:form0|2:form1|:form2}
726/// Romanian:
727/// {1:form0|0,%100=[1,19]:form1|:form2}
728/// Lithuanian:
729/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
730/// Russian (requires repeated form):
731/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
732/// Slovak
733/// {1:form0|[2,4]:form1|:form2}
734/// Polish (requires repeated form):
735/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
736static void HandlePluralModifier(unsigned ValNo,
737 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000738 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000739 const char *ArgumentEnd = Argument + ArgumentLen;
740 while (1) {
741 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
742 const char *ExprEnd = Argument;
743 while (*ExprEnd != ':') {
744 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
745 ++ExprEnd;
746 }
747 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
748 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000749 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
Sebastian Redle4c452c2008-11-22 13:44:36 +0000750 OutStr.append(Argument, ExprEnd);
751 return;
752 }
John McCall909c1822010-01-14 20:11:39 +0000753 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000754 }
755}
756
757
Chris Lattnerf4c83962008-11-19 06:51:40 +0000758/// FormatDiagnostic - Format this diagnostic into a string, substituting the
759/// formal arguments into the %0 slots. The result is appended onto the Str
760/// array.
761void DiagnosticInfo::
762FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
763 const char *DiagStr = getDiags()->getDescription(getID());
764 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
John McCall9f286142010-01-13 23:58:20 +0000766 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
767}
768
769void DiagnosticInfo::
770FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
771 llvm::SmallVectorImpl<char> &OutStr) const {
772
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000773 /// FormattedArgs - Keep track of all of the arguments formatted by
774 /// ConvertArgToString and pass them into subsequent calls to
775 /// ConvertArgToString, allowing the implementation to avoid redundancies in
776 /// obvious cases.
777 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
778
Chris Lattnerf4c83962008-11-19 06:51:40 +0000779 while (DiagStr != DiagEnd) {
780 if (DiagStr[0] != '%') {
781 // Append non-%0 substrings to Str if we have one.
782 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
783 OutStr.append(DiagStr, StrEnd);
784 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000785 continue;
John McCall909c1822010-01-14 20:11:39 +0000786 } else if (ispunct(DiagStr[1])) {
787 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000788 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000789 continue;
790 }
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000792 // Skip the %.
793 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000795 // This must be a placeholder for a diagnostic argument. The format for a
796 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
797 // The digit is a number from 0-9 indicating which argument this comes from.
798 // The modifier is a string of digits from the set [-a-z]+, arguments is a
799 // brace enclosed string.
800 const char *Modifier = 0, *Argument = 0;
801 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000803 // Check to see if we have a modifier. If so eat it.
804 if (!isdigit(DiagStr[0])) {
805 Modifier = DiagStr;
806 while (DiagStr[0] == '-' ||
807 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
808 ++DiagStr;
809 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000810
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000811 // If we have an argument, get it next.
812 if (DiagStr[0] == '{') {
813 ++DiagStr; // Skip {.
814 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
John McCall909c1822010-01-14 20:11:39 +0000816 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
817 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000818 ArgumentLen = DiagStr-Argument;
819 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000820 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000823 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000824 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000825
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000826 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
827
828 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000829 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000830 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000831 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000832 assert(ModifierLen == 0 && "No modifiers for strings yet");
833 OutStr.append(S.begin(), S.end());
834 break;
835 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000836 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000837 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000838 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000839
840 // Don't crash if get passed a null pointer by accident.
841 if (!S)
842 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000844 OutStr.append(S, S + strlen(S));
845 break;
846 }
Chris Lattner08631c52008-11-23 21:45:46 +0000847 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000848 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000849 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000851 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000852 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000853 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
854 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000855 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
856 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000857 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
858 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000859 } else {
860 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000861 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000862 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000863 break;
864 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000865 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000866 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000868 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000869 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000870 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
871 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000872 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
873 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000874 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
875 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000876 } else {
877 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000878 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000879 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000880 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000881 }
Chris Lattner08631c52008-11-23 21:45:46 +0000882 // ---- NAMES and TYPES ----
883 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +0000884 const IdentifierInfo *II = getArgIdentifier(ArgNo);
885 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000886
887 // Don't crash if get passed a null pointer by accident.
888 if (!II) {
889 const char *S = "(null)";
890 OutStr.append(S, S + strlen(S));
891 continue;
892 }
893
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000894 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +0000895 break;
896 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000897 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +0000898 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000899 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +0000900 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +0000901 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000902 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000903 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000904 Argument, ArgumentLen,
905 FormattedArgs.data(), FormattedArgs.size(),
906 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +0000907 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000908 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000909
910 // Remember this argument info for subsequent formatting operations. Turn
911 // std::strings into a null terminated string to make it be the same case as
912 // all the other ones.
913 if (Kind != Diagnostic::ak_std_string)
914 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
915 else
916 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
917 (intptr_t)getArgStdStr(ArgNo).c_str()));
918
Nico Weber7bfaaae2008-08-10 19:59:06 +0000919 }
Nico Weber7bfaaae2008-08-10 19:59:06 +0000920}
Ted Kremenekcabe6682009-01-23 20:28:53 +0000921
Douglas Gregora88084b2010-02-18 18:08:43 +0000922StoredDiagnostic::StoredDiagnostic() { }
923
924StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
925 llvm::StringRef Message)
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000926 : Level(Level), Loc(), Message(Message) { }
Douglas Gregora88084b2010-02-18 18:08:43 +0000927
928StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
929 const DiagnosticInfo &Info)
930 : Level(Level), Loc(Info.getLocation())
931{
932 llvm::SmallString<64> Message;
933 Info.FormatDiagnostic(Message);
934 this->Message.assign(Message.begin(), Message.end());
935
936 Ranges.reserve(Info.getNumRanges());
937 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
938 Ranges.push_back(Info.getRange(I));
939
940 FixIts.reserve(Info.getNumCodeModificationHints());
941 for (unsigned I = 0, N = Info.getNumCodeModificationHints(); I != N; ++I)
942 FixIts.push_back(Info.getCodeModificationHint(I));
943}
944
945StoredDiagnostic::~StoredDiagnostic() { }
946
Douglas Gregord93256e2010-01-28 06:00:51 +0000947static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
948 OS.write((const char *)&Value, sizeof(unsigned));
949}
950
951static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
952 WriteUnsigned(OS, String.size());
953 OS.write(String.data(), String.size());
954}
955
956static void WriteSourceLocation(llvm::raw_ostream &OS,
957 SourceManager *SM,
958 SourceLocation Location) {
959 if (!SM || Location.isInvalid()) {
960 // If we don't have a source manager or this location is invalid,
961 // just write an invalid location.
962 WriteUnsigned(OS, 0);
963 WriteUnsigned(OS, 0);
964 WriteUnsigned(OS, 0);
965 return;
966 }
967
968 Location = SM->getInstantiationLoc(Location);
969 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
970
971 WriteString(OS, SM->getFileEntryForID(Decomposed.first)->getName());
972 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
973 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
974}
975
Douglas Gregora88084b2010-02-18 18:08:43 +0000976void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
Douglas Gregord93256e2010-01-28 06:00:51 +0000977 SourceManager *SM = 0;
978 if (getLocation().isValid())
979 SM = &const_cast<SourceManager &>(getLocation().getManager());
980
Douglas Gregorb9c903b2010-02-19 00:40:40 +0000981 // Write a short header to help identify diagnostics.
982 OS << (char)0x06 << (char)0x07;
983
Douglas Gregord93256e2010-01-28 06:00:51 +0000984 // Write the diagnostic level and location.
Douglas Gregora88084b2010-02-18 18:08:43 +0000985 WriteUnsigned(OS, (unsigned)Level);
Douglas Gregord93256e2010-01-28 06:00:51 +0000986 WriteSourceLocation(OS, SM, getLocation());
987
988 // Write the diagnostic message.
989 llvm::SmallString<64> Message;
Douglas Gregora88084b2010-02-18 18:08:43 +0000990 WriteString(OS, getMessage());
Douglas Gregord93256e2010-01-28 06:00:51 +0000991
992 // Count the number of ranges that don't point into macros, since
993 // only simple file ranges serialize well.
994 unsigned NumNonMacroRanges = 0;
Douglas Gregora88084b2010-02-18 18:08:43 +0000995 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
996 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +0000997 continue;
998
999 ++NumNonMacroRanges;
1000 }
1001
1002 // Write the ranges.
1003 WriteUnsigned(OS, NumNonMacroRanges);
1004 if (NumNonMacroRanges) {
Douglas Gregora88084b2010-02-18 18:08:43 +00001005 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1006 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +00001007 continue;
1008
Douglas Gregora88084b2010-02-18 18:08:43 +00001009 WriteSourceLocation(OS, SM, R->getBegin());
1010 WriteSourceLocation(OS, SM, R->getEnd());
Douglas Gregord93256e2010-01-28 06:00:51 +00001011 }
1012 }
1013
1014 // Determine if all of the fix-its involve rewrites with simple file
1015 // locations (not in macro instantiations). If so, we can write
1016 // fix-it information.
Douglas Gregora88084b2010-02-18 18:08:43 +00001017 unsigned NumFixIts = 0;
1018 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1019 if (F->RemoveRange.isValid() &&
1020 (F->RemoveRange.getBegin().isMacroID() ||
1021 F->RemoveRange.getEnd().isMacroID())) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001022 NumFixIts = 0;
1023 break;
1024 }
1025
Douglas Gregora88084b2010-02-18 18:08:43 +00001026 if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001027 NumFixIts = 0;
1028 break;
1029 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001030
1031 ++NumFixIts;
Douglas Gregord93256e2010-01-28 06:00:51 +00001032 }
1033
1034 // Write the fix-its.
1035 WriteUnsigned(OS, NumFixIts);
Douglas Gregora88084b2010-02-18 18:08:43 +00001036 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1037 WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1038 WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
1039 WriteSourceLocation(OS, SM, F->InsertionLoc);
1040 WriteString(OS, F->CodeToInsert);
Douglas Gregord93256e2010-01-28 06:00:51 +00001041 }
1042}
1043
Douglas Gregora88084b2010-02-18 18:08:43 +00001044static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1045 unsigned &Value) {
1046 if (Memory + sizeof(unsigned) > MemoryEnd)
1047 return true;
1048
1049 memmove(&Value, Memory, sizeof(unsigned));
1050 Memory += sizeof(unsigned);
1051 return false;
1052}
1053
1054static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1055 const char *&Memory, const char *MemoryEnd,
1056 SourceLocation &Location) {
1057 // Read the filename.
1058 unsigned FileNameLen = 0;
1059 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1060 Memory + FileNameLen > MemoryEnd)
1061 return true;
1062
1063 llvm::StringRef FileName(Memory, FileNameLen);
1064 Memory += FileNameLen;
1065
1066 // Read the line, column.
1067 unsigned Line = 0, Column = 0;
1068 if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1069 ReadUnsigned(Memory, MemoryEnd, Column))
1070 return true;
1071
1072 if (FileName.empty()) {
1073 Location = SourceLocation();
1074 return false;
1075 }
1076
1077 const FileEntry *File = FM.getFile(FileName);
1078 if (!File)
1079 return true;
1080
1081 // Make sure that this file has an entry in the source manager.
1082 if (!SM.hasFileInfo(File))
1083 SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1084
1085 Location = SM.getLocation(File, Line, Column);
1086 return false;
1087}
1088
1089StoredDiagnostic
1090StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1091 const char *&Memory, const char *MemoryEnd) {
Douglas Gregorb9c903b2010-02-19 00:40:40 +00001092 while (true) {
1093 if (Memory == MemoryEnd)
1094 return StoredDiagnostic();
1095
1096 if (*Memory != 0x06) {
1097 ++Memory;
1098 continue;
1099 }
1100
1101 ++Memory;
1102 if (Memory == MemoryEnd)
1103 return StoredDiagnostic();
1104
1105 if (*Memory != 0x07) {
1106 ++Memory;
1107 continue;
1108 }
1109
1110 // We found the header. We're done.
1111 ++Memory;
1112 break;
1113 }
1114
Douglas Gregora88084b2010-02-18 18:08:43 +00001115 // Read the severity level.
1116 unsigned Level = 0;
1117 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1118 return StoredDiagnostic();
1119
1120 // Read the source location.
1121 SourceLocation Location;
1122 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1123 return StoredDiagnostic();
1124
1125 // Read the diagnostic text.
1126 if (Memory == MemoryEnd)
1127 return StoredDiagnostic();
1128
1129 unsigned MessageLen = 0;
1130 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1131 Memory + MessageLen > MemoryEnd)
1132 return StoredDiagnostic();
1133
1134 llvm::StringRef Message(Memory, MessageLen);
1135 Memory += MessageLen;
1136
1137
1138 // At this point, we have enough information to form a diagnostic. Do so.
1139 StoredDiagnostic Diag;
1140 Diag.Level = (Diagnostic::Level)Level;
1141 Diag.Loc = FullSourceLoc(Location, SM);
1142 Diag.Message = Message;
1143 if (Memory == MemoryEnd)
1144 return Diag;
1145
1146 // Read the source ranges.
1147 unsigned NumSourceRanges = 0;
1148 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1149 return Diag;
1150 for (unsigned I = 0; I != NumSourceRanges; ++I) {
1151 SourceLocation Begin, End;
1152 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
1153 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End))
1154 return Diag;
1155
1156 Diag.Ranges.push_back(SourceRange(Begin, End));
1157 }
1158
1159 // Read the fix-it hints.
1160 unsigned NumFixIts = 0;
1161 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1162 return Diag;
1163 for (unsigned I = 0; I != NumFixIts; ++I) {
1164 SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
1165 unsigned InsertLen = 0;
1166 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1167 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
1168 ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
1169 ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1170 Memory + InsertLen > MemoryEnd) {
1171 Diag.FixIts.clear();
1172 return Diag;
1173 }
1174
1175 CodeModificationHint Hint;
1176 Hint.RemoveRange = SourceRange(RemoveBegin, RemoveEnd);
1177 Hint.InsertionLoc = InsertionLoc;
1178 Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1179 Memory += InsertLen;
1180 Diag.FixIts.push_back(Hint);
1181 }
1182
1183 return Diag;
1184}
1185
Ted Kremenekcabe6682009-01-23 20:28:53 +00001186/// IncludeInDiagnosticCounts - This method (whose default implementation
1187/// returns true) indicates whether the diagnostics handled by this
1188/// DiagnosticClient should be included in the number of diagnostics
1189/// reported by Diagnostic.
1190bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }