blob: 9a263c1d0bc0a58f1f5254f814303a3fe7ff17ee [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"
Chris Lattner22eb9722006-06-18 05:43:12 +000019using namespace clang;
20
Chris Lattner63ecc502008-11-23 09:21:17 +000021static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
22 const char *Modifier, unsigned ML,
23 const char *Argument, unsigned ArgLen,
Chris Lattnerc243f292009-10-20 05:25:22 +000024 const Diagnostic::ArgumentValue *PrevArgs,
25 unsigned NumPrevArgs,
Chris Lattnercf868c42009-02-19 23:53:20 +000026 llvm::SmallVectorImpl<char> &Output,
27 void *Cookie) {
Chris Lattner63ecc502008-11-23 09:21:17 +000028 const char *Str = "<can't format argument>";
Chris Lattner6a2ed6f2008-11-23 09:13:29 +000029 Output.append(Str, Str+strlen(Str));
30}
31
32
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000033Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
34 DiagnosticClient *client, bool ShouldOwnClient)
35 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
36 SourceMgr(0) {
Chris Lattner63ecc502008-11-23 09:21:17 +000037 ArgToStringFn = DummyArgToStringFn;
Chris Lattnercf868c42009-02-19 23:53:20 +000038 ArgToStringCookie = 0;
Mike Stump11289f42009-09-09 15:08:12 +000039
Douglas Gregor0e119552010-07-31 00:40:00 +000040 AllExtensionsSilenced = 0;
41 IgnoreAllWarnings = false;
42 WarningsAsErrors = false;
43 ErrorsAsFatal = false;
44 SuppressSystemWarnings = false;
45 SuppressAllDiagnostics = false;
46 ShowOverloads = Ovl_All;
47 ExtBehavior = Ext_Ignore;
48
49 ErrorLimit = 0;
50 TemplateBacktraceLimit = 0;
Douglas Gregor0e119552010-07-31 00:40:00 +000051
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000052 // Create a DiagState and DiagStatePoint representing diagnostic changes
53 // through command-line.
54 DiagStates.push_back(DiagState());
55 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregor0e119552010-07-31 00:40:00 +000056
Douglas Gregoraa21cc42010-07-19 21:46:24 +000057 Reset();
Chris Lattnerae411572006-07-05 00:55:08 +000058}
59
Chris Lattnere6535cf2007-12-02 01:09:57 +000060Diagnostic::~Diagnostic() {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000061 if (OwnsDiagClient)
62 delete Client;
Chris Lattnere6535cf2007-12-02 01:09:57 +000063}
64
Chris Lattnerfb42a182009-07-12 21:18:45 +000065
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000066void Diagnostic::pushMappings(SourceLocation Loc) {
67 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000068}
69
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000070bool Diagnostic::popMappings(SourceLocation Loc) {
71 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +000072 return false;
73
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000074 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
75 // State changed at some point between push/pop.
76 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
77 }
78 DiagStateOnPushStack.pop_back();
Chris Lattnerfb42a182009-07-12 21:18:45 +000079 return true;
80}
81
Douglas Gregoraa21cc42010-07-19 21:46:24 +000082void Diagnostic::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +000083 ErrorOccurred = false;
84 FatalErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000085
86 NumWarnings = 0;
87 NumErrors = 0;
88 NumErrorsSuppressed = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089 CurDiagID = ~0U;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000090 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
91 // using a Diagnostic associated to a translation unit that follow
92 // diagnostics from a Diagnostic associated to anoter t.u. will not be
93 // displayed.
94 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000095 DelayedDiagID = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000096}
Chris Lattner22eb9722006-06-18 05:43:12 +000097
Douglas Gregor85795312010-03-22 15:10:57 +000098void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
99 llvm::StringRef Arg2) {
100 if (DelayedDiagID)
101 return;
102
103 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000104 DelayedDiagArg1 = Arg1.str();
105 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000106}
107
108void Diagnostic::ReportDelayed() {
109 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
110 DelayedDiagID = 0;
111 DelayedDiagArg1.clear();
112 DelayedDiagArg2.clear();
113}
114
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000115Diagnostic::DiagStatePointsTy::iterator
116Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
117 assert(!DiagStatePoints.empty());
118 assert(DiagStatePoints.front().Loc.isInvalid() &&
119 "Should have created a DiagStatePoint for command-line");
120
121 FullSourceLoc Loc(L, *SourceMgr);
122 if (Loc.isInvalid())
123 return DiagStatePoints.end() - 1;
124
125 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
126 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
127 if (LastStateChangePos.isValid() &&
128 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
129 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
130 DiagStatePoint(0, Loc));
131 --Pos;
132 return Pos;
133}
134
135/// \brief This allows the client to specify that certain
136/// warnings are ignored. Notes can never be mapped, errors can only be
137/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
138///
139/// \param The source location that this change of diagnostic state should
140/// take affect. It can be null if we are setting the latest state.
141void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
142 SourceLocation L) {
143 assert(Diag < diag::DIAG_UPPER_LIMIT &&
144 "Can only map builtin diagnostics");
145 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
146 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
147 "Cannot map errors into warnings!");
148 assert(!DiagStatePoints.empty());
149
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000150 bool isPragma = L.isValid();
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000151 FullSourceLoc Loc(L, *SourceMgr);
152 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
153
154 // Common case; setting all the diagnostics of a group in one place.
155 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000156 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000157 return;
158 }
159
160 // Another common case; modifying diagnostic state in a source location
161 // after the previous one.
162 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
163 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
164 // A diagnostic pragma occured, create a new DiagState initialized with
165 // the current one and a new DiagStatePoint to record at which location
166 // the new state became active.
167 DiagStates.push_back(*GetCurDiagState());
168 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000169 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000170 return;
171 }
172
173 // We allow setting the diagnostic state in random source order for
174 // completeness but it should not be actually happening in normal practice.
175
176 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
177 assert(Pos != DiagStatePoints.end());
178
179 // Update all diagnostic states that are active after the given location.
180 for (DiagStatePointsTy::iterator
181 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000182 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000183 }
184
185 // If the location corresponds to an existing point, just update its state.
186 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000187 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000188 return;
189 }
190
191 // Create a new state/point and fit it into the vector of DiagStatePoints
192 // so that the vector is always ordered according to location.
193 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
194 DiagStates.push_back(*Pos->State);
195 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000196 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000197 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
198 FullSourceLoc(Loc, *SourceMgr)));
199}
200
Douglas Gregorb3921592010-10-13 17:22:14 +0000201void DiagnosticBuilder::FlushCounts() {
202 DiagObj->NumDiagArgs = NumArgs;
203 DiagObj->NumDiagRanges = NumRanges;
204 DiagObj->NumFixItHints = NumFixItHints;
205}
206
Douglas Gregor85795312010-03-22 15:10:57 +0000207bool DiagnosticBuilder::Emit() {
208 // If DiagObj is null, then its soul was stolen by the copy ctor
209 // or the user called Emit().
210 if (DiagObj == 0) return false;
211
212 // When emitting diagnostics, we set the final argument count into
213 // the Diagnostic object.
Douglas Gregorb3921592010-10-13 17:22:14 +0000214 FlushCounts();
Douglas Gregor85795312010-03-22 15:10:57 +0000215
216 // Process the diagnostic, sending the accumulated information to the
217 // DiagnosticClient.
218 bool Emitted = DiagObj->ProcessDiag();
219
220 // Clear out the current diagnostic object.
Douglas Gregor96380982010-03-22 15:47:45 +0000221 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000222 DiagObj->Clear();
223
224 // If there was a delayed diagnostic, emit it now.
Douglas Gregor96380982010-03-22 15:47:45 +0000225 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor85795312010-03-22 15:10:57 +0000226 DiagObj->ReportDelayed();
227
228 // This diagnostic is dead.
229 DiagObj = 0;
230
231 return Emitted;
232}
233
Nico Weber4c311642008-08-10 19:59:06 +0000234
Chris Lattner22eb9722006-06-18 05:43:12 +0000235DiagnosticClient::~DiagnosticClient() {}
Nico Weber4c311642008-08-10 19:59:06 +0000236
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000237void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
238 const DiagnosticInfo &Info) {
239 if (!IncludeInDiagnosticCounts())
240 return;
241
242 if (DiagLevel == Diagnostic::Warning)
243 ++NumWarnings;
244 else if (DiagLevel >= Diagnostic::Error)
245 ++NumErrors;
246}
Chris Lattner23be0672008-11-19 06:51:40 +0000247
Chris Lattner2b786902008-11-21 07:50:02 +0000248/// ModifierIs - Return true if the specified modifier matches specified string.
249template <std::size_t StrLen>
250static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
251 const char (&Str)[StrLen]) {
252 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
253}
254
John McCall8cb7a8a32010-01-14 20:11:39 +0000255/// ScanForward - Scans forward, looking for the given character, skipping
256/// nested clauses and escaped characters.
257static const char *ScanFormat(const char *I, const char *E, char Target) {
258 unsigned Depth = 0;
259
260 for ( ; I != E; ++I) {
261 if (Depth == 0 && *I == Target) return I;
262 if (Depth != 0 && *I == '}') Depth--;
263
264 if (*I == '%') {
265 I++;
266 if (I == E) break;
267
268 // Escaped characters get implicitly skipped here.
269
270 // Format specifier.
271 if (!isdigit(*I) && !ispunct(*I)) {
272 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
273 if (I == E) break;
274 if (*I == '{')
275 Depth++;
276 }
277 }
278 }
279 return E;
280}
281
Chris Lattner2b786902008-11-21 07:50:02 +0000282/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
283/// like this: %select{foo|bar|baz}2. This means that the integer argument
284/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
285/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
286/// This is very useful for certain classes of variant diagnostics.
John McCalle4d54322010-01-13 23:58:20 +0000287static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000288 const char *Argument, unsigned ArgumentLen,
289 llvm::SmallVectorImpl<char> &OutStr) {
290 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner2b786902008-11-21 07:50:02 +0000292 // Skip over 'ValNo' |'s.
293 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000294 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000295 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
296 " larger than the number of options in the diagnostic string!");
297 Argument = NextVal+1; // Skip this string.
298 --ValNo;
299 }
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattner2b786902008-11-21 07:50:02 +0000301 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000302 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000303
304 // Recursively format the result of the select clause into the output string.
305 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000306}
307
308/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
309/// letter 's' to the string if the value is not 1. This is used in cases like
310/// this: "you idiot, you have %4 parameter%s4!".
311static void HandleIntegerSModifier(unsigned ValNo,
312 llvm::SmallVectorImpl<char> &OutStr) {
313 if (ValNo != 1)
314 OutStr.push_back('s');
315}
316
John McCall9015cde2010-01-14 00:50:32 +0000317/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
318/// prints the ordinal form of the given integer, with 1 corresponding
319/// to the first ordinal. Currently this is hard-coded to use the
320/// English form.
321static void HandleOrdinalModifier(unsigned ValNo,
322 llvm::SmallVectorImpl<char> &OutStr) {
323 assert(ValNo != 0 && "ValNo must be strictly positive!");
324
325 llvm::raw_svector_ostream Out(OutStr);
326
327 // We could use text forms for the first N ordinals, but the numeric
328 // forms are actually nicer in diagnostics because they stand out.
329 Out << ValNo;
330
331 // It is critically important that we do this perfectly for
332 // user-written sequences with over 100 elements.
333 switch (ValNo % 100) {
334 case 11:
335 case 12:
336 case 13:
337 Out << "th"; return;
338 default:
339 switch (ValNo % 10) {
340 case 1: Out << "st"; return;
341 case 2: Out << "nd"; return;
342 case 3: Out << "rd"; return;
343 default: Out << "th"; return;
344 }
345 }
346}
347
Chris Lattner2b786902008-11-21 07:50:02 +0000348
Sebastian Redl15b02d22008-11-22 13:44:36 +0000349/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000350static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000351 // Programming 101: Parse a decimal number :-)
352 unsigned Val = 0;
353 while (Start != End && *Start >= '0' && *Start <= '9') {
354 Val *= 10;
355 Val += *Start - '0';
356 ++Start;
357 }
358 return Val;
359}
360
361/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000362static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000363 if (*Start != '[') {
364 unsigned Ref = PluralNumber(Start, End);
365 return Ref == Val;
366 }
367
368 ++Start;
369 unsigned Low = PluralNumber(Start, End);
370 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
371 ++Start;
372 unsigned High = PluralNumber(Start, End);
373 assert(*Start == ']' && "Bad plural expression syntax: expected )");
374 ++Start;
375 return Low <= Val && Val <= High;
376}
377
378/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000379static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000380 // Empty condition?
381 if (*Start == ':')
382 return true;
383
384 while (1) {
385 char C = *Start;
386 if (C == '%') {
387 // Modulo expression
388 ++Start;
389 unsigned Arg = PluralNumber(Start, End);
390 assert(*Start == '=' && "Bad plural expression syntax: expected =");
391 ++Start;
392 unsigned ValMod = ValNo % Arg;
393 if (TestPluralRange(ValMod, Start, End))
394 return true;
395 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000396 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000397 "Bad plural expression syntax: unexpected character");
398 // Range expression
399 if (TestPluralRange(ValNo, Start, End))
400 return true;
401 }
402
403 // Scan for next or-expr part.
404 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000405 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000406 break;
407 ++Start;
408 }
409 return false;
410}
411
412/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
413/// for complex plural forms, or in languages where all plurals are complex.
414/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
415/// conditions that are tested in order, the form corresponding to the first
416/// that applies being emitted. The empty condition is always true, making the
417/// last form a default case.
418/// Conditions are simple boolean expressions, where n is the number argument.
419/// Here are the rules.
420/// condition := expression | empty
421/// empty := -> always true
422/// expression := numeric [',' expression] -> logical or
423/// numeric := range -> true if n in range
424/// | '%' number '=' range -> true if n % number in range
425/// range := number
426/// | '[' number ',' number ']' -> ranges are inclusive both ends
427///
428/// Here are some examples from the GNU gettext manual written in this form:
429/// English:
430/// {1:form0|:form1}
431/// Latvian:
432/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
433/// Gaeilge:
434/// {1:form0|2:form1|:form2}
435/// Romanian:
436/// {1:form0|0,%100=[1,19]:form1|:form2}
437/// Lithuanian:
438/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
439/// Russian (requires repeated form):
440/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
441/// Slovak
442/// {1:form0|[2,4]:form1|:form2}
443/// Polish (requires repeated form):
444/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCall43b61682010-10-14 01:55:31 +0000445static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000446 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb8e73152009-04-16 05:04:32 +0000447 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000448 const char *ArgumentEnd = Argument + ArgumentLen;
449 while (1) {
450 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
451 const char *ExprEnd = Argument;
452 while (*ExprEnd != ':') {
453 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
454 ++ExprEnd;
455 }
456 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
457 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000458 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000459
460 // Recursively format the result of the plural clause into the
461 // output string.
462 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000463 return;
464 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000465 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000466 }
467}
468
469
Chris Lattner23be0672008-11-19 06:51:40 +0000470/// FormatDiagnostic - Format this diagnostic into a string, substituting the
471/// formal arguments into the %0 slots. The result is appended onto the Str
472/// array.
473void DiagnosticInfo::
474FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000475 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
Chris Lattner23be0672008-11-19 06:51:40 +0000476 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump11289f42009-09-09 15:08:12 +0000477
John McCalle4d54322010-01-13 23:58:20 +0000478 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
479}
480
481void DiagnosticInfo::
482FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
483 llvm::SmallVectorImpl<char> &OutStr) const {
484
Chris Lattnerc243f292009-10-20 05:25:22 +0000485 /// FormattedArgs - Keep track of all of the arguments formatted by
486 /// ConvertArgToString and pass them into subsequent calls to
487 /// ConvertArgToString, allowing the implementation to avoid redundancies in
488 /// obvious cases.
489 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
490
Chris Lattner23be0672008-11-19 06:51:40 +0000491 while (DiagStr != DiagEnd) {
492 if (DiagStr[0] != '%') {
493 // Append non-%0 substrings to Str if we have one.
494 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
495 OutStr.append(DiagStr, StrEnd);
496 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000497 continue;
John McCall8cb7a8a32010-01-14 20:11:39 +0000498 } else if (ispunct(DiagStr[1])) {
499 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000500 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000501 continue;
502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattner2b786902008-11-21 07:50:02 +0000504 // Skip the %.
505 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner2b786902008-11-21 07:50:02 +0000507 // This must be a placeholder for a diagnostic argument. The format for a
508 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
509 // The digit is a number from 0-9 indicating which argument this comes from.
510 // The modifier is a string of digits from the set [-a-z]+, arguments is a
511 // brace enclosed string.
512 const char *Modifier = 0, *Argument = 0;
513 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattner2b786902008-11-21 07:50:02 +0000515 // Check to see if we have a modifier. If so eat it.
516 if (!isdigit(DiagStr[0])) {
517 Modifier = DiagStr;
518 while (DiagStr[0] == '-' ||
519 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
520 ++DiagStr;
521 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000522
Chris Lattner2b786902008-11-21 07:50:02 +0000523 // If we have an argument, get it next.
524 if (DiagStr[0] == '{') {
525 ++DiagStr; // Skip {.
526 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000527
John McCall8cb7a8a32010-01-14 20:11:39 +0000528 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
529 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000530 ArgumentLen = DiagStr-Argument;
531 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000532 }
Chris Lattner2b786902008-11-21 07:50:02 +0000533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattner2b786902008-11-21 07:50:02 +0000535 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000536 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000537
Chris Lattnerc243f292009-10-20 05:25:22 +0000538 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
539
540 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000541 // ---- STRINGS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000542 case Diagnostic::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000543 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000544 assert(ModifierLen == 0 && "No modifiers for strings yet");
545 OutStr.append(S.begin(), S.end());
546 break;
547 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000548 case Diagnostic::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000549 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000550 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000551
552 // Don't crash if get passed a null pointer by accident.
553 if (!S)
554 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000555
Chris Lattner2b786902008-11-21 07:50:02 +0000556 OutStr.append(S, S + strlen(S));
557 break;
558 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000559 // ---- INTEGERS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000560 case Diagnostic::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000561 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattner2b786902008-11-21 07:50:02 +0000563 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000564 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
565 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000566 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
567 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000568 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000569 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
570 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000571 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
572 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000573 } else {
574 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000575 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000576 }
Chris Lattner2b786902008-11-21 07:50:02 +0000577 break;
578 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000579 case Diagnostic::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000580 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattner2b786902008-11-21 07:50:02 +0000582 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000583 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000584 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
585 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000586 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000587 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
588 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000589 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
590 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000591 } else {
592 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000593 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000594 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000595 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000596 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000597 // ---- NAMES and TYPES ----
598 case Diagnostic::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000599 const IdentifierInfo *II = getArgIdentifier(ArgNo);
600 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000601
602 // Don't crash if get passed a null pointer by accident.
603 if (!II) {
604 const char *S = "(null)";
605 OutStr.append(S, S + strlen(S));
606 continue;
607 }
608
Daniel Dunbar07d07852009-10-18 21:17:35 +0000609 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000610 break;
611 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000612 case Diagnostic::ak_qualtype:
Chris Lattnerf7e69d52008-11-23 20:28:15 +0000613 case Diagnostic::ak_declarationname:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000614 case Diagnostic::ak_nameddecl:
Douglas Gregor053f6912009-08-26 00:04:55 +0000615 case Diagnostic::ak_nestednamespec:
Douglas Gregore40876a2009-10-13 21:16:44 +0000616 case Diagnostic::ak_declcontext:
Chris Lattnerc243f292009-10-20 05:25:22 +0000617 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner63ecc502008-11-23 09:21:17 +0000618 Modifier, ModifierLen,
Chris Lattnerc243f292009-10-20 05:25:22 +0000619 Argument, ArgumentLen,
620 FormattedArgs.data(), FormattedArgs.size(),
621 OutStr);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000622 break;
Nico Weber4c311642008-08-10 19:59:06 +0000623 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000624
625 // Remember this argument info for subsequent formatting operations. Turn
626 // std::strings into a null terminated string to make it be the same case as
627 // all the other ones.
628 if (Kind != Diagnostic::ak_std_string)
629 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
630 else
631 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
632 (intptr_t)getArgStdStr(ArgNo).c_str()));
633
Nico Weber4c311642008-08-10 19:59:06 +0000634 }
Nico Weber4c311642008-08-10 19:59:06 +0000635}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000636
Douglas Gregor33cdd812010-02-18 18:08:43 +0000637StoredDiagnostic::StoredDiagnostic() { }
638
Douglas Gregora750e8e2010-11-19 16:18:16 +0000639StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000640 llvm::StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000641 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000642
643StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
644 const DiagnosticInfo &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000645 : ID(Info.getID()), Level(Level)
646{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000647 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
648 "Valid source location without setting a source manager for diagnostic");
649 if (Info.getLocation().isValid())
650 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000651 llvm::SmallString<64> Message;
652 Info.FormatDiagnostic(Message);
653 this->Message.assign(Message.begin(), Message.end());
654
655 Ranges.reserve(Info.getNumRanges());
656 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
657 Ranges.push_back(Info.getRange(I));
658
Douglas Gregora771f462010-03-31 17:46:05 +0000659 FixIts.reserve(Info.getNumFixItHints());
660 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
661 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000662}
663
664StoredDiagnostic::~StoredDiagnostic() { }
665
Ted Kremenekea06ec12009-01-23 20:28:53 +0000666/// IncludeInDiagnosticCounts - This method (whose default implementation
667/// returns true) indicates whether the diagnostics handled by this
668/// DiagnosticClient should be included in the number of diagnostics
669/// reported by Diagnostic.
670bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +0000671
672PartialDiagnostic::StorageAllocator::StorageAllocator() {
673 for (unsigned I = 0; I != NumCached; ++I)
674 FreeList[I] = Cached + I;
675 NumFreeListEntries = NumCached;
676}
677
678PartialDiagnostic::StorageAllocator::~StorageAllocator() {
679 assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
680}