blob: 094f7760a8ec430d2433181ecc0836d47abb16f5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/Diagnostic.h"
Chris Lattner27ceb9d2009-04-15 07:01:18 +000015
16#include "clang/Lex/LexDiagnostic.h"
17#include "clang/Parse/ParseDiagnostic.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/Sema/SemaDiagnostic.h"
20#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Analysis/AnalysisDiagnostic.h"
22#include "clang/Driver/DriverDiagnostic.h"
23
Douglas Gregord93256e2010-01-28 06:00:51 +000024#include "clang/Basic/FileManager.h"
Chris Lattner43b628c2008-11-19 07:32:16 +000025#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/SourceLocation.h"
Douglas Gregord93256e2010-01-28 06:00:51 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000028#include "llvm/ADT/SmallVector.h"
Chris Lattner30bc9652008-11-19 07:22:31 +000029#include "llvm/ADT/StringExtras.h"
Daniel Dunbar23e47c62009-10-17 18:12:14 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner182745a2007-12-02 01:09:57 +000031#include <vector>
32#include <map>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000033#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattner182745a2007-12-02 01:09:57 +000036//===----------------------------------------------------------------------===//
37// Builtin Diagnostic information
38//===----------------------------------------------------------------------===//
39
Chris Lattner121f60c2009-04-16 06:07:15 +000040// Diagnostic classes.
41enum {
42 CLASS_NOTE = 0x01,
43 CLASS_WARNING = 0x02,
44 CLASS_EXTENSION = 0x03,
45 CLASS_ERROR = 0x04
46};
Chris Lattner27ceb9d2009-04-15 07:01:18 +000047
Chris Lattner33dd2822009-04-16 06:00:24 +000048struct StaticDiagInfoRec {
Chris Lattner121f60c2009-04-16 06:07:15 +000049 unsigned short DiagID;
50 unsigned Mapping : 3;
51 unsigned Class : 3;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000052 bool SFINAE : 1;
Chris Lattner121f60c2009-04-16 06:07:15 +000053 const char *Description;
Chris Lattner33dd2822009-04-16 06:00:24 +000054 const char *OptionGroup;
Mike Stump1eb44332009-09-09 15:08:12 +000055
Chris Lattner87d854e2009-04-16 06:13:46 +000056 bool operator<(const StaticDiagInfoRec &RHS) const {
57 return DiagID < RHS.DiagID;
58 }
59 bool operator>(const StaticDiagInfoRec &RHS) const {
60 return DiagID > RHS.DiagID;
61 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +000062};
63
Chris Lattner33dd2822009-04-16 06:00:24 +000064static const StaticDiagInfoRec StaticDiagInfo[] = {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000065#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) \
66 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, DESC, GROUP },
Chris Lattner27ceb9d2009-04-15 07:01:18 +000067#include "clang/Basic/DiagnosticCommonKinds.inc"
68#include "clang/Basic/DiagnosticDriverKinds.inc"
69#include "clang/Basic/DiagnosticFrontendKinds.inc"
70#include "clang/Basic/DiagnosticLexKinds.inc"
71#include "clang/Basic/DiagnosticParseKinds.inc"
72#include "clang/Basic/DiagnosticASTKinds.inc"
73#include "clang/Basic/DiagnosticSemaKinds.inc"
74#include "clang/Basic/DiagnosticAnalysisKinds.inc"
Douglas Gregor5e9f35c2009-06-14 07:33:30 +000075 { 0, 0, 0, 0, 0, 0}
Chris Lattner27ceb9d2009-04-15 07:01:18 +000076};
Chris Lattner8a941e02009-04-15 16:56:26 +000077#undef DIAG
Chris Lattner27ceb9d2009-04-15 07:01:18 +000078
Chris Lattner87d854e2009-04-16 06:13:46 +000079/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
80/// or null if the ID is invalid.
Chris Lattner33dd2822009-04-16 06:00:24 +000081static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
Chris Lattner87d854e2009-04-16 06:13:46 +000082 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
83
84 // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
85#ifndef NDEBUG
86 static bool IsFirst = true;
87 if (IsFirst) {
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000088 for (unsigned i = 1; i != NumDiagEntries; ++i) {
89 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
90 "Diag ID conflict, the enums at the start of clang::diag (in "
91 "Diagnostic.h) probably need to be increased");
92
Chris Lattner87d854e2009-04-16 06:13:46 +000093 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
94 "Improperly sorted diag info");
Chris Lattner5a3ce9b2009-10-16 02:34:51 +000095 }
Chris Lattner87d854e2009-04-16 06:13:46 +000096 IsFirst = false;
97 }
98#endif
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner87d854e2009-04-16 06:13:46 +0000100 // Search the diagnostic table with a binary search.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000101 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 };
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner87d854e2009-04-16 06:13:46 +0000103 const StaticDiagInfoRec *Found =
104 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
105 if (Found == StaticDiagInfo + NumDiagEntries ||
106 Found->DiagID != DiagID)
107 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner87d854e2009-04-16 06:13:46 +0000109 return Found;
Chris Lattner33dd2822009-04-16 06:00:24 +0000110}
111
112static unsigned GetDefaultDiagMapping(unsigned DiagID) {
113 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Chris Lattner121f60c2009-04-16 06:07:15 +0000114 return Info->Mapping;
Chris Lattner691f1ae2009-04-16 04:12:40 +0000115 return diag::MAP_FATAL;
116}
117
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000118/// getWarningOptionForDiag - Return the lowest-level warning option that
119/// enables the specified diagnostic. If there is no -Wfoo flag that controls
120/// the diagnostic, this returns null.
121const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
Chris Lattner33dd2822009-04-16 06:00:24 +0000122 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
123 return Info->OptionGroup;
124 return 0;
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000125}
126
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000127bool Diagnostic::isBuiltinSFINAEDiag(unsigned DiagID) {
128 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
Douglas Gregor8439fac2009-06-15 16:52:15 +0000129 return Info->SFINAE && Info->Class == CLASS_ERROR;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000130 return false;
131}
132
Reid Spencer5f016e22007-07-11 17:01:13 +0000133/// getDiagClass - Return the class field of the diagnostic.
134///
Chris Lattner07506182007-11-30 22:53:43 +0000135static unsigned getBuiltinDiagClass(unsigned DiagID) {
Chris Lattner121f60c2009-04-16 06:07:15 +0000136 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
137 return Info->Class;
138 return ~0U;
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
Chris Lattner182745a2007-12-02 01:09:57 +0000141//===----------------------------------------------------------------------===//
142// Custom Diagnostic information
143//===----------------------------------------------------------------------===//
144
145namespace clang {
146 namespace diag {
147 class CustomDiagInfo {
148 typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
149 std::vector<DiagDesc> DiagInfo;
150 std::map<DiagDesc, unsigned> DiagIDs;
151 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Chris Lattner182745a2007-12-02 01:09:57 +0000153 /// getDescription - Return the description of the specified custom
154 /// diagnostic.
155 const char *getDescription(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000156 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000157 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000158 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
Chris Lattner182745a2007-12-02 01:09:57 +0000159 }
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner182745a2007-12-02 01:09:57 +0000161 /// getLevel - Return the level of the specified custom diagnostic.
162 Diagnostic::Level getLevel(unsigned DiagID) const {
Chris Lattner88eccaf2009-01-29 06:55:46 +0000163 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
Chris Lattner182745a2007-12-02 01:09:57 +0000164 "Invalid diagnosic ID");
Chris Lattner88eccaf2009-01-29 06:55:46 +0000165 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
Chris Lattner182745a2007-12-02 01:09:57 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000168 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000169 Diagnostic &Diags) {
Chris Lattner182745a2007-12-02 01:09:57 +0000170 DiagDesc D(L, Message);
171 // Check to see if it already exists.
172 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
173 if (I != DiagIDs.end() && I->first == D)
174 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattner182745a2007-12-02 01:09:57 +0000176 // If not, assign a new ID.
Chris Lattner88eccaf2009-01-29 06:55:46 +0000177 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
Chris Lattner182745a2007-12-02 01:09:57 +0000178 DiagIDs.insert(std::make_pair(D, ID));
179 DiagInfo.push_back(D);
180 return ID;
181 }
182 };
Mike Stump1eb44332009-09-09 15:08:12 +0000183
184 } // end diag namespace
185} // end clang namespace
Chris Lattner182745a2007-12-02 01:09:57 +0000186
187
188//===----------------------------------------------------------------------===//
189// Common Diagnostic implementation
190//===----------------------------------------------------------------------===//
191
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000192static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
193 const char *Modifier, unsigned ML,
194 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000195 const Diagnostic::ArgumentValue *PrevArgs,
196 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +0000197 llvm::SmallVectorImpl<char> &Output,
198 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000199 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +0000200 Output.append(Str, Str+strlen(Str));
201}
202
203
Ted Kremenekb4398aa2008-08-07 17:49:57 +0000204Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000205 AllExtensionsSilenced = 0;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000206 IgnoreAllWarnings = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 WarningsAsErrors = false;
Chris Lattnere663c722009-12-22 23:12:53 +0000208 ErrorsAsFatal = false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000209 SuppressSystemWarnings = false;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000210 SuppressAllDiagnostics = false;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000211 ExtBehavior = Ext_Ignore;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 ErrorOccurred = false;
Chris Lattner15221422009-02-06 04:16:02 +0000214 FatalErrorOccurred = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 NumDiagnostics = 0;
Steve Naroffe0c4d892009-12-05 02:14:08 +0000216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 NumErrors = 0;
Chris Lattner182745a2007-12-02 01:09:57 +0000218 CustomDiagInfo = 0;
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000219 CurDiagID = ~0U;
Douglas Gregor525c4b02009-03-19 18:55:06 +0000220 LastDiagLevel = Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000222 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +0000223 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner691f1ae2009-04-16 04:12:40 +0000225 // Set all mappings to 'unset'.
Chris Lattner04ae2df2009-07-12 21:18:45 +0000226 DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
227 DiagMappingsStack.push_back(BlankDiags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000228}
229
Chris Lattner182745a2007-12-02 01:09:57 +0000230Diagnostic::~Diagnostic() {
231 delete CustomDiagInfo;
232}
233
Chris Lattner04ae2df2009-07-12 21:18:45 +0000234
235void Diagnostic::pushMappings() {
John Thompsonca2c3e22009-10-23 02:21:17 +0000236 // Avoids undefined behavior when the stack has to resize.
237 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000238 DiagMappingsStack.push_back(DiagMappingsStack.back());
239}
240
241bool Diagnostic::popMappings() {
242 if (DiagMappingsStack.size() == 1)
243 return false;
244
245 DiagMappingsStack.pop_back();
246 return true;
247}
248
Chris Lattner182745a2007-12-02 01:09:57 +0000249/// getCustomDiagID - Return an ID for a diagnostic with the specified message
250/// and level. If this is the first request for this diagnosic, it is
251/// registered and created, otherwise the existing ID is returned.
Daniel Dunbar32d4d802009-12-01 17:42:06 +0000252unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
Mike Stump1eb44332009-09-09 15:08:12 +0000253 if (CustomDiagInfo == 0)
Chris Lattner182745a2007-12-02 01:09:57 +0000254 CustomDiagInfo = new diag::CustomDiagInfo();
Chris Lattnera1f23cc2008-10-17 21:24:47 +0000255 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
Chris Lattner182745a2007-12-02 01:09:57 +0000256}
257
258
Chris Lattnerf5d23282009-02-17 06:49:55 +0000259/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
260/// level of the specified diagnostic ID is a Warning or Extension.
261/// This only works on builtin diagnostics, not custom ones, and is not legal to
262/// call on NOTEs.
263bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000264 return DiagID < diag::DIAG_UPPER_LIMIT &&
265 getBuiltinDiagClass(DiagID) != CLASS_ERROR;
Reid Spencer5f016e22007-07-11 17:01:13 +0000266}
267
Douglas Gregoree1828a2009-03-10 18:03:33 +0000268/// \brief Determine whether the given built-in diagnostic ID is a
269/// Note.
270bool Diagnostic::isBuiltinNote(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000271 return DiagID < diag::DIAG_UPPER_LIMIT &&
272 getBuiltinDiagClass(DiagID) == CLASS_NOTE;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000273}
274
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000275/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
276/// ID is for an extension of some sort.
277///
278bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) {
Chris Lattner8a941e02009-04-15 16:56:26 +0000279 return DiagID < diag::DIAG_UPPER_LIMIT &&
280 getBuiltinDiagClass(DiagID) == CLASS_EXTENSION;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000281}
282
Reid Spencer5f016e22007-07-11 17:01:13 +0000283
284/// getDescription - Given a diagnostic ID, return a description of the
285/// issue.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000286const char *Diagnostic::getDescription(unsigned DiagID) const {
Chris Lattner121f60c2009-04-16 06:07:15 +0000287 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
288 return Info->Description;
Chris Lattner20c6b3b2009-01-27 18:30:58 +0000289 return CustomDiagInfo->getDescription(DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000290}
291
292/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
293/// object, classify the specified diagnostic ID into a Level, consumable by
294/// the DiagnosticClient.
295Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
Chris Lattner182745a2007-12-02 01:09:57 +0000296 // Handle custom diagnostics, which cannot be mapped.
Chris Lattner19e8e2c2009-01-29 17:46:13 +0000297 if (DiagID >= diag::DIAG_UPPER_LIMIT)
Chris Lattner182745a2007-12-02 01:09:57 +0000298 return CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattner07506182007-11-30 22:53:43 +0000300 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000301 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
Chris Lattnerf5d23282009-02-17 06:49:55 +0000302 return getDiagnosticLevel(DiagID, DiagClass);
303}
304
305/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
306/// object, classify the specified diagnostic ID into a Level, consumable by
307/// the DiagnosticClient.
308Diagnostic::Level
309Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 // Specific non-error diagnostics may be mapped to various levels from ignored
Chris Lattnerf5d23282009-02-17 06:49:55 +0000311 // to error. Errors can only be mapped to fatal.
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000312 Diagnostic::Level Result = Diagnostic::Fatal;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner691f1ae2009-04-16 04:12:40 +0000314 // Get the mapping information, if unset, compute it lazily.
315 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
316 if (MappingInfo == 0) {
317 MappingInfo = GetDefaultDiagMapping(DiagID);
318 setDiagnosticMappingInternal(DiagID, MappingInfo, false);
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner691f1ae2009-04-16 04:12:40 +0000321 switch (MappingInfo & 7) {
322 default: assert(0 && "Unknown mapping!");
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000323 case diag::MAP_IGNORE:
Chris Lattnerb54b2762009-04-16 05:04:32 +0000324 // Ignore this, unless this is an extension diagnostic and we're mapping
325 // them onto warnings or errors.
326 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension
327 ExtBehavior == Ext_Ignore || // Extensions ignored anyway
328 (MappingInfo & 8) != 0) // User explicitly mapped it.
329 return Diagnostic::Ignored;
330 Result = Diagnostic::Warning;
331 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000332 if (Result == Diagnostic::Error && ErrorsAsFatal)
333 Result = Diagnostic::Fatal;
Chris Lattnerb54b2762009-04-16 05:04:32 +0000334 break;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000335 case diag::MAP_ERROR:
336 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000337 if (ErrorsAsFatal)
338 Result = Diagnostic::Fatal;
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000339 break;
340 case diag::MAP_FATAL:
341 Result = Diagnostic::Fatal;
342 break;
343 case diag::MAP_WARNING:
344 // If warnings are globally mapped to ignore or error, do it.
Chris Lattner5b4681c2008-05-29 15:36:45 +0000345 if (IgnoreAllWarnings)
346 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000348 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattnerb54b2762009-04-16 05:04:32 +0000350 // If this is an extension diagnostic and we're in -pedantic-error mode, and
351 // if the user didn't explicitly map it, upgrade to an error.
352 if (ExtBehavior == Ext_Error &&
353 (MappingInfo & 8) == 0 &&
354 isBuiltinExtensionDiag(DiagID))
355 Result = Diagnostic::Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000357 if (WarningsAsErrors)
358 Result = Diagnostic::Error;
Chris Lattnere663c722009-12-22 23:12:53 +0000359 if (Result == Diagnostic::Error && ErrorsAsFatal)
360 Result = Diagnostic::Fatal;
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000361 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000363 case diag::MAP_WARNING_NO_WERROR:
364 // Diagnostics specified with -Wno-error=foo should be set to warnings, but
365 // not be adjusted by -Werror or -pedantic-errors.
366 Result = Diagnostic::Warning;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner2b07d8f2009-04-16 04:32:54 +0000368 // If warnings are globally mapped to ignore or error, do it.
369 if (IgnoreAllWarnings)
370 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000372 break;
Chris Lattnere663c722009-12-22 23:12:53 +0000373
374 case diag::MAP_ERROR_NO_WFATAL:
375 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
376 // unaffected by -Wfatal-errors.
377 Result = Diagnostic::Error;
378 break;
Chris Lattner5b4681c2008-05-29 15:36:45 +0000379 }
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000380
381 // Okay, we're about to return this as a "diagnostic to emit" one last check:
382 // if this is any sort of extension warning, and if we're in an __extension__
383 // block, silence it.
384 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
385 return Diagnostic::Ignored;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner27ceb9d2009-04-15 07:01:18 +0000387 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Douglas Gregord93256e2010-01-28 06:00:51 +0000390static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
391 unsigned &Value) {
392 if (Memory + sizeof(unsigned) > MemoryEnd)
393 return true;
394
395 memmove(&Value, Memory, sizeof(unsigned));
396 Memory += sizeof(unsigned);
397 return false;
398}
399
400static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
401 const char *&Memory, const char *MemoryEnd,
402 SourceLocation &Location) {
403 // Read the filename.
404 unsigned FileNameLen = 0;
405 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
406 Memory + FileNameLen > MemoryEnd)
407 return true;
408
409 llvm::StringRef FileName(Memory, FileNameLen);
410 Memory += FileNameLen;
411
412 // Read the line, column.
413 unsigned Line = 0, Column = 0;
414 if (ReadUnsigned(Memory, MemoryEnd, Line) ||
415 ReadUnsigned(Memory, MemoryEnd, Column))
416 return true;
417
418 if (FileName.empty()) {
419 Location = SourceLocation();
420 return false;
421 }
422
423 const FileEntry *File = FM.getFile(FileName);
424 if (!File)
425 return true;
426
427 // Make sure that this file has an entry in the source manager.
428 if (!SM.hasFileInfo(File))
429 SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
430
431 Location = SM.getLocation(File, Line, Column);
432 return false;
433}
434
435DiagnosticBuilder Diagnostic::Deserialize(FileManager &FM, SourceManager &SM,
436 const char *&Memory,
437 const char *MemoryEnd) {
438 if (Memory == MemoryEnd)
439 return DiagnosticBuilder(0);
440
441 // Read the severity level.
442 unsigned Level = 0;
443 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Fatal)
444 return DiagnosticBuilder(0);
445
446 // Read the source location.
447 SourceLocation Location;
448 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
449 return DiagnosticBuilder(0);
450
451 // Read the diagnostic text.
452 if (Memory == MemoryEnd)
453 return DiagnosticBuilder(0);
454
455 unsigned MessageLen = 0;
456 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
457 Memory + MessageLen > MemoryEnd)
458 return DiagnosticBuilder(0);
459
460 llvm::StringRef Message(Memory, MessageLen);
461 Memory += MessageLen;
462
463 // At this point, we have enough information to form a diagnostic. Do so.
464 unsigned DiagID = getCustomDiagID((enum Level)Level, Message);
465 DiagnosticBuilder DB = Report(FullSourceLoc(Location, SM), DiagID);
466 if (Memory == MemoryEnd)
467 return DB;
468
469 // Read the source ranges.
470 unsigned NumSourceRanges = 0;
471 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
472 return DB;
473 for (unsigned I = 0; I != NumSourceRanges; ++I) {
474 SourceLocation Begin, End;
475 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
476 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End))
477 return DB;
478
479 DB << SourceRange(Begin, End);
480 }
481
482 // Read the fix-it hints.
483 unsigned NumFixIts = 0;
484 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
485 return DB;
486 for (unsigned I = 0; I != NumFixIts; ++I) {
487 SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
488 unsigned InsertLen = 0;
489 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
490 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
491 ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
492 ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
493 Memory + InsertLen > MemoryEnd)
494 return DB;
495
496 CodeModificationHint Hint;
497 Hint.RemoveRange = SourceRange(RemoveBegin, RemoveEnd);
498 Hint.InsertionLoc = InsertionLoc;
499 Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
500 Memory += InsertLen;
501 DB << Hint;
502 }
503
504 return DB;
505}
506
Chris Lattner3bc172b2009-04-19 22:34:23 +0000507struct WarningOption {
508 const char *Name;
509 const short *Members;
510 const char *SubGroups;
511};
512
513#define GET_DIAG_ARRAYS
514#include "clang/Basic/DiagnosticGroups.inc"
515#undef GET_DIAG_ARRAYS
516
517// Second the table of options, sorted by name for fast binary lookup.
518static const WarningOption OptionTable[] = {
519#define GET_DIAG_TABLE
520#include "clang/Basic/DiagnosticGroups.inc"
521#undef GET_DIAG_TABLE
522};
523static const size_t OptionTableSize =
524sizeof(OptionTable) / sizeof(OptionTable[0]);
525
526static bool WarningOptionCompare(const WarningOption &LHS,
527 const WarningOption &RHS) {
528 return strcmp(LHS.Name, RHS.Name) < 0;
529}
530
531static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
532 Diagnostic &Diags) {
533 // Option exists, poke all the members of its diagnostic set.
534 if (const short *Member = Group->Members) {
535 for (; *Member != -1; ++Member)
536 Diags.setDiagnosticMapping(*Member, Mapping);
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner3bc172b2009-04-19 22:34:23 +0000539 // Enable/disable all subgroups along with this one.
540 if (const char *SubGroups = Group->SubGroups) {
541 for (; *SubGroups != (char)-1; ++SubGroups)
542 MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
543 }
544}
545
546/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
547/// "unknown-pragmas" to have the specified mapping. This returns true and
548/// ignores the request if "Group" was unknown, false otherwise.
549bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
550 diag::Mapping Map) {
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattner3bc172b2009-04-19 22:34:23 +0000552 WarningOption Key = { Group, 0, 0 };
553 const WarningOption *Found =
554 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
555 WarningOptionCompare);
556 if (Found == OptionTable + OptionTableSize ||
557 strcmp(Found->Name, Group) != 0)
558 return true; // Option not found.
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner3bc172b2009-04-19 22:34:23 +0000560 MapGroupMembers(Found, Map, *this);
561 return false;
562}
563
564
Chris Lattner0a14eee2008-11-18 07:04:44 +0000565/// ProcessDiag - This is the method used to report a diagnostic that is
566/// finally fully formed.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000567bool Diagnostic::ProcessDiag() {
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000568 DiagnosticInfo Info(this);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Douglas Gregor81b747b2009-09-17 21:32:03 +0000570 if (SuppressAllDiagnostics)
571 return false;
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 // Figure out the diagnostic level of this message.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000574 Diagnostic::Level DiagLevel;
575 unsigned DiagID = Info.getID();
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattnerf5d23282009-02-17 06:49:55 +0000577 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
578 // in a system header.
579 bool ShouldEmitInSystemHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Chris Lattnerf5d23282009-02-17 06:49:55 +0000581 if (DiagID >= diag::DIAG_UPPER_LIMIT) {
582 // Handle custom diagnostics, which cannot be mapped.
583 DiagLevel = CustomDiagInfo->getLevel(DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattnerf5d23282009-02-17 06:49:55 +0000585 // Custom diagnostics always are emitted in system headers.
586 ShouldEmitInSystemHeader = true;
587 } else {
588 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever
589 // the diagnostic level was for the previous diagnostic so that it is
590 // filtered the same as the previous diagnostic.
591 unsigned DiagClass = getBuiltinDiagClass(DiagID);
Chris Lattner8a941e02009-04-15 16:56:26 +0000592 if (DiagClass == CLASS_NOTE) {
Chris Lattnerf5d23282009-02-17 06:49:55 +0000593 DiagLevel = Diagnostic::Note;
594 ShouldEmitInSystemHeader = false; // extra consideration is needed
595 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 // If this is not an error and we are in a system header, we ignore it.
Chris Lattnerf5d23282009-02-17 06:49:55 +0000597 // Check the original Diag ID here, because we also want to ignore
598 // extensions and warnings in -Werror and -pedantic-errors modes, which
599 // *map* warnings/extensions to errors.
Chris Lattner8a941e02009-04-15 16:56:26 +0000600 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattnerf5d23282009-02-17 06:49:55 +0000602 DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
603 }
604 }
605
Douglas Gregor525c4b02009-03-19 18:55:06 +0000606 if (DiagLevel != Diagnostic::Note) {
607 // Record that a fatal error occurred only when we see a second
608 // non-note diagnostic. This allows notes to be attached to the
609 // fatal error, but suppresses any diagnostics that follow those
610 // notes.
611 if (LastDiagLevel == Diagnostic::Fatal)
612 FatalErrorOccurred = true;
613
Chris Lattnerf5d23282009-02-17 06:49:55 +0000614 LastDiagLevel = DiagLevel;
Mike Stump1eb44332009-09-09 15:08:12 +0000615 }
Douglas Gregor525c4b02009-03-19 18:55:06 +0000616
617 // If a fatal error has already been emitted, silence all subsequent
618 // diagnostics.
619 if (FatalErrorOccurred)
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000620 return false;
Douglas Gregor525c4b02009-03-19 18:55:06 +0000621
Chris Lattnerf5d23282009-02-17 06:49:55 +0000622 // If the client doesn't care about this message, don't issue it. If this is
623 // a note and the last real diagnostic was ignored, ignore it too.
624 if (DiagLevel == Diagnostic::Ignored ||
625 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000626 return false;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000627
Chris Lattnerf5d23282009-02-17 06:49:55 +0000628 // If this diagnostic is in a system header and is not a clang error, suppress
629 // it.
630 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
Chris Lattner0a14eee2008-11-18 07:04:44 +0000631 Info.getLocation().isValid() &&
John McCall779cf422010-02-11 10:04:29 +0000632 Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
Chris Lattner336f26b2009-02-17 06:52:20 +0000633 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
634 LastDiagLevel = Diagnostic::Ignored;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000635 return false;
Chris Lattner336f26b2009-02-17 06:52:20 +0000636 }
Chris Lattnerf5d23282009-02-17 06:49:55 +0000637
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 if (DiagLevel >= Diagnostic::Error) {
639 ErrorOccurred = true;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000640 ++NumErrors;
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 }
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 // Finally, report it.
Chris Lattner0a14eee2008-11-18 07:04:44 +0000644 Client->HandleDiagnostic(DiagLevel, Info);
Ted Kremenekcabe6682009-01-23 20:28:53 +0000645 if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000646
Douglas Gregoree1828a2009-03-10 18:03:33 +0000647 CurDiagID = ~0U;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000648
649 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000650}
651
Nico Weber7bfaaae2008-08-10 19:59:06 +0000652
Reid Spencer5f016e22007-07-11 17:01:13 +0000653DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000654
Chris Lattnerf4c83962008-11-19 06:51:40 +0000655
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000656/// ModifierIs - Return true if the specified modifier matches specified string.
657template <std::size_t StrLen>
658static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
659 const char (&Str)[StrLen]) {
660 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
661}
662
John McCall909c1822010-01-14 20:11:39 +0000663/// ScanForward - Scans forward, looking for the given character, skipping
664/// nested clauses and escaped characters.
665static const char *ScanFormat(const char *I, const char *E, char Target) {
666 unsigned Depth = 0;
667
668 for ( ; I != E; ++I) {
669 if (Depth == 0 && *I == Target) return I;
670 if (Depth != 0 && *I == '}') Depth--;
671
672 if (*I == '%') {
673 I++;
674 if (I == E) break;
675
676 // Escaped characters get implicitly skipped here.
677
678 // Format specifier.
679 if (!isdigit(*I) && !ispunct(*I)) {
680 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
681 if (I == E) break;
682 if (*I == '{')
683 Depth++;
684 }
685 }
686 }
687 return E;
688}
689
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000690/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
691/// like this: %select{foo|bar|baz}2. This means that the integer argument
692/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
693/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
694/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000695static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000696 const char *Argument, unsigned ArgumentLen,
697 llvm::SmallVectorImpl<char> &OutStr) {
698 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000700 // Skip over 'ValNo' |'s.
701 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000702 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000703 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
704 " larger than the number of options in the diagnostic string!");
705 Argument = NextVal+1; // Skip this string.
706 --ValNo;
707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000709 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000710 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000711
712 // Recursively format the result of the select clause into the output string.
713 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000714}
715
716/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
717/// letter 's' to the string if the value is not 1. This is used in cases like
718/// this: "you idiot, you have %4 parameter%s4!".
719static void HandleIntegerSModifier(unsigned ValNo,
720 llvm::SmallVectorImpl<char> &OutStr) {
721 if (ValNo != 1)
722 OutStr.push_back('s');
723}
724
John McCall3be16b72010-01-14 00:50:32 +0000725/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
726/// prints the ordinal form of the given integer, with 1 corresponding
727/// to the first ordinal. Currently this is hard-coded to use the
728/// English form.
729static void HandleOrdinalModifier(unsigned ValNo,
730 llvm::SmallVectorImpl<char> &OutStr) {
731 assert(ValNo != 0 && "ValNo must be strictly positive!");
732
733 llvm::raw_svector_ostream Out(OutStr);
734
735 // We could use text forms for the first N ordinals, but the numeric
736 // forms are actually nicer in diagnostics because they stand out.
737 Out << ValNo;
738
739 // It is critically important that we do this perfectly for
740 // user-written sequences with over 100 elements.
741 switch (ValNo % 100) {
742 case 11:
743 case 12:
744 case 13:
745 Out << "th"; return;
746 default:
747 switch (ValNo % 10) {
748 case 1: Out << "st"; return;
749 case 2: Out << "nd"; return;
750 case 3: Out << "rd"; return;
751 default: Out << "th"; return;
752 }
753 }
754}
755
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000756
Sebastian Redle4c452c2008-11-22 13:44:36 +0000757/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000758static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000759 // Programming 101: Parse a decimal number :-)
760 unsigned Val = 0;
761 while (Start != End && *Start >= '0' && *Start <= '9') {
762 Val *= 10;
763 Val += *Start - '0';
764 ++Start;
765 }
766 return Val;
767}
768
769/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000770static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000771 if (*Start != '[') {
772 unsigned Ref = PluralNumber(Start, End);
773 return Ref == Val;
774 }
775
776 ++Start;
777 unsigned Low = PluralNumber(Start, End);
778 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
779 ++Start;
780 unsigned High = PluralNumber(Start, End);
781 assert(*Start == ']' && "Bad plural expression syntax: expected )");
782 ++Start;
783 return Low <= Val && Val <= High;
784}
785
786/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000787static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000788 // Empty condition?
789 if (*Start == ':')
790 return true;
791
792 while (1) {
793 char C = *Start;
794 if (C == '%') {
795 // Modulo expression
796 ++Start;
797 unsigned Arg = PluralNumber(Start, End);
798 assert(*Start == '=' && "Bad plural expression syntax: expected =");
799 ++Start;
800 unsigned ValMod = ValNo % Arg;
801 if (TestPluralRange(ValMod, Start, End))
802 return true;
803 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000804 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000805 "Bad plural expression syntax: unexpected character");
806 // Range expression
807 if (TestPluralRange(ValNo, Start, End))
808 return true;
809 }
810
811 // Scan for next or-expr part.
812 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000813 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000814 break;
815 ++Start;
816 }
817 return false;
818}
819
820/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
821/// for complex plural forms, or in languages where all plurals are complex.
822/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
823/// conditions that are tested in order, the form corresponding to the first
824/// that applies being emitted. The empty condition is always true, making the
825/// last form a default case.
826/// Conditions are simple boolean expressions, where n is the number argument.
827/// Here are the rules.
828/// condition := expression | empty
829/// empty := -> always true
830/// expression := numeric [',' expression] -> logical or
831/// numeric := range -> true if n in range
832/// | '%' number '=' range -> true if n % number in range
833/// range := number
834/// | '[' number ',' number ']' -> ranges are inclusive both ends
835///
836/// Here are some examples from the GNU gettext manual written in this form:
837/// English:
838/// {1:form0|:form1}
839/// Latvian:
840/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
841/// Gaeilge:
842/// {1:form0|2:form1|:form2}
843/// Romanian:
844/// {1:form0|0,%100=[1,19]:form1|:form2}
845/// Lithuanian:
846/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
847/// Russian (requires repeated form):
848/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
849/// Slovak
850/// {1:form0|[2,4]:form1|:form2}
851/// Polish (requires repeated form):
852/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
853static void HandlePluralModifier(unsigned ValNo,
854 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000855 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000856 const char *ArgumentEnd = Argument + ArgumentLen;
857 while (1) {
858 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
859 const char *ExprEnd = Argument;
860 while (*ExprEnd != ':') {
861 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
862 ++ExprEnd;
863 }
864 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
865 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000866 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
Sebastian Redle4c452c2008-11-22 13:44:36 +0000867 OutStr.append(Argument, ExprEnd);
868 return;
869 }
John McCall909c1822010-01-14 20:11:39 +0000870 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000871 }
872}
873
874
Chris Lattnerf4c83962008-11-19 06:51:40 +0000875/// FormatDiagnostic - Format this diagnostic into a string, substituting the
876/// formal arguments into the %0 slots. The result is appended onto the Str
877/// array.
878void DiagnosticInfo::
879FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
880 const char *DiagStr = getDiags()->getDescription(getID());
881 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
John McCall9f286142010-01-13 23:58:20 +0000883 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
884}
885
886void DiagnosticInfo::
887FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
888 llvm::SmallVectorImpl<char> &OutStr) const {
889
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000890 /// FormattedArgs - Keep track of all of the arguments formatted by
891 /// ConvertArgToString and pass them into subsequent calls to
892 /// ConvertArgToString, allowing the implementation to avoid redundancies in
893 /// obvious cases.
894 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
895
Chris Lattnerf4c83962008-11-19 06:51:40 +0000896 while (DiagStr != DiagEnd) {
897 if (DiagStr[0] != '%') {
898 // Append non-%0 substrings to Str if we have one.
899 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
900 OutStr.append(DiagStr, StrEnd);
901 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000902 continue;
John McCall909c1822010-01-14 20:11:39 +0000903 } else if (ispunct(DiagStr[1])) {
904 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000905 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000906 continue;
907 }
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000909 // Skip the %.
910 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000912 // This must be a placeholder for a diagnostic argument. The format for a
913 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
914 // The digit is a number from 0-9 indicating which argument this comes from.
915 // The modifier is a string of digits from the set [-a-z]+, arguments is a
916 // brace enclosed string.
917 const char *Modifier = 0, *Argument = 0;
918 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000920 // Check to see if we have a modifier. If so eat it.
921 if (!isdigit(DiagStr[0])) {
922 Modifier = DiagStr;
923 while (DiagStr[0] == '-' ||
924 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
925 ++DiagStr;
926 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000927
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000928 // If we have an argument, get it next.
929 if (DiagStr[0] == '{') {
930 ++DiagStr; // Skip {.
931 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCall909c1822010-01-14 20:11:39 +0000933 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
934 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000935 ArgumentLen = DiagStr-Argument;
936 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000937 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000940 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000941 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000942
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000943 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
944
945 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000946 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000947 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000948 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000949 assert(ModifierLen == 0 && "No modifiers for strings yet");
950 OutStr.append(S.begin(), S.end());
951 break;
952 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000953 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000954 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000955 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000956
957 // Don't crash if get passed a null pointer by accident.
958 if (!S)
959 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000961 OutStr.append(S, S + strlen(S));
962 break;
963 }
Chris Lattner08631c52008-11-23 21:45:46 +0000964 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000965 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000966 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000968 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000969 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000970 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
971 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000972 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
973 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000974 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
975 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000976 } else {
977 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000978 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000979 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000980 break;
981 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000982 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000983 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000985 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000986 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000987 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
988 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000989 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
990 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000991 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
992 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000993 } else {
994 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000995 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000996 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000997 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000998 }
Chris Lattner08631c52008-11-23 21:45:46 +0000999 // ---- NAMES and TYPES ----
1000 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +00001001 const IdentifierInfo *II = getArgIdentifier(ArgNo);
1002 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +00001003
1004 // Don't crash if get passed a null pointer by accident.
1005 if (!II) {
1006 const char *S = "(null)";
1007 OutStr.append(S, S + strlen(S));
1008 continue;
1009 }
1010
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00001011 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +00001012 break;
1013 }
Chris Lattner22caddc2008-11-23 09:13:29 +00001014 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +00001015 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001016 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +00001017 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +00001018 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001019 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +00001020 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001021 Argument, ArgumentLen,
1022 FormattedArgs.data(), FormattedArgs.size(),
1023 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +00001024 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +00001025 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +00001026
1027 // Remember this argument info for subsequent formatting operations. Turn
1028 // std::strings into a null terminated string to make it be the same case as
1029 // all the other ones.
1030 if (Kind != Diagnostic::ak_std_string)
1031 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1032 else
1033 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1034 (intptr_t)getArgStdStr(ArgNo).c_str()));
1035
Nico Weber7bfaaae2008-08-10 19:59:06 +00001036 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001037}
Ted Kremenekcabe6682009-01-23 20:28:53 +00001038
Douglas Gregord93256e2010-01-28 06:00:51 +00001039static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1040 OS.write((const char *)&Value, sizeof(unsigned));
1041}
1042
1043static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1044 WriteUnsigned(OS, String.size());
1045 OS.write(String.data(), String.size());
1046}
1047
1048static void WriteSourceLocation(llvm::raw_ostream &OS,
1049 SourceManager *SM,
1050 SourceLocation Location) {
1051 if (!SM || Location.isInvalid()) {
1052 // If we don't have a source manager or this location is invalid,
1053 // just write an invalid location.
1054 WriteUnsigned(OS, 0);
1055 WriteUnsigned(OS, 0);
1056 WriteUnsigned(OS, 0);
1057 return;
1058 }
1059
1060 Location = SM->getInstantiationLoc(Location);
1061 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
1062
1063 WriteString(OS, SM->getFileEntryForID(Decomposed.first)->getName());
1064 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1065 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1066}
1067
1068void DiagnosticInfo::Serialize(Diagnostic::Level DiagLevel,
1069 llvm::raw_ostream &OS) const {
1070 SourceManager *SM = 0;
1071 if (getLocation().isValid())
1072 SM = &const_cast<SourceManager &>(getLocation().getManager());
1073
1074 // Write the diagnostic level and location.
1075 WriteUnsigned(OS, (unsigned)DiagLevel);
1076 WriteSourceLocation(OS, SM, getLocation());
1077
1078 // Write the diagnostic message.
1079 llvm::SmallString<64> Message;
1080 FormatDiagnostic(Message);
1081 WriteString(OS, Message);
1082
1083 // Count the number of ranges that don't point into macros, since
1084 // only simple file ranges serialize well.
1085 unsigned NumNonMacroRanges = 0;
1086 for (unsigned I = 0, N = getNumRanges(); I != N; ++I) {
1087 SourceRange R = getRange(I);
1088 if (R.getBegin().isMacroID() || R.getEnd().isMacroID())
1089 continue;
1090
1091 ++NumNonMacroRanges;
1092 }
1093
1094 // Write the ranges.
1095 WriteUnsigned(OS, NumNonMacroRanges);
1096 if (NumNonMacroRanges) {
1097 for (unsigned I = 0, N = getNumRanges(); I != N; ++I) {
1098 SourceRange R = getRange(I);
1099 if (R.getBegin().isMacroID() || R.getEnd().isMacroID())
1100 continue;
1101
1102 WriteSourceLocation(OS, SM, R.getBegin());
1103 WriteSourceLocation(OS, SM, R.getEnd());
1104 }
1105 }
1106
1107 // Determine if all of the fix-its involve rewrites with simple file
1108 // locations (not in macro instantiations). If so, we can write
1109 // fix-it information.
1110 unsigned NumFixIts = getNumCodeModificationHints();
1111 for (unsigned I = 0; I != NumFixIts; ++I) {
1112 const CodeModificationHint &Hint = getCodeModificationHint(I);
1113 if (Hint.RemoveRange.isValid() &&
1114 (Hint.RemoveRange.getBegin().isMacroID() ||
1115 Hint.RemoveRange.getEnd().isMacroID())) {
1116 NumFixIts = 0;
1117 break;
1118 }
1119
1120 if (Hint.InsertionLoc.isValid() && Hint.InsertionLoc.isMacroID()) {
1121 NumFixIts = 0;
1122 break;
1123 }
1124 }
1125
1126 // Write the fix-its.
1127 WriteUnsigned(OS, NumFixIts);
1128 for (unsigned I = 0; I != NumFixIts; ++I) {
1129 const CodeModificationHint &Hint = getCodeModificationHint(I);
1130 WriteSourceLocation(OS, SM, Hint.RemoveRange.getBegin());
1131 WriteSourceLocation(OS, SM, Hint.RemoveRange.getEnd());
1132 WriteSourceLocation(OS, SM, Hint.InsertionLoc);
1133 WriteString(OS, Hint.CodeToInsert);
1134 }
1135}
1136
Ted Kremenekcabe6682009-01-23 20:28:53 +00001137/// IncludeInDiagnosticCounts - This method (whose default implementation
1138/// returns true) indicates whether the diagnostics handled by this
1139/// DiagnosticClient should be included in the number of diagnostics
1140/// reported by Diagnostic.
1141bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }