blob: 31e33315cce2052c3027ea0f5fb88fc70e44f56c [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
Douglas Gregor7a964ad2011-01-31 22:04:05 +000065void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
66 if (OwnsDiagClient && Client)
67 delete Client;
68
69 Client = client;
70 OwnsDiagClient = ShouldOwnClient;
71}
Chris Lattnerfb42a182009-07-12 21:18:45 +000072
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000073void Diagnostic::pushMappings(SourceLocation Loc) {
74 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000075}
76
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000077bool Diagnostic::popMappings(SourceLocation Loc) {
78 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +000079 return false;
80
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000081 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
82 // State changed at some point between push/pop.
83 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
84 }
85 DiagStateOnPushStack.pop_back();
Chris Lattnerfb42a182009-07-12 21:18:45 +000086 return true;
87}
88
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089void Diagnostic::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +000090 ErrorOccurred = false;
91 FatalErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000092
93 NumWarnings = 0;
94 NumErrors = 0;
95 NumErrorsSuppressed = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000096 CurDiagID = ~0U;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000097 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
98 // using a Diagnostic associated to a translation unit that follow
99 // diagnostics from a Diagnostic associated to anoter t.u. will not be
100 // displayed.
101 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000102 DelayedDiagID = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000103}
Chris Lattner22eb9722006-06-18 05:43:12 +0000104
Douglas Gregor85795312010-03-22 15:10:57 +0000105void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
106 llvm::StringRef Arg2) {
107 if (DelayedDiagID)
108 return;
109
110 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000111 DelayedDiagArg1 = Arg1.str();
112 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000113}
114
115void Diagnostic::ReportDelayed() {
116 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
117 DelayedDiagID = 0;
118 DelayedDiagArg1.clear();
119 DelayedDiagArg2.clear();
120}
121
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000122Diagnostic::DiagStatePointsTy::iterator
123Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
124 assert(!DiagStatePoints.empty());
125 assert(DiagStatePoints.front().Loc.isInvalid() &&
126 "Should have created a DiagStatePoint for command-line");
127
128 FullSourceLoc Loc(L, *SourceMgr);
129 if (Loc.isInvalid())
130 return DiagStatePoints.end() - 1;
131
132 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
133 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
134 if (LastStateChangePos.isValid() &&
135 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
136 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
137 DiagStatePoint(0, Loc));
138 --Pos;
139 return Pos;
140}
141
142/// \brief This allows the client to specify that certain
143/// warnings are ignored. Notes can never be mapped, errors can only be
144/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
145///
146/// \param The source location that this change of diagnostic state should
147/// take affect. It can be null if we are setting the latest state.
148void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
149 SourceLocation L) {
150 assert(Diag < diag::DIAG_UPPER_LIMIT &&
151 "Can only map builtin diagnostics");
152 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
153 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
154 "Cannot map errors into warnings!");
155 assert(!DiagStatePoints.empty());
156
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000157 bool isPragma = L.isValid();
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000158 FullSourceLoc Loc(L, *SourceMgr);
159 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
160
161 // Common case; setting all the diagnostics of a group in one place.
162 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000163 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000164 return;
165 }
166
167 // Another common case; modifying diagnostic state in a source location
168 // after the previous one.
169 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
170 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
171 // A diagnostic pragma occured, create a new DiagState initialized with
172 // the current one and a new DiagStatePoint to record at which location
173 // the new state became active.
174 DiagStates.push_back(*GetCurDiagState());
175 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000176 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000177 return;
178 }
179
180 // We allow setting the diagnostic state in random source order for
181 // completeness but it should not be actually happening in normal practice.
182
183 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
184 assert(Pos != DiagStatePoints.end());
185
186 // Update all diagnostic states that are active after the given location.
187 for (DiagStatePointsTy::iterator
188 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000189 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000190 }
191
192 // If the location corresponds to an existing point, just update its state.
193 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000194 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000195 return;
196 }
197
198 // Create a new state/point and fit it into the vector of DiagStatePoints
199 // so that the vector is always ordered according to location.
200 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
201 DiagStates.push_back(*Pos->State);
202 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000203 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000204 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
205 FullSourceLoc(Loc, *SourceMgr)));
206}
207
Douglas Gregorb3921592010-10-13 17:22:14 +0000208void DiagnosticBuilder::FlushCounts() {
209 DiagObj->NumDiagArgs = NumArgs;
210 DiagObj->NumDiagRanges = NumRanges;
211 DiagObj->NumFixItHints = NumFixItHints;
212}
213
Douglas Gregor85795312010-03-22 15:10:57 +0000214bool DiagnosticBuilder::Emit() {
215 // If DiagObj is null, then its soul was stolen by the copy ctor
216 // or the user called Emit().
217 if (DiagObj == 0) return false;
218
219 // When emitting diagnostics, we set the final argument count into
220 // the Diagnostic object.
Douglas Gregorb3921592010-10-13 17:22:14 +0000221 FlushCounts();
Douglas Gregor85795312010-03-22 15:10:57 +0000222
223 // Process the diagnostic, sending the accumulated information to the
224 // DiagnosticClient.
225 bool Emitted = DiagObj->ProcessDiag();
226
227 // Clear out the current diagnostic object.
Douglas Gregor96380982010-03-22 15:47:45 +0000228 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000229 DiagObj->Clear();
230
231 // If there was a delayed diagnostic, emit it now.
Douglas Gregor96380982010-03-22 15:47:45 +0000232 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor85795312010-03-22 15:10:57 +0000233 DiagObj->ReportDelayed();
234
235 // This diagnostic is dead.
236 DiagObj = 0;
237
238 return Emitted;
239}
240
Nico Weber4c311642008-08-10 19:59:06 +0000241
Chris Lattner22eb9722006-06-18 05:43:12 +0000242DiagnosticClient::~DiagnosticClient() {}
Nico Weber4c311642008-08-10 19:59:06 +0000243
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000244void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
245 const DiagnosticInfo &Info) {
246 if (!IncludeInDiagnosticCounts())
247 return;
248
249 if (DiagLevel == Diagnostic::Warning)
250 ++NumWarnings;
251 else if (DiagLevel >= Diagnostic::Error)
252 ++NumErrors;
253}
Chris Lattner23be0672008-11-19 06:51:40 +0000254
Chris Lattner2b786902008-11-21 07:50:02 +0000255/// ModifierIs - Return true if the specified modifier matches specified string.
256template <std::size_t StrLen>
257static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
258 const char (&Str)[StrLen]) {
259 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
260}
261
John McCall8cb7a8a32010-01-14 20:11:39 +0000262/// ScanForward - Scans forward, looking for the given character, skipping
263/// nested clauses and escaped characters.
264static const char *ScanFormat(const char *I, const char *E, char Target) {
265 unsigned Depth = 0;
266
267 for ( ; I != E; ++I) {
268 if (Depth == 0 && *I == Target) return I;
269 if (Depth != 0 && *I == '}') Depth--;
270
271 if (*I == '%') {
272 I++;
273 if (I == E) break;
274
275 // Escaped characters get implicitly skipped here.
276
277 // Format specifier.
278 if (!isdigit(*I) && !ispunct(*I)) {
279 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
280 if (I == E) break;
281 if (*I == '{')
282 Depth++;
283 }
284 }
285 }
286 return E;
287}
288
Chris Lattner2b786902008-11-21 07:50:02 +0000289/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
290/// like this: %select{foo|bar|baz}2. This means that the integer argument
291/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
292/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
293/// This is very useful for certain classes of variant diagnostics.
John McCalle4d54322010-01-13 23:58:20 +0000294static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000295 const char *Argument, unsigned ArgumentLen,
296 llvm::SmallVectorImpl<char> &OutStr) {
297 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner2b786902008-11-21 07:50:02 +0000299 // Skip over 'ValNo' |'s.
300 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000301 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000302 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
303 " larger than the number of options in the diagnostic string!");
304 Argument = NextVal+1; // Skip this string.
305 --ValNo;
306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattner2b786902008-11-21 07:50:02 +0000308 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000309 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000310
311 // Recursively format the result of the select clause into the output string.
312 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000313}
314
315/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
316/// letter 's' to the string if the value is not 1. This is used in cases like
317/// this: "you idiot, you have %4 parameter%s4!".
318static void HandleIntegerSModifier(unsigned ValNo,
319 llvm::SmallVectorImpl<char> &OutStr) {
320 if (ValNo != 1)
321 OutStr.push_back('s');
322}
323
John McCall9015cde2010-01-14 00:50:32 +0000324/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
325/// prints the ordinal form of the given integer, with 1 corresponding
326/// to the first ordinal. Currently this is hard-coded to use the
327/// English form.
328static void HandleOrdinalModifier(unsigned ValNo,
329 llvm::SmallVectorImpl<char> &OutStr) {
330 assert(ValNo != 0 && "ValNo must be strictly positive!");
331
332 llvm::raw_svector_ostream Out(OutStr);
333
334 // We could use text forms for the first N ordinals, but the numeric
335 // forms are actually nicer in diagnostics because they stand out.
336 Out << ValNo;
337
338 // It is critically important that we do this perfectly for
339 // user-written sequences with over 100 elements.
340 switch (ValNo % 100) {
341 case 11:
342 case 12:
343 case 13:
344 Out << "th"; return;
345 default:
346 switch (ValNo % 10) {
347 case 1: Out << "st"; return;
348 case 2: Out << "nd"; return;
349 case 3: Out << "rd"; return;
350 default: Out << "th"; return;
351 }
352 }
353}
354
Chris Lattner2b786902008-11-21 07:50:02 +0000355
Sebastian Redl15b02d22008-11-22 13:44:36 +0000356/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000357static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000358 // Programming 101: Parse a decimal number :-)
359 unsigned Val = 0;
360 while (Start != End && *Start >= '0' && *Start <= '9') {
361 Val *= 10;
362 Val += *Start - '0';
363 ++Start;
364 }
365 return Val;
366}
367
368/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000369static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000370 if (*Start != '[') {
371 unsigned Ref = PluralNumber(Start, End);
372 return Ref == Val;
373 }
374
375 ++Start;
376 unsigned Low = PluralNumber(Start, End);
377 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
378 ++Start;
379 unsigned High = PluralNumber(Start, End);
380 assert(*Start == ']' && "Bad plural expression syntax: expected )");
381 ++Start;
382 return Low <= Val && Val <= High;
383}
384
385/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000386static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000387 // Empty condition?
388 if (*Start == ':')
389 return true;
390
391 while (1) {
392 char C = *Start;
393 if (C == '%') {
394 // Modulo expression
395 ++Start;
396 unsigned Arg = PluralNumber(Start, End);
397 assert(*Start == '=' && "Bad plural expression syntax: expected =");
398 ++Start;
399 unsigned ValMod = ValNo % Arg;
400 if (TestPluralRange(ValMod, Start, End))
401 return true;
402 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000403 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000404 "Bad plural expression syntax: unexpected character");
405 // Range expression
406 if (TestPluralRange(ValNo, Start, End))
407 return true;
408 }
409
410 // Scan for next or-expr part.
411 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000412 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000413 break;
414 ++Start;
415 }
416 return false;
417}
418
419/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
420/// for complex plural forms, or in languages where all plurals are complex.
421/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
422/// conditions that are tested in order, the form corresponding to the first
423/// that applies being emitted. The empty condition is always true, making the
424/// last form a default case.
425/// Conditions are simple boolean expressions, where n is the number argument.
426/// Here are the rules.
427/// condition := expression | empty
428/// empty := -> always true
429/// expression := numeric [',' expression] -> logical or
430/// numeric := range -> true if n in range
431/// | '%' number '=' range -> true if n % number in range
432/// range := number
433/// | '[' number ',' number ']' -> ranges are inclusive both ends
434///
435/// Here are some examples from the GNU gettext manual written in this form:
436/// English:
437/// {1:form0|:form1}
438/// Latvian:
439/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
440/// Gaeilge:
441/// {1:form0|2:form1|:form2}
442/// Romanian:
443/// {1:form0|0,%100=[1,19]:form1|:form2}
444/// Lithuanian:
445/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
446/// Russian (requires repeated form):
447/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
448/// Slovak
449/// {1:form0|[2,4]:form1|:form2}
450/// Polish (requires repeated form):
451/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCall43b61682010-10-14 01:55:31 +0000452static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000453 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb8e73152009-04-16 05:04:32 +0000454 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000455 const char *ArgumentEnd = Argument + ArgumentLen;
456 while (1) {
457 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
458 const char *ExprEnd = Argument;
459 while (*ExprEnd != ':') {
460 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
461 ++ExprEnd;
462 }
463 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
464 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000465 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000466
467 // Recursively format the result of the plural clause into the
468 // output string.
469 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000470 return;
471 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000472 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000473 }
474}
475
476
Chris Lattner23be0672008-11-19 06:51:40 +0000477/// FormatDiagnostic - Format this diagnostic into a string, substituting the
478/// formal arguments into the %0 slots. The result is appended onto the Str
479/// array.
480void DiagnosticInfo::
481FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000482 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
Chris Lattner23be0672008-11-19 06:51:40 +0000483 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump11289f42009-09-09 15:08:12 +0000484
John McCalle4d54322010-01-13 23:58:20 +0000485 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
486}
487
488void DiagnosticInfo::
489FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
490 llvm::SmallVectorImpl<char> &OutStr) const {
491
Chris Lattnerc243f292009-10-20 05:25:22 +0000492 /// FormattedArgs - Keep track of all of the arguments formatted by
493 /// ConvertArgToString and pass them into subsequent calls to
494 /// ConvertArgToString, allowing the implementation to avoid redundancies in
495 /// obvious cases.
496 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
497
Chris Lattner23be0672008-11-19 06:51:40 +0000498 while (DiagStr != DiagEnd) {
499 if (DiagStr[0] != '%') {
500 // Append non-%0 substrings to Str if we have one.
501 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
502 OutStr.append(DiagStr, StrEnd);
503 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000504 continue;
John McCall8cb7a8a32010-01-14 20:11:39 +0000505 } else if (ispunct(DiagStr[1])) {
506 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000507 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000508 continue;
509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner2b786902008-11-21 07:50:02 +0000511 // Skip the %.
512 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattner2b786902008-11-21 07:50:02 +0000514 // This must be a placeholder for a diagnostic argument. The format for a
515 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
516 // The digit is a number from 0-9 indicating which argument this comes from.
517 // The modifier is a string of digits from the set [-a-z]+, arguments is a
518 // brace enclosed string.
519 const char *Modifier = 0, *Argument = 0;
520 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattner2b786902008-11-21 07:50:02 +0000522 // Check to see if we have a modifier. If so eat it.
523 if (!isdigit(DiagStr[0])) {
524 Modifier = DiagStr;
525 while (DiagStr[0] == '-' ||
526 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
527 ++DiagStr;
528 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000529
Chris Lattner2b786902008-11-21 07:50:02 +0000530 // If we have an argument, get it next.
531 if (DiagStr[0] == '{') {
532 ++DiagStr; // Skip {.
533 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000534
John McCall8cb7a8a32010-01-14 20:11:39 +0000535 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
536 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000537 ArgumentLen = DiagStr-Argument;
538 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000539 }
Chris Lattner2b786902008-11-21 07:50:02 +0000540 }
Mike Stump11289f42009-09-09 15:08:12 +0000541
Chris Lattner2b786902008-11-21 07:50:02 +0000542 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000543 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000544
Chris Lattnerc243f292009-10-20 05:25:22 +0000545 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
546
547 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000548 // ---- STRINGS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000549 case Diagnostic::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000550 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000551 assert(ModifierLen == 0 && "No modifiers for strings yet");
552 OutStr.append(S.begin(), S.end());
553 break;
554 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000555 case Diagnostic::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000556 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000557 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000558
559 // Don't crash if get passed a null pointer by accident.
560 if (!S)
561 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattner2b786902008-11-21 07:50:02 +0000563 OutStr.append(S, S + strlen(S));
564 break;
565 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000566 // ---- INTEGERS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000567 case Diagnostic::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000568 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000569
Chris Lattner2b786902008-11-21 07:50:02 +0000570 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000571 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
572 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000573 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
574 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000575 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000576 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
577 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000578 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
579 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000580 } else {
581 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000582 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000583 }
Chris Lattner2b786902008-11-21 07:50:02 +0000584 break;
585 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000586 case Diagnostic::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000587 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattner2b786902008-11-21 07:50:02 +0000589 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000590 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000591 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
592 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000593 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000594 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
595 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000596 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
597 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000598 } else {
599 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000600 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000601 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000602 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000603 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000604 // ---- NAMES and TYPES ----
605 case Diagnostic::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000606 const IdentifierInfo *II = getArgIdentifier(ArgNo);
607 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000608
609 // Don't crash if get passed a null pointer by accident.
610 if (!II) {
611 const char *S = "(null)";
612 OutStr.append(S, S + strlen(S));
613 continue;
614 }
615
Daniel Dunbar07d07852009-10-18 21:17:35 +0000616 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000617 break;
618 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000619 case Diagnostic::ak_qualtype:
Chris Lattnerf7e69d52008-11-23 20:28:15 +0000620 case Diagnostic::ak_declarationname:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000621 case Diagnostic::ak_nameddecl:
Douglas Gregor053f6912009-08-26 00:04:55 +0000622 case Diagnostic::ak_nestednamespec:
Douglas Gregore40876a2009-10-13 21:16:44 +0000623 case Diagnostic::ak_declcontext:
Chris Lattnerc243f292009-10-20 05:25:22 +0000624 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner63ecc502008-11-23 09:21:17 +0000625 Modifier, ModifierLen,
Chris Lattnerc243f292009-10-20 05:25:22 +0000626 Argument, ArgumentLen,
627 FormattedArgs.data(), FormattedArgs.size(),
628 OutStr);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000629 break;
Nico Weber4c311642008-08-10 19:59:06 +0000630 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000631
632 // Remember this argument info for subsequent formatting operations. Turn
633 // std::strings into a null terminated string to make it be the same case as
634 // all the other ones.
635 if (Kind != Diagnostic::ak_std_string)
636 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
637 else
638 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
639 (intptr_t)getArgStdStr(ArgNo).c_str()));
640
Nico Weber4c311642008-08-10 19:59:06 +0000641 }
Nico Weber4c311642008-08-10 19:59:06 +0000642}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000643
Douglas Gregor33cdd812010-02-18 18:08:43 +0000644StoredDiagnostic::StoredDiagnostic() { }
645
Douglas Gregora750e8e2010-11-19 16:18:16 +0000646StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000647 llvm::StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000648 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000649
650StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
651 const DiagnosticInfo &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000652 : ID(Info.getID()), Level(Level)
653{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000654 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
655 "Valid source location without setting a source manager for diagnostic");
656 if (Info.getLocation().isValid())
657 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000658 llvm::SmallString<64> Message;
659 Info.FormatDiagnostic(Message);
660 this->Message.assign(Message.begin(), Message.end());
661
662 Ranges.reserve(Info.getNumRanges());
663 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
664 Ranges.push_back(Info.getRange(I));
665
Douglas Gregora771f462010-03-31 17:46:05 +0000666 FixIts.reserve(Info.getNumFixItHints());
667 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
668 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000669}
670
671StoredDiagnostic::~StoredDiagnostic() { }
672
Ted Kremenekea06ec12009-01-23 20:28:53 +0000673/// IncludeInDiagnosticCounts - This method (whose default implementation
674/// returns true) indicates whether the diagnostics handled by this
675/// DiagnosticClient should be included in the number of diagnostics
676/// reported by Diagnostic.
677bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +0000678
679PartialDiagnostic::StorageAllocator::StorageAllocator() {
680 for (unsigned I = 0; I != NumCached; ++I)
681 FreeList[I] = Cached + I;
682 NumFreeListEntries = NumCached;
683}
684
685PartialDiagnostic::StorageAllocator::~StorageAllocator() {
686 assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
687}