blob: 1e911ec8029d8e4e1df542fadcde0d5c133cd7b3 [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 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +000064};
65
Dan Gohman3c46e8d2010-07-26 21:25:24 +000066}
67
Chris Lattner33dd2822009-04-16 06:00:24 +000068static const StaticDiagInfoRec StaticDiagInfo[] = {
Chris Lattner27b0f512010-05-04 20:44:26 +000069#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY) \
70 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP },
Chris Lattner27ceb9d2009-04-15 07:01:18 +000071#include "clang/Basic/DiagnosticCommonKinds.inc"
72#include "clang/Basic/DiagnosticDriverKinds.inc"
73#include "clang/Basic/DiagnosticFrontendKinds.inc"
74#include "clang/Basic/DiagnosticLexKinds.inc"
75#include "clang/Basic/DiagnosticParseKinds.inc"
76#include "clang/Basic/DiagnosticASTKinds.inc"
77#include "clang/Basic/DiagnosticSemaKinds.inc"
78#include "clang/Basic/DiagnosticAnalysisKinds.inc"
Chris Lattner27b0f512010-05-04 20:44:26 +000079 { 0, 0, 0, 0, 0, 0, 0}
Chris Lattner27ceb9d2009-04-15 07:01:18 +000080};
Chris Lattner8a941e02009-04-15 16:56:26 +000081#undef DIAG
Chris Lattner27ceb9d2009-04-15 07:01:18 +000082
Chris Lattner87d854e2009-04-16 06:13:46 +000083/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
84/// or null if the ID is invalid.
Chris Lattner33dd2822009-04-16 06:00:24 +000085static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
Chris Lattner87d854e2009-04-16 06:13:46 +000086 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
87
88 // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
89#ifndef NDEBUG
90 static bool IsFirst = true;
91 if (IsFirst) {
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000092 for (unsigned i = 1; i != NumDiagEntries; ++i) {
93 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
94 "Diag ID conflict, the enums at the start of clang::diag (in "
95 "Diagnostic.h) probably need to be increased");
96
Chris Lattner87d854e2009-04-16 06:13:46 +000097 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
98 "Improperly sorted diag info");
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000099 }
Chris Lattner87d854e2009-04-16 06:13:46 +0000100 IsFirst = false;
101 }
102#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Chris Lattner87d854e2009-04-16 06:13:46 +0000104 // Search the diagnostic table with a binary search.
Chris Lattner27b0f512010-05-04 20:44:26 +0000105 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 };
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner87d854e2009-04-16 06:13:46 +0000107 const StaticDiagInfoRec *Found =
108 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
109 if (Found == StaticDiagInfo + NumDiagEntries ||
110 Found->DiagID != DiagID)
111 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Chris Lattner87d854e2009-04-16 06:13:46 +0000113 return Found;
Chris Lattner33dd2822009-04-16 06:00:24 +0000114}
115
116static unsigned GetDefaultDiagMapping(unsigned DiagID) {
117 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Chris Lattner121f60c2009-04-16 06:07:15 +0000118 return Info->Mapping;
Chris Lattner691f1ae2009-04-16 04:12:40 +0000119 return diag::MAP_FATAL;
120}
121
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000122/// getWarningOptionForDiag - Return the lowest-level warning option that
123/// enables the specified diagnostic. If there is no -Wfoo flag that controls
124/// the diagnostic, this returns null.
125const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
Chris Lattner33dd2822009-04-16 06:00:24 +0000126 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
127 return Info->OptionGroup;
128 return 0;
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000129}
130
Chris Lattnerc9b88902010-05-04 21:13:21 +0000131/// getWarningOptionForDiag - Return the category number that a specified
132/// DiagID belongs to, or 0 if no category.
133unsigned Diagnostic::getCategoryNumberForDiag(unsigned DiagID) {
134 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
135 return Info->Category;
136 return 0;
137}
138
139/// getCategoryNameFromID - Given a category ID, return the name of the
140/// category, an empty string if CategoryID is zero, or null if CategoryID is
141/// invalid.
142const char *Diagnostic::getCategoryNameFromID(unsigned CategoryID) {
143 // Second the table of options, sorted by name for fast binary lookup.
144 static const char *CategoryNameTable[] = {
145#define GET_CATEGORY_TABLE
146#define CATEGORY(X) X,
147#include "clang/Basic/DiagnosticGroups.inc"
148#undef GET_CATEGORY_TABLE
149 "<<END>>"
150 };
151 static const size_t CategoryNameTableSize =
152 sizeof(CategoryNameTable) / sizeof(CategoryNameTable[0])-1;
153
154 if (CategoryID >= CategoryNameTableSize) return 0;
155 return CategoryNameTable[CategoryID];
156}
157
158
159
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000160Diagnostic::SFINAEResponse
161Diagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) {
162 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) {
163 if (!Info->SFINAE)
164 return SFINAE_Report;
165
166 if (Info->Class == CLASS_ERROR)
167 return SFINAE_SubstitutionFailure;
168
169 // Suppress notes, warnings, and extensions;
170 return SFINAE_Suppress;
171 }
172
173 return SFINAE_Report;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000174}
175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176/// getDiagClass - Return the class field of the diagnostic.
177///
Chris Lattner07506182007-11-30 22:53:43 +0000178static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner121f60c2009-04-16 06:07:15 +0000179 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
180 return Info->Class;
181 return ~0U;
Reid Spencer5f016e22007-07-11 17:01:13 +0000182}
183
Chris Lattner182745a2007-12-02 01:09:57 +0000184//===----------------------------------------------------------------------===//
185// Custom Diagnostic information
186//===----------------------------------------------------------------------===//
187
188namespace clang {
189 namespace diag {
190 class CustomDiagInfo {
191 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
192 std::vector<DiagDesc> DiagInfo;
193 std::map<DiagDesc, unsigned> DiagIDs;
194 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner182745a2007-12-02 01:09:57 +0000196 /// getDescription - Return the description of the specified custom
197 /// diagnostic.
198 const char *getDescription(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000199 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000200 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000201 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner182745a2007-12-02 01:09:57 +0000202 }
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner182745a2007-12-02 01:09:57 +0000204 /// getLevel - Return the level of the specified custom diagnostic.
205 Diagnostic::Level getLevel(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000206 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000207 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000208 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner182745a2007-12-02 01:09:57 +0000209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000211 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000212 Diagnostic &Diags) {
Chris Lattner182745a2007-12-02 01:09:57 +0000213 DiagDesc D(L, Message);
214 // Check to see if it already exists.
215 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
216 if (I != DiagIDs.end() && I->first == D)
217 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattner182745a2007-12-02 01:09:57 +0000219 // If not, assign a new ID.
Chris Lattner88eccaf2009-01-29 06:55:46 +0000220 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner182745a2007-12-02 01:09:57 +0000221 DiagIDs.insert(std::make_pair(D, ID));
222 DiagInfo.push_back(D);
223 return ID;
224 }
225 };
Mike Stump1eb44332009-09-09 15:08:12 +0000226
227 } // end diag namespace
228} // end clang namespace
Chris Lattner182745a2007-12-02 01:09:57 +0000229
230
231//===----------------------------------------------------------------------===//
232// Common Diagnostic implementation
233//===----------------------------------------------------------------------===//
234
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000235static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
236 const char *Modifier, unsigned ML,
237 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000238 const Diagnostic::ArgumentValue *PrevArgs,
239 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +0000240 llvm::SmallVectorImpl<char> &Output,
241 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000242 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +0000243 Output.append(Str, Str+strlen(Str));
244}
245
246
Ted Kremenekb4398aa2008-08-07 17:49:57 +0000247Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000248 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +0000249 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000251 AllExtensionsSilenced = 0;
252 IgnoreAllWarnings = false;
253 WarningsAsErrors = false;
254 ErrorsAsFatal = false;
255 SuppressSystemWarnings = false;
256 SuppressAllDiagnostics = false;
257 ShowOverloads = Ovl_All;
258 ExtBehavior = Ext_Ignore;
259
260 ErrorLimit = 0;
261 TemplateBacktraceLimit = 0;
262 CustomDiagInfo = 0;
263
264 // Set all mappings to 'unset'.
265 DiagMappingsStack.clear();
266 DiagMappingsStack.push_back(DiagMappings());
267
Douglas Gregorabc563f2010-07-19 21:46:24 +0000268 Reset();
Reid Spencer5f016e22007-07-11 17:01:13 +0000269}
270
Chris Lattner182745a2007-12-02 01:09:57 +0000271Diagnostic::~Diagnostic() {
272 delete CustomDiagInfo;
273}
274
Chris Lattner04ae2df2009-07-12 21:18:45 +0000275
276void Diagnostic::pushMappings() {
John Thompsonca2c3e22009-10-23 02:21:17 +0000277 // Avoids undefined behavior when the stack has to resize.
278 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000279 DiagMappingsStack.push_back(DiagMappingsStack.back());
280}
281
282bool Diagnostic::popMappings() {
283 if (DiagMappingsStack.size() == 1)
284 return false;
285
286 DiagMappingsStack.pop_back();
287 return true;
288}
289
Chris Lattner182745a2007-12-02 01:09:57 +0000290/// getCustomDiagID - Return an ID for a diagnostic with the specified message
291/// and level. If this is the first request for this diagnosic, it is
292/// registered and created, otherwise the existing ID is returned.
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000293unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
Mike Stump1eb44332009-09-09 15:08:12 +0000294 if (CustomDiagInfo == 0)
Chris Lattner182745a2007-12-02 01:09:57 +0000295 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000296 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner182745a2007-12-02 01:09:57 +0000297}
298
299
Chris Lattnerf5d23282009-02-17 06:49:55 +0000300/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
301/// level of the specified diagnostic ID is a Warning or Extension.
302/// This only works on builtin diagnostics, not custom ones, and is not legal to
303/// call on NOTEs.
304bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000305 return DiagID < diag::DIAG_UPPER_LIMIT &&
306 getBuiltinDiagClass(DiagID) != CLASS_ERROR;
Reid Spencer5f016e22007-07-11 17:01:13 +0000307}
308
Douglas Gregoree1828a2009-03-10 18:03:33 +0000309/// \brief Determine whether the given built-in diagnostic ID is a
310/// Note.
311bool Diagnostic::isBuiltinNote(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000312 return DiagID < diag::DIAG_UPPER_LIMIT &&
313 getBuiltinDiagClass(DiagID) == CLASS_NOTE;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000314}
315
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000316/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
Chris Lattner04e44272010-04-12 21:53:11 +0000317/// ID is for an extension of some sort. This also returns EnabledByDefault,
318/// which is set to indicate whether the diagnostic is ignored by default (in
319/// which case -pedantic enables it) or treated as a warning/error by default.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000320///
Chris Lattner04e44272010-04-12 21:53:11 +0000321bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID,
322 bool &EnabledByDefault) {
323 if (DiagID >= diag::DIAG_UPPER_LIMIT ||
324 getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
325 return false;
326
Eli Friedman270c0352010-08-01 22:13:15 +0000327 EnabledByDefault = GetDefaultDiagMapping(DiagID) != diag::MAP_IGNORE;
Chris Lattner04e44272010-04-12 21:53:11 +0000328 return true;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000329}
330
Douglas Gregorabc563f2010-07-19 21:46:24 +0000331void Diagnostic::Reset() {
Douglas Gregorabc563f2010-07-19 21:46:24 +0000332 ErrorOccurred = false;
333 FatalErrorOccurred = false;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000334
335 NumWarnings = 0;
336 NumErrors = 0;
337 NumErrorsSuppressed = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000338 CurDiagID = ~0U;
339 LastDiagLevel = Ignored;
340 DelayedDiagID = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000341}
Reid Spencer5f016e22007-07-11 17:01:13 +0000342
343/// getDescription - Given a diagnostic ID, return a description of the
344/// issue.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000345const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattner121f60c2009-04-16 06:07:15 +0000346 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
347 return Info->Description;
Chris Lattner20c6b3b2009-01-27 18:30:58 +0000348 return CustomDiagInfo->getDescription(DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000349}
350
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000351void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
352 llvm::StringRef Arg2) {
353 if (DelayedDiagID)
354 return;
355
356 DelayedDiagID = DiagID;
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000357 DelayedDiagArg1 = Arg1.str();
358 DelayedDiagArg2 = Arg2.str();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000359}
360
361void Diagnostic::ReportDelayed() {
362 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
363 DelayedDiagID = 0;
364 DelayedDiagArg1.clear();
365 DelayedDiagArg2.clear();
366}
367
Reid Spencer5f016e22007-07-11 17:01:13 +0000368/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
369/// object, classify the specified diagnostic ID into a Level, consumable by
370/// the DiagnosticClient.
371Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner182745a2007-12-02 01:09:57 +0000372 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000373 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner182745a2007-12-02 01:09:57 +0000374 return CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner07506182007-11-30 22:53:43 +0000376 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000377 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
Chris Lattnerf5d23282009-02-17 06:49:55 +0000378 return getDiagnosticLevel(DiagID, DiagClass);
379}
380
381/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
382/// object, classify the specified diagnostic ID into a Level, consumable by
383/// the DiagnosticClient.
384Diagnostic::Level
385Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattnerf5d23282009-02-17 06:49:55 +0000387 // to error. Errors can only be mapped to fatal.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000388 Diagnostic::Level Result = Diagnostic::Fatal;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner691f1ae2009-04-16 04:12:40 +0000390 // Get the mapping information, if unset, compute it lazily.
391 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
392 if (MappingInfo == 0) {
393 MappingInfo = GetDefaultDiagMapping(DiagID);
394 setDiagnosticMappingInternal(DiagID, MappingInfo, false);
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner691f1ae2009-04-16 04:12:40 +0000397 switch (MappingInfo & 7) {
398 default: assert(0 && "Unknown mapping!");
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000399 case diag::MAP_IGNORE:
Chris Lattnerb54b2762009-04-16 05:04:32 +0000400 // Ignore this, unless this is an extension diagnostic and we're mapping
401 // them onto warnings or errors.
402 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension
403 ExtBehavior == Ext_Ignore || // Extensions ignored anyway
404 (MappingInfo & 8) != 0) // User explicitly mapped it.
405 return Diagnostic::Ignored;
406 Result = Diagnostic::Warning;
407 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000408 if (Result == Diagnostic::Error && ErrorsAsFatal)
409 Result = Diagnostic::Fatal;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000410 break;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000411 case diag::MAP_ERROR:
412 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000413 if (ErrorsAsFatal)
414 Result = Diagnostic::Fatal;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000415 break;
416 case diag::MAP_FATAL:
417 Result = Diagnostic::Fatal;
418 break;
419 case diag::MAP_WARNING:
420 // If warnings are globally mapped to ignore or error, do it.
Chris Lattner5b4681c2008-05-29 15:36:45 +0000421 if (IgnoreAllWarnings)
422 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000424 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Chris Lattnerb54b2762009-04-16 05:04:32 +0000426 // If this is an extension diagnostic and we're in -pedantic-error mode, and
427 // if the user didn't explicitly map it, upgrade to an error.
428 if (ExtBehavior == Ext_Error &&
429 (MappingInfo & 8) == 0 &&
430 isBuiltinExtensionDiag(DiagID))
431 Result = Diagnostic::Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000433 if (WarningsAsErrors)
434 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000435 if (Result == Diagnostic::Error && ErrorsAsFatal)
436 Result = Diagnostic::Fatal;
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000437 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000439 case diag::MAP_WARNING_NO_WERROR:
440 // Diagnostics specified with -Wno-error=foo should be set to warnings, but
441 // not be adjusted by -Werror or -pedantic-errors.
442 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000444 // If warnings are globally mapped to ignore or error, do it.
445 if (IgnoreAllWarnings)
446 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000448 break;
Chris Lattnere663c722009-12-22 23:12:53 +0000449
450 case diag::MAP_ERROR_NO_WFATAL:
451 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
452 // unaffected by -Wfatal-errors.
453 Result = Diagnostic::Error;
454 break;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000455 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000456
457 // Okay, we're about to return this as a "diagnostic to emit" one last check:
458 // if this is any sort of extension warning, and if we're in an __extension__
459 // block, silence it.
460 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
461 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000463 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000464}
465
Chris Lattner3bc172b2009-04-19 22:34:23 +0000466struct WarningOption {
467 const char *Name;
468 const short *Members;
Chandler Carruth5ef12b32010-05-13 07:43:05 +0000469 const short *SubGroups;
Chris Lattner3bc172b2009-04-19 22:34:23 +0000470};
471
472#define GET_DIAG_ARRAYS
473#include "clang/Basic/DiagnosticGroups.inc"
474#undef GET_DIAG_ARRAYS
475
476// Second the table of options, sorted by name for fast binary lookup.
477static const WarningOption OptionTable[] = {
478#define GET_DIAG_TABLE
479#include "clang/Basic/DiagnosticGroups.inc"
480#undef GET_DIAG_TABLE
481};
482static const size_t OptionTableSize =
483sizeof(OptionTable) / sizeof(OptionTable[0]);
484
485static bool WarningOptionCompare(const WarningOption &LHS,
486 const WarningOption &RHS) {
487 return strcmp(LHS.Name, RHS.Name) < 0;
488}
489
490static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
491 Diagnostic &Diags) {
492 // Option exists, poke all the members of its diagnostic set.
493 if (const short *Member = Group->Members) {
494 for (; *Member != -1; ++Member)
495 Diags.setDiagnosticMapping(*Member, Mapping);
496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattner3bc172b2009-04-19 22:34:23 +0000498 // Enable/disable all subgroups along with this one.
Chandler Carruth5ef12b32010-05-13 07:43:05 +0000499 if (const short *SubGroups = Group->SubGroups) {
500 for (; *SubGroups != (short)-1; ++SubGroups)
501 MapGroupMembers(&OptionTable[(short)*SubGroups], Mapping, Diags);
Chris Lattner3bc172b2009-04-19 22:34:23 +0000502 }
503}
504
505/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
506/// "unknown-pragmas" to have the specified mapping. This returns true and
507/// ignores the request if "Group" was unknown, false otherwise.
508bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
509 diag::Mapping Map) {
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner3bc172b2009-04-19 22:34:23 +0000511 WarningOption Key = { Group, 0, 0 };
512 const WarningOption *Found =
513 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
514 WarningOptionCompare);
515 if (Found == OptionTable + OptionTableSize ||
516 strcmp(Found->Name, Group) != 0)
517 return true; // Option not found.
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattner3bc172b2009-04-19 22:34:23 +0000519 MapGroupMembers(Found, Map, *this);
520 return false;
521}
522
523
Chris Lattner0a14eee2008-11-18 07:04:44 +0000524/// ProcessDiag - This is the method used to report a diagnostic that is
525/// finally fully formed.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000526bool Diagnostic::ProcessDiag() {
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000527 DiagnosticInfo Info(this);
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor81b747b2009-09-17 21:32:03 +0000529 if (SuppressAllDiagnostics)
530 return false;
531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 // Figure out the diagnostic level of this message.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000533 Diagnostic::Level DiagLevel;
534 unsigned DiagID = Info.getID();
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattnerf5d23282009-02-17 06:49:55 +0000536 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
537 // in a system header.
538 bool ShouldEmitInSystemHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattnerf5d23282009-02-17 06:49:55 +0000540 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
541 // Handle custom diagnostics, which cannot be mapped.
542 DiagLevel = CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattnerf5d23282009-02-17 06:49:55 +0000544 // Custom diagnostics always are emitted in system headers.
545 ShouldEmitInSystemHeader = true;
546 } else {
547 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
548 // the diagnostic level was for the previous diagnostic so that it is
549 // filtered the same as the previous diagnostic.
550 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000551 if (DiagClass == CLASS_NOTE) {
Chris Lattnerf5d23282009-02-17 06:49:55 +0000552 DiagLevel = Diagnostic::Note;
553 ShouldEmitInSystemHeader = false; // extra consideration is needed
554 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000555 // If this is not an error and we are in a system header, we ignore it.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000556 // Check the original Diag ID here, because we also want to ignore
557 // extensions and warnings in -Werror and -pedantic-errors modes, which
558 // *map* warnings/extensions to errors.
Chris Lattner8a941e02009-04-15 16:56:26 +0000559 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattnerf5d23282009-02-17 06:49:55 +0000561 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
562 }
563 }
564
Douglas Gregor525c4b02009-03-19 18:55:06 +0000565 if (DiagLevel != Diagnostic::Note) {
566 // Record that a fatal error occurred only when we see a second
567 // non-note diagnostic. This allows notes to be attached to the
568 // fatal error, but suppresses any diagnostics that follow those
569 // notes.
570 if (LastDiagLevel == Diagnostic::Fatal)
571 FatalErrorOccurred = true;
572
Chris Lattnerf5d23282009-02-17 06:49:55 +0000573 LastDiagLevel = DiagLevel;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000575
576 // If a fatal error has already been emitted, silence all subsequent
577 // diagnostics.
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000578 if (FatalErrorOccurred) {
579 if (DiagLevel >= Diagnostic::Error) {
580 ++NumErrors;
581 ++NumErrorsSuppressed;
582 }
583
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000584 return false;
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000585 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000586
Chris Lattnerf5d23282009-02-17 06:49:55 +0000587 // If the client doesn't care about this message, don't issue it. If this is
588 // a note and the last real diagnostic was ignored, ignore it too.
589 if (DiagLevel == Diagnostic::Ignored ||
590 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000591 return false;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000592
Chris Lattnerf5d23282009-02-17 06:49:55 +0000593 // If this diagnostic is in a system header and is not a clang error, suppress
594 // it.
595 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner0a14eee2008-11-18 07:04:44 +0000596 Info.getLocation().isValid() &&
John McCall779cf422010-02-11 10:04:29 +0000597 Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
Chris Lattner336f26b2009-02-17 06:52:20 +0000598 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
599 LastDiagLevel = Diagnostic::Ignored;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000600 return false;
Chris Lattner336f26b2009-02-17 06:52:20 +0000601 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000602
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 if (DiagLevel >= Diagnostic::Error) {
604 ErrorOccurred = true;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000605 ++NumErrors;
Chris Lattnerb205ac92010-04-07 20:21:58 +0000606
607 // If we've emitted a lot of errors, emit a fatal error after it to stop a
608 // flood of bogus errors.
Chris Lattnerc1002142010-04-07 20:37:06 +0000609 if (ErrorLimit && NumErrors >= ErrorLimit &&
Chris Lattnerb205ac92010-04-07 20:21:58 +0000610 DiagLevel == Diagnostic::Error)
611 SetDelayedDiagnostic(diag::fatal_too_many_errors);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 // Finally, report it.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000615 Client->HandleDiagnostic(DiagLevel, Info);
Chris Lattner53eee7b2010-04-07 18:47:42 +0000616 if (Client->IncludeInDiagnosticCounts()) {
617 if (DiagLevel == Diagnostic::Warning)
618 ++NumWarnings;
619 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000620
Douglas Gregoree1828a2009-03-10 18:03:33 +0000621 CurDiagID = ~0U;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000622
623 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000624}
625
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000626bool DiagnosticBuilder::Emit() {
627 // If DiagObj is null, then its soul was stolen by the copy ctor
628 // or the user called Emit().
629 if (DiagObj == 0) return false;
630
631 // When emitting diagnostics, we set the final argument count into
632 // the Diagnostic object.
633 DiagObj->NumDiagArgs = NumArgs;
634 DiagObj->NumDiagRanges = NumRanges;
Douglas Gregor849b2432010-03-31 17:46:05 +0000635 DiagObj->NumFixItHints = NumFixItHints;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000636
637 // Process the diagnostic, sending the accumulated information to the
638 // DiagnosticClient.
639 bool Emitted = DiagObj->ProcessDiag();
640
641 // Clear out the current diagnostic object.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000642 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000643 DiagObj->Clear();
644
645 // If there was a delayed diagnostic, emit it now.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000646 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000647 DiagObj->ReportDelayed();
648
649 // This diagnostic is dead.
650 DiagObj = 0;
651
652 return Emitted;
653}
654
Nico Weber7bfaaae2008-08-10 19:59:06 +0000655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000657
Chris Lattnerf4c83962008-11-19 06:51:40 +0000658
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000659/// ModifierIs - Return true if the specified modifier matches specified string.
660template <std::size_t StrLen>
661static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
662 const char (&Str)[StrLen]) {
663 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
664}
665
John McCall909c1822010-01-14 20:11:39 +0000666/// ScanForward - Scans forward, looking for the given character, skipping
667/// nested clauses and escaped characters.
668static const char *ScanFormat(const char *I, const char *E, char Target) {
669 unsigned Depth = 0;
670
671 for ( ; I != E; ++I) {
672 if (Depth == 0 && *I == Target) return I;
673 if (Depth != 0 && *I == '}') Depth--;
674
675 if (*I == '%') {
676 I++;
677 if (I == E) break;
678
679 // Escaped characters get implicitly skipped here.
680
681 // Format specifier.
682 if (!isdigit(*I) && !ispunct(*I)) {
683 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
684 if (I == E) break;
685 if (*I == '{')
686 Depth++;
687 }
688 }
689 }
690 return E;
691}
692
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000693/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
694/// like this: %select{foo|bar|baz}2. This means that the integer argument
695/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
696/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
697/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000698static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000699 const char *Argument, unsigned ArgumentLen,
700 llvm::SmallVectorImpl<char> &OutStr) {
701 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000703 // Skip over 'ValNo' |'s.
704 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000705 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000706 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
707 " larger than the number of options in the diagnostic string!");
708 Argument = NextVal+1; // Skip this string.
709 --ValNo;
710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000712 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000713 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000714
715 // Recursively format the result of the select clause into the output string.
716 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000717}
718
719/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
720/// letter 's' to the string if the value is not 1. This is used in cases like
721/// this: "you idiot, you have %4 parameter%s4!".
722static void HandleIntegerSModifier(unsigned ValNo,
723 llvm::SmallVectorImpl<char> &OutStr) {
724 if (ValNo != 1)
725 OutStr.push_back('s');
726}
727
John McCall3be16b72010-01-14 00:50:32 +0000728/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
729/// prints the ordinal form of the given integer, with 1 corresponding
730/// to the first ordinal. Currently this is hard-coded to use the
731/// English form.
732static void HandleOrdinalModifier(unsigned ValNo,
733 llvm::SmallVectorImpl<char> &OutStr) {
734 assert(ValNo != 0 && "ValNo must be strictly positive!");
735
736 llvm::raw_svector_ostream Out(OutStr);
737
738 // We could use text forms for the first N ordinals, but the numeric
739 // forms are actually nicer in diagnostics because they stand out.
740 Out << ValNo;
741
742 // It is critically important that we do this perfectly for
743 // user-written sequences with over 100 elements.
744 switch (ValNo % 100) {
745 case 11:
746 case 12:
747 case 13:
748 Out << "th"; return;
749 default:
750 switch (ValNo % 10) {
751 case 1: Out << "st"; return;
752 case 2: Out << "nd"; return;
753 case 3: Out << "rd"; return;
754 default: Out << "th"; return;
755 }
756 }
757}
758
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000759
Sebastian Redle4c452c2008-11-22 13:44:36 +0000760/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000761static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000762 // Programming 101: Parse a decimal number :-)
763 unsigned Val = 0;
764 while (Start != End && *Start >= '0' && *Start <= '9') {
765 Val *= 10;
766 Val += *Start - '0';
767 ++Start;
768 }
769 return Val;
770}
771
772/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000773static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000774 if (*Start != '[') {
775 unsigned Ref = PluralNumber(Start, End);
776 return Ref == Val;
777 }
778
779 ++Start;
780 unsigned Low = PluralNumber(Start, End);
781 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
782 ++Start;
783 unsigned High = PluralNumber(Start, End);
784 assert(*Start == ']' && "Bad plural expression syntax: expected )");
785 ++Start;
786 return Low <= Val && Val <= High;
787}
788
789/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000790static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000791 // Empty condition?
792 if (*Start == ':')
793 return true;
794
795 while (1) {
796 char C = *Start;
797 if (C == '%') {
798 // Modulo expression
799 ++Start;
800 unsigned Arg = PluralNumber(Start, End);
801 assert(*Start == '=' && "Bad plural expression syntax: expected =");
802 ++Start;
803 unsigned ValMod = ValNo % Arg;
804 if (TestPluralRange(ValMod, Start, End))
805 return true;
806 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000807 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000808 "Bad plural expression syntax: unexpected character");
809 // Range expression
810 if (TestPluralRange(ValNo, Start, End))
811 return true;
812 }
813
814 // Scan for next or-expr part.
815 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000816 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000817 break;
818 ++Start;
819 }
820 return false;
821}
822
823/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
824/// for complex plural forms, or in languages where all plurals are complex.
825/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
826/// conditions that are tested in order, the form corresponding to the first
827/// that applies being emitted. The empty condition is always true, making the
828/// last form a default case.
829/// Conditions are simple boolean expressions, where n is the number argument.
830/// Here are the rules.
831/// condition := expression | empty
832/// empty := -> always true
833/// expression := numeric [',' expression] -> logical or
834/// numeric := range -> true if n in range
835/// | '%' number '=' range -> true if n % number in range
836/// range := number
837/// | '[' number ',' number ']' -> ranges are inclusive both ends
838///
839/// Here are some examples from the GNU gettext manual written in this form:
840/// English:
841/// {1:form0|:form1}
842/// Latvian:
843/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
844/// Gaeilge:
845/// {1:form0|2:form1|:form2}
846/// Romanian:
847/// {1:form0|0,%100=[1,19]:form1|:form2}
848/// Lithuanian:
849/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
850/// Russian (requires repeated form):
851/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
852/// Slovak
853/// {1:form0|[2,4]:form1|:form2}
854/// Polish (requires repeated form):
855/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
856static void HandlePluralModifier(unsigned ValNo,
857 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000858 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000859 const char *ArgumentEnd = Argument + ArgumentLen;
860 while (1) {
861 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
862 const char *ExprEnd = Argument;
863 while (*ExprEnd != ':') {
864 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
865 ++ExprEnd;
866 }
867 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
868 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000869 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
Sebastian Redle4c452c2008-11-22 13:44:36 +0000870 OutStr.append(Argument, ExprEnd);
871 return;
872 }
John McCall909c1822010-01-14 20:11:39 +0000873 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000874 }
875}
876
877
Chris Lattnerf4c83962008-11-19 06:51:40 +0000878/// FormatDiagnostic - Format this diagnostic into a string, substituting the
879/// formal arguments into the %0 slots. The result is appended onto the Str
880/// array.
881void DiagnosticInfo::
882FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
883 const char *DiagStr = getDiags()->getDescription(getID());
884 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
John McCall9f286142010-01-13 23:58:20 +0000886 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
887}
888
889void DiagnosticInfo::
890FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
891 llvm::SmallVectorImpl<char> &OutStr) const {
892
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000893 /// FormattedArgs - Keep track of all of the arguments formatted by
894 /// ConvertArgToString and pass them into subsequent calls to
895 /// ConvertArgToString, allowing the implementation to avoid redundancies in
896 /// obvious cases.
897 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
898
Chris Lattnerf4c83962008-11-19 06:51:40 +0000899 while (DiagStr != DiagEnd) {
900 if (DiagStr[0] != '%') {
901 // Append non-%0 substrings to Str if we have one.
902 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
903 OutStr.append(DiagStr, StrEnd);
904 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000905 continue;
John McCall909c1822010-01-14 20:11:39 +0000906 } else if (ispunct(DiagStr[1])) {
907 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000908 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000909 continue;
910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000912 // Skip the %.
913 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000915 // This must be a placeholder for a diagnostic argument. The format for a
916 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
917 // The digit is a number from 0-9 indicating which argument this comes from.
918 // The modifier is a string of digits from the set [-a-z]+, arguments is a
919 // brace enclosed string.
920 const char *Modifier = 0, *Argument = 0;
921 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000923 // Check to see if we have a modifier. If so eat it.
924 if (!isdigit(DiagStr[0])) {
925 Modifier = DiagStr;
926 while (DiagStr[0] == '-' ||
927 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
928 ++DiagStr;
929 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000930
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000931 // If we have an argument, get it next.
932 if (DiagStr[0] == '{') {
933 ++DiagStr; // Skip {.
934 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
John McCall909c1822010-01-14 20:11:39 +0000936 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
937 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000938 ArgumentLen = DiagStr-Argument;
939 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000940 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000943 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000944 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000945
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000946 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
947
948 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000949 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000950 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000951 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000952 assert(ModifierLen == 0 && "No modifiers for strings yet");
953 OutStr.append(S.begin(), S.end());
954 break;
955 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000956 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000957 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000958 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000959
960 // Don't crash if get passed a null pointer by accident.
961 if (!S)
962 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000964 OutStr.append(S, S + strlen(S));
965 break;
966 }
Chris Lattner08631c52008-11-23 21:45:46 +0000967 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000968 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000969 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000971 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000972 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000973 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
974 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000975 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
976 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000977 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
978 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000979 } else {
980 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000981 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000982 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000983 break;
984 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000985 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000986 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000988 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000989 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000990 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
991 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000992 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
993 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000994 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
995 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000996 } else {
997 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000998 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000999 }
Chris Lattner22caddc2008-11-23 09:13:29 +00001000 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001001 }
Chris Lattner08631c52008-11-23 21:45:46 +00001002 // ---- NAMES and TYPES ----
1003 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +00001004 const IdentifierInfo *II = getArgIdentifier(ArgNo);
1005 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +00001006
1007 // Don't crash if get passed a null pointer by accident.
1008 if (!II) {
1009 const char *S = "(null)";
1010 OutStr.append(S, S + strlen(S));
1011 continue;
1012 }
1013
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00001014 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +00001015 break;
1016 }
Chris Lattner22caddc2008-11-23 09:13:29 +00001017 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +00001018 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001019 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +00001020 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +00001021 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001022 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +00001023 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001024 Argument, ArgumentLen,
1025 FormattedArgs.data(), FormattedArgs.size(),
1026 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +00001027 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +00001028 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001029
1030 // Remember this argument info for subsequent formatting operations. Turn
1031 // std::strings into a null terminated string to make it be the same case as
1032 // all the other ones.
1033 if (Kind != Diagnostic::ak_std_string)
1034 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1035 else
1036 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1037 (intptr_t)getArgStdStr(ArgNo).c_str()));
1038
Nico Weber7bfaaae2008-08-10 19:59:06 +00001039 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001040}
Ted Kremenekcabe6682009-01-23 20:28:53 +00001041
Douglas Gregora88084b2010-02-18 18:08:43 +00001042StoredDiagnostic::StoredDiagnostic() { }
1043
1044StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1045 llvm::StringRef Message)
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001046 : Level(Level), Loc(), Message(Message) { }
Douglas Gregora88084b2010-02-18 18:08:43 +00001047
1048StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1049 const DiagnosticInfo &Info)
Chris Lattner0a76aae2010-06-18 22:45:06 +00001050 : Level(Level), Loc(Info.getLocation()) {
Douglas Gregora88084b2010-02-18 18:08:43 +00001051 llvm::SmallString<64> Message;
1052 Info.FormatDiagnostic(Message);
1053 this->Message.assign(Message.begin(), Message.end());
1054
1055 Ranges.reserve(Info.getNumRanges());
1056 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
1057 Ranges.push_back(Info.getRange(I));
1058
Douglas Gregor849b2432010-03-31 17:46:05 +00001059 FixIts.reserve(Info.getNumFixItHints());
1060 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
1061 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregora88084b2010-02-18 18:08:43 +00001062}
1063
1064StoredDiagnostic::~StoredDiagnostic() { }
1065
Douglas Gregord93256e2010-01-28 06:00:51 +00001066static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1067 OS.write((const char *)&Value, sizeof(unsigned));
1068}
1069
1070static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1071 WriteUnsigned(OS, String.size());
1072 OS.write(String.data(), String.size());
1073}
1074
1075static void WriteSourceLocation(llvm::raw_ostream &OS,
1076 SourceManager *SM,
1077 SourceLocation Location) {
1078 if (!SM || Location.isInvalid()) {
1079 // If we don't have a source manager or this location is invalid,
1080 // just write an invalid location.
1081 WriteUnsigned(OS, 0);
1082 WriteUnsigned(OS, 0);
1083 WriteUnsigned(OS, 0);
1084 return;
1085 }
1086
1087 Location = SM->getInstantiationLoc(Location);
1088 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
Ted Kremenekec55c942010-04-12 19:54:17 +00001089
1090 const FileEntry *FE = SM->getFileEntryForID(Decomposed.first);
1091 if (FE)
1092 WriteString(OS, FE->getName());
1093 else {
1094 // Fallback to using the buffer name when there is no entry.
1095 WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier());
1096 }
1097
Douglas Gregord93256e2010-01-28 06:00:51 +00001098 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1099 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1100}
1101
Douglas Gregora88084b2010-02-18 18:08:43 +00001102void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
Douglas Gregord93256e2010-01-28 06:00:51 +00001103 SourceManager *SM = 0;
1104 if (getLocation().isValid())
1105 SM = &const_cast<SourceManager &>(getLocation().getManager());
1106
Douglas Gregorb9c903b2010-02-19 00:40:40 +00001107 // Write a short header to help identify diagnostics.
1108 OS << (char)0x06 << (char)0x07;
1109
Douglas Gregord93256e2010-01-28 06:00:51 +00001110 // Write the diagnostic level and location.
Douglas Gregora88084b2010-02-18 18:08:43 +00001111 WriteUnsigned(OS, (unsigned)Level);
Douglas Gregord93256e2010-01-28 06:00:51 +00001112 WriteSourceLocation(OS, SM, getLocation());
1113
1114 // Write the diagnostic message.
1115 llvm::SmallString<64> Message;
Douglas Gregora88084b2010-02-18 18:08:43 +00001116 WriteString(OS, getMessage());
Douglas Gregord93256e2010-01-28 06:00:51 +00001117
1118 // Count the number of ranges that don't point into macros, since
1119 // only simple file ranges serialize well.
1120 unsigned NumNonMacroRanges = 0;
Douglas Gregora88084b2010-02-18 18:08:43 +00001121 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1122 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +00001123 continue;
1124
1125 ++NumNonMacroRanges;
1126 }
1127
1128 // Write the ranges.
1129 WriteUnsigned(OS, NumNonMacroRanges);
1130 if (NumNonMacroRanges) {
Douglas Gregora88084b2010-02-18 18:08:43 +00001131 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1132 if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
Douglas Gregord93256e2010-01-28 06:00:51 +00001133 continue;
1134
Douglas Gregora88084b2010-02-18 18:08:43 +00001135 WriteSourceLocation(OS, SM, R->getBegin());
1136 WriteSourceLocation(OS, SM, R->getEnd());
Chris Lattner0a76aae2010-06-18 22:45:06 +00001137 WriteUnsigned(OS, R->isTokenRange());
Douglas Gregord93256e2010-01-28 06:00:51 +00001138 }
1139 }
1140
1141 // Determine if all of the fix-its involve rewrites with simple file
1142 // locations (not in macro instantiations). If so, we can write
1143 // fix-it information.
Douglas Gregora88084b2010-02-18 18:08:43 +00001144 unsigned NumFixIts = 0;
1145 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1146 if (F->RemoveRange.isValid() &&
1147 (F->RemoveRange.getBegin().isMacroID() ||
1148 F->RemoveRange.getEnd().isMacroID())) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001149 NumFixIts = 0;
1150 break;
1151 }
1152
Douglas Gregora88084b2010-02-18 18:08:43 +00001153 if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) {
Douglas Gregord93256e2010-01-28 06:00:51 +00001154 NumFixIts = 0;
1155 break;
1156 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001157
1158 ++NumFixIts;
Douglas Gregord93256e2010-01-28 06:00:51 +00001159 }
1160
1161 // Write the fix-its.
1162 WriteUnsigned(OS, NumFixIts);
Douglas Gregora88084b2010-02-18 18:08:43 +00001163 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1164 WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1165 WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
Chris Lattner0a76aae2010-06-18 22:45:06 +00001166 WriteUnsigned(OS, F->RemoveRange.isTokenRange());
Douglas Gregora88084b2010-02-18 18:08:43 +00001167 WriteSourceLocation(OS, SM, F->InsertionLoc);
1168 WriteString(OS, F->CodeToInsert);
Douglas Gregord93256e2010-01-28 06:00:51 +00001169 }
1170}
1171
Douglas Gregora88084b2010-02-18 18:08:43 +00001172static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1173 unsigned &Value) {
1174 if (Memory + sizeof(unsigned) > MemoryEnd)
1175 return true;
1176
1177 memmove(&Value, Memory, sizeof(unsigned));
1178 Memory += sizeof(unsigned);
1179 return false;
1180}
1181
1182static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1183 const char *&Memory, const char *MemoryEnd,
1184 SourceLocation &Location) {
1185 // Read the filename.
1186 unsigned FileNameLen = 0;
1187 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1188 Memory + FileNameLen > MemoryEnd)
1189 return true;
1190
1191 llvm::StringRef FileName(Memory, FileNameLen);
1192 Memory += FileNameLen;
1193
1194 // Read the line, column.
1195 unsigned Line = 0, Column = 0;
1196 if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1197 ReadUnsigned(Memory, MemoryEnd, Column))
1198 return true;
1199
1200 if (FileName.empty()) {
1201 Location = SourceLocation();
1202 return false;
1203 }
1204
1205 const FileEntry *File = FM.getFile(FileName);
1206 if (!File)
1207 return true;
1208
1209 // Make sure that this file has an entry in the source manager.
1210 if (!SM.hasFileInfo(File))
1211 SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1212
1213 Location = SM.getLocation(File, Line, Column);
1214 return false;
1215}
1216
1217StoredDiagnostic
1218StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1219 const char *&Memory, const char *MemoryEnd) {
Douglas Gregorb9c903b2010-02-19 00:40:40 +00001220 while (true) {
1221 if (Memory == MemoryEnd)
1222 return StoredDiagnostic();
1223
1224 if (*Memory != 0x06) {
1225 ++Memory;
1226 continue;
1227 }
1228
1229 ++Memory;
1230 if (Memory == MemoryEnd)
1231 return StoredDiagnostic();
1232
1233 if (*Memory != 0x07) {
1234 ++Memory;
1235 continue;
1236 }
1237
1238 // We found the header. We're done.
1239 ++Memory;
1240 break;
1241 }
1242
Douglas Gregora88084b2010-02-18 18:08:43 +00001243 // Read the severity level.
1244 unsigned Level = 0;
1245 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1246 return StoredDiagnostic();
1247
1248 // Read the source location.
1249 SourceLocation Location;
1250 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1251 return StoredDiagnostic();
1252
1253 // Read the diagnostic text.
1254 if (Memory == MemoryEnd)
1255 return StoredDiagnostic();
1256
1257 unsigned MessageLen = 0;
1258 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1259 Memory + MessageLen > MemoryEnd)
1260 return StoredDiagnostic();
1261
1262 llvm::StringRef Message(Memory, MessageLen);
1263 Memory += MessageLen;
1264
1265
1266 // At this point, we have enough information to form a diagnostic. Do so.
1267 StoredDiagnostic Diag;
1268 Diag.Level = (Diagnostic::Level)Level;
1269 Diag.Loc = FullSourceLoc(Location, SM);
1270 Diag.Message = Message;
1271 if (Memory == MemoryEnd)
1272 return Diag;
1273
1274 // Read the source ranges.
1275 unsigned NumSourceRanges = 0;
1276 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1277 return Diag;
1278 for (unsigned I = 0; I != NumSourceRanges; ++I) {
1279 SourceLocation Begin, End;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001280 unsigned IsTokenRange;
Douglas Gregora88084b2010-02-18 18:08:43 +00001281 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
Chris Lattner0a76aae2010-06-18 22:45:06 +00001282 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End) ||
1283 ReadUnsigned(Memory, MemoryEnd, IsTokenRange))
Douglas Gregora88084b2010-02-18 18:08:43 +00001284 return Diag;
1285
Chris Lattner0a76aae2010-06-18 22:45:06 +00001286 Diag.Ranges.push_back(CharSourceRange(SourceRange(Begin, End),
1287 IsTokenRange));
Douglas Gregora88084b2010-02-18 18:08:43 +00001288 }
1289
1290 // Read the fix-it hints.
1291 unsigned NumFixIts = 0;
1292 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1293 return Diag;
1294 for (unsigned I = 0; I != NumFixIts; ++I) {
1295 SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001296 unsigned InsertLen = 0, RemoveIsTokenRange;
Douglas Gregora88084b2010-02-18 18:08:43 +00001297 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1298 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
Chris Lattner0a76aae2010-06-18 22:45:06 +00001299 ReadUnsigned(Memory, MemoryEnd, RemoveIsTokenRange) ||
Douglas Gregora88084b2010-02-18 18:08:43 +00001300 ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
1301 ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1302 Memory + InsertLen > MemoryEnd) {
1303 Diag.FixIts.clear();
1304 return Diag;
1305 }
1306
Douglas Gregor849b2432010-03-31 17:46:05 +00001307 FixItHint Hint;
Chris Lattner0a76aae2010-06-18 22:45:06 +00001308 Hint.RemoveRange = CharSourceRange(SourceRange(RemoveBegin, RemoveEnd),
1309 RemoveIsTokenRange);
Douglas Gregora88084b2010-02-18 18:08:43 +00001310 Hint.InsertionLoc = InsertionLoc;
1311 Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1312 Memory += InsertLen;
1313 Diag.FixIts.push_back(Hint);
1314 }
1315
1316 return Diag;
1317}
1318
Ted Kremenekcabe6682009-01-23 20:28:53 +00001319/// IncludeInDiagnosticCounts - This method (whose default implementation
1320/// returns true) indicates whether the diagnostics handled by this
1321/// DiagnosticClient should be included in the number of diagnostics
1322/// reported by Diagnostic.
1323bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001324
1325PartialDiagnostic::StorageAllocator::StorageAllocator() {
1326 for (unsigned I = 0; I != NumCached; ++I)
1327 FreeList[I] = Cached + I;
1328 NumFreeListEntries = NumCached;
1329}
1330
1331PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1332 assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
1333}