blob: 83ccd22e2843b287b60fdd03898acd62c5237c3b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/Diagnostic.h"
Chris Lattnere46b8792008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/Basic/SourceLocation.h"
Chris Lattnerbe8e5a42008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Chris Lattner68f621c2008-11-19 07:22:31 +000018#include "llvm/ADT/StringExtras.h"
Chris Lattner217df512007-12-02 01:09:57 +000019#include <vector>
20#include <map>
Chris Lattner8b8720f2008-03-10 17:04:53 +000021#include <cstring>
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
Chris Lattner217df512007-12-02 01:09:57 +000024//===----------------------------------------------------------------------===//
25// Builtin Diagnostic information
26//===----------------------------------------------------------------------===//
27
Chris Lattner4b009652007-07-25 00:24:17 +000028/// Flag values for diagnostics.
29enum {
30 // Diagnostic classes.
31 NOTE = 0x01,
32 WARNING = 0x02,
33 EXTENSION = 0x03,
Daniel Dunbar103baef2008-08-05 00:07:51 +000034 EXTWARN = 0x04,
35 ERROR = 0x05,
Chris Lattner6d6f11f2009-02-05 22:47:05 +000036 FATAL = 0x06,
Chris Lattner4b009652007-07-25 00:24:17 +000037 class_mask = 0x07
38};
39
40/// DiagnosticFlags - A set of flags, or'd together, that describe the
41/// diagnostic.
Chris Lattner4b009652007-07-25 00:24:17 +000042#define DIAG(ENUM,FLAGS,DESC) FLAGS,
Chris Lattner52a425b2009-01-27 18:30:58 +000043static unsigned char DiagnosticFlagsCommon[] = {
44#include "clang/Basic/DiagnosticCommonKinds.def"
Chris Lattner4b009652007-07-25 00:24:17 +000045 0
46};
Chris Lattner52a425b2009-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
Chris Lattner4b009652007-07-25 00:24:17 +000068
69/// getDiagClass - Return the class field of the diagnostic.
70///
Chris Lattner4478db92007-11-30 22:53:43 +000071static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner8d9b1d82009-01-29 17:46:13 +000072 assert(DiagID < diag::DIAG_UPPER_LIMIT &&
Chris Lattner4478db92007-11-30 22:53:43 +000073 "Diagnostic ID out of range!");
Chris Lattner52a425b2009-01-27 18:30:58 +000074 unsigned res;
Chris Lattner8d9b1d82009-01-29 17:46:13 +000075 if (DiagID < diag::DIAG_START_LEX)
Chris Lattner52a425b2009-01-27 18:30:58 +000076 res = DiagnosticFlagsCommon[DiagID];
Chris Lattner8d9b1d82009-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 Lattner52a425b2009-01-27 18:30:58 +000085 else
Chris Lattner8d9b1d82009-01-29 17:46:13 +000086 res = DiagnosticFlagsAnalysis[DiagID - diag::DIAG_START_ANALYSIS - 1];
Chris Lattner52a425b2009-01-27 18:30:58 +000087 return res & class_mask;
Chris Lattner4b009652007-07-25 00:24:17 +000088}
89
90/// DiagnosticText - An english message to print for the diagnostic. These
91/// should be localized.
Chris Lattner4b009652007-07-25 00:24:17 +000092#define DIAG(ENUM,FLAGS,DESC) DESC,
Chris Lattner52a425b2009-01-27 18:30:58 +000093static const char * const DiagnosticTextCommon[] = {
94#include "clang/Basic/DiagnosticCommonKinds.def"
Chris Lattner4b009652007-07-25 00:24:17 +000095 0
96};
Chris Lattner52a425b2009-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
Chris Lattner4b009652007-07-25 00:24:17 +0000118
Chris Lattner217df512007-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 Lattner86a24842009-01-29 06:55:46 +0000134 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner217df512007-12-02 01:09:57 +0000135 "Invalid diagnosic ID");
Chris Lattner86a24842009-01-29 06:55:46 +0000136 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner217df512007-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 Lattner86a24842009-01-29 06:55:46 +0000141 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner217df512007-12-02 01:09:57 +0000142 "Invalid diagnosic ID");
Chris Lattner86a24842009-01-29 06:55:46 +0000143 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner217df512007-12-02 01:09:57 +0000144 }
145
Chris Lattnerb90f3cd2008-10-17 21:24:47 +0000146 unsigned getOrCreateDiagID(Diagnostic::Level L, const char *Message,
147 Diagnostic &Diags) {
Chris Lattner217df512007-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 Lattner86a24842009-01-29 06:55:46 +0000155 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner217df512007-12-02 01:09:57 +0000156 DiagIDs.insert(std::make_pair(D, ID));
157 DiagInfo.push_back(D);
Chris Lattnerb90f3cd2008-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 Lattner217df512007-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 Lattnerf5b269a2008-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,
178 llvm::SmallVectorImpl<char> &Output) {
179 const char *Str = "<can't format argument>";
Chris Lattnerda5c0872008-11-23 09:13:29 +0000180 Output.append(Str, Str+strlen(Str));
181}
182
183
Ted Kremenek5c341732008-08-07 17:49:57 +0000184Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000185 IgnoreAllWarnings = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000186 WarningsAsErrors = false;
187 WarnOnExtensions = false;
188 ErrorOnExtensions = false;
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000189 SuppressSystemWarnings = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000190 // Clear all mappings, setting them to MAP_DEFAULT.
191 memset(DiagMappings, 0, sizeof(DiagMappings));
192
193 ErrorOccurred = false;
Chris Lattneraab419a2009-02-06 04:16:02 +0000194 FatalErrorOccurred = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000195 NumDiagnostics = 0;
196 NumErrors = 0;
Chris Lattner217df512007-12-02 01:09:57 +0000197 CustomDiagInfo = 0;
Chris Lattner9943e982008-11-22 00:59:29 +0000198 CurDiagID = ~0U;
Chris Lattner44b39832009-02-17 06:49:55 +0000199 LastDiagLevel = Fatal;
Chris Lattnerda5c0872008-11-23 09:13:29 +0000200
Chris Lattnerf5b269a2008-11-23 09:21:17 +0000201 ArgToStringFn = DummyArgToStringFn;
Chris Lattner4b009652007-07-25 00:24:17 +0000202}
203
Chris Lattner217df512007-12-02 01:09:57 +0000204Diagnostic::~Diagnostic() {
205 delete CustomDiagInfo;
206}
207
208/// getCustomDiagID - Return an ID for a diagnostic with the specified message
209/// and level. If this is the first request for this diagnosic, it is
210/// registered and created, otherwise the existing ID is returned.
211unsigned Diagnostic::getCustomDiagID(Level L, const char *Message) {
212 if (CustomDiagInfo == 0)
213 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnerb90f3cd2008-10-17 21:24:47 +0000214 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner217df512007-12-02 01:09:57 +0000215}
216
217
Chris Lattner44b39832009-02-17 06:49:55 +0000218/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
219/// level of the specified diagnostic ID is a Warning or Extension.
220/// This only works on builtin diagnostics, not custom ones, and is not legal to
221/// call on NOTEs.
222bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner8d9b1d82009-01-29 17:46:13 +0000223 return DiagID < diag::DIAG_UPPER_LIMIT && getBuiltinDiagClass(DiagID) < ERROR;
Chris Lattner4b009652007-07-25 00:24:17 +0000224}
225
226
227/// getDescription - Given a diagnostic ID, return a description of the
228/// issue.
Chris Lattner6948ae62008-11-18 07:04:44 +0000229const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattner44b39832009-02-17 06:49:55 +0000230 if (DiagID < diag::DIAG_START_LEX)
231 return DiagnosticTextCommon[DiagID];
232 else if (DiagID < diag::DIAG_START_PARSE)
233 return DiagnosticTextLex[DiagID - diag::DIAG_START_LEX - 1];
234 else if (DiagID < diag::DIAG_START_AST)
235 return DiagnosticTextParse[DiagID - diag::DIAG_START_PARSE - 1];
236 else if (DiagID < diag::DIAG_START_SEMA)
237 return DiagnosticTextAST[DiagID - diag::DIAG_START_AST - 1];
238 else if (DiagID < diag::DIAG_START_ANALYSIS)
239 return DiagnosticTextSema[DiagID - diag::DIAG_START_SEMA - 1];
240 else if (DiagID < diag::DIAG_UPPER_LIMIT)
241 return DiagnosticTextAnalysis[DiagID - diag::DIAG_START_ANALYSIS - 1];
Chris Lattner52a425b2009-01-27 18:30:58 +0000242 return CustomDiagInfo->getDescription(DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000243}
244
245/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
246/// object, classify the specified diagnostic ID into a Level, consumable by
247/// the DiagnosticClient.
248Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner217df512007-12-02 01:09:57 +0000249 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner8d9b1d82009-01-29 17:46:13 +0000250 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner217df512007-12-02 01:09:57 +0000251 return CustomDiagInfo->getLevel(DiagID);
Chris Lattner4478db92007-11-30 22:53:43 +0000252
253 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner44b39832009-02-17 06:49:55 +0000254 assert(DiagClass != NOTE && "Cannot get the diagnostic level of a note!");
255 return getDiagnosticLevel(DiagID, DiagClass);
256}
257
258/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
259/// object, classify the specified diagnostic ID into a Level, consumable by
260/// the DiagnosticClient.
261Diagnostic::Level
262Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Chris Lattner4b009652007-07-25 00:24:17 +0000263 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattner44b39832009-02-17 06:49:55 +0000264 // to error. Errors can only be mapped to fatal.
265 switch (getDiagnosticMapping((diag::kind)DiagID)) {
266 case diag::MAP_DEFAULT: break;
267 case diag::MAP_IGNORE: return Diagnostic::Ignored;
268 case diag::MAP_WARNING: DiagClass = WARNING; break;
269 case diag::MAP_ERROR: DiagClass = ERROR; break;
270 case diag::MAP_FATAL: DiagClass = FATAL; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000271 }
272
273 // Map diagnostic classes based on command line argument settings.
274 if (DiagClass == EXTENSION) {
275 if (ErrorOnExtensions)
276 DiagClass = ERROR;
277 else if (WarnOnExtensions)
278 DiagClass = WARNING;
279 else
280 return Ignored;
Daniel Dunbar103baef2008-08-05 00:07:51 +0000281 } else if (DiagClass == EXTWARN) {
282 DiagClass = ErrorOnExtensions ? ERROR : WARNING;
Chris Lattner4b009652007-07-25 00:24:17 +0000283 }
284
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000285 // If warnings are globally mapped to ignore or error, do it.
286 if (DiagClass == WARNING) {
287 if (IgnoreAllWarnings)
288 return Diagnostic::Ignored;
289 if (WarningsAsErrors)
290 DiagClass = ERROR;
291 }
Chris Lattner4b009652007-07-25 00:24:17 +0000292
293 switch (DiagClass) {
294 default: assert(0 && "Unknown diagnostic class!");
Chris Lattner4b009652007-07-25 00:24:17 +0000295 case WARNING: return Diagnostic::Warning;
296 case ERROR: return Diagnostic::Error;
Chris Lattner6d6f11f2009-02-05 22:47:05 +0000297 case FATAL: return Diagnostic::Fatal;
Chris Lattner4b009652007-07-25 00:24:17 +0000298 }
299}
300
Chris Lattner6948ae62008-11-18 07:04:44 +0000301/// ProcessDiag - This is the method used to report a diagnostic that is
302/// finally fully formed.
Chris Lattner9943e982008-11-22 00:59:29 +0000303void Diagnostic::ProcessDiag() {
304 DiagnosticInfo Info(this);
305
Chris Lattneraab419a2009-02-06 04:16:02 +0000306 // If a fatal error has already been emitted, silence all subsequent
307 // diagnostics.
308 if (FatalErrorOccurred)
309 return;
310
Chris Lattner4b009652007-07-25 00:24:17 +0000311 // Figure out the diagnostic level of this message.
Chris Lattner44b39832009-02-17 06:49:55 +0000312 Diagnostic::Level DiagLevel;
313 unsigned DiagID = Info.getID();
Chris Lattner4b009652007-07-25 00:24:17 +0000314
Chris Lattner44b39832009-02-17 06:49:55 +0000315 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
316 // in a system header.
317 bool ShouldEmitInSystemHeader;
318
319 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
320 // Handle custom diagnostics, which cannot be mapped.
321 DiagLevel = CustomDiagInfo->getLevel(DiagID);
322
323 // Custom diagnostics always are emitted in system headers.
324 ShouldEmitInSystemHeader = true;
325 } else {
326 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
327 // the diagnostic level was for the previous diagnostic so that it is
328 // filtered the same as the previous diagnostic.
329 unsigned DiagClass = getBuiltinDiagClass(DiagID);
330 if (DiagClass == NOTE) {
331 DiagLevel = Diagnostic::Note;
332 ShouldEmitInSystemHeader = false; // extra consideration is needed
333 } else {
334 // If this is not an error and we are in a system header, we ignore it.
335 // Check the original Diag ID here, because we also want to ignore
336 // extensions and warnings in -Werror and -pedantic-errors modes, which
337 // *map* warnings/extensions to errors.
338 ShouldEmitInSystemHeader = DiagClass == ERROR;
339
340 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
341 }
342 }
343
344 if (DiagLevel != Diagnostic::Note)
345 LastDiagLevel = DiagLevel;
346
347 // If the client doesn't care about this message, don't issue it. If this is
348 // a note and the last real diagnostic was ignored, ignore it too.
349 if (DiagLevel == Diagnostic::Ignored ||
350 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Chris Lattner4b009652007-07-25 00:24:17 +0000351 return;
Nico Weberd2a6ac92008-08-10 19:59:06 +0000352
Chris Lattner44b39832009-02-17 06:49:55 +0000353 // If this diagnostic is in a system header and is not a clang error, suppress
354 // it.
355 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner6948ae62008-11-18 07:04:44 +0000356 Info.getLocation().isValid() &&
Chris Lattner44b39832009-02-17 06:49:55 +0000357 Info.getLocation().getSpellingLoc().isInSystemHeader() &&
Chris Lattner724231a2009-02-17 06:52:20 +0000358 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
359 LastDiagLevel = Diagnostic::Ignored;
Chris Lattner84602d72008-02-03 09:00:04 +0000360 return;
Chris Lattner724231a2009-02-17 06:52:20 +0000361 }
Chris Lattner44b39832009-02-17 06:49:55 +0000362
Chris Lattner4b009652007-07-25 00:24:17 +0000363 if (DiagLevel >= Diagnostic::Error) {
364 ErrorOccurred = true;
Chris Lattner6948ae62008-11-18 07:04:44 +0000365 ++NumErrors;
Chris Lattneraab419a2009-02-06 04:16:02 +0000366
367 if (DiagLevel == Diagnostic::Fatal)
368 FatalErrorOccurred = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000369 }
Chris Lattner44b39832009-02-17 06:49:55 +0000370
Chris Lattner4b009652007-07-25 00:24:17 +0000371 // Finally, report it.
Chris Lattner6948ae62008-11-18 07:04:44 +0000372 Client->HandleDiagnostic(DiagLevel, Info);
Ted Kremenek1e1a34b2009-01-23 20:28:53 +0000373 if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
Chris Lattner4b009652007-07-25 00:24:17 +0000374}
375
Nico Weberd2a6ac92008-08-10 19:59:06 +0000376
Chris Lattner4b009652007-07-25 00:24:17 +0000377DiagnosticClient::~DiagnosticClient() {}
Nico Weberd2a6ac92008-08-10 19:59:06 +0000378
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000379
Chris Lattnera7021ee2008-11-21 07:50:02 +0000380/// ModifierIs - Return true if the specified modifier matches specified string.
381template <std::size_t StrLen>
382static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
383 const char (&Str)[StrLen]) {
384 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
385}
386
387/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
388/// like this: %select{foo|bar|baz}2. This means that the integer argument
389/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
390/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
391/// This is very useful for certain classes of variant diagnostics.
392static void HandleSelectModifier(unsigned ValNo,
393 const char *Argument, unsigned ArgumentLen,
394 llvm::SmallVectorImpl<char> &OutStr) {
395 const char *ArgumentEnd = Argument+ArgumentLen;
396
397 // Skip over 'ValNo' |'s.
398 while (ValNo) {
399 const char *NextVal = std::find(Argument, ArgumentEnd, '|');
400 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
401 " larger than the number of options in the diagnostic string!");
402 Argument = NextVal+1; // Skip this string.
403 --ValNo;
404 }
405
406 // Get the end of the value. This is either the } or the |.
407 const char *EndPtr = std::find(Argument, ArgumentEnd, '|');
408 // Add the value to the output string.
409 OutStr.append(Argument, EndPtr);
410}
411
412/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
413/// letter 's' to the string if the value is not 1. This is used in cases like
414/// this: "you idiot, you have %4 parameter%s4!".
415static void HandleIntegerSModifier(unsigned ValNo,
416 llvm::SmallVectorImpl<char> &OutStr) {
417 if (ValNo != 1)
418 OutStr.push_back('s');
419}
420
421
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +0000422/// PluralNumber - Parse an unsigned integer and advance Start.
423static unsigned PluralNumber(const char *&Start, const char *End)
424{
425 // Programming 101: Parse a decimal number :-)
426 unsigned Val = 0;
427 while (Start != End && *Start >= '0' && *Start <= '9') {
428 Val *= 10;
429 Val += *Start - '0';
430 ++Start;
431 }
432 return Val;
433}
434
435/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
436static bool TestPluralRange(unsigned Val, const char *&Start, const char *End)
437{
438 if (*Start != '[') {
439 unsigned Ref = PluralNumber(Start, End);
440 return Ref == Val;
441 }
442
443 ++Start;
444 unsigned Low = PluralNumber(Start, End);
445 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
446 ++Start;
447 unsigned High = PluralNumber(Start, End);
448 assert(*Start == ']' && "Bad plural expression syntax: expected )");
449 ++Start;
450 return Low <= Val && Val <= High;
451}
452
453/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
454static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End)
455{
456 // Empty condition?
457 if (*Start == ':')
458 return true;
459
460 while (1) {
461 char C = *Start;
462 if (C == '%') {
463 // Modulo expression
464 ++Start;
465 unsigned Arg = PluralNumber(Start, End);
466 assert(*Start == '=' && "Bad plural expression syntax: expected =");
467 ++Start;
468 unsigned ValMod = ValNo % Arg;
469 if (TestPluralRange(ValMod, Start, End))
470 return true;
471 } else {
Sebastian Redlc43ec3b2008-11-27 07:28:14 +0000472 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +0000473 "Bad plural expression syntax: unexpected character");
474 // Range expression
475 if (TestPluralRange(ValNo, Start, End))
476 return true;
477 }
478
479 // Scan for next or-expr part.
480 Start = std::find(Start, End, ',');
481 if(Start == End)
482 break;
483 ++Start;
484 }
485 return false;
486}
487
488/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
489/// for complex plural forms, or in languages where all plurals are complex.
490/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
491/// conditions that are tested in order, the form corresponding to the first
492/// that applies being emitted. The empty condition is always true, making the
493/// last form a default case.
494/// Conditions are simple boolean expressions, where n is the number argument.
495/// Here are the rules.
496/// condition := expression | empty
497/// empty := -> always true
498/// expression := numeric [',' expression] -> logical or
499/// numeric := range -> true if n in range
500/// | '%' number '=' range -> true if n % number in range
501/// range := number
502/// | '[' number ',' number ']' -> ranges are inclusive both ends
503///
504/// Here are some examples from the GNU gettext manual written in this form:
505/// English:
506/// {1:form0|:form1}
507/// Latvian:
508/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
509/// Gaeilge:
510/// {1:form0|2:form1|:form2}
511/// Romanian:
512/// {1:form0|0,%100=[1,19]:form1|:form2}
513/// Lithuanian:
514/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
515/// Russian (requires repeated form):
516/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
517/// Slovak
518/// {1:form0|[2,4]:form1|:form2}
519/// Polish (requires repeated form):
520/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
521static void HandlePluralModifier(unsigned ValNo,
522 const char *Argument, unsigned ArgumentLen,
523 llvm::SmallVectorImpl<char> &OutStr)
524{
525 const char *ArgumentEnd = Argument + ArgumentLen;
526 while (1) {
527 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
528 const char *ExprEnd = Argument;
529 while (*ExprEnd != ':') {
530 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
531 ++ExprEnd;
532 }
533 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
534 Argument = ExprEnd + 1;
535 ExprEnd = std::find(Argument, ArgumentEnd, '|');
536 OutStr.append(Argument, ExprEnd);
537 return;
538 }
539 Argument = std::find(Argument, ArgumentEnd - 1, '|') + 1;
540 }
541}
542
543
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000544/// FormatDiagnostic - Format this diagnostic into a string, substituting the
545/// formal arguments into the %0 slots. The result is appended onto the Str
546/// array.
547void DiagnosticInfo::
548FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
549 const char *DiagStr = getDiags()->getDescription(getID());
550 const char *DiagEnd = DiagStr+strlen(DiagStr);
Nico Weberd2a6ac92008-08-10 19:59:06 +0000551
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000552 while (DiagStr != DiagEnd) {
553 if (DiagStr[0] != '%') {
554 // Append non-%0 substrings to Str if we have one.
555 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
556 OutStr.append(DiagStr, StrEnd);
557 DiagStr = StrEnd;
Chris Lattnera7021ee2008-11-21 07:50:02 +0000558 continue;
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000559 } else if (DiagStr[1] == '%') {
560 OutStr.push_back('%'); // %% -> %.
561 DiagStr += 2;
Chris Lattnera7021ee2008-11-21 07:50:02 +0000562 continue;
563 }
564
565 // Skip the %.
566 ++DiagStr;
567
568 // This must be a placeholder for a diagnostic argument. The format for a
569 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
570 // The digit is a number from 0-9 indicating which argument this comes from.
571 // The modifier is a string of digits from the set [-a-z]+, arguments is a
572 // brace enclosed string.
573 const char *Modifier = 0, *Argument = 0;
574 unsigned ModifierLen = 0, ArgumentLen = 0;
575
576 // Check to see if we have a modifier. If so eat it.
577 if (!isdigit(DiagStr[0])) {
578 Modifier = DiagStr;
579 while (DiagStr[0] == '-' ||
580 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
581 ++DiagStr;
582 ModifierLen = DiagStr-Modifier;
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000583
Chris Lattnera7021ee2008-11-21 07:50:02 +0000584 // If we have an argument, get it next.
585 if (DiagStr[0] == '{') {
586 ++DiagStr; // Skip {.
587 Argument = DiagStr;
588
589 for (; DiagStr[0] != '}'; ++DiagStr)
590 assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!");
591 ArgumentLen = DiagStr-Argument;
592 ++DiagStr; // Skip }.
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000593 }
Chris Lattnera7021ee2008-11-21 07:50:02 +0000594 }
595
596 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattnerda5c0872008-11-23 09:13:29 +0000597 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattnera7021ee2008-11-21 07:50:02 +0000598
Chris Lattnerda5c0872008-11-23 09:13:29 +0000599 switch (getArgKind(ArgNo)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000600 // ---- STRINGS ----
Chris Lattner9943e982008-11-22 00:59:29 +0000601 case Diagnostic::ak_std_string: {
Chris Lattnerda5c0872008-11-23 09:13:29 +0000602 const std::string &S = getArgStdStr(ArgNo);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000603 assert(ModifierLen == 0 && "No modifiers for strings yet");
604 OutStr.append(S.begin(), S.end());
605 break;
606 }
Chris Lattner9943e982008-11-22 00:59:29 +0000607 case Diagnostic::ak_c_string: {
Chris Lattnerda5c0872008-11-23 09:13:29 +0000608 const char *S = getArgCStr(ArgNo);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000609 assert(ModifierLen == 0 && "No modifiers for strings yet");
610 OutStr.append(S, S + strlen(S));
611 break;
612 }
Chris Lattnerb1753422008-11-23 21:45:46 +0000613 // ---- INTEGERS ----
Chris Lattner9943e982008-11-22 00:59:29 +0000614 case Diagnostic::ak_sint: {
Chris Lattnerda5c0872008-11-23 09:13:29 +0000615 int Val = getArgSInt(ArgNo);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000616
617 if (ModifierIs(Modifier, ModifierLen, "select")) {
618 HandleSelectModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
619 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
620 HandleIntegerSModifier(Val, OutStr);
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +0000621 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
622 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000623 } else {
624 assert(ModifierLen == 0 && "Unknown integer modifier");
Chris Lattner68f621c2008-11-19 07:22:31 +0000625 // FIXME: Optimize
Chris Lattnera7021ee2008-11-21 07:50:02 +0000626 std::string S = llvm::itostr(Val);
Chris Lattner68f621c2008-11-19 07:22:31 +0000627 OutStr.append(S.begin(), S.end());
Chris Lattner68f621c2008-11-19 07:22:31 +0000628 }
Chris Lattnera7021ee2008-11-21 07:50:02 +0000629 break;
630 }
Chris Lattner9943e982008-11-22 00:59:29 +0000631 case Diagnostic::ak_uint: {
Chris Lattnerda5c0872008-11-23 09:13:29 +0000632 unsigned Val = getArgUInt(ArgNo);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000633
634 if (ModifierIs(Modifier, ModifierLen, "select")) {
635 HandleSelectModifier(Val, Argument, ArgumentLen, OutStr);
636 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
637 HandleIntegerSModifier(Val, OutStr);
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +0000638 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
639 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattnera7021ee2008-11-21 07:50:02 +0000640 } else {
641 assert(ModifierLen == 0 && "Unknown integer modifier");
642
Chris Lattner68f621c2008-11-19 07:22:31 +0000643 // FIXME: Optimize
Chris Lattnera7021ee2008-11-21 07:50:02 +0000644 std::string S = llvm::utostr_32(Val);
Chris Lattner68f621c2008-11-19 07:22:31 +0000645 OutStr.append(S.begin(), S.end());
Chris Lattner68f621c2008-11-19 07:22:31 +0000646 }
Chris Lattnerda5c0872008-11-23 09:13:29 +0000647 break;
Chris Lattnera7021ee2008-11-21 07:50:02 +0000648 }
Chris Lattnerb1753422008-11-23 21:45:46 +0000649 // ---- NAMES and TYPES ----
650 case Diagnostic::ak_identifierinfo: {
Chris Lattnerb1753422008-11-23 21:45:46 +0000651 const IdentifierInfo *II = getArgIdentifier(ArgNo);
652 assert(ModifierLen == 0 && "No modifiers for strings yet");
Chris Lattner2bd4a5a2009-02-19 23:45:49 +0000653 OutStr.push_back('\'');
Chris Lattnerb1753422008-11-23 21:45:46 +0000654 OutStr.append(II->getName(), II->getName() + II->getLength());
655 OutStr.push_back('\'');
656 break;
657 }
Chris Lattnerda5c0872008-11-23 09:13:29 +0000658 case Diagnostic::ak_qualtype:
Chris Lattner254de7d2008-11-23 20:28:15 +0000659 case Diagnostic::ak_declarationname:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000660 case Diagnostic::ak_nameddecl:
Chris Lattnerf5b269a2008-11-23 09:21:17 +0000661 getDiags()->ConvertArgToString(getArgKind(ArgNo), getRawArg(ArgNo),
662 Modifier, ModifierLen,
663 Argument, ArgumentLen, OutStr);
Chris Lattnerda5c0872008-11-23 09:13:29 +0000664 break;
Nico Weberd2a6ac92008-08-10 19:59:06 +0000665 }
666 }
Nico Weberd2a6ac92008-08-10 19:59:06 +0000667}
Ted Kremenek1e1a34b2009-01-23 20:28:53 +0000668
669/// IncludeInDiagnosticCounts - This method (whose default implementation
670/// returns true) indicates whether the diagnostics handled by this
671/// DiagnosticClient should be included in the number of diagnostics
672/// reported by Diagnostic.
673bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }