blob: 0e4159db8db8c7a45518233df343ecaa92f75324 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek39a76652010-04-12 19:54:17 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattnerb91fd172008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Ted Kremenek39a76652010-04-12 19:54:17 +000016#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner23be0672008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Daniel Dunbare3633792009-10-17 18:12:14 +000018#include "llvm/Support/raw_ostream.h"
Ted Kremenek84de4a12011-03-21 18:40:07 +000019#include "llvm/Support/CrashRecoveryContext.h"
20
Chris Lattner22eb9722006-06-18 05:43:12 +000021using namespace clang;
22
Chris Lattner63ecc502008-11-23 09:21:17 +000023static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
24 const char *Modifier, unsigned ML,
25 const char *Argument, unsigned ArgLen,
Chris Lattnerc243f292009-10-20 05:25:22 +000026 const Diagnostic::ArgumentValue *PrevArgs,
27 unsigned NumPrevArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000028 SmallVectorImpl<char> &Output,
Chandler Carruthd5173952011-07-11 17:49:21 +000029 void *Cookie,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000030 SmallVectorImpl<intptr_t> &QualTypeVals) {
Chris Lattner63ecc502008-11-23 09:21:17 +000031 const char *Str = "<can't format argument>";
Chris Lattner6a2ed6f2008-11-23 09:13:29 +000032 Output.append(Str, Str+strlen(Str));
33}
34
35
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000036Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
37 DiagnosticClient *client, bool ShouldOwnClient)
38 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
39 SourceMgr(0) {
Chris Lattner63ecc502008-11-23 09:21:17 +000040 ArgToStringFn = DummyArgToStringFn;
Chris Lattnercf868c42009-02-19 23:53:20 +000041 ArgToStringCookie = 0;
Mike Stump11289f42009-09-09 15:08:12 +000042
Douglas Gregor0e119552010-07-31 00:40:00 +000043 AllExtensionsSilenced = 0;
44 IgnoreAllWarnings = false;
45 WarningsAsErrors = false;
Ted Kremenekfbbdced2011-08-18 01:12:56 +000046 EnableAllWarnings = false;
Douglas Gregor0e119552010-07-31 00:40:00 +000047 ErrorsAsFatal = false;
48 SuppressSystemWarnings = false;
49 SuppressAllDiagnostics = false;
50 ShowOverloads = Ovl_All;
51 ExtBehavior = Ext_Ignore;
52
53 ErrorLimit = 0;
54 TemplateBacktraceLimit = 0;
Douglas Gregor0e119552010-07-31 00:40:00 +000055
Douglas Gregoraa21cc42010-07-19 21:46:24 +000056 Reset();
Chris Lattnerae411572006-07-05 00:55:08 +000057}
58
Chris Lattnere6535cf2007-12-02 01:09:57 +000059Diagnostic::~Diagnostic() {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000060 if (OwnsDiagClient)
61 delete Client;
Chris Lattnere6535cf2007-12-02 01:09:57 +000062}
63
Douglas Gregor7a964ad2011-01-31 22:04:05 +000064void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
65 if (OwnsDiagClient && Client)
66 delete Client;
67
68 Client = client;
69 OwnsDiagClient = ShouldOwnClient;
70}
Chris Lattnerfb42a182009-07-12 21:18:45 +000071
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000072void Diagnostic::pushMappings(SourceLocation Loc) {
73 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000074}
75
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000076bool Diagnostic::popMappings(SourceLocation Loc) {
77 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +000078 return false;
79
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000080 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
81 // State changed at some point between push/pop.
82 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
83 }
84 DiagStateOnPushStack.pop_back();
Chris Lattnerfb42a182009-07-12 21:18:45 +000085 return true;
86}
87
Douglas Gregoraa21cc42010-07-19 21:46:24 +000088void Diagnostic::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089 ErrorOccurred = false;
90 FatalErrorOccurred = false;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +000091 UnrecoverableErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000092
93 NumWarnings = 0;
94 NumErrors = 0;
95 NumErrorsSuppressed = 0;
Argyrios Kyrtzidis1fa8b4b2011-07-29 01:25:44 +000096 TrapNumErrorsOccurred = 0;
97 TrapNumUnrecoverableErrorsOccurred = 0;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +000098
Douglas Gregoraa21cc42010-07-19 21:46:24 +000099 CurDiagID = ~0U;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000100 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
101 // using a Diagnostic associated to a translation unit that follow
102 // diagnostics from a Diagnostic associated to anoter t.u. will not be
103 // displayed.
104 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000105 DelayedDiagID = 0;
Argyrios Kyrtzidisbbbeea12011-03-26 18:58:17 +0000106
107 // Clear state related to #pragma diagnostic.
108 DiagStates.clear();
109 DiagStatePoints.clear();
110 DiagStateOnPushStack.clear();
111
112 // Create a DiagState and DiagStatePoint representing diagnostic changes
113 // through command-line.
114 DiagStates.push_back(DiagState());
115 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000116}
Chris Lattner22eb9722006-06-18 05:43:12 +0000117
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000118void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
119 StringRef Arg2) {
Douglas Gregor85795312010-03-22 15:10:57 +0000120 if (DelayedDiagID)
121 return;
122
123 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000124 DelayedDiagArg1 = Arg1.str();
125 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000126}
127
128void Diagnostic::ReportDelayed() {
129 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
130 DelayedDiagID = 0;
131 DelayedDiagArg1.clear();
132 DelayedDiagArg2.clear();
133}
134
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000135Diagnostic::DiagStatePointsTy::iterator
136Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
137 assert(!DiagStatePoints.empty());
138 assert(DiagStatePoints.front().Loc.isInvalid() &&
139 "Should have created a DiagStatePoint for command-line");
140
141 FullSourceLoc Loc(L, *SourceMgr);
142 if (Loc.isInvalid())
143 return DiagStatePoints.end() - 1;
144
145 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
146 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
147 if (LastStateChangePos.isValid() &&
148 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
149 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
150 DiagStatePoint(0, Loc));
151 --Pos;
152 return Pos;
153}
154
155/// \brief This allows the client to specify that certain
156/// warnings are ignored. Notes can never be mapped, errors can only be
157/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
158///
159/// \param The source location that this change of diagnostic state should
160/// take affect. It can be null if we are setting the latest state.
161void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
162 SourceLocation L) {
163 assert(Diag < diag::DIAG_UPPER_LIMIT &&
164 "Can only map builtin diagnostics");
165 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
166 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
167 "Cannot map errors into warnings!");
168 assert(!DiagStatePoints.empty());
169
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000170 bool isPragma = L.isValid();
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000171 FullSourceLoc Loc(L, *SourceMgr);
172 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
173
174 // Common case; setting all the diagnostics of a group in one place.
175 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000176 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000177 return;
178 }
179
180 // Another common case; modifying diagnostic state in a source location
181 // after the previous one.
182 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
183 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
Chris Lattner57540c52011-04-15 05:22:18 +0000184 // A diagnostic pragma occurred, create a new DiagState initialized with
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000185 // the current one and a new DiagStatePoint to record at which location
186 // the new state became active.
187 DiagStates.push_back(*GetCurDiagState());
188 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000189 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000190 return;
191 }
192
193 // We allow setting the diagnostic state in random source order for
194 // completeness but it should not be actually happening in normal practice.
195
196 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
197 assert(Pos != DiagStatePoints.end());
198
199 // Update all diagnostic states that are active after the given location.
200 for (DiagStatePointsTy::iterator
201 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000202 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000203 }
204
205 // If the location corresponds to an existing point, just update its state.
206 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000207 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000208 return;
209 }
210
211 // Create a new state/point and fit it into the vector of DiagStatePoints
212 // so that the vector is always ordered according to location.
213 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
214 DiagStates.push_back(*Pos->State);
215 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000216 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000217 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
218 FullSourceLoc(Loc, *SourceMgr)));
219}
220
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000221void Diagnostic::Report(const StoredDiagnostic &storedDiag) {
222 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
223
224 CurDiagLoc = storedDiag.getLocation();
225 CurDiagID = storedDiag.getID();
226 NumDiagArgs = 0;
227
228 NumDiagRanges = storedDiag.range_size();
229 assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
230 "Too many arguments to diagnostic!");
231 unsigned i = 0;
232 for (StoredDiagnostic::range_iterator
233 RI = storedDiag.range_begin(),
234 RE = storedDiag.range_end(); RI != RE; ++RI)
235 DiagRanges[i++] = *RI;
236
237 NumFixItHints = storedDiag.fixit_size();
238 assert(NumFixItHints < Diagnostic::MaxFixItHints && "Too many fix-it hints!");
239 i = 0;
240 for (StoredDiagnostic::fixit_iterator
241 FI = storedDiag.fixit_begin(),
242 FE = storedDiag.fixit_end(); FI != FE; ++FI)
243 FixItHints[i++] = *FI;
244
245 assert(Client && "DiagnosticClient not set!");
246 Level DiagLevel = storedDiag.getLevel();
247 DiagnosticInfo Info(this, storedDiag.getMessage());
248 Client->HandleDiagnostic(DiagLevel, Info);
249 if (Client->IncludeInDiagnosticCounts()) {
250 if (DiagLevel == Diagnostic::Warning)
251 ++NumWarnings;
252 }
253
254 CurDiagID = ~0U;
255}
256
Douglas Gregorb3921592010-10-13 17:22:14 +0000257void DiagnosticBuilder::FlushCounts() {
258 DiagObj->NumDiagArgs = NumArgs;
259 DiagObj->NumDiagRanges = NumRanges;
260 DiagObj->NumFixItHints = NumFixItHints;
261}
262
Douglas Gregor85795312010-03-22 15:10:57 +0000263bool DiagnosticBuilder::Emit() {
264 // If DiagObj is null, then its soul was stolen by the copy ctor
265 // or the user called Emit().
266 if (DiagObj == 0) return false;
267
268 // When emitting diagnostics, we set the final argument count into
269 // the Diagnostic object.
Douglas Gregorb3921592010-10-13 17:22:14 +0000270 FlushCounts();
Douglas Gregor85795312010-03-22 15:10:57 +0000271
272 // Process the diagnostic, sending the accumulated information to the
273 // DiagnosticClient.
274 bool Emitted = DiagObj->ProcessDiag();
275
276 // Clear out the current diagnostic object.
Douglas Gregor96380982010-03-22 15:47:45 +0000277 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000278 DiagObj->Clear();
279
280 // If there was a delayed diagnostic, emit it now.
Douglas Gregor96380982010-03-22 15:47:45 +0000281 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor85795312010-03-22 15:10:57 +0000282 DiagObj->ReportDelayed();
283
284 // This diagnostic is dead.
285 DiagObj = 0;
286
287 return Emitted;
288}
289
Nico Weber4c311642008-08-10 19:59:06 +0000290
Chris Lattner22eb9722006-06-18 05:43:12 +0000291DiagnosticClient::~DiagnosticClient() {}
Nico Weber4c311642008-08-10 19:59:06 +0000292
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000293void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
294 const DiagnosticInfo &Info) {
295 if (!IncludeInDiagnosticCounts())
296 return;
297
298 if (DiagLevel == Diagnostic::Warning)
299 ++NumWarnings;
300 else if (DiagLevel >= Diagnostic::Error)
301 ++NumErrors;
302}
Chris Lattner23be0672008-11-19 06:51:40 +0000303
Chris Lattner2b786902008-11-21 07:50:02 +0000304/// ModifierIs - Return true if the specified modifier matches specified string.
305template <std::size_t StrLen>
306static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
307 const char (&Str)[StrLen]) {
308 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
309}
310
John McCall8cb7a8a32010-01-14 20:11:39 +0000311/// ScanForward - Scans forward, looking for the given character, skipping
312/// nested clauses and escaped characters.
313static const char *ScanFormat(const char *I, const char *E, char Target) {
314 unsigned Depth = 0;
315
316 for ( ; I != E; ++I) {
317 if (Depth == 0 && *I == Target) return I;
318 if (Depth != 0 && *I == '}') Depth--;
319
320 if (*I == '%') {
321 I++;
322 if (I == E) break;
323
324 // Escaped characters get implicitly skipped here.
325
326 // Format specifier.
327 if (!isdigit(*I) && !ispunct(*I)) {
328 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
329 if (I == E) break;
330 if (*I == '{')
331 Depth++;
332 }
333 }
334 }
335 return E;
336}
337
Chris Lattner2b786902008-11-21 07:50:02 +0000338/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
339/// like this: %select{foo|bar|baz}2. This means that the integer argument
340/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
341/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
342/// This is very useful for certain classes of variant diagnostics.
John McCalle4d54322010-01-13 23:58:20 +0000343static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000344 const char *Argument, unsigned ArgumentLen,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000345 SmallVectorImpl<char> &OutStr) {
Chris Lattner2b786902008-11-21 07:50:02 +0000346 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattner2b786902008-11-21 07:50:02 +0000348 // Skip over 'ValNo' |'s.
349 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000350 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000351 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
352 " larger than the number of options in the diagnostic string!");
353 Argument = NextVal+1; // Skip this string.
354 --ValNo;
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattner2b786902008-11-21 07:50:02 +0000357 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000358 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000359
360 // Recursively format the result of the select clause into the output string.
361 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000362}
363
364/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
365/// letter 's' to the string if the value is not 1. This is used in cases like
366/// this: "you idiot, you have %4 parameter%s4!".
367static void HandleIntegerSModifier(unsigned ValNo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000368 SmallVectorImpl<char> &OutStr) {
Chris Lattner2b786902008-11-21 07:50:02 +0000369 if (ValNo != 1)
370 OutStr.push_back('s');
371}
372
John McCall9015cde2010-01-14 00:50:32 +0000373/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
374/// prints the ordinal form of the given integer, with 1 corresponding
375/// to the first ordinal. Currently this is hard-coded to use the
376/// English form.
377static void HandleOrdinalModifier(unsigned ValNo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000378 SmallVectorImpl<char> &OutStr) {
John McCall9015cde2010-01-14 00:50:32 +0000379 assert(ValNo != 0 && "ValNo must be strictly positive!");
380
381 llvm::raw_svector_ostream Out(OutStr);
382
383 // We could use text forms for the first N ordinals, but the numeric
384 // forms are actually nicer in diagnostics because they stand out.
385 Out << ValNo;
386
387 // It is critically important that we do this perfectly for
388 // user-written sequences with over 100 elements.
389 switch (ValNo % 100) {
390 case 11:
391 case 12:
392 case 13:
393 Out << "th"; return;
394 default:
395 switch (ValNo % 10) {
396 case 1: Out << "st"; return;
397 case 2: Out << "nd"; return;
398 case 3: Out << "rd"; return;
399 default: Out << "th"; return;
400 }
401 }
402}
403
Chris Lattner2b786902008-11-21 07:50:02 +0000404
Sebastian Redl15b02d22008-11-22 13:44:36 +0000405/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000406static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000407 // Programming 101: Parse a decimal number :-)
408 unsigned Val = 0;
409 while (Start != End && *Start >= '0' && *Start <= '9') {
410 Val *= 10;
411 Val += *Start - '0';
412 ++Start;
413 }
414 return Val;
415}
416
417/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000418static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000419 if (*Start != '[') {
420 unsigned Ref = PluralNumber(Start, End);
421 return Ref == Val;
422 }
423
424 ++Start;
425 unsigned Low = PluralNumber(Start, End);
426 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
427 ++Start;
428 unsigned High = PluralNumber(Start, End);
429 assert(*Start == ']' && "Bad plural expression syntax: expected )");
430 ++Start;
431 return Low <= Val && Val <= High;
432}
433
434/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000435static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000436 // Empty condition?
437 if (*Start == ':')
438 return true;
439
440 while (1) {
441 char C = *Start;
442 if (C == '%') {
443 // Modulo expression
444 ++Start;
445 unsigned Arg = PluralNumber(Start, End);
446 assert(*Start == '=' && "Bad plural expression syntax: expected =");
447 ++Start;
448 unsigned ValMod = ValNo % Arg;
449 if (TestPluralRange(ValMod, Start, End))
450 return true;
451 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000452 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000453 "Bad plural expression syntax: unexpected character");
454 // Range expression
455 if (TestPluralRange(ValNo, Start, End))
456 return true;
457 }
458
459 // Scan for next or-expr part.
460 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000461 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000462 break;
463 ++Start;
464 }
465 return false;
466}
467
468/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
469/// for complex plural forms, or in languages where all plurals are complex.
470/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
471/// conditions that are tested in order, the form corresponding to the first
472/// that applies being emitted. The empty condition is always true, making the
473/// last form a default case.
474/// Conditions are simple boolean expressions, where n is the number argument.
475/// Here are the rules.
476/// condition := expression | empty
477/// empty := -> always true
478/// expression := numeric [',' expression] -> logical or
479/// numeric := range -> true if n in range
480/// | '%' number '=' range -> true if n % number in range
481/// range := number
482/// | '[' number ',' number ']' -> ranges are inclusive both ends
483///
484/// Here are some examples from the GNU gettext manual written in this form:
485/// English:
486/// {1:form0|:form1}
487/// Latvian:
488/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
489/// Gaeilge:
490/// {1:form0|2:form1|:form2}
491/// Romanian:
492/// {1:form0|0,%100=[1,19]:form1|:form2}
493/// Lithuanian:
494/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
495/// Russian (requires repeated form):
496/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
497/// Slovak
498/// {1:form0|[2,4]:form1|:form2}
499/// Polish (requires repeated form):
500/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCall43b61682010-10-14 01:55:31 +0000501static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000502 const char *Argument, unsigned ArgumentLen,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000504 const char *ArgumentEnd = Argument + ArgumentLen;
505 while (1) {
506 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
507 const char *ExprEnd = Argument;
508 while (*ExprEnd != ':') {
509 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
510 ++ExprEnd;
511 }
512 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
513 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000514 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000515
516 // Recursively format the result of the plural clause into the
517 // output string.
518 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000519 return;
520 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000521 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000522 }
523}
524
525
Chris Lattner23be0672008-11-19 06:51:40 +0000526/// FormatDiagnostic - Format this diagnostic into a string, substituting the
527/// formal arguments into the %0 slots. The result is appended onto the Str
528/// array.
529void DiagnosticInfo::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000530FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000531 if (!StoredDiagMessage.empty()) {
532 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
533 return;
534 }
535
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536 StringRef Diag =
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000537 getDiags()->getDiagnosticIDs()->getDescription(getID());
Mike Stump11289f42009-09-09 15:08:12 +0000538
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000539 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
John McCalle4d54322010-01-13 23:58:20 +0000540}
541
542void DiagnosticInfo::
543FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000544 SmallVectorImpl<char> &OutStr) const {
John McCalle4d54322010-01-13 23:58:20 +0000545
Chris Lattnerc243f292009-10-20 05:25:22 +0000546 /// FormattedArgs - Keep track of all of the arguments formatted by
547 /// ConvertArgToString and pass them into subsequent calls to
548 /// ConvertArgToString, allowing the implementation to avoid redundancies in
549 /// obvious cases.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000550 SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
Chandler Carruthd5173952011-07-11 17:49:21 +0000551
552 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
553 /// compared to see if more information is needed to be printed.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000554 SmallVector<intptr_t, 2> QualTypeVals;
Chandler Carruthd5173952011-07-11 17:49:21 +0000555 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
556 if (getArgKind(i) == Diagnostic::ak_qualtype)
557 QualTypeVals.push_back(getRawArg(i));
558
Chris Lattner23be0672008-11-19 06:51:40 +0000559 while (DiagStr != DiagEnd) {
560 if (DiagStr[0] != '%') {
561 // Append non-%0 substrings to Str if we have one.
562 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
563 OutStr.append(DiagStr, StrEnd);
564 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000565 continue;
John McCall8cb7a8a32010-01-14 20:11:39 +0000566 } else if (ispunct(DiagStr[1])) {
567 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000568 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000569 continue;
570 }
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattner2b786902008-11-21 07:50:02 +0000572 // Skip the %.
573 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Chris Lattner2b786902008-11-21 07:50:02 +0000575 // This must be a placeholder for a diagnostic argument. The format for a
576 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
577 // The digit is a number from 0-9 indicating which argument this comes from.
578 // The modifier is a string of digits from the set [-a-z]+, arguments is a
579 // brace enclosed string.
580 const char *Modifier = 0, *Argument = 0;
581 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000582
Chris Lattner2b786902008-11-21 07:50:02 +0000583 // Check to see if we have a modifier. If so eat it.
584 if (!isdigit(DiagStr[0])) {
585 Modifier = DiagStr;
586 while (DiagStr[0] == '-' ||
587 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
588 ++DiagStr;
589 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000590
Chris Lattner2b786902008-11-21 07:50:02 +0000591 // If we have an argument, get it next.
592 if (DiagStr[0] == '{') {
593 ++DiagStr; // Skip {.
594 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000595
John McCall8cb7a8a32010-01-14 20:11:39 +0000596 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
597 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000598 ArgumentLen = DiagStr-Argument;
599 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000600 }
Chris Lattner2b786902008-11-21 07:50:02 +0000601 }
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner2b786902008-11-21 07:50:02 +0000603 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000604 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000605
Chris Lattnerc243f292009-10-20 05:25:22 +0000606 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
607
608 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000609 // ---- STRINGS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000610 case Diagnostic::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000611 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000612 assert(ModifierLen == 0 && "No modifiers for strings yet");
613 OutStr.append(S.begin(), S.end());
614 break;
615 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000616 case Diagnostic::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000617 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000618 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000619
620 // Don't crash if get passed a null pointer by accident.
621 if (!S)
622 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000623
Chris Lattner2b786902008-11-21 07:50:02 +0000624 OutStr.append(S, S + strlen(S));
625 break;
626 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000627 // ---- INTEGERS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000628 case Diagnostic::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000629 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner2b786902008-11-21 07:50:02 +0000631 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000632 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
633 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000634 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
635 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000636 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000637 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
638 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000639 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
640 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000641 } else {
642 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000643 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000644 }
Chris Lattner2b786902008-11-21 07:50:02 +0000645 break;
646 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000647 case Diagnostic::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000648 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattner2b786902008-11-21 07:50:02 +0000650 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000651 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000652 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
653 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000654 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000655 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
656 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000657 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
658 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000659 } else {
660 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000661 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000662 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000663 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000664 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000665 // ---- NAMES and TYPES ----
666 case Diagnostic::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000667 const IdentifierInfo *II = getArgIdentifier(ArgNo);
668 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000669
670 // Don't crash if get passed a null pointer by accident.
671 if (!II) {
672 const char *S = "(null)";
673 OutStr.append(S, S + strlen(S));
674 continue;
675 }
676
Daniel Dunbar07d07852009-10-18 21:17:35 +0000677 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000678 break;
679 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000680 case Diagnostic::ak_qualtype:
Chris Lattnerf7e69d52008-11-23 20:28:15 +0000681 case Diagnostic::ak_declarationname:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000682 case Diagnostic::ak_nameddecl:
Douglas Gregor053f6912009-08-26 00:04:55 +0000683 case Diagnostic::ak_nestednamespec:
Douglas Gregore40876a2009-10-13 21:16:44 +0000684 case Diagnostic::ak_declcontext:
Chris Lattnerc243f292009-10-20 05:25:22 +0000685 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner63ecc502008-11-23 09:21:17 +0000686 Modifier, ModifierLen,
Chris Lattnerc243f292009-10-20 05:25:22 +0000687 Argument, ArgumentLen,
688 FormattedArgs.data(), FormattedArgs.size(),
Chandler Carruthd5173952011-07-11 17:49:21 +0000689 OutStr, QualTypeVals);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000690 break;
Nico Weber4c311642008-08-10 19:59:06 +0000691 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000692
693 // Remember this argument info for subsequent formatting operations. Turn
694 // std::strings into a null terminated string to make it be the same case as
695 // all the other ones.
696 if (Kind != Diagnostic::ak_std_string)
697 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
698 else
699 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
700 (intptr_t)getArgStdStr(ArgNo).c_str()));
701
Nico Weber4c311642008-08-10 19:59:06 +0000702 }
Nico Weber4c311642008-08-10 19:59:06 +0000703}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000704
Douglas Gregor33cdd812010-02-18 18:08:43 +0000705StoredDiagnostic::StoredDiagnostic() { }
706
Douglas Gregora750e8e2010-11-19 16:18:16 +0000707StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000708 StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000709 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000710
711StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
712 const DiagnosticInfo &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000713 : ID(Info.getID()), Level(Level)
714{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000715 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
716 "Valid source location without setting a source manager for diagnostic");
717 if (Info.getLocation().isValid())
718 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000719 llvm::SmallString<64> Message;
720 Info.FormatDiagnostic(Message);
721 this->Message.assign(Message.begin(), Message.end());
722
723 Ranges.reserve(Info.getNumRanges());
724 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
725 Ranges.push_back(Info.getRange(I));
726
Douglas Gregora771f462010-03-31 17:46:05 +0000727 FixIts.reserve(Info.getNumFixItHints());
728 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
729 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000730}
731
Douglas Gregor925296b2011-07-19 16:10:42 +0000732StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000733 StringRef Message, FullSourceLoc Loc,
Chris Lattner54b16772011-07-23 17:14:25 +0000734 ArrayRef<CharSourceRange> Ranges,
735 ArrayRef<FixItHint> Fixits)
Douglas Gregor925296b2011-07-19 16:10:42 +0000736 : ID(ID), Level(Level), Loc(Loc), Message(Message)
737{
738 this->Ranges.assign(Ranges.begin(), Ranges.end());
739 this->FixIts.assign(FixIts.begin(), FixIts.end());
740}
741
Douglas Gregor33cdd812010-02-18 18:08:43 +0000742StoredDiagnostic::~StoredDiagnostic() { }
743
Ted Kremenekea06ec12009-01-23 20:28:53 +0000744/// IncludeInDiagnosticCounts - This method (whose default implementation
745/// returns true) indicates whether the diagnostics handled by this
746/// DiagnosticClient should be included in the number of diagnostics
747/// reported by Diagnostic.
748bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +0000749
750PartialDiagnostic::StorageAllocator::StorageAllocator() {
751 for (unsigned I = 0; I != NumCached; ++I)
752 FreeList[I] = Cached + I;
753 NumFreeListEntries = NumCached;
754}
755
756PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Ted Kremenek84de4a12011-03-21 18:40:07 +0000757 // Don't assert if we are in a CrashRecovery context, as this
758 // invariant may be invalidated during a crash.
Ted Kremenek0aaa67b2011-03-21 18:40:10 +0000759 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
Douglas Gregor89336232010-03-29 23:34:08 +0000760}