blob: 0dc57e4ecbf4a2ce9cfe0c9d04950d67215c1ad4 [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
Chris Lattner27ceb9d2009-04-15 07:01:18 +000014#include "clang/AST/ASTDiagnostic.h"
Chris Lattner27ceb9d2009-04-15 07:01:18 +000015#include "clang/Analysis/AnalysisDiagnostic.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregord93256e2010-01-28 06:00:51 +000017#include "clang/Basic/FileManager.h"
Chris Lattner43b628c2008-11-19 07:32:16 +000018#include "clang/Basic/IdentifierTable.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000019#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Basic/SourceLocation.h"
Douglas Gregord93256e2010-01-28 06:00:51 +000021#include "clang/Basic/SourceManager.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000022#include "clang/Driver/DriverDiagnostic.h"
23#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Lex/LexDiagnostic.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Sema/SemaDiagnostic.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattner30bc9652008-11-19 07:22:31 +000028#include "llvm/ADT/StringExtras.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000029#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar23e47c62009-10-17 18:12:14 +000030#include "llvm/Support/raw_ostream.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000031
Chris Lattner182745a2007-12-02 01:09:57 +000032#include <vector>
33#include <map>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000034#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Chris Lattner182745a2007-12-02 01:09:57 +000037//===----------------------------------------------------------------------===//
38// Builtin Diagnostic information
39//===----------------------------------------------------------------------===//
40
Dan Gohman3c46e8d2010-07-26 21:25:24 +000041namespace {
42
Chris Lattner121f60c2009-04-16 06:07:15 +000043// Diagnostic classes.
44enum {
45 CLASS_NOTE = 0x01,
46 CLASS_WARNING = 0x02,
47 CLASS_EXTENSION = 0x03,
48 CLASS_ERROR = 0x04
49};
Chris Lattner27ceb9d2009-04-15 07:01:18 +000050
Chris Lattner33dd2822009-04-16 06:00:24 +000051struct StaticDiagInfoRec {
Chris Lattner121f60c2009-04-16 06:07:15 +000052 unsigned short DiagID;
53 unsigned Mapping : 3;
54 unsigned Class : 3;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000055 bool SFINAE : 1;
Chris Lattner27b0f512010-05-04 20:44:26 +000056 unsigned Category : 5;
57
Chris Lattner121f60c2009-04-16 06:07:15 +000058 const char *Description;
Chris Lattner33dd2822009-04-16 06:00:24 +000059 const char *OptionGroup;
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner87d854e2009-04-16 06:13:46 +000061 bool operator<(const StaticDiagInfoRec &RHS) const {
62 return DiagID < RHS.DiagID;
63 }
64 bool operator>(const StaticDiagInfoRec &RHS) const {
65 return DiagID > RHS.DiagID;
66 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +000067};
68
Dan Gohman3c46e8d2010-07-26 21:25:24 +000069}
70
Chris Lattner33dd2822009-04-16 06:00:24 +000071static const StaticDiagInfoRec StaticDiagInfo[] = {
Chris Lattner27b0f512010-05-04 20:44:26 +000072#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY) \
73 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP },
Chris Lattner27ceb9d2009-04-15 07:01:18 +000074#include "clang/Basic/DiagnosticCommonKinds.inc"
75#include "clang/Basic/DiagnosticDriverKinds.inc"
76#include "clang/Basic/DiagnosticFrontendKinds.inc"
77#include "clang/Basic/DiagnosticLexKinds.inc"
78#include "clang/Basic/DiagnosticParseKinds.inc"
79#include "clang/Basic/DiagnosticASTKinds.inc"
80#include "clang/Basic/DiagnosticSemaKinds.inc"
81#include "clang/Basic/DiagnosticAnalysisKinds.inc"
Chris Lattner27b0f512010-05-04 20:44:26 +000082 { 0, 0, 0, 0, 0, 0, 0}
Chris Lattner27ceb9d2009-04-15 07:01:18 +000083};
Chris Lattner8a941e02009-04-15 16:56:26 +000084#undef DIAG
Chris Lattner27ceb9d2009-04-15 07:01:18 +000085
Chris Lattner87d854e2009-04-16 06:13:46 +000086/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
87/// or null if the ID is invalid.
Chris Lattner33dd2822009-04-16 06:00:24 +000088static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
Chris Lattner87d854e2009-04-16 06:13:46 +000089 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
90
91 // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
92#ifndef NDEBUG
93 static bool IsFirst = true;
94 if (IsFirst) {
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000095 for (unsigned i = 1; i != NumDiagEntries; ++i) {
96 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
97 "Diag ID conflict, the enums at the start of clang::diag (in "
98 "Diagnostic.h) probably need to be increased");
99
Chris Lattner87d854e2009-04-16 06:13:46 +0000100 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
101 "Improperly sorted diag info");
Chris Lattner5a3ce9b2009-10-16 02:34:51 +0000102 }
Chris Lattner87d854e2009-04-16 06:13:46 +0000103 IsFirst = false;
104 }
105#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner87d854e2009-04-16 06:13:46 +0000107 // Search the diagnostic table with a binary search.
Chris Lattner27b0f512010-05-04 20:44:26 +0000108 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 };
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattner87d854e2009-04-16 06:13:46 +0000110 const StaticDiagInfoRec *Found =
111 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
112 if (Found == StaticDiagInfo + NumDiagEntries ||
113 Found->DiagID != DiagID)
114 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Chris Lattner87d854e2009-04-16 06:13:46 +0000116 return Found;
Chris Lattner33dd2822009-04-16 06:00:24 +0000117}
118
119static unsigned GetDefaultDiagMapping(unsigned DiagID) {
120 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Chris Lattner121f60c2009-04-16 06:07:15 +0000121 return Info->Mapping;
Chris Lattner691f1ae2009-04-16 04:12:40 +0000122 return diag::MAP_FATAL;
123}
124
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000125/// getWarningOptionForDiag - Return the lowest-level warning option that
126/// enables the specified diagnostic. If there is no -Wfoo flag that controls
127/// the diagnostic, this returns null.
128const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
Chris Lattner33dd2822009-04-16 06:00:24 +0000129 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
130 return Info->OptionGroup;
131 return 0;
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000132}
133
Chris Lattnerc9b88902010-05-04 21:13:21 +0000134/// getWarningOptionForDiag - Return the category number that a specified
135/// DiagID belongs to, or 0 if no category.
136unsigned Diagnostic::getCategoryNumberForDiag(unsigned DiagID) {
137 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
138 return Info->Category;
139 return 0;
140}
141
142/// getCategoryNameFromID - Given a category ID, return the name of the
143/// category, an empty string if CategoryID is zero, or null if CategoryID is
144/// invalid.
145const char *Diagnostic::getCategoryNameFromID(unsigned CategoryID) {
146 // Second the table of options, sorted by name for fast binary lookup.
147 static const char *CategoryNameTable[] = {
148#define GET_CATEGORY_TABLE
149#define CATEGORY(X) X,
150#include "clang/Basic/DiagnosticGroups.inc"
151#undef GET_CATEGORY_TABLE
152 "<<END>>"
153 };
154 static const size_t CategoryNameTableSize =
155 sizeof(CategoryNameTable) / sizeof(CategoryNameTable[0])-1;
156
157 if (CategoryID >= CategoryNameTableSize) return 0;
158 return CategoryNameTable[CategoryID];
159}
160
161
162
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000163Diagnostic::SFINAEResponse
164Diagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) {
165 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) {
166 if (!Info->SFINAE)
167 return SFINAE_Report;
168
169 if (Info->Class == CLASS_ERROR)
170 return SFINAE_SubstitutionFailure;
171
172 // Suppress notes, warnings, and extensions;
173 return SFINAE_Suppress;
174 }
175
176 return SFINAE_Report;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000177}
178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179/// getDiagClass - Return the class field of the diagnostic.
180///
Chris Lattner07506182007-11-30 22:53:43 +0000181static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner121f60c2009-04-16 06:07:15 +0000182 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
183 return Info->Class;
184 return ~0U;
Reid Spencer5f016e22007-07-11 17:01:13 +0000185}
186
Chris Lattner182745a2007-12-02 01:09:57 +0000187//===----------------------------------------------------------------------===//
188// Custom Diagnostic information
189//===----------------------------------------------------------------------===//
190
191namespace clang {
192 namespace diag {
193 class CustomDiagInfo {
194 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
195 std::vector<DiagDesc> DiagInfo;
196 std::map<DiagDesc, unsigned> DiagIDs;
197 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner182745a2007-12-02 01:09:57 +0000199 /// getDescription - Return the description of the specified custom
200 /// diagnostic.
201 const char *getDescription(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000202 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000203 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000204 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner182745a2007-12-02 01:09:57 +0000205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattner182745a2007-12-02 01:09:57 +0000207 /// getLevel - Return the level of the specified custom diagnostic.
208 Diagnostic::Level getLevel(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000209 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000210 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000211 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner182745a2007-12-02 01:09:57 +0000212 }
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000214 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000215 Diagnostic &Diags) {
Chris Lattner182745a2007-12-02 01:09:57 +0000216 DiagDesc D(L, Message);
217 // Check to see if it already exists.
218 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
219 if (I != DiagIDs.end() && I->first == D)
220 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattner182745a2007-12-02 01:09:57 +0000222 // If not, assign a new ID.
Chris Lattner88eccaf2009-01-29 06:55:46 +0000223 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner182745a2007-12-02 01:09:57 +0000224 DiagIDs.insert(std::make_pair(D, ID));
225 DiagInfo.push_back(D);
226 return ID;
227 }
228 };
Mike Stump1eb44332009-09-09 15:08:12 +0000229
230 } // end diag namespace
231} // end clang namespace
Chris Lattner182745a2007-12-02 01:09:57 +0000232
233
234//===----------------------------------------------------------------------===//
235// Common Diagnostic implementation
236//===----------------------------------------------------------------------===//
237
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000238static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
239 const char *Modifier, unsigned ML,
240 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000241 const Diagnostic::ArgumentValue *PrevArgs,
242 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +0000243 llvm::SmallVectorImpl<char> &Output,
244 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000245 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +0000246 Output.append(Str, Str+strlen(Str));
247}
248
249
Ted Kremenekb4398aa2008-08-07 17:49:57 +0000250Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000251 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +0000252 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000254 AllExtensionsSilenced = 0;
255 IgnoreAllWarnings = false;
256 WarningsAsErrors = false;
257 ErrorsAsFatal = false;
258 SuppressSystemWarnings = false;
259 SuppressAllDiagnostics = false;
260 ShowOverloads = Ovl_All;
261 ExtBehavior = Ext_Ignore;
262
263 ErrorLimit = 0;
264 TemplateBacktraceLimit = 0;
265 CustomDiagInfo = 0;
266
267 // Set all mappings to 'unset'.
268 DiagMappingsStack.clear();
269 DiagMappingsStack.push_back(DiagMappings());
270
Douglas Gregorabc563f2010-07-19 21:46:24 +0000271 Reset();
Reid Spencer5f016e22007-07-11 17:01:13 +0000272}
273
Chris Lattner182745a2007-12-02 01:09:57 +0000274Diagnostic::~Diagnostic() {
275 delete CustomDiagInfo;
276}
277
Chris Lattner04ae2df2009-07-12 21:18:45 +0000278
279void Diagnostic::pushMappings() {
John Thompsonca2c3e22009-10-23 02:21:17 +0000280 // Avoids undefined behavior when the stack has to resize.
281 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000282 DiagMappingsStack.push_back(DiagMappingsStack.back());
283}
284
285bool Diagnostic::popMappings() {
286 if (DiagMappingsStack.size() == 1)
287 return false;
288
289 DiagMappingsStack.pop_back();
290 return true;
291}
292
Chris Lattner182745a2007-12-02 01:09:57 +0000293/// getCustomDiagID - Return an ID for a diagnostic with the specified message
294/// and level. If this is the first request for this diagnosic, it is
295/// registered and created, otherwise the existing ID is returned.
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000296unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
Mike Stump1eb44332009-09-09 15:08:12 +0000297 if (CustomDiagInfo == 0)
Chris Lattner182745a2007-12-02 01:09:57 +0000298 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000299 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner182745a2007-12-02 01:09:57 +0000300}
301
302
Chris Lattnerf5d23282009-02-17 06:49:55 +0000303/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
304/// level of the specified diagnostic ID is a Warning or Extension.
305/// This only works on builtin diagnostics, not custom ones, and is not legal to
306/// call on NOTEs.
307bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000308 return DiagID < diag::DIAG_UPPER_LIMIT &&
309 getBuiltinDiagClass(DiagID) != CLASS_ERROR;
Reid Spencer5f016e22007-07-11 17:01:13 +0000310}
311
Douglas Gregoree1828a2009-03-10 18:03:33 +0000312/// \brief Determine whether the given built-in diagnostic ID is a
313/// Note.
314bool Diagnostic::isBuiltinNote(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000315 return DiagID < diag::DIAG_UPPER_LIMIT &&
316 getBuiltinDiagClass(DiagID) == CLASS_NOTE;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000317}
318
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000319/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
Chris Lattner04e44272010-04-12 21:53:11 +0000320/// ID is for an extension of some sort. This also returns EnabledByDefault,
321/// which is set to indicate whether the diagnostic is ignored by default (in
322/// which case -pedantic enables it) or treated as a warning/error by default.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000323///
Chris Lattner04e44272010-04-12 21:53:11 +0000324bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID,
325 bool &EnabledByDefault) {
326 if (DiagID >= diag::DIAG_UPPER_LIMIT ||
327 getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
328 return false;
329
330 EnabledByDefault = StaticDiagInfo[DiagID].Mapping != diag::MAP_IGNORE;
331 return true;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000332}
333
Douglas Gregorabc563f2010-07-19 21:46:24 +0000334void Diagnostic::Reset() {
Douglas Gregorabc563f2010-07-19 21:46:24 +0000335 ErrorOccurred = false;
336 FatalErrorOccurred = false;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000337
338 NumWarnings = 0;
339 NumErrors = 0;
340 NumErrorsSuppressed = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000341 CurDiagID = ~0U;
342 LastDiagLevel = Ignored;
343 DelayedDiagID = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000344}
Reid Spencer5f016e22007-07-11 17:01:13 +0000345
346/// getDescription - Given a diagnostic ID, return a description of the
347/// issue.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000348const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattner121f60c2009-04-16 06:07:15 +0000349 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
350 return Info->Description;
Chris Lattner20c6b3b2009-01-27 18:30:58 +0000351 return CustomDiagInfo->getDescription(DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000354void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
355 llvm::StringRef Arg2) {
356 if (DelayedDiagID)
357 return;
358
359 DelayedDiagID = DiagID;
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000360 DelayedDiagArg1 = Arg1.str();
361 DelayedDiagArg2 = Arg2.str();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000362}
363
364void Diagnostic::ReportDelayed() {
365 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
366 DelayedDiagID = 0;
367 DelayedDiagArg1.clear();
368 DelayedDiagArg2.clear();
369}
370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
372/// object, classify the specified diagnostic ID into a Level, consumable by
373/// the DiagnosticClient.
374Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner182745a2007-12-02 01:09:57 +0000375 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000376 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner182745a2007-12-02 01:09:57 +0000377 return CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner07506182007-11-30 22:53:43 +0000379 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000380 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
Chris Lattnerf5d23282009-02-17 06:49:55 +0000381 return getDiagnosticLevel(DiagID, DiagClass);
382}
383
384/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
385/// object, classify the specified diagnostic ID into a Level, consumable by
386/// the DiagnosticClient.
387Diagnostic::Level
388Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattnerf5d23282009-02-17 06:49:55 +0000390 // to error. Errors can only be mapped to fatal.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000391 Diagnostic::Level Result = Diagnostic::Fatal;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner691f1ae2009-04-16 04:12:40 +0000393 // Get the mapping information, if unset, compute it lazily.
394 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
395 if (MappingInfo == 0) {
396 MappingInfo = GetDefaultDiagMapping(DiagID);
397 setDiagnosticMappingInternal(DiagID, MappingInfo, false);
398 }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner691f1ae2009-04-16 04:12:40 +0000400 switch (MappingInfo & 7) {
401 default: assert(0 && "Unknown mapping!");
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000402 case diag::MAP_IGNORE:
Chris Lattnerb54b2762009-04-16 05:04:32 +0000403 // Ignore this, unless this is an extension diagnostic and we're mapping
404 // them onto warnings or errors.
405 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension
406 ExtBehavior == Ext_Ignore || // Extensions ignored anyway
407 (MappingInfo & 8) != 0) // User explicitly mapped it.
408 return Diagnostic::Ignored;
409 Result = Diagnostic::Warning;
410 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000411 if (Result == Diagnostic::Error && ErrorsAsFatal)
412 Result = Diagnostic::Fatal;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000413 break;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000414 case diag::MAP_ERROR:
415 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000416 if (ErrorsAsFatal)
417 Result = Diagnostic::Fatal;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000418 break;
419 case diag::MAP_FATAL:
420 Result = Diagnostic::Fatal;
421 break;
422 case diag::MAP_WARNING:
423 // If warnings are globally mapped to ignore or error, do it.
Chris Lattner5b4681c2008-05-29 15:36:45 +0000424 if (IgnoreAllWarnings)
425 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000427 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattnerb54b2762009-04-16 05:04:32 +0000429 // If this is an extension diagnostic and we're in -pedantic-error mode, and
430 // if the user didn't explicitly map it, upgrade to an error.
431 if (ExtBehavior == Ext_Error &&
432 (MappingInfo & 8) == 0 &&
433 isBuiltinExtensionDiag(DiagID))
434 Result = Diagnostic::Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000436 if (WarningsAsErrors)
437 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000438 if (Result == Diagnostic::Error && ErrorsAsFatal)
439 Result = Diagnostic::Fatal;
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000440 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000442 case diag::MAP_WARNING_NO_WERROR:
443 // Diagnostics specified with -Wno-error=foo should be set to warnings, but
444 // not be adjusted by -Werror or -pedantic-errors.
445 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000447 // If warnings are globally mapped to ignore or error, do it.
448 if (IgnoreAllWarnings)
449 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000451 break;
Chris Lattnere663c722009-12-22 23:12:53 +0000452
453 case diag::MAP_ERROR_NO_WFATAL:
454 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
455 // unaffected by -Wfatal-errors.
456 Result = Diagnostic::Error;
457 break;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000458 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000459
460 // Okay, we're about to return this as a "diagnostic to emit" one last check:
461 // if this is any sort of extension warning, and if we're in an __extension__
462 // block, silence it.
463 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
464 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000466 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
468
Chris Lattner3bc172b2009-04-19 22:34:23 +0000469struct WarningOption {
470 const char *Name;
471 const short *Members;
Chandler Carruth5ef12b32010-05-13 07:43:05 +0000472 const short *SubGroups;
Chris Lattner3bc172b2009-04-19 22:34:23 +0000473};
474
475#define GET_DIAG_ARRAYS
476#include "clang/Basic/DiagnosticGroups.inc"
477#undef GET_DIAG_ARRAYS
478
479// Second the table of options, sorted by name for fast binary lookup.
480static const WarningOption OptionTable[] = {
481#define GET_DIAG_TABLE
482#include "clang/Basic/DiagnosticGroups.inc"
483#undef GET_DIAG_TABLE
484};
485static const size_t OptionTableSize =
486sizeof(OptionTable) / sizeof(OptionTable[0]);
487
488static bool WarningOptionCompare(const WarningOption &LHS,
489 const WarningOption &RHS) {
490 return strcmp(LHS.Name, RHS.Name) < 0;
491}
492
493static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
494 Diagnostic &Diags) {
495 // Option exists, poke all the members of its diagnostic set.
496 if (const short *Member = Group->Members) {
497 for (; *Member != -1; ++Member)
498 Diags.setDiagnosticMapping(*Member, Mapping);
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner3bc172b2009-04-19 22:34:23 +0000501 // Enable/disable all subgroups along with this one.
Chandler Carruth5ef12b32010-05-13 07:43:05 +0000502 if (const short *SubGroups = Group->SubGroups) {
503 for (; *SubGroups != (short)-1; ++SubGroups)
504 MapGroupMembers(&OptionTable[(short)*SubGroups], Mapping, Diags);
Chris Lattner3bc172b2009-04-19 22:34:23 +0000505 }
506}
507
508/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
509/// "unknown-pragmas" to have the specified mapping. This returns true and
510/// ignores the request if "Group" was unknown, false otherwise.
511bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
512 diag::Mapping Map) {
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattner3bc172b2009-04-19 22:34:23 +0000514 WarningOption Key = { Group, 0, 0 };
515 const WarningOption *Found =
516 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
517 WarningOptionCompare);
518 if (Found == OptionTable + OptionTableSize ||
519 strcmp(Found->Name, Group) != 0)
520 return true; // Option not found.
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner3bc172b2009-04-19 22:34:23 +0000522 MapGroupMembers(Found, Map, *this);
523 return false;
524}
525
526
Chris Lattner0a14eee2008-11-18 07:04:44 +0000527/// ProcessDiag - This is the method used to report a diagnostic that is
528/// finally fully formed.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000529bool Diagnostic::ProcessDiag() {
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000530 DiagnosticInfo Info(this);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor81b747b2009-09-17 21:32:03 +0000532 if (SuppressAllDiagnostics)
533 return false;
534
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 // Figure out the diagnostic level of this message.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000536 Diagnostic::Level DiagLevel;
537 unsigned DiagID = Info.getID();
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattnerf5d23282009-02-17 06:49:55 +0000539 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
540 // in a system header.
541 bool ShouldEmitInSystemHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattnerf5d23282009-02-17 06:49:55 +0000543 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
544 // Handle custom diagnostics, which cannot be mapped.
545 DiagLevel = CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattnerf5d23282009-02-17 06:49:55 +0000547 // Custom diagnostics always are emitted in system headers.
548 ShouldEmitInSystemHeader = true;
549 } else {
550 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
551 // the diagnostic level was for the previous diagnostic so that it is
552 // filtered the same as the previous diagnostic.
553 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000554 if (DiagClass == CLASS_NOTE) {
Chris Lattnerf5d23282009-02-17 06:49:55 +0000555 DiagLevel = Diagnostic::Note;
556 ShouldEmitInSystemHeader = false; // extra consideration is needed
557 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // If this is not an error and we are in a system header, we ignore it.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000559 // Check the original Diag ID here, because we also want to ignore
560 // extensions and warnings in -Werror and -pedantic-errors modes, which
561 // *map* warnings/extensions to errors.
Chris Lattner8a941e02009-04-15 16:56:26 +0000562 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattnerf5d23282009-02-17 06:49:55 +0000564 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
565 }
566 }
567
Douglas Gregor525c4b02009-03-19 18:55:06 +0000568 if (DiagLevel != Diagnostic::Note) {
569 // Record that a fatal error occurred only when we see a second
570 // non-note diagnostic. This allows notes to be attached to the
571 // fatal error, but suppresses any diagnostics that follow those
572 // notes.
573 if (LastDiagLevel == Diagnostic::Fatal)
574 FatalErrorOccurred = true;
575
Chris Lattnerf5d23282009-02-17 06:49:55 +0000576 LastDiagLevel = DiagLevel;
Mike Stump1eb44332009-09-09 15:08:12 +0000577 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000578
579 // If a fatal error has already been emitted, silence all subsequent
580 // diagnostics.
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000581 if (FatalErrorOccurred) {
582 if (DiagLevel >= Diagnostic::Error) {
583 ++NumErrors;
584 ++NumErrorsSuppressed;
585 }
586
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000587 return false;
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000588 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000589
Chris Lattnerf5d23282009-02-17 06:49:55 +0000590 // If the client doesn't care about this message, don't issue it. If this is
591 // a note and the last real diagnostic was ignored, ignore it too.
592 if (DiagLevel == Diagnostic::Ignored ||
593 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000594 return false;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000595
Chris Lattnerf5d23282009-02-17 06:49:55 +0000596 // If this diagnostic is in a system header and is not a clang error, suppress
597 // it.
598 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner0a14eee2008-11-18 07:04:44 +0000599 Info.getLocation().isValid() &&
John McCall779cf422010-02-11 10:04:29 +0000600 Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
Chris Lattner336f26b2009-02-17 06:52:20 +0000601 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
602 LastDiagLevel = Diagnostic::Ignored;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000603 return false;
Chris Lattner336f26b2009-02-17 06:52:20 +0000604 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000605
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 if (DiagLevel >= Diagnostic::Error) {
607 ErrorOccurred = true;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000608 ++NumErrors;
Chris Lattnerb205ac92010-04-07 20:21:58 +0000609
610 // If we've emitted a lot of errors, emit a fatal error after it to stop a
611 // flood of bogus errors.
Chris Lattnerc1002142010-04-07 20:37:06 +0000612 if (ErrorLimit && NumErrors >= ErrorLimit &&
Chris Lattnerb205ac92010-04-07 20:21:58 +0000613 DiagLevel == Diagnostic::Error)
614 SetDelayedDiagnostic(diag::fatal_too_many_errors);
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 }
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 // Finally, report it.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000618 Client->HandleDiagnostic(DiagLevel, Info);
Chris Lattner53eee7b2010-04-07 18:47:42 +0000619 if (Client->IncludeInDiagnosticCounts()) {
620 if (DiagLevel == Diagnostic::Warning)
621 ++NumWarnings;
622 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000623
Douglas Gregoree1828a2009-03-10 18:03:33 +0000624 CurDiagID = ~0U;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000625
626 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000627}
628
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000629bool DiagnosticBuilder::Emit() {
630 // If DiagObj is null, then its soul was stolen by the copy ctor
631 // or the user called Emit().
632 if (DiagObj == 0) return false;
633
634 // When emitting diagnostics, we set the final argument count into
635 // the Diagnostic object.
636 DiagObj->NumDiagArgs = NumArgs;
637 DiagObj->NumDiagRanges = NumRanges;
Douglas Gregor849b2432010-03-31 17:46:05 +0000638 DiagObj->NumFixItHints = NumFixItHints;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000639
640 // Process the diagnostic, sending the accumulated information to the
641 // DiagnosticClient.
642 bool Emitted = DiagObj->ProcessDiag();
643
644 // Clear out the current diagnostic object.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000645 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000646 DiagObj->Clear();
647
648 // If there was a delayed diagnostic, emit it now.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000649 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000650 DiagObj->ReportDelayed();
651
652 // This diagnostic is dead.
653 DiagObj = 0;
654
655 return Emitted;
656}
657
Nico Weber7bfaaae2008-08-10 19:59:06 +0000658
Reid Spencer5f016e22007-07-11 17:01:13 +0000659DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000660
Chris Lattnerf4c83962008-11-19 06:51:40 +0000661
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000662/// ModifierIs - Return true if the specified modifier matches specified string.
663template <std::size_t StrLen>
664static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
665 const char (&Str)[StrLen]) {
666 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
667}
668
John McCall909c1822010-01-14 20:11:39 +0000669/// ScanForward - Scans forward, looking for the given character, skipping
670/// nested clauses and escaped characters.
671static const char *ScanFormat(const char *I, const char *E, char Target) {
672 unsigned Depth = 0;
673
674 for ( ; I != E; ++I) {
675 if (Depth == 0 && *I == Target) return I;
676 if (Depth != 0 && *I == '}') Depth--;
677
678 if (*I == '%') {
679 I++;
680 if (I == E) break;
681
682 // Escaped characters get implicitly skipped here.
683
684 // Format specifier.
685 if (!isdigit(*I) && !ispunct(*I)) {
686 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
687 if (I == E) break;
688 if (*I == '{')
689 Depth++;
690 }
691 }
692 }
693 return E;
694}
695
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000696/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
697/// like this: %select{foo|bar|baz}2. This means that the integer argument
698/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
699/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
700/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000701static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000702 const char *Argument, unsigned ArgumentLen,
703 llvm::SmallVectorImpl<char> &OutStr) {
704 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000706 // Skip over 'ValNo' |'s.
707 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000708 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000709 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
710 " larger than the number of options in the diagnostic string!");
711 Argument = NextVal+1; // Skip this string.
712 --ValNo;
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000715 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000716 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000717
718 // Recursively format the result of the select clause into the output string.
719 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000720}
721
722/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
723/// letter 's' to the string if the value is not 1. This is used in cases like
724/// this: "you idiot, you have %4 parameter%s4!".
725static void HandleIntegerSModifier(unsigned ValNo,
726 llvm::SmallVectorImpl<char> &OutStr) {
727 if (ValNo != 1)
728 OutStr.push_back('s');
729}
730
John McCall3be16b72010-01-14 00:50:32 +0000731/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
732/// prints the ordinal form of the given integer, with 1 corresponding
733/// to the first ordinal. Currently this is hard-coded to use the
734/// English form.
735static void HandleOrdinalModifier(unsigned ValNo,
736 llvm::SmallVectorImpl<char> &OutStr) {
737 assert(ValNo != 0 && "ValNo must be strictly positive!");
738
739 llvm::raw_svector_ostream Out(OutStr);
740
741 // We could use text forms for the first N ordinals, but the numeric
742 // forms are actually nicer in diagnostics because they stand out.
743 Out << ValNo;
744
745 // It is critically important that we do this perfectly for
746 // user-written sequences with over 100 elements.
747 switch (ValNo % 100) {
748 case 11:
749 case 12:
750 case 13:
751 Out << "th"; return;
752 default:
753 switch (ValNo % 10) {
754 case 1: Out << "st"; return;
755 case 2: Out << "nd"; return;
756 case 3: Out << "rd"; return;
757 default: Out << "th"; return;
758 }
759 }
760}
761
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000762
Sebastian Redle4c452c2008-11-22 13:44:36 +0000763/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000764static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000765 // Programming 101: Parse a decimal number :-)
766 unsigned Val = 0;
767 while (Start != End && *Start >= '0' && *Start <= '9') {
768 Val *= 10;
769 Val += *Start - '0';
770 ++Start;
771 }
772 return Val;
773}
774
775/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000776static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000777 if (*Start != '[') {
778 unsigned Ref = PluralNumber(Start, End);
779 return Ref == Val;
780 }
781
782 ++Start;
783 unsigned Low = PluralNumber(Start, End);
784 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
785 ++Start;
786 unsigned High = PluralNumber(Start, End);
787 assert(*Start == ']' && "Bad plural expression syntax: expected )");
788 ++Start;
789 return Low <= Val && Val <= High;
790}
791
792/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000793static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000794 // Empty condition?
795 if (*Start == ':')
796 return true;
797
798 while (1) {
799 char C = *Start;
800 if (C == '%') {
801 // Modulo expression
802 ++Start;
803 unsigned Arg = PluralNumber(Start, End);
804 assert(*Start == '=' && "Bad plural expression syntax: expected =");
805 ++Start;
806 unsigned ValMod = ValNo % Arg;
807 if (TestPluralRange(ValMod, Start, End))
808 return true;
809 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000810 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000811 "Bad plural expression syntax: unexpected character");
812 // Range expression
813 if (TestPluralRange(ValNo, Start, End))
814 return true;
815 }
816
817 // Scan for next or-expr part.
818 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000819 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000820 break;
821 ++Start;
822 }
823 return false;
824}
825
826/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
827/// for complex plural forms, or in languages where all plurals are complex.
828/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
829/// conditions that are tested in order, the form corresponding to the first
830/// that applies being emitted. The empty condition is always true, making the
831/// last form a default case.
832/// Conditions are simple boolean expressions, where n is the number argument.
833/// Here are the rules.
834/// condition := expression | empty
835/// empty := -> always true
836/// expression := numeric [',' expression] -> logical or
837/// numeric := range -> true if n in range
838/// | '%' number '=' range -> true if n % number in range
839/// range := number
840/// | '[' number ',' number ']' -> ranges are inclusive both ends
841///
842/// Here are some examples from the GNU gettext manual written in this form:
843/// English:
844/// {1:form0|:form1}
845/// Latvian:
846/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
847/// Gaeilge:
848/// {1:form0|2:form1|:form2}
849/// Romanian:
850/// {1:form0|0,%100=[1,19]:form1|:form2}
851/// Lithuanian:
852/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
853/// Russian (requires repeated form):
854/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
855/// Slovak
856/// {1:form0|[2,4]:form1|:form2}
857/// Polish (requires repeated form):
858/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
859static void HandlePluralModifier(unsigned ValNo,
860 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000861 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000862 const char *ArgumentEnd = Argument + ArgumentLen;
863 while (1) {
864 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
865 const char *ExprEnd = Argument;
866 while (*ExprEnd != ':') {
867 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
868 ++ExprEnd;
869 }
870 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
871 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000872 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
Sebastian Redle4c452c2008-11-22 13:44:36 +0000873 OutStr.append(Argument, ExprEnd);
874 return;
875 }
John McCall909c1822010-01-14 20:11:39 +0000876 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000877 }
878}
879
880
Chris Lattnerf4c83962008-11-19 06:51:40 +0000881/// FormatDiagnostic - Format this diagnostic into a string, substituting the
882/// formal arguments into the %0 slots. The result is appended onto the Str
883/// array.
884void DiagnosticInfo::
885FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
886 const char *DiagStr = getDiags()->getDescription(getID());
887 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000888
John McCall9f286142010-01-13 23:58:20 +0000889 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
890}
891
892void DiagnosticInfo::
893FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
894 llvm::SmallVectorImpl<char> &OutStr) const {
895
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000896 /// FormattedArgs - Keep track of all of the arguments formatted by
897 /// ConvertArgToString and pass them into subsequent calls to
898 /// ConvertArgToString, allowing the implementation to avoid redundancies in
899 /// obvious cases.
900 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
901
Chris Lattnerf4c83962008-11-19 06:51:40 +0000902 while (DiagStr != DiagEnd) {
903 if (DiagStr[0] != '%') {
904 // Append non-%0 substrings to Str if we have one.
905 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
906 OutStr.append(DiagStr, StrEnd);
907 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000908 continue;
John McCall909c1822010-01-14 20:11:39 +0000909 } else if (ispunct(DiagStr[1])) {
910 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000911 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000912 continue;
913 }
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000915 // Skip the %.
916 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000918 // This must be a placeholder for a diagnostic argument. The format for a
919 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
920 // The digit is a number from 0-9 indicating which argument this comes from.
921 // The modifier is a string of digits from the set [-a-z]+, arguments is a
922 // brace enclosed string.
923 const char *Modifier = 0, *Argument = 0;
924 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000926 // Check to see if we have a modifier. If so eat it.
927 if (!isdigit(DiagStr[0])) {
928 Modifier = DiagStr;
929 while (DiagStr[0] == '-' ||
930 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
931 ++DiagStr;
932 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000933
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000934 // If we have an argument, get it next.
935 if (DiagStr[0] == '{') {
936 ++DiagStr; // Skip {.
937 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
John McCall909c1822010-01-14 20:11:39 +0000939 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
940 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000941 ArgumentLen = DiagStr-Argument;
942 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000943 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000946 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000947 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000948
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000949 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
950
951 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000952 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000953 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000954 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000955 assert(ModifierLen == 0 && "No modifiers for strings yet");
956 OutStr.append(S.begin(), S.end());
957 break;
958 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000959 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000960 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000961 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000962
963 // Don't crash if get passed a null pointer by accident.
964 if (!S)
965 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000967 OutStr.append(S, S + strlen(S));
968 break;
969 }
Chris Lattner08631c52008-11-23 21:45:46 +0000970 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000971 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000972 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000974 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000975 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000976 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
977 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000978 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
979 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000980 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
981 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000982 } else {
983 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000984 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000985 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000986 break;
987 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000988 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000989 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000991 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000992 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000993 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
994 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000995 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
996 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000997 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
998 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000999 } else {
1000 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +00001001 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +00001002 }
Chris Lattner22caddc2008-11-23 09:13:29 +00001003 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001004 }
Chris Lattner08631c52008-11-23 21:45:46 +00001005 // ---- NAMES and TYPES ----
1006 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +00001007 const IdentifierInfo *II = getArgIdentifier(ArgNo);
1008 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +00001009
1010 // Don't crash if get passed a null pointer by accident.
1011 if (!II) {
1012 const char *S = "(null)";
1013 OutStr.append(S, S + strlen(S));
1014 continue;
1015 }
1016
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00001017 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +00001018 break;
1019 }
Chris Lattner22caddc2008-11-23 09:13:29 +00001020 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +00001021 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001022 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +00001023 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +00001024 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001025 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +00001026 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001027 Argument, ArgumentLen,
1028 FormattedArgs.data(), FormattedArgs.size(),
1029 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +00001030 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +00001031 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001032
1033 // Remember this argument info for subsequent formatting operations. Turn
1034 // std::strings into a null terminated string to make it be the same case as
1035 // all the other ones.
1036 if (Kind != Diagnostic::ak_std_string)
1037 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1038 else
1039 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1040 (intptr_t)getArgStdStr(ArgNo).c_str()));
1041
Nico Weber7bfaaae2008-08-10 19:59:06 +00001042 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001043}
Ted Kremenekcabe6682009-01-23 20:28:53 +00001044
Douglas Gregora88084b2010-02-18 18:08:43 +00001045StoredDiagnostic::StoredDiagnostic() { }
1046
1047StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1048 llvm::StringRef Message)
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001049 : Level(Level), Loc(), Message(Message) { }
Douglas Gregora88084b2010-02-18 18:08:43 +00001050
1051StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1052 const DiagnosticInfo &Info)
Chris Lattner0a76aae2010-06-18 22:45:06 +00001053 : Level(Level), Loc(Info.getLocation()) {
Douglas Gregora88084b2010-02-18 18:08:43 +00001054 llvm::SmallString<64> Message;
1055 Info.FormatDiagnostic(Message);
1056 this->Message.assign(Message.begin(), Message.end());
1057
1058 Ranges.reserve(Info.getNumRanges());
1059 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
1060 Ranges.push_back(Info.getRange(I));
1061
Douglas Gregor849b2432010-03-31 17:46:05 +00001062 FixIts.reserve(Info.getNumFixItHints());
1063 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
1064 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregora88084b2010-02-18 18:08:43 +00001065}
1066
1067StoredDiagnostic::~StoredDiagnostic() { }
1068
Douglas Gregord93256e2010-01-28 06:00:51 +00001069static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1070 OS.write((const char *)&Value, sizeof(unsigned));
1071}
1072
1073static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1074 WriteUnsigned(OS, String.size());
1075 OS.write(String.data(), String.size());
1076}
1077
1078static void WriteSourceLocation(llvm::raw_ostream &OS,
1079 SourceManager *SM,
1080 SourceLocation Location) {
1081 if (!SM || Location.isInvalid()) {
1082 // If we don't have a source manager or this location is invalid,
1083 // just write an invalid location.
1084 WriteUnsigned(OS, 0);
1085 WriteUnsigned(OS, 0);
1086 WriteUnsigned(OS, 0);
1087 return;
1088 }
1089
1090 Location = SM->getInstantiationLoc(Location);
1091 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
Ted Kremenekec55c942010-04-12 19:54:17 +00001092
1093 const FileEntry *FE = SM->getFileEntryForID(Decomposed.first);
1094 if (FE)
1095 WriteString(OS, FE->getName());
1096 else {
1097 // Fallback to using the buffer name when there is no entry.
1098 WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier());
1099 }
1100
Douglas Gregord93256e2010-01-28 06:00:51 +00001101 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1102 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1103}
1104
Douglas Gregora88084b2010-02-18 18:08:43 +00001105void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
Douglas Gregord93256e2010-01-28 06:00:51 +00001106 SourceManager *SM = 0;
1107 if (getLocation().isValid())
1108 SM = &const_cast<SourceManager &>(getLocation().getManager());
1109
Douglas Gregorb9c903b2010-02-19 00:40:40 +00001110 // Write a short header to help identify diagnostics.
1111 OS << (char)0x06 << (char)0x07;
1112
Douglas Gregord93256e2010-01-28 06:00:51 +00001113 // Write the diagnostic level and location.
Douglas Gregora88084b2010-02-18 18:08:43 +00001114 WriteUnsigned(OS, (unsigned)Level);
Douglas Gregord93256e2010-01-28 06:00:51 +00001115 WriteSourceLocation(OS, SM, getLocation());
1116
1117 // Write the diagnostic message.
1118 llvm::SmallString<64> Message;
Douglas Gregora88084b2010-02-18 18:08:43 +00001119 WriteString(OS, getMessage());
Douglas Gregord93256e2010-01-28 06:00:51 +00001120
1121 // Count the number of ranges that don't point into macros, since
1122 // only simple file ranges serialize well.
1123 unsigned NumNonMacroRanges = 0;
Douglas Gregora88084b2010-02-18 18:08:43 +00001124 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1125 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +00001126 continue;
1127
1128 ++NumNonMacroRanges;
1129 }
1130
1131 // Write the ranges.
1132 WriteUnsigned(OS, NumNonMacroRanges);
1133 if (NumNonMacroRanges) {
Douglas Gregora88084b2010-02-18 18:08:43 +00001134 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1135 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +00001136 continue;
1137
Douglas Gregora88084b2010-02-18 18:08:43 +00001138 WriteSourceLocation(OS, SM, R->getBegin());
1139 WriteSourceLocation(OS, SM, R->getEnd());
Chris Lattner0a76aae2010-06-18 22:45:06 +00001140 WriteUnsigned(OS, R->isTokenRange());
Douglas Gregord93256e2010-01-28 06:00:51 +00001141 }
1142 }
1143
1144 // Determine if all of the fix-its involve rewrites with simple file
1145 // locations (not in macro instantiations). If so, we can write
1146 // fix-it information.
Douglas Gregora88084b2010-02-18 18:08:43 +00001147 unsigned NumFixIts = 0;
1148 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1149 if (F->RemoveRange.isValid() &&
1150 (F->RemoveRange.getBegin().isMacroID() ||
1151 F->RemoveRange.getEnd().isMacroID())) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001152 NumFixIts = 0;
1153 break;
1154 }
1155
Douglas Gregora88084b2010-02-18 18:08:43 +00001156 if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001157 NumFixIts = 0;
1158 break;
1159 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001160
1161 ++NumFixIts;
Douglas Gregord93256e2010-01-28 06:00:51 +00001162 }
1163
1164 // Write the fix-its.
1165 WriteUnsigned(OS, NumFixIts);
Douglas Gregora88084b2010-02-18 18:08:43 +00001166 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1167 WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1168 WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
Chris Lattner0a76aae2010-06-18 22:45:06 +00001169 WriteUnsigned(OS, F->RemoveRange.isTokenRange());
Douglas Gregora88084b2010-02-18 18:08:43 +00001170 WriteSourceLocation(OS, SM, F->InsertionLoc);
1171 WriteString(OS, F->CodeToInsert);
Douglas Gregord93256e2010-01-28 06:00:51 +00001172 }
1173}
1174
Douglas Gregora88084b2010-02-18 18:08:43 +00001175static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1176 unsigned &Value) {
1177 if (Memory + sizeof(unsigned) > MemoryEnd)
1178 return true;
1179
1180 memmove(&Value, Memory, sizeof(unsigned));
1181 Memory += sizeof(unsigned);
1182 return false;
1183}
1184
1185static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1186 const char *&Memory, const char *MemoryEnd,
1187 SourceLocation &Location) {
1188 // Read the filename.
1189 unsigned FileNameLen = 0;
1190 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1191 Memory + FileNameLen > MemoryEnd)
1192 return true;
1193
1194 llvm::StringRef FileName(Memory, FileNameLen);
1195 Memory += FileNameLen;
1196
1197 // Read the line, column.
1198 unsigned Line = 0, Column = 0;
1199 if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1200 ReadUnsigned(Memory, MemoryEnd, Column))
1201 return true;
1202
1203 if (FileName.empty()) {
1204 Location = SourceLocation();
1205 return false;
1206 }
1207
1208 const FileEntry *File = FM.getFile(FileName);
1209 if (!File)
1210 return true;
1211
1212 // Make sure that this file has an entry in the source manager.
1213 if (!SM.hasFileInfo(File))
1214 SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1215
1216 Location = SM.getLocation(File, Line, Column);
1217 return false;
1218}
1219
1220StoredDiagnostic
1221StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1222 const char *&Memory, const char *MemoryEnd) {
Douglas Gregorb9c903b2010-02-19 00:40:40 +00001223 while (true) {
1224 if (Memory == MemoryEnd)
1225 return StoredDiagnostic();
1226
1227 if (*Memory != 0x06) {
1228 ++Memory;
1229 continue;
1230 }
1231
1232 ++Memory;
1233 if (Memory == MemoryEnd)
1234 return StoredDiagnostic();
1235
1236 if (*Memory != 0x07) {
1237 ++Memory;
1238 continue;
1239 }
1240
1241 // We found the header. We're done.
1242 ++Memory;
1243 break;
1244 }
1245
Douglas Gregora88084b2010-02-18 18:08:43 +00001246 // Read the severity level.
1247 unsigned Level = 0;
1248 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1249 return StoredDiagnostic();
1250
1251 // Read the source location.
1252 SourceLocation Location;
1253 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1254 return StoredDiagnostic();
1255
1256 // Read the diagnostic text.
1257 if (Memory == MemoryEnd)
1258 return StoredDiagnostic();
1259
1260 unsigned MessageLen = 0;
1261 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1262 Memory + MessageLen > MemoryEnd)
1263 return StoredDiagnostic();
1264
1265 llvm::StringRef Message(Memory, MessageLen);
1266 Memory += MessageLen;
1267
1268
1269 // At this point, we have enough information to form a diagnostic. Do so.
1270 StoredDiagnostic Diag;
1271 Diag.Level = (Diagnostic::Level)Level;
1272 Diag.Loc = FullSourceLoc(Location, SM);
1273 Diag.Message = Message;
1274 if (Memory == MemoryEnd)
1275 return Diag;
1276
1277 // Read the source ranges.
1278 unsigned NumSourceRanges = 0;
1279 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1280 return Diag;
1281 for (unsigned I = 0; I != NumSourceRanges; ++I) {
1282 SourceLocation Begin, End;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001283 unsigned IsTokenRange;
Douglas Gregora88084b2010-02-18 18:08:43 +00001284 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
Chris Lattner0a76aae2010-06-18 22:45:06 +00001285 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End) ||
1286 ReadUnsigned(Memory, MemoryEnd, IsTokenRange))
Douglas Gregora88084b2010-02-18 18:08:43 +00001287 return Diag;
1288
Chris Lattner0a76aae2010-06-18 22:45:06 +00001289 Diag.Ranges.push_back(CharSourceRange(SourceRange(Begin, End),
1290 IsTokenRange));
Douglas Gregora88084b2010-02-18 18:08:43 +00001291 }
1292
1293 // Read the fix-it hints.
1294 unsigned NumFixIts = 0;
1295 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1296 return Diag;
1297 for (unsigned I = 0; I != NumFixIts; ++I) {
1298 SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001299 unsigned InsertLen = 0, RemoveIsTokenRange;
Douglas Gregora88084b2010-02-18 18:08:43 +00001300 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1301 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
Chris Lattner0a76aae2010-06-18 22:45:06 +00001302 ReadUnsigned(Memory, MemoryEnd, RemoveIsTokenRange) ||
Douglas Gregora88084b2010-02-18 18:08:43 +00001303 ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
1304 ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1305 Memory + InsertLen > MemoryEnd) {
1306 Diag.FixIts.clear();
1307 return Diag;
1308 }
1309
Douglas Gregor849b2432010-03-31 17:46:05 +00001310 FixItHint Hint;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001311 Hint.RemoveRange = CharSourceRange(SourceRange(RemoveBegin, RemoveEnd),
1312 RemoveIsTokenRange);
Douglas Gregora88084b2010-02-18 18:08:43 +00001313 Hint.InsertionLoc = InsertionLoc;
1314 Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1315 Memory += InsertLen;
1316 Diag.FixIts.push_back(Hint);
1317 }
1318
1319 return Diag;
1320}
1321
Ted Kremenekcabe6682009-01-23 20:28:53 +00001322/// IncludeInDiagnosticCounts - This method (whose default implementation
1323/// returns true) indicates whether the diagnostics handled by this
1324/// DiagnosticClient should be included in the number of diagnostics
1325/// reported by Diagnostic.
1326bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001327
1328PartialDiagnostic::StorageAllocator::StorageAllocator() {
1329 for (unsigned I = 0; I != NumCached; ++I)
1330 FreeList[I] = Cached + I;
1331 NumFreeListEntries = NumCached;
1332}
1333
1334PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1335 assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
1336}