blob: dc81f88c5c595daac7aa02fecfa9e1ba6f551826 [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 Lattnercf868c42009-02-19 23:53:20 +000028 llvm::SmallVectorImpl<char> &Output,
29 void *Cookie) {
Chris Lattner63ecc502008-11-23 09:21:17 +000030 const char *Str = "<can't format argument>";
Chris Lattner6a2ed6f2008-11-23 09:13:29 +000031 Output.append(Str, Str+strlen(Str));
32}
33
34
Argyrios Kyrtzidisd0040642010-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 Lattner63ecc502008-11-23 09:21:17 +000039 ArgToStringFn = DummyArgToStringFn;
Chris Lattnercf868c42009-02-19 23:53:20 +000040 ArgToStringCookie = 0;
Mike Stump11289f42009-09-09 15:08:12 +000041
Douglas Gregor0e119552010-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 Gregor0e119552010-07-31 00:40:00 +000053
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000054 // Create a DiagState and DiagStatePoint representing diagnostic changes
55 // through command-line.
56 DiagStates.push_back(DiagState());
57 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregor0e119552010-07-31 00:40:00 +000058
Douglas Gregoraa21cc42010-07-19 21:46:24 +000059 Reset();
Chris Lattnerae411572006-07-05 00:55:08 +000060}
61
Chris Lattnere6535cf2007-12-02 01:09:57 +000062Diagnostic::~Diagnostic() {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000063 if (OwnsDiagClient)
64 delete Client;
Chris Lattnere6535cf2007-12-02 01:09:57 +000065}
66
Douglas Gregor7a964ad2011-01-31 22:04:05 +000067void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
68 if (OwnsDiagClient && Client)
69 delete Client;
70
71 Client = client;
72 OwnsDiagClient = ShouldOwnClient;
73}
Chris Lattnerfb42a182009-07-12 21:18:45 +000074
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000075void Diagnostic::pushMappings(SourceLocation Loc) {
76 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000077}
78
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000079bool Diagnostic::popMappings(SourceLocation Loc) {
80 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +000081 return false;
82
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000083 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
84 // State changed at some point between push/pop.
85 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
86 }
87 DiagStateOnPushStack.pop_back();
Chris Lattnerfb42a182009-07-12 21:18:45 +000088 return true;
89}
90
Douglas Gregoraa21cc42010-07-19 21:46:24 +000091void Diagnostic::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +000092 ErrorOccurred = false;
93 FatalErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094
95 NumWarnings = 0;
96 NumErrors = 0;
97 NumErrorsSuppressed = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000098 CurDiagID = ~0U;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000099 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
100 // using a Diagnostic associated to a translation unit that follow
101 // diagnostics from a Diagnostic associated to anoter t.u. will not be
102 // displayed.
103 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000104 DelayedDiagID = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000105}
Chris Lattner22eb9722006-06-18 05:43:12 +0000106
Douglas Gregor85795312010-03-22 15:10:57 +0000107void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
108 llvm::StringRef Arg2) {
109 if (DelayedDiagID)
110 return;
111
112 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000113 DelayedDiagArg1 = Arg1.str();
114 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000115}
116
117void Diagnostic::ReportDelayed() {
118 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
119 DelayedDiagID = 0;
120 DelayedDiagArg1.clear();
121 DelayedDiagArg2.clear();
122}
123
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000124Diagnostic::DiagStatePointsTy::iterator
125Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
126 assert(!DiagStatePoints.empty());
127 assert(DiagStatePoints.front().Loc.isInvalid() &&
128 "Should have created a DiagStatePoint for command-line");
129
130 FullSourceLoc Loc(L, *SourceMgr);
131 if (Loc.isInvalid())
132 return DiagStatePoints.end() - 1;
133
134 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
135 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
136 if (LastStateChangePos.isValid() &&
137 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
138 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
139 DiagStatePoint(0, Loc));
140 --Pos;
141 return Pos;
142}
143
144/// \brief This allows the client to specify that certain
145/// warnings are ignored. Notes can never be mapped, errors can only be
146/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
147///
148/// \param The source location that this change of diagnostic state should
149/// take affect. It can be null if we are setting the latest state.
150void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
151 SourceLocation L) {
152 assert(Diag < diag::DIAG_UPPER_LIMIT &&
153 "Can only map builtin diagnostics");
154 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
155 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
156 "Cannot map errors into warnings!");
157 assert(!DiagStatePoints.empty());
158
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000159 bool isPragma = L.isValid();
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000160 FullSourceLoc Loc(L, *SourceMgr);
161 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
162
163 // Common case; setting all the diagnostics of a group in one place.
164 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000165 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000166 return;
167 }
168
169 // Another common case; modifying diagnostic state in a source location
170 // after the previous one.
171 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
172 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
173 // A diagnostic pragma occured, create a new DiagState initialized with
174 // the current one and a new DiagStatePoint to record at which location
175 // the new state became active.
176 DiagStates.push_back(*GetCurDiagState());
177 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000178 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000179 return;
180 }
181
182 // We allow setting the diagnostic state in random source order for
183 // completeness but it should not be actually happening in normal practice.
184
185 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
186 assert(Pos != DiagStatePoints.end());
187
188 // Update all diagnostic states that are active after the given location.
189 for (DiagStatePointsTy::iterator
190 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000191 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000192 }
193
194 // If the location corresponds to an existing point, just update its state.
195 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000196 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000197 return;
198 }
199
200 // Create a new state/point and fit it into the vector of DiagStatePoints
201 // so that the vector is always ordered according to location.
202 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
203 DiagStates.push_back(*Pos->State);
204 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000205 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000206 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
207 FullSourceLoc(Loc, *SourceMgr)));
208}
209
Douglas Gregorb3921592010-10-13 17:22:14 +0000210void DiagnosticBuilder::FlushCounts() {
211 DiagObj->NumDiagArgs = NumArgs;
212 DiagObj->NumDiagRanges = NumRanges;
213 DiagObj->NumFixItHints = NumFixItHints;
214}
215
Douglas Gregor85795312010-03-22 15:10:57 +0000216bool DiagnosticBuilder::Emit() {
217 // If DiagObj is null, then its soul was stolen by the copy ctor
218 // or the user called Emit().
219 if (DiagObj == 0) return false;
220
221 // When emitting diagnostics, we set the final argument count into
222 // the Diagnostic object.
Douglas Gregorb3921592010-10-13 17:22:14 +0000223 FlushCounts();
Douglas Gregor85795312010-03-22 15:10:57 +0000224
225 // Process the diagnostic, sending the accumulated information to the
226 // DiagnosticClient.
227 bool Emitted = DiagObj->ProcessDiag();
228
229 // Clear out the current diagnostic object.
Douglas Gregor96380982010-03-22 15:47:45 +0000230 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000231 DiagObj->Clear();
232
233 // If there was a delayed diagnostic, emit it now.
Douglas Gregor96380982010-03-22 15:47:45 +0000234 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor85795312010-03-22 15:10:57 +0000235 DiagObj->ReportDelayed();
236
237 // This diagnostic is dead.
238 DiagObj = 0;
239
240 return Emitted;
241}
242
Nico Weber4c311642008-08-10 19:59:06 +0000243
Chris Lattner22eb9722006-06-18 05:43:12 +0000244DiagnosticClient::~DiagnosticClient() {}
Nico Weber4c311642008-08-10 19:59:06 +0000245
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000246void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
247 const DiagnosticInfo &Info) {
248 if (!IncludeInDiagnosticCounts())
249 return;
250
251 if (DiagLevel == Diagnostic::Warning)
252 ++NumWarnings;
253 else if (DiagLevel >= Diagnostic::Error)
254 ++NumErrors;
255}
Chris Lattner23be0672008-11-19 06:51:40 +0000256
Chris Lattner2b786902008-11-21 07:50:02 +0000257/// ModifierIs - Return true if the specified modifier matches specified string.
258template <std::size_t StrLen>
259static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
260 const char (&Str)[StrLen]) {
261 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
262}
263
John McCall8cb7a8a32010-01-14 20:11:39 +0000264/// ScanForward - Scans forward, looking for the given character, skipping
265/// nested clauses and escaped characters.
266static const char *ScanFormat(const char *I, const char *E, char Target) {
267 unsigned Depth = 0;
268
269 for ( ; I != E; ++I) {
270 if (Depth == 0 && *I == Target) return I;
271 if (Depth != 0 && *I == '}') Depth--;
272
273 if (*I == '%') {
274 I++;
275 if (I == E) break;
276
277 // Escaped characters get implicitly skipped here.
278
279 // Format specifier.
280 if (!isdigit(*I) && !ispunct(*I)) {
281 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
282 if (I == E) break;
283 if (*I == '{')
284 Depth++;
285 }
286 }
287 }
288 return E;
289}
290
Chris Lattner2b786902008-11-21 07:50:02 +0000291/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
292/// like this: %select{foo|bar|baz}2. This means that the integer argument
293/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
294/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
295/// This is very useful for certain classes of variant diagnostics.
John McCalle4d54322010-01-13 23:58:20 +0000296static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000297 const char *Argument, unsigned ArgumentLen,
298 llvm::SmallVectorImpl<char> &OutStr) {
299 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattner2b786902008-11-21 07:50:02 +0000301 // Skip over 'ValNo' |'s.
302 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000303 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000304 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
305 " larger than the number of options in the diagnostic string!");
306 Argument = NextVal+1; // Skip this string.
307 --ValNo;
308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattner2b786902008-11-21 07:50:02 +0000310 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000311 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000312
313 // Recursively format the result of the select clause into the output string.
314 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000315}
316
317/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
318/// letter 's' to the string if the value is not 1. This is used in cases like
319/// this: "you idiot, you have %4 parameter%s4!".
320static void HandleIntegerSModifier(unsigned ValNo,
321 llvm::SmallVectorImpl<char> &OutStr) {
322 if (ValNo != 1)
323 OutStr.push_back('s');
324}
325
John McCall9015cde2010-01-14 00:50:32 +0000326/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
327/// prints the ordinal form of the given integer, with 1 corresponding
328/// to the first ordinal. Currently this is hard-coded to use the
329/// English form.
330static void HandleOrdinalModifier(unsigned ValNo,
331 llvm::SmallVectorImpl<char> &OutStr) {
332 assert(ValNo != 0 && "ValNo must be strictly positive!");
333
334 llvm::raw_svector_ostream Out(OutStr);
335
336 // We could use text forms for the first N ordinals, but the numeric
337 // forms are actually nicer in diagnostics because they stand out.
338 Out << ValNo;
339
340 // It is critically important that we do this perfectly for
341 // user-written sequences with over 100 elements.
342 switch (ValNo % 100) {
343 case 11:
344 case 12:
345 case 13:
346 Out << "th"; return;
347 default:
348 switch (ValNo % 10) {
349 case 1: Out << "st"; return;
350 case 2: Out << "nd"; return;
351 case 3: Out << "rd"; return;
352 default: Out << "th"; return;
353 }
354 }
355}
356
Chris Lattner2b786902008-11-21 07:50:02 +0000357
Sebastian Redl15b02d22008-11-22 13:44:36 +0000358/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000359static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000360 // Programming 101: Parse a decimal number :-)
361 unsigned Val = 0;
362 while (Start != End && *Start >= '0' && *Start <= '9') {
363 Val *= 10;
364 Val += *Start - '0';
365 ++Start;
366 }
367 return Val;
368}
369
370/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000371static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000372 if (*Start != '[') {
373 unsigned Ref = PluralNumber(Start, End);
374 return Ref == Val;
375 }
376
377 ++Start;
378 unsigned Low = PluralNumber(Start, End);
379 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
380 ++Start;
381 unsigned High = PluralNumber(Start, End);
382 assert(*Start == ']' && "Bad plural expression syntax: expected )");
383 ++Start;
384 return Low <= Val && Val <= High;
385}
386
387/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000388static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000389 // Empty condition?
390 if (*Start == ':')
391 return true;
392
393 while (1) {
394 char C = *Start;
395 if (C == '%') {
396 // Modulo expression
397 ++Start;
398 unsigned Arg = PluralNumber(Start, End);
399 assert(*Start == '=' && "Bad plural expression syntax: expected =");
400 ++Start;
401 unsigned ValMod = ValNo % Arg;
402 if (TestPluralRange(ValMod, Start, End))
403 return true;
404 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000405 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000406 "Bad plural expression syntax: unexpected character");
407 // Range expression
408 if (TestPluralRange(ValNo, Start, End))
409 return true;
410 }
411
412 // Scan for next or-expr part.
413 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000414 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000415 break;
416 ++Start;
417 }
418 return false;
419}
420
421/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
422/// for complex plural forms, or in languages where all plurals are complex.
423/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
424/// conditions that are tested in order, the form corresponding to the first
425/// that applies being emitted. The empty condition is always true, making the
426/// last form a default case.
427/// Conditions are simple boolean expressions, where n is the number argument.
428/// Here are the rules.
429/// condition := expression | empty
430/// empty := -> always true
431/// expression := numeric [',' expression] -> logical or
432/// numeric := range -> true if n in range
433/// | '%' number '=' range -> true if n % number in range
434/// range := number
435/// | '[' number ',' number ']' -> ranges are inclusive both ends
436///
437/// Here are some examples from the GNU gettext manual written in this form:
438/// English:
439/// {1:form0|:form1}
440/// Latvian:
441/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
442/// Gaeilge:
443/// {1:form0|2:form1|:form2}
444/// Romanian:
445/// {1:form0|0,%100=[1,19]:form1|:form2}
446/// Lithuanian:
447/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
448/// Russian (requires repeated form):
449/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
450/// Slovak
451/// {1:form0|[2,4]:form1|:form2}
452/// Polish (requires repeated form):
453/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCall43b61682010-10-14 01:55:31 +0000454static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000455 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb8e73152009-04-16 05:04:32 +0000456 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000457 const char *ArgumentEnd = Argument + ArgumentLen;
458 while (1) {
459 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
460 const char *ExprEnd = Argument;
461 while (*ExprEnd != ':') {
462 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
463 ++ExprEnd;
464 }
465 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
466 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000467 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000468
469 // Recursively format the result of the plural clause into the
470 // output string.
471 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000472 return;
473 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000474 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000475 }
476}
477
478
Chris Lattner23be0672008-11-19 06:51:40 +0000479/// FormatDiagnostic - Format this diagnostic into a string, substituting the
480/// formal arguments into the %0 slots. The result is appended onto the Str
481/// array.
482void DiagnosticInfo::
483FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000484 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
Chris Lattner23be0672008-11-19 06:51:40 +0000485 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump11289f42009-09-09 15:08:12 +0000486
John McCalle4d54322010-01-13 23:58:20 +0000487 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
488}
489
490void DiagnosticInfo::
491FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
492 llvm::SmallVectorImpl<char> &OutStr) const {
493
Chris Lattnerc243f292009-10-20 05:25:22 +0000494 /// FormattedArgs - Keep track of all of the arguments formatted by
495 /// ConvertArgToString and pass them into subsequent calls to
496 /// ConvertArgToString, allowing the implementation to avoid redundancies in
497 /// obvious cases.
498 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
499
Chris Lattner23be0672008-11-19 06:51:40 +0000500 while (DiagStr != DiagEnd) {
501 if (DiagStr[0] != '%') {
502 // Append non-%0 substrings to Str if we have one.
503 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
504 OutStr.append(DiagStr, StrEnd);
505 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000506 continue;
John McCall8cb7a8a32010-01-14 20:11:39 +0000507 } else if (ispunct(DiagStr[1])) {
508 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000509 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000510 continue;
511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Chris Lattner2b786902008-11-21 07:50:02 +0000513 // Skip the %.
514 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattner2b786902008-11-21 07:50:02 +0000516 // This must be a placeholder for a diagnostic argument. The format for a
517 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
518 // The digit is a number from 0-9 indicating which argument this comes from.
519 // The modifier is a string of digits from the set [-a-z]+, arguments is a
520 // brace enclosed string.
521 const char *Modifier = 0, *Argument = 0;
522 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattner2b786902008-11-21 07:50:02 +0000524 // Check to see if we have a modifier. If so eat it.
525 if (!isdigit(DiagStr[0])) {
526 Modifier = DiagStr;
527 while (DiagStr[0] == '-' ||
528 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
529 ++DiagStr;
530 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000531
Chris Lattner2b786902008-11-21 07:50:02 +0000532 // If we have an argument, get it next.
533 if (DiagStr[0] == '{') {
534 ++DiagStr; // Skip {.
535 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000536
John McCall8cb7a8a32010-01-14 20:11:39 +0000537 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
538 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000539 ArgumentLen = DiagStr-Argument;
540 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000541 }
Chris Lattner2b786902008-11-21 07:50:02 +0000542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Chris Lattner2b786902008-11-21 07:50:02 +0000544 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000545 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000546
Chris Lattnerc243f292009-10-20 05:25:22 +0000547 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
548
549 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000550 // ---- STRINGS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000551 case Diagnostic::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000552 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000553 assert(ModifierLen == 0 && "No modifiers for strings yet");
554 OutStr.append(S.begin(), S.end());
555 break;
556 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000557 case Diagnostic::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000558 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000559 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000560
561 // Don't crash if get passed a null pointer by accident.
562 if (!S)
563 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000564
Chris Lattner2b786902008-11-21 07:50:02 +0000565 OutStr.append(S, S + strlen(S));
566 break;
567 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000568 // ---- INTEGERS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000569 case Diagnostic::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000570 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattner2b786902008-11-21 07:50:02 +0000572 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000573 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
574 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000575 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
576 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000577 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000578 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
579 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000580 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
581 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000582 } else {
583 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000584 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000585 }
Chris Lattner2b786902008-11-21 07:50:02 +0000586 break;
587 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000588 case Diagnostic::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000589 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000590
Chris Lattner2b786902008-11-21 07:50:02 +0000591 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000592 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000593 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
594 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000595 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000596 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
597 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000598 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
599 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000600 } else {
601 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000602 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000603 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000604 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000605 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000606 // ---- NAMES and TYPES ----
607 case Diagnostic::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000608 const IdentifierInfo *II = getArgIdentifier(ArgNo);
609 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000610
611 // Don't crash if get passed a null pointer by accident.
612 if (!II) {
613 const char *S = "(null)";
614 OutStr.append(S, S + strlen(S));
615 continue;
616 }
617
Daniel Dunbar07d07852009-10-18 21:17:35 +0000618 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000619 break;
620 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000621 case Diagnostic::ak_qualtype:
Chris Lattnerf7e69d52008-11-23 20:28:15 +0000622 case Diagnostic::ak_declarationname:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000623 case Diagnostic::ak_nameddecl:
Douglas Gregor053f6912009-08-26 00:04:55 +0000624 case Diagnostic::ak_nestednamespec:
Douglas Gregore40876a2009-10-13 21:16:44 +0000625 case Diagnostic::ak_declcontext:
Chris Lattnerc243f292009-10-20 05:25:22 +0000626 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner63ecc502008-11-23 09:21:17 +0000627 Modifier, ModifierLen,
Chris Lattnerc243f292009-10-20 05:25:22 +0000628 Argument, ArgumentLen,
629 FormattedArgs.data(), FormattedArgs.size(),
630 OutStr);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000631 break;
Nico Weber4c311642008-08-10 19:59:06 +0000632 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000633
634 // Remember this argument info for subsequent formatting operations. Turn
635 // std::strings into a null terminated string to make it be the same case as
636 // all the other ones.
637 if (Kind != Diagnostic::ak_std_string)
638 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
639 else
640 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
641 (intptr_t)getArgStdStr(ArgNo).c_str()));
642
Nico Weber4c311642008-08-10 19:59:06 +0000643 }
Nico Weber4c311642008-08-10 19:59:06 +0000644}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000645
Douglas Gregor33cdd812010-02-18 18:08:43 +0000646StoredDiagnostic::StoredDiagnostic() { }
647
Douglas Gregora750e8e2010-11-19 16:18:16 +0000648StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000649 llvm::StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000650 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000651
652StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
653 const DiagnosticInfo &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000654 : ID(Info.getID()), Level(Level)
655{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000656 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
657 "Valid source location without setting a source manager for diagnostic");
658 if (Info.getLocation().isValid())
659 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000660 llvm::SmallString<64> Message;
661 Info.FormatDiagnostic(Message);
662 this->Message.assign(Message.begin(), Message.end());
663
664 Ranges.reserve(Info.getNumRanges());
665 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
666 Ranges.push_back(Info.getRange(I));
667
Douglas Gregora771f462010-03-31 17:46:05 +0000668 FixIts.reserve(Info.getNumFixItHints());
669 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
670 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000671}
672
673StoredDiagnostic::~StoredDiagnostic() { }
674
Ted Kremenekea06ec12009-01-23 20:28:53 +0000675/// IncludeInDiagnosticCounts - This method (whose default implementation
676/// returns true) indicates whether the diagnostics handled by this
677/// DiagnosticClient should be included in the number of diagnostics
678/// reported by Diagnostic.
679bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +0000680
681PartialDiagnostic::StorageAllocator::StorageAllocator() {
682 for (unsigned I = 0; I != NumCached; ++I)
683 FreeList[I] = Cached + I;
684 NumFreeListEntries = NumCached;
685}
686
687PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Ted Kremenek84de4a12011-03-21 18:40:07 +0000688 // Don't assert if we are in a CrashRecovery context, as this
689 // invariant may be invalidated during a crash.
Ted Kremenek0aaa67b2011-03-21 18:40:10 +0000690 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
Douglas Gregor89336232010-03-29 23:34:08 +0000691}