blob: fa5ca57dfe68b5d6423965b5d967e19a3317c1d2 [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 Lattner43b628c2008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/SourceLocation.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Chris Lattner30bc9652008-11-19 07:22:31 +000018#include "llvm/ADT/StringExtras.h"
Chris Lattner182745a2007-12-02 01:09:57 +000019#include <vector>
20#include <map>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000021#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Chris Lattner182745a2007-12-02 01:09:57 +000024//===----------------------------------------------------------------------===//
25// Builtin Diagnostic information
26//===----------------------------------------------------------------------===//
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028/// Flag values for diagnostics.
29enum {
30 // Diagnostic classes.
31 NOTE = 0x01,
32 WARNING = 0x02,
33 EXTENSION = 0x03,
Daniel Dunbar4489fe12008-08-05 00:07:51 +000034 EXTWARN = 0x04,
35 ERROR = 0x05,
Chris Lattnerda0cbc12009-02-05 22:47:05 +000036 FATAL = 0x06,
Reid Spencer5f016e22007-07-11 17:01:13 +000037 class_mask = 0x07
38};
39
40/// DiagnosticFlags - A set of flags, or'd together, that describe the
41/// diagnostic.
Reid Spencer5f016e22007-07-11 17:01:13 +000042#define DIAG(ENUM,FLAGS,DESC) FLAGS,
Chris Lattner20c6b3b2009-01-27 18:30:58 +000043static unsigned char DiagnosticFlagsCommon[] = {
44#include "clang/Basic/DiagnosticCommonKinds.def"
Reid Spencer5f016e22007-07-11 17:01:13 +000045 0
46};
Chris Lattner20c6b3b2009-01-27 18:30:58 +000047static unsigned char DiagnosticFlagsLex[] = {
48#include "clang/Basic/DiagnosticLexKinds.def"
49 0
50};
51static unsigned char DiagnosticFlagsParse[] = {
52#include "clang/Basic/DiagnosticParseKinds.def"
53 0
54};
55static unsigned char DiagnosticFlagsAST[] = {
56#include "clang/Basic/DiagnosticASTKinds.def"
57 0
58};
59static unsigned char DiagnosticFlagsSema[] = {
60#include "clang/Basic/DiagnosticSemaKinds.def"
61 0
62};
63static unsigned char DiagnosticFlagsAnalysis[] = {
64#include "clang/Basic/DiagnosticAnalysisKinds.def"
65 0
66};
67#undef DIAG
Reid Spencer5f016e22007-07-11 17:01:13 +000068
69/// getDiagClass - Return the class field of the diagnostic.
70///
Chris Lattner07506182007-11-30 22:53:43 +000071static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner19e8e2c2009-01-29 17:46:13 +000072 assert(DiagID < diag::DIAG_UPPER_LIMIT &&
Chris Lattner07506182007-11-30 22:53:43 +000073 "Diagnostic ID out of range!");
Chris Lattner20c6b3b2009-01-27 18:30:58 +000074 unsigned res;
Chris Lattner19e8e2c2009-01-29 17:46:13 +000075 if (DiagID < diag::DIAG_START_LEX)
Chris Lattner20c6b3b2009-01-27 18:30:58 +000076 res = DiagnosticFlagsCommon[DiagID];
Chris Lattner19e8e2c2009-01-29 17:46:13 +000077 else if (DiagID < diag::DIAG_START_PARSE)
78 res = DiagnosticFlagsLex[DiagID - diag::DIAG_START_LEX - 1];
79 else if (DiagID < diag::DIAG_START_AST)
80 res = DiagnosticFlagsParse[DiagID - diag::DIAG_START_PARSE - 1];
81 else if (DiagID < diag::DIAG_START_SEMA)
82 res = DiagnosticFlagsAST[DiagID - diag::DIAG_START_AST - 1];
83 else if (DiagID < diag::DIAG_START_ANALYSIS)
84 res = DiagnosticFlagsSema[DiagID - diag::DIAG_START_SEMA - 1];
Chris Lattner20c6b3b2009-01-27 18:30:58 +000085 else
Chris Lattner19e8e2c2009-01-29 17:46:13 +000086 res = DiagnosticFlagsAnalysis[DiagID - diag::DIAG_START_ANALYSIS - 1];
Chris Lattner20c6b3b2009-01-27 18:30:58 +000087 return res & class_mask;
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
90/// DiagnosticText - An english message to print for the diagnostic. These
91/// should be localized.
Reid Spencer5f016e22007-07-11 17:01:13 +000092#define DIAG(ENUM,FLAGS,DESC) DESC,
Chris Lattner20c6b3b2009-01-27 18:30:58 +000093static const char * const DiagnosticTextCommon[] = {
94#include "clang/Basic/DiagnosticCommonKinds.def"
Reid Spencer5f016e22007-07-11 17:01:13 +000095 0
96};
Chris Lattner20c6b3b2009-01-27 18:30:58 +000097static const char * const DiagnosticTextLex[] = {
98#include "clang/Basic/DiagnosticLexKinds.def"
99 0
100};
101static const char * const DiagnosticTextParse[] = {
102#include "clang/Basic/DiagnosticParseKinds.def"
103 0
104};
105static const char * const DiagnosticTextAST[] = {
106#include "clang/Basic/DiagnosticASTKinds.def"
107 0
108};
109static const char * const DiagnosticTextSema[] = {
110#include "clang/Basic/DiagnosticSemaKinds.def"
111 0
112};
113static const char * const DiagnosticTextAnalysis[] = {
114#include "clang/Basic/DiagnosticAnalysisKinds.def"
115 0
116};
117#undef DIAG
Reid Spencer5f016e22007-07-11 17:01:13 +0000118
Chris Lattner182745a2007-12-02 01:09:57 +0000119//===----------------------------------------------------------------------===//
120// Custom Diagnostic information
121//===----------------------------------------------------------------------===//
122
123namespace clang {
124 namespace diag {
125 class CustomDiagInfo {
126 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
127 std::vector<DiagDesc> DiagInfo;
128 std::map<DiagDesc, unsigned> DiagIDs;
129 public:
130
131 /// getDescription - Return the description of the specified custom
132 /// diagnostic.
133 const char *getDescription(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000134 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000135 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000136 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner182745a2007-12-02 01:09:57 +0000137 }
138
139 /// getLevel - Return the level of the specified custom diagnostic.
140 Diagnostic::Level getLevel(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000141 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000142 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000143 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner182745a2007-12-02 01:09:57 +0000144 }
145
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000146 unsigned getOrCreateDiagID(Diagnostic::Level L, const char *Message,
147 Diagnostic &Diags) {
Chris Lattner182745a2007-12-02 01:09:57 +0000148 DiagDesc D(L, Message);
149 // Check to see if it already exists.
150 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
151 if (I != DiagIDs.end() && I->first == D)
152 return I->second;
153
154 // If not, assign a new ID.
Chris Lattner88eccaf2009-01-29 06:55:46 +0000155 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner182745a2007-12-02 01:09:57 +0000156 DiagIDs.insert(std::make_pair(D, ID));
157 DiagInfo.push_back(D);
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000158
159 // If this is a warning, and all warnings are supposed to map to errors,
160 // insert the mapping now.
161 if (L == Diagnostic::Warning && Diags.getWarningsAsErrors())
162 Diags.setDiagnosticMapping((diag::kind)ID, diag::MAP_ERROR);
Chris Lattner182745a2007-12-02 01:09:57 +0000163 return ID;
164 }
165 };
166
167 } // end diag namespace
168} // end clang namespace
169
170
171//===----------------------------------------------------------------------===//
172// Common Diagnostic implementation
173//===----------------------------------------------------------------------===//
174
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000175static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
176 const char *Modifier, unsigned ML,
177 const char *Argument, unsigned ArgLen,
Chris Lattner92dd3862009-02-19 23:53:20 +0000178 llvm::SmallVectorImpl<char> &Output,
179 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000180 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +0000181 Output.append(Str, Str+strlen(Str));
182}
183
184
Ted Kremenekb4398aa2008-08-07 17:49:57 +0000185Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000186 IgnoreAllWarnings = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 WarningsAsErrors = false;
188 WarnOnExtensions = false;
189 ErrorOnExtensions = false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000190 SuppressSystemWarnings = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 // Clear all mappings, setting them to MAP_DEFAULT.
192 memset(DiagMappings, 0, sizeof(DiagMappings));
193
194 ErrorOccurred = false;
Chris Lattner15221422009-02-06 04:16:02 +0000195 FatalErrorOccurred = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 NumDiagnostics = 0;
197 NumErrors = 0;
Chris Lattner182745a2007-12-02 01:09:57 +0000198 CustomDiagInfo = 0;
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000199 CurDiagID = ~0U;
Chris Lattnerf5d23282009-02-17 06:49:55 +0000200 LastDiagLevel = Fatal;
Chris Lattner22caddc2008-11-23 09:13:29 +0000201
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000202 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +0000203 ArgToStringCookie = 0;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000204
205 InPostDiagnosticHook = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000206}
207
Chris Lattner182745a2007-12-02 01:09:57 +0000208Diagnostic::~Diagnostic() {
209 delete CustomDiagInfo;
210}
211
212/// getCustomDiagID - Return an ID for a diagnostic with the specified message
213/// and level. If this is the first request for this diagnosic, it is
214/// registered and created, otherwise the existing ID is returned.
215unsigned Diagnostic::getCustomDiagID(Level L, const char *Message) {
216 if (CustomDiagInfo == 0)
217 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000218 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner182745a2007-12-02 01:09:57 +0000219}
220
221
Chris Lattnerf5d23282009-02-17 06:49:55 +0000222/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
223/// level of the specified diagnostic ID is a Warning or Extension.
224/// This only works on builtin diagnostics, not custom ones, and is not legal to
225/// call on NOTEs.
226bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000227 return DiagID < diag::DIAG_UPPER_LIMIT && getBuiltinDiagClass(DiagID) < ERROR;
Reid Spencer5f016e22007-07-11 17:01:13 +0000228}
229
Douglas Gregoree1828a2009-03-10 18:03:33 +0000230/// \brief Determine whether the given built-in diagnostic ID is a
231/// Note.
232bool Diagnostic::isBuiltinNote(unsigned DiagID) {
233 return DiagID < diag::DIAG_UPPER_LIMIT && getBuiltinDiagClass(DiagID) == NOTE;
234}
235
Reid Spencer5f016e22007-07-11 17:01:13 +0000236
237/// getDescription - Given a diagnostic ID, return a description of the
238/// issue.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000239const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattnerf5d23282009-02-17 06:49:55 +0000240 if (DiagID < diag::DIAG_START_LEX)
241 return DiagnosticTextCommon[DiagID];
242 else if (DiagID < diag::DIAG_START_PARSE)
243 return DiagnosticTextLex[DiagID - diag::DIAG_START_LEX - 1];
244 else if (DiagID < diag::DIAG_START_AST)
245 return DiagnosticTextParse[DiagID - diag::DIAG_START_PARSE - 1];
246 else if (DiagID < diag::DIAG_START_SEMA)
247 return DiagnosticTextAST[DiagID - diag::DIAG_START_AST - 1];
248 else if (DiagID < diag::DIAG_START_ANALYSIS)
249 return DiagnosticTextSema[DiagID - diag::DIAG_START_SEMA - 1];
250 else if (DiagID < diag::DIAG_UPPER_LIMIT)
251 return DiagnosticTextAnalysis[DiagID - diag::DIAG_START_ANALYSIS - 1];
Chris Lattner20c6b3b2009-01-27 18:30:58 +0000252 return CustomDiagInfo->getDescription(DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253}
254
255/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
256/// object, classify the specified diagnostic ID into a Level, consumable by
257/// the DiagnosticClient.
258Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner182745a2007-12-02 01:09:57 +0000259 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000260 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner182745a2007-12-02 01:09:57 +0000261 return CustomDiagInfo->getLevel(DiagID);
Chris Lattner07506182007-11-30 22:53:43 +0000262
263 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattnerf5d23282009-02-17 06:49:55 +0000264 assert(DiagClass != NOTE && "Cannot get the diagnostic level of a note!");
265 return getDiagnosticLevel(DiagID, DiagClass);
266}
267
268/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
269/// object, classify the specified diagnostic ID into a Level, consumable by
270/// the DiagnosticClient.
271Diagnostic::Level
272Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattnerf5d23282009-02-17 06:49:55 +0000274 // to error. Errors can only be mapped to fatal.
275 switch (getDiagnosticMapping((diag::kind)DiagID)) {
276 case diag::MAP_DEFAULT: break;
277 case diag::MAP_IGNORE: return Diagnostic::Ignored;
278 case diag::MAP_WARNING: DiagClass = WARNING; break;
279 case diag::MAP_ERROR: DiagClass = ERROR; break;
280 case diag::MAP_FATAL: DiagClass = FATAL; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 }
282
283 // Map diagnostic classes based on command line argument settings.
284 if (DiagClass == EXTENSION) {
285 if (ErrorOnExtensions)
286 DiagClass = ERROR;
287 else if (WarnOnExtensions)
288 DiagClass = WARNING;
289 else
290 return Ignored;
Daniel Dunbar4489fe12008-08-05 00:07:51 +0000291 } else if (DiagClass == EXTWARN) {
292 DiagClass = ErrorOnExtensions ? ERROR : WARNING;
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 }
294
Chris Lattner5b4681c2008-05-29 15:36:45 +0000295 // If warnings are globally mapped to ignore or error, do it.
296 if (DiagClass == WARNING) {
297 if (IgnoreAllWarnings)
298 return Diagnostic::Ignored;
299 if (WarningsAsErrors)
300 DiagClass = ERROR;
301 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303 switch (DiagClass) {
304 default: assert(0 && "Unknown diagnostic class!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 case WARNING: return Diagnostic::Warning;
306 case ERROR: return Diagnostic::Error;
Chris Lattnerda0cbc12009-02-05 22:47:05 +0000307 case FATAL: return Diagnostic::Fatal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 }
309}
310
Chris Lattner0a14eee2008-11-18 07:04:44 +0000311/// ProcessDiag - This is the method used to report a diagnostic that is
312/// finally fully formed.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000313void Diagnostic::ProcessDiag() {
314 DiagnosticInfo Info(this);
315
Chris Lattner15221422009-02-06 04:16:02 +0000316 // If a fatal error has already been emitted, silence all subsequent
317 // diagnostics.
318 if (FatalErrorOccurred)
319 return;
320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // Figure out the diagnostic level of this message.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000322 Diagnostic::Level DiagLevel;
323 unsigned DiagID = Info.getID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
Chris Lattnerf5d23282009-02-17 06:49:55 +0000325 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
326 // in a system header.
327 bool ShouldEmitInSystemHeader;
328
329 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
330 // Handle custom diagnostics, which cannot be mapped.
331 DiagLevel = CustomDiagInfo->getLevel(DiagID);
332
333 // Custom diagnostics always are emitted in system headers.
334 ShouldEmitInSystemHeader = true;
335 } else {
336 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
337 // the diagnostic level was for the previous diagnostic so that it is
338 // filtered the same as the previous diagnostic.
339 unsigned DiagClass = getBuiltinDiagClass(DiagID);
340 if (DiagClass == NOTE) {
341 DiagLevel = Diagnostic::Note;
342 ShouldEmitInSystemHeader = false; // extra consideration is needed
343 } else {
344 // If this is not an error and we are in a system header, we ignore it.
345 // Check the original Diag ID here, because we also want to ignore
346 // extensions and warnings in -Werror and -pedantic-errors modes, which
347 // *map* warnings/extensions to errors.
348 ShouldEmitInSystemHeader = DiagClass == ERROR;
349
350 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
351 }
352 }
353
354 if (DiagLevel != Diagnostic::Note)
355 LastDiagLevel = DiagLevel;
356
357 // If the client doesn't care about this message, don't issue it. If this is
358 // a note and the last real diagnostic was ignored, ignore it too.
359 if (DiagLevel == Diagnostic::Ignored ||
360 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 return;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000362
Chris Lattnerf5d23282009-02-17 06:49:55 +0000363 // If this diagnostic is in a system header and is not a clang error, suppress
364 // it.
365 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner0a14eee2008-11-18 07:04:44 +0000366 Info.getLocation().isValid() &&
Chris Lattnerf5d23282009-02-17 06:49:55 +0000367 Info.getLocation().getSpellingLoc().isInSystemHeader() &&
Chris Lattner336f26b2009-02-17 06:52:20 +0000368 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
369 LastDiagLevel = Diagnostic::Ignored;
Chris Lattner7097d912008-02-03 09:00:04 +0000370 return;
Chris Lattner336f26b2009-02-17 06:52:20 +0000371 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 if (DiagLevel >= Diagnostic::Error) {
374 ErrorOccurred = true;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000375 ++NumErrors;
Chris Lattner15221422009-02-06 04:16:02 +0000376
377 if (DiagLevel == Diagnostic::Fatal)
378 FatalErrorOccurred = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Finally, report it.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000382 Client->HandleDiagnostic(DiagLevel, Info);
Ted Kremenekcabe6682009-01-23 20:28:53 +0000383 if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000384
385 // Invoke any post-diagnostic hooks.
386 unsigned LastDiag = CurDiagID;
387 CurDiagID = ~0U;
388
389 InPostDiagnosticHook = true;
390 for (unsigned Hook = 0; Hook < NumPostDiagnosticHooks; ++Hook)
391 PostDiagnosticHooks[Hook].Hook(LastDiag,
392 PostDiagnosticHooks[Hook].Cookie);
393 InPostDiagnosticHook = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
Nico Weber7bfaaae2008-08-10 19:59:06 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000398
Chris Lattnerf4c83962008-11-19 06:51:40 +0000399
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000400/// ModifierIs - Return true if the specified modifier matches specified string.
401template <std::size_t StrLen>
402static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
403 const char (&Str)[StrLen]) {
404 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
405}
406
407/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
408/// like this: %select{foo|bar|baz}2. This means that the integer argument
409/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
410/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
411/// This is very useful for certain classes of variant diagnostics.
412static void HandleSelectModifier(unsigned ValNo,
413 const char *Argument, unsigned ArgumentLen,
414 llvm::SmallVectorImpl<char> &OutStr) {
415 const char *ArgumentEnd = Argument+ArgumentLen;
416
417 // Skip over 'ValNo' |'s.
418 while (ValNo) {
419 const char *NextVal = std::find(Argument, ArgumentEnd, '|');
420 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
421 " larger than the number of options in the diagnostic string!");
422 Argument = NextVal+1; // Skip this string.
423 --ValNo;
424 }
425
426 // Get the end of the value. This is either the } or the |.
427 const char *EndPtr = std::find(Argument, ArgumentEnd, '|');
428 // Add the value to the output string.
429 OutStr.append(Argument, EndPtr);
430}
431
432/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
433/// letter 's' to the string if the value is not 1. This is used in cases like
434/// this: "you idiot, you have %4 parameter%s4!".
435static void HandleIntegerSModifier(unsigned ValNo,
436 llvm::SmallVectorImpl<char> &OutStr) {
437 if (ValNo != 1)
438 OutStr.push_back('s');
439}
440
441
Sebastian Redle4c452c2008-11-22 13:44:36 +0000442/// PluralNumber - Parse an unsigned integer and advance Start.
443static unsigned PluralNumber(const char *&Start, const char *End)
444{
445 // Programming 101: Parse a decimal number :-)
446 unsigned Val = 0;
447 while (Start != End && *Start >= '0' && *Start <= '9') {
448 Val *= 10;
449 Val += *Start - '0';
450 ++Start;
451 }
452 return Val;
453}
454
455/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
456static bool TestPluralRange(unsigned Val, const char *&Start, const char *End)
457{
458 if (*Start != '[') {
459 unsigned Ref = PluralNumber(Start, End);
460 return Ref == Val;
461 }
462
463 ++Start;
464 unsigned Low = PluralNumber(Start, End);
465 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
466 ++Start;
467 unsigned High = PluralNumber(Start, End);
468 assert(*Start == ']' && "Bad plural expression syntax: expected )");
469 ++Start;
470 return Low <= Val && Val <= High;
471}
472
473/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
474static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End)
475{
476 // Empty condition?
477 if (*Start == ':')
478 return true;
479
480 while (1) {
481 char C = *Start;
482 if (C == '%') {
483 // Modulo expression
484 ++Start;
485 unsigned Arg = PluralNumber(Start, End);
486 assert(*Start == '=' && "Bad plural expression syntax: expected =");
487 ++Start;
488 unsigned ValMod = ValNo % Arg;
489 if (TestPluralRange(ValMod, Start, End))
490 return true;
491 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000492 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000493 "Bad plural expression syntax: unexpected character");
494 // Range expression
495 if (TestPluralRange(ValNo, Start, End))
496 return true;
497 }
498
499 // Scan for next or-expr part.
500 Start = std::find(Start, End, ',');
501 if(Start == End)
502 break;
503 ++Start;
504 }
505 return false;
506}
507
508/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
509/// for complex plural forms, or in languages where all plurals are complex.
510/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
511/// conditions that are tested in order, the form corresponding to the first
512/// that applies being emitted. The empty condition is always true, making the
513/// last form a default case.
514/// Conditions are simple boolean expressions, where n is the number argument.
515/// Here are the rules.
516/// condition := expression | empty
517/// empty := -> always true
518/// expression := numeric [',' expression] -> logical or
519/// numeric := range -> true if n in range
520/// | '%' number '=' range -> true if n % number in range
521/// range := number
522/// | '[' number ',' number ']' -> ranges are inclusive both ends
523///
524/// Here are some examples from the GNU gettext manual written in this form:
525/// English:
526/// {1:form0|:form1}
527/// Latvian:
528/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
529/// Gaeilge:
530/// {1:form0|2:form1|:form2}
531/// Romanian:
532/// {1:form0|0,%100=[1,19]:form1|:form2}
533/// Lithuanian:
534/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
535/// Russian (requires repeated form):
536/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
537/// Slovak
538/// {1:form0|[2,4]:form1|:form2}
539/// Polish (requires repeated form):
540/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
541static void HandlePluralModifier(unsigned ValNo,
542 const char *Argument, unsigned ArgumentLen,
543 llvm::SmallVectorImpl<char> &OutStr)
544{
545 const char *ArgumentEnd = Argument + ArgumentLen;
546 while (1) {
547 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
548 const char *ExprEnd = Argument;
549 while (*ExprEnd != ':') {
550 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
551 ++ExprEnd;
552 }
553 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
554 Argument = ExprEnd + 1;
555 ExprEnd = std::find(Argument, ArgumentEnd, '|');
556 OutStr.append(Argument, ExprEnd);
557 return;
558 }
559 Argument = std::find(Argument, ArgumentEnd - 1, '|') + 1;
560 }
561}
562
563
Chris Lattnerf4c83962008-11-19 06:51:40 +0000564/// FormatDiagnostic - Format this diagnostic into a string, substituting the
565/// formal arguments into the %0 slots. The result is appended onto the Str
566/// array.
567void DiagnosticInfo::
568FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
569 const char *DiagStr = getDiags()->getDescription(getID());
570 const char *DiagEnd = DiagStr+strlen(DiagStr);
Nico Weber7bfaaae2008-08-10 19:59:06 +0000571
Chris Lattnerf4c83962008-11-19 06:51:40 +0000572 while (DiagStr != DiagEnd) {
573 if (DiagStr[0] != '%') {
574 // Append non-%0 substrings to Str if we have one.
575 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
576 OutStr.append(DiagStr, StrEnd);
577 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000578 continue;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000579 } else if (DiagStr[1] == '%') {
580 OutStr.push_back('%'); // %% -> %.
581 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000582 continue;
583 }
584
585 // Skip the %.
586 ++DiagStr;
587
588 // This must be a placeholder for a diagnostic argument. The format for a
589 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
590 // The digit is a number from 0-9 indicating which argument this comes from.
591 // The modifier is a string of digits from the set [-a-z]+, arguments is a
592 // brace enclosed string.
593 const char *Modifier = 0, *Argument = 0;
594 unsigned ModifierLen = 0, ArgumentLen = 0;
595
596 // Check to see if we have a modifier. If so eat it.
597 if (!isdigit(DiagStr[0])) {
598 Modifier = DiagStr;
599 while (DiagStr[0] == '-' ||
600 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
601 ++DiagStr;
602 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000603
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000604 // If we have an argument, get it next.
605 if (DiagStr[0] == '{') {
606 ++DiagStr; // Skip {.
607 Argument = DiagStr;
608
609 for (; DiagStr[0] != '}'; ++DiagStr)
610 assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!");
611 ArgumentLen = DiagStr-Argument;
612 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000613 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000614 }
615
616 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000617 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000618
Chris Lattner22caddc2008-11-23 09:13:29 +0000619 switch (getArgKind(ArgNo)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000620 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000621 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000622 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000623 assert(ModifierLen == 0 && "No modifiers for strings yet");
624 OutStr.append(S.begin(), S.end());
625 break;
626 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000627 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000628 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000629 assert(ModifierLen == 0 && "No modifiers for strings yet");
630 OutStr.append(S, S + strlen(S));
631 break;
632 }
Chris Lattner08631c52008-11-23 21:45:46 +0000633 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000634 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000635 int Val = getArgSInt(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000636
637 if (ModifierIs(Modifier, ModifierLen, "select")) {
638 HandleSelectModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
639 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
640 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000641 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
642 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000643 } else {
644 assert(ModifierLen == 0 && "Unknown integer modifier");
Chris Lattner30bc9652008-11-19 07:22:31 +0000645 // FIXME: Optimize
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000646 std::string S = llvm::itostr(Val);
Chris Lattner30bc9652008-11-19 07:22:31 +0000647 OutStr.append(S.begin(), S.end());
Chris Lattner30bc9652008-11-19 07:22:31 +0000648 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000649 break;
650 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000651 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000652 unsigned Val = getArgUInt(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000653
654 if (ModifierIs(Modifier, ModifierLen, "select")) {
655 HandleSelectModifier(Val, Argument, ArgumentLen, OutStr);
656 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
657 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000658 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
659 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000660 } else {
661 assert(ModifierLen == 0 && "Unknown integer modifier");
662
Chris Lattner30bc9652008-11-19 07:22:31 +0000663 // FIXME: Optimize
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000664 std::string S = llvm::utostr_32(Val);
Chris Lattner30bc9652008-11-19 07:22:31 +0000665 OutStr.append(S.begin(), S.end());
Chris Lattner30bc9652008-11-19 07:22:31 +0000666 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000667 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000668 }
Chris Lattner08631c52008-11-23 21:45:46 +0000669 // ---- NAMES and TYPES ----
670 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +0000671 const IdentifierInfo *II = getArgIdentifier(ArgNo);
672 assert(ModifierLen == 0 && "No modifiers for strings yet");
Chris Lattnerd0344a42009-02-19 23:45:49 +0000673 OutStr.push_back('\'');
Chris Lattner08631c52008-11-23 21:45:46 +0000674 OutStr.append(II->getName(), II->getName() + II->getLength());
675 OutStr.push_back('\'');
676 break;
677 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000678 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +0000679 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000680 case Diagnostic::ak_nameddecl:
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000681 getDiags()->ConvertArgToString(getArgKind(ArgNo), getRawArg(ArgNo),
682 Modifier, ModifierLen,
683 Argument, ArgumentLen, OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +0000684 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000685 }
686 }
Nico Weber7bfaaae2008-08-10 19:59:06 +0000687}
Ted Kremenekcabe6682009-01-23 20:28:53 +0000688
689/// IncludeInDiagnosticCounts - This method (whose default implementation
690/// returns true) indicates whether the diagnostics handled by this
691/// DiagnosticClient should be included in the number of diagnostics
692/// reported by Diagnostic.
693bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }