blob: 7601d49d4dfef72bf8208f1e72d969009262b6cc [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
Ted Kremenekec55c942010-04-12 19:54:17 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattner43b628c2008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000016#include "clang/Basic/PartialDiagnostic.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Daniel Dunbar23e47c62009-10-17 18:12:14 +000018#include "llvm/Support/raw_ostream.h"
Ted Kremenek03201fb2011-03-21 18:40:07 +000019#include "llvm/Support/CrashRecoveryContext.h"
20
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
Chris Lattner3fdf4b02008-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 Lattnerb54d8af2009-10-20 05:25:22 +000026 const Diagnostic::ArgumentValue *PrevArgs,
27 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +000028 llvm::SmallVectorImpl<char> &Output,
29 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +000030 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +000031 Output.append(Str, Str+strlen(Str));
32}
33
34
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000035Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
36 DiagnosticClient *client, bool ShouldOwnClient)
37 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
38 SourceMgr(0) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +000039 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +000040 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000041
Douglas Gregorcc5888d2010-07-31 00:40:00 +000042 AllExtensionsSilenced = 0;
43 IgnoreAllWarnings = false;
44 WarningsAsErrors = false;
45 ErrorsAsFatal = false;
46 SuppressSystemWarnings = false;
47 SuppressAllDiagnostics = false;
48 ShowOverloads = Ovl_All;
49 ExtBehavior = Ext_Ignore;
50
51 ErrorLimit = 0;
52 TemplateBacktraceLimit = 0;
Douglas Gregorcc5888d2010-07-31 00:40:00 +000053
Douglas Gregorabc563f2010-07-19 21:46:24 +000054 Reset();
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Chris Lattner182745a2007-12-02 01:09:57 +000057Diagnostic::~Diagnostic() {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000058 if (OwnsDiagClient)
59 delete Client;
Chris Lattner182745a2007-12-02 01:09:57 +000060}
61
Douglas Gregor4f5e21e2011-01-31 22:04:05 +000062void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
63 if (OwnsDiagClient && Client)
64 delete Client;
65
66 Client = client;
67 OwnsDiagClient = ShouldOwnClient;
68}
Chris Lattner04ae2df2009-07-12 21:18:45 +000069
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000070void Diagnostic::pushMappings(SourceLocation Loc) {
71 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattner04ae2df2009-07-12 21:18:45 +000072}
73
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000074bool Diagnostic::popMappings(SourceLocation Loc) {
75 if (DiagStateOnPushStack.empty())
Chris Lattner04ae2df2009-07-12 21:18:45 +000076 return false;
77
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000078 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
79 // State changed at some point between push/pop.
80 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
81 }
82 DiagStateOnPushStack.pop_back();
Chris Lattner04ae2df2009-07-12 21:18:45 +000083 return true;
84}
85
Douglas Gregorabc563f2010-07-19 21:46:24 +000086void Diagnostic::Reset() {
Douglas Gregorabc563f2010-07-19 21:46:24 +000087 ErrorOccurred = false;
88 FatalErrorOccurred = false;
Douglas Gregorabc563f2010-07-19 21:46:24 +000089
90 NumWarnings = 0;
91 NumErrors = 0;
92 NumErrorsSuppressed = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +000093 CurDiagID = ~0U;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000094 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
95 // using a Diagnostic associated to a translation unit that follow
96 // diagnostics from a Diagnostic associated to anoter t.u. will not be
97 // displayed.
98 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregorabc563f2010-07-19 21:46:24 +000099 DelayedDiagID = 0;
Argyrios Kyrtzidisdc0a2da2011-03-26 18:58:17 +0000100
101 // Clear state related to #pragma diagnostic.
102 DiagStates.clear();
103 DiagStatePoints.clear();
104 DiagStateOnPushStack.clear();
105
106 // Create a DiagState and DiagStatePoint representing diagnostic changes
107 // through command-line.
108 DiagStates.push_back(DiagState());
109 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000110}
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000112void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
113 llvm::StringRef Arg2) {
114 if (DelayedDiagID)
115 return;
116
117 DelayedDiagID = DiagID;
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000118 DelayedDiagArg1 = Arg1.str();
119 DelayedDiagArg2 = Arg2.str();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000120}
121
122void Diagnostic::ReportDelayed() {
123 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
124 DelayedDiagID = 0;
125 DelayedDiagArg1.clear();
126 DelayedDiagArg2.clear();
127}
128
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000129Diagnostic::DiagStatePointsTy::iterator
130Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
131 assert(!DiagStatePoints.empty());
132 assert(DiagStatePoints.front().Loc.isInvalid() &&
133 "Should have created a DiagStatePoint for command-line");
134
135 FullSourceLoc Loc(L, *SourceMgr);
136 if (Loc.isInvalid())
137 return DiagStatePoints.end() - 1;
138
139 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
140 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
141 if (LastStateChangePos.isValid() &&
142 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
143 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
144 DiagStatePoint(0, Loc));
145 --Pos;
146 return Pos;
147}
148
149/// \brief This allows the client to specify that certain
150/// warnings are ignored. Notes can never be mapped, errors can only be
151/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
152///
153/// \param The source location that this change of diagnostic state should
154/// take affect. It can be null if we are setting the latest state.
155void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
156 SourceLocation L) {
157 assert(Diag < diag::DIAG_UPPER_LIMIT &&
158 "Can only map builtin diagnostics");
159 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
160 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
161 "Cannot map errors into warnings!");
162 assert(!DiagStatePoints.empty());
163
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000164 bool isPragma = L.isValid();
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000165 FullSourceLoc Loc(L, *SourceMgr);
166 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
167
168 // Common case; setting all the diagnostics of a group in one place.
169 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000170 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000171 return;
172 }
173
174 // Another common case; modifying diagnostic state in a source location
175 // after the previous one.
176 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
177 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
178 // A diagnostic pragma occured, create a new DiagState initialized with
179 // the current one and a new DiagStatePoint to record at which location
180 // the new state became active.
181 DiagStates.push_back(*GetCurDiagState());
182 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000183 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000184 return;
185 }
186
187 // We allow setting the diagnostic state in random source order for
188 // completeness but it should not be actually happening in normal practice.
189
190 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
191 assert(Pos != DiagStatePoints.end());
192
193 // Update all diagnostic states that are active after the given location.
194 for (DiagStatePointsTy::iterator
195 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000196 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000197 }
198
199 // If the location corresponds to an existing point, just update its state.
200 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000201 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000202 return;
203 }
204
205 // Create a new state/point and fit it into the vector of DiagStatePoints
206 // so that the vector is always ordered according to location.
207 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
208 DiagStates.push_back(*Pos->State);
209 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000210 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000211 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
212 FullSourceLoc(Loc, *SourceMgr)));
213}
214
Douglas Gregorb5350412010-10-13 17:22:14 +0000215void DiagnosticBuilder::FlushCounts() {
216 DiagObj->NumDiagArgs = NumArgs;
217 DiagObj->NumDiagRanges = NumRanges;
218 DiagObj->NumFixItHints = NumFixItHints;
219}
220
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000221bool DiagnosticBuilder::Emit() {
222 // If DiagObj is null, then its soul was stolen by the copy ctor
223 // or the user called Emit().
224 if (DiagObj == 0) return false;
225
226 // When emitting diagnostics, we set the final argument count into
227 // the Diagnostic object.
Douglas Gregorb5350412010-10-13 17:22:14 +0000228 FlushCounts();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000229
230 // Process the diagnostic, sending the accumulated information to the
231 // DiagnosticClient.
232 bool Emitted = DiagObj->ProcessDiag();
233
234 // Clear out the current diagnostic object.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000235 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000236 DiagObj->Clear();
237
238 // If there was a delayed diagnostic, emit it now.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000239 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000240 DiagObj->ReportDelayed();
241
242 // This diagnostic is dead.
243 DiagObj = 0;
244
245 return Emitted;
246}
247
Nico Weber7bfaaae2008-08-10 19:59:06 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000250
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000251void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
252 const DiagnosticInfo &Info) {
253 if (!IncludeInDiagnosticCounts())
254 return;
255
256 if (DiagLevel == Diagnostic::Warning)
257 ++NumWarnings;
258 else if (DiagLevel >= Diagnostic::Error)
259 ++NumErrors;
260}
Chris Lattnerf4c83962008-11-19 06:51:40 +0000261
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000262/// ModifierIs - Return true if the specified modifier matches specified string.
263template <std::size_t StrLen>
264static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
265 const char (&Str)[StrLen]) {
266 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
267}
268
John McCall909c1822010-01-14 20:11:39 +0000269/// ScanForward - Scans forward, looking for the given character, skipping
270/// nested clauses and escaped characters.
271static const char *ScanFormat(const char *I, const char *E, char Target) {
272 unsigned Depth = 0;
273
274 for ( ; I != E; ++I) {
275 if (Depth == 0 && *I == Target) return I;
276 if (Depth != 0 && *I == '}') Depth--;
277
278 if (*I == '%') {
279 I++;
280 if (I == E) break;
281
282 // Escaped characters get implicitly skipped here.
283
284 // Format specifier.
285 if (!isdigit(*I) && !ispunct(*I)) {
286 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
287 if (I == E) break;
288 if (*I == '{')
289 Depth++;
290 }
291 }
292 }
293 return E;
294}
295
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000296/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
297/// like this: %select{foo|bar|baz}2. This means that the integer argument
298/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
299/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
300/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000301static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000302 const char *Argument, unsigned ArgumentLen,
303 llvm::SmallVectorImpl<char> &OutStr) {
304 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000306 // Skip over 'ValNo' |'s.
307 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000308 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000309 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
310 " larger than the number of options in the diagnostic string!");
311 Argument = NextVal+1; // Skip this string.
312 --ValNo;
313 }
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000315 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000316 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000317
318 // Recursively format the result of the select clause into the output string.
319 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000320}
321
322/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
323/// letter 's' to the string if the value is not 1. This is used in cases like
324/// this: "you idiot, you have %4 parameter%s4!".
325static void HandleIntegerSModifier(unsigned ValNo,
326 llvm::SmallVectorImpl<char> &OutStr) {
327 if (ValNo != 1)
328 OutStr.push_back('s');
329}
330
John McCall3be16b72010-01-14 00:50:32 +0000331/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
332/// prints the ordinal form of the given integer, with 1 corresponding
333/// to the first ordinal. Currently this is hard-coded to use the
334/// English form.
335static void HandleOrdinalModifier(unsigned ValNo,
336 llvm::SmallVectorImpl<char> &OutStr) {
337 assert(ValNo != 0 && "ValNo must be strictly positive!");
338
339 llvm::raw_svector_ostream Out(OutStr);
340
341 // We could use text forms for the first N ordinals, but the numeric
342 // forms are actually nicer in diagnostics because they stand out.
343 Out << ValNo;
344
345 // It is critically important that we do this perfectly for
346 // user-written sequences with over 100 elements.
347 switch (ValNo % 100) {
348 case 11:
349 case 12:
350 case 13:
351 Out << "th"; return;
352 default:
353 switch (ValNo % 10) {
354 case 1: Out << "st"; return;
355 case 2: Out << "nd"; return;
356 case 3: Out << "rd"; return;
357 default: Out << "th"; return;
358 }
359 }
360}
361
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000362
Sebastian Redle4c452c2008-11-22 13:44:36 +0000363/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000364static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000365 // Programming 101: Parse a decimal number :-)
366 unsigned Val = 0;
367 while (Start != End && *Start >= '0' && *Start <= '9') {
368 Val *= 10;
369 Val += *Start - '0';
370 ++Start;
371 }
372 return Val;
373}
374
375/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000376static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000377 if (*Start != '[') {
378 unsigned Ref = PluralNumber(Start, End);
379 return Ref == Val;
380 }
381
382 ++Start;
383 unsigned Low = PluralNumber(Start, End);
384 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
385 ++Start;
386 unsigned High = PluralNumber(Start, End);
387 assert(*Start == ']' && "Bad plural expression syntax: expected )");
388 ++Start;
389 return Low <= Val && Val <= High;
390}
391
392/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000393static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000394 // Empty condition?
395 if (*Start == ':')
396 return true;
397
398 while (1) {
399 char C = *Start;
400 if (C == '%') {
401 // Modulo expression
402 ++Start;
403 unsigned Arg = PluralNumber(Start, End);
404 assert(*Start == '=' && "Bad plural expression syntax: expected =");
405 ++Start;
406 unsigned ValMod = ValNo % Arg;
407 if (TestPluralRange(ValMod, Start, End))
408 return true;
409 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000410 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000411 "Bad plural expression syntax: unexpected character");
412 // Range expression
413 if (TestPluralRange(ValNo, Start, End))
414 return true;
415 }
416
417 // Scan for next or-expr part.
418 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000420 break;
421 ++Start;
422 }
423 return false;
424}
425
426/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
427/// for complex plural forms, or in languages where all plurals are complex.
428/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
429/// conditions that are tested in order, the form corresponding to the first
430/// that applies being emitted. The empty condition is always true, making the
431/// last form a default case.
432/// Conditions are simple boolean expressions, where n is the number argument.
433/// Here are the rules.
434/// condition := expression | empty
435/// empty := -> always true
436/// expression := numeric [',' expression] -> logical or
437/// numeric := range -> true if n in range
438/// | '%' number '=' range -> true if n % number in range
439/// range := number
440/// | '[' number ',' number ']' -> ranges are inclusive both ends
441///
442/// Here are some examples from the GNU gettext manual written in this form:
443/// English:
444/// {1:form0|:form1}
445/// Latvian:
446/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
447/// Gaeilge:
448/// {1:form0|2:form1|:form2}
449/// Romanian:
450/// {1:form0|0,%100=[1,19]:form1|:form2}
451/// Lithuanian:
452/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
453/// Russian (requires repeated form):
454/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
455/// Slovak
456/// {1:form0|[2,4]:form1|:form2}
457/// Polish (requires repeated form):
458/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCalle53a44b2010-10-14 01:55:31 +0000459static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redle4c452c2008-11-22 13:44:36 +0000460 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000461 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000462 const char *ArgumentEnd = Argument + ArgumentLen;
463 while (1) {
464 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
465 const char *ExprEnd = Argument;
466 while (*ExprEnd != ':') {
467 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
468 ++ExprEnd;
469 }
470 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
471 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000472 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle53a44b2010-10-14 01:55:31 +0000473
474 // Recursively format the result of the plural clause into the
475 // output string.
476 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000477 return;
478 }
John McCall909c1822010-01-14 20:11:39 +0000479 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000480 }
481}
482
483
Chris Lattnerf4c83962008-11-19 06:51:40 +0000484/// FormatDiagnostic - Format this diagnostic into a string, substituting the
485/// formal arguments into the %0 slots. The result is appended onto the Str
486/// array.
487void DiagnosticInfo::
488FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000489 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
Chris Lattnerf4c83962008-11-19 06:51:40 +0000490 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
John McCall9f286142010-01-13 23:58:20 +0000492 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
493}
494
495void DiagnosticInfo::
496FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
497 llvm::SmallVectorImpl<char> &OutStr) const {
498
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000499 /// FormattedArgs - Keep track of all of the arguments formatted by
500 /// ConvertArgToString and pass them into subsequent calls to
501 /// ConvertArgToString, allowing the implementation to avoid redundancies in
502 /// obvious cases.
503 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
504
Chris Lattnerf4c83962008-11-19 06:51:40 +0000505 while (DiagStr != DiagEnd) {
506 if (DiagStr[0] != '%') {
507 // Append non-%0 substrings to Str if we have one.
508 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
509 OutStr.append(DiagStr, StrEnd);
510 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000511 continue;
John McCall909c1822010-01-14 20:11:39 +0000512 } else if (ispunct(DiagStr[1])) {
513 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000514 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000515 continue;
516 }
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000518 // Skip the %.
519 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000521 // This must be a placeholder for a diagnostic argument. The format for a
522 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
523 // The digit is a number from 0-9 indicating which argument this comes from.
524 // The modifier is a string of digits from the set [-a-z]+, arguments is a
525 // brace enclosed string.
526 const char *Modifier = 0, *Argument = 0;
527 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000529 // Check to see if we have a modifier. If so eat it.
530 if (!isdigit(DiagStr[0])) {
531 Modifier = DiagStr;
532 while (DiagStr[0] == '-' ||
533 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
534 ++DiagStr;
535 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000536
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000537 // If we have an argument, get it next.
538 if (DiagStr[0] == '{') {
539 ++DiagStr; // Skip {.
540 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
John McCall909c1822010-01-14 20:11:39 +0000542 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
543 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000544 ArgumentLen = DiagStr-Argument;
545 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000546 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000549 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000550 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000551
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000552 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
553
554 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000555 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000556 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000557 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000558 assert(ModifierLen == 0 && "No modifiers for strings yet");
559 OutStr.append(S.begin(), S.end());
560 break;
561 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000562 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000563 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000564 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000565
566 // Don't crash if get passed a null pointer by accident.
567 if (!S)
568 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000570 OutStr.append(S, S + strlen(S));
571 break;
572 }
Chris Lattner08631c52008-11-23 21:45:46 +0000573 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000574 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000575 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000577 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle53a44b2010-10-14 01:55:31 +0000578 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
579 OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000580 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
581 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000582 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCalle53a44b2010-10-14 01:55:31 +0000583 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
584 OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000585 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
586 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000587 } else {
588 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000589 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000590 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000591 break;
592 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000593 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000594 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000596 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000597 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000598 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
599 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000600 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCalle53a44b2010-10-14 01:55:31 +0000601 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
602 OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000603 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
604 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000605 } else {
606 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000607 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000608 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000609 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000610 }
Chris Lattner08631c52008-11-23 21:45:46 +0000611 // ---- NAMES and TYPES ----
612 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +0000613 const IdentifierInfo *II = getArgIdentifier(ArgNo);
614 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000615
616 // Don't crash if get passed a null pointer by accident.
617 if (!II) {
618 const char *S = "(null)";
619 OutStr.append(S, S + strlen(S));
620 continue;
621 }
622
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000623 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +0000624 break;
625 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000626 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +0000627 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000628 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +0000629 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +0000630 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000631 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000632 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000633 Argument, ArgumentLen,
634 FormattedArgs.data(), FormattedArgs.size(),
635 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +0000636 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000637 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000638
639 // Remember this argument info for subsequent formatting operations. Turn
640 // std::strings into a null terminated string to make it be the same case as
641 // all the other ones.
642 if (Kind != Diagnostic::ak_std_string)
643 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
644 else
645 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
646 (intptr_t)getArgStdStr(ArgNo).c_str()));
647
Nico Weber7bfaaae2008-08-10 19:59:06 +0000648 }
Nico Weber7bfaaae2008-08-10 19:59:06 +0000649}
Ted Kremenekcabe6682009-01-23 20:28:53 +0000650
Douglas Gregora88084b2010-02-18 18:08:43 +0000651StoredDiagnostic::StoredDiagnostic() { }
652
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000653StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregora88084b2010-02-18 18:08:43 +0000654 llvm::StringRef Message)
Benjamin Kramera6a32e22010-11-19 17:36:51 +0000655 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregora88084b2010-02-18 18:08:43 +0000656
657StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
658 const DiagnosticInfo &Info)
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000659 : ID(Info.getID()), Level(Level)
660{
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000661 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
662 "Valid source location without setting a source manager for diagnostic");
663 if (Info.getLocation().isValid())
664 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregora88084b2010-02-18 18:08:43 +0000665 llvm::SmallString<64> Message;
666 Info.FormatDiagnostic(Message);
667 this->Message.assign(Message.begin(), Message.end());
668
669 Ranges.reserve(Info.getNumRanges());
670 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
671 Ranges.push_back(Info.getRange(I));
672
Douglas Gregor849b2432010-03-31 17:46:05 +0000673 FixIts.reserve(Info.getNumFixItHints());
674 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
675 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregora88084b2010-02-18 18:08:43 +0000676}
677
678StoredDiagnostic::~StoredDiagnostic() { }
679
Ted Kremenekcabe6682009-01-23 20:28:53 +0000680/// IncludeInDiagnosticCounts - This method (whose default implementation
681/// returns true) indicates whether the diagnostics handled by this
682/// DiagnosticClient should be included in the number of diagnostics
683/// reported by Diagnostic.
684bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000685
686PartialDiagnostic::StorageAllocator::StorageAllocator() {
687 for (unsigned I = 0; I != NumCached; ++I)
688 FreeList[I] = Cached + I;
689 NumFreeListEntries = NumCached;
690}
691
692PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Ted Kremenek03201fb2011-03-21 18:40:07 +0000693 // Don't assert if we are in a CrashRecovery context, as this
694 // invariant may be invalidated during a crash.
Ted Kremenekcd1eecf2011-03-21 18:40:10 +0000695 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000696}