blob: c79fe7b83d3bc8ccc3b3a3b310284e78df28c7e7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekec55c942010-04-12 19:54:17 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattner43b628c2008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Ted Kremenekec55c942010-04-12 19:54:17 +000016#include "clang/Basic/PartialDiagnostic.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Daniel Dunbar23e47c62009-10-17 18:12:14 +000018#include "llvm/Support/raw_ostream.h"
Ted Kremenek03201fb2011-03-21 18:40:07 +000019#include "llvm/Support/CrashRecoveryContext.h"
20
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
Chris Lattner3fdf4b02008-11-23 09:21:17 +000023static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
24 const char *Modifier, unsigned ML,
25 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +000026 const Diagnostic::ArgumentValue *PrevArgs,
27 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +000028 llvm::SmallVectorImpl<char> &Output,
29 void *Cookie) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +000030 const char *Str = "<can't format argument>";
Chris Lattner22caddc2008-11-23 09:13:29 +000031 Output.append(Str, Str+strlen(Str));
32}
33
34
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000035Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
36 DiagnosticClient *client, bool ShouldOwnClient)
37 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
38 SourceMgr(0) {
Chris Lattner3fdf4b02008-11-23 09:21:17 +000039 ArgToStringFn = DummyArgToStringFn;
Chris Lattner92dd3862009-02-19 23:53:20 +000040 ArgToStringCookie = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000041
Douglas Gregorcc5888d2010-07-31 00:40:00 +000042 AllExtensionsSilenced = 0;
43 IgnoreAllWarnings = false;
44 WarningsAsErrors = false;
45 ErrorsAsFatal = false;
46 SuppressSystemWarnings = false;
47 SuppressAllDiagnostics = false;
48 ShowOverloads = Ovl_All;
49 ExtBehavior = Ext_Ignore;
50
51 ErrorLimit = 0;
52 TemplateBacktraceLimit = 0;
Douglas Gregorcc5888d2010-07-31 00:40:00 +000053
Douglas Gregorabc563f2010-07-19 21:46:24 +000054 Reset();
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Chris Lattner182745a2007-12-02 01:09:57 +000057Diagnostic::~Diagnostic() {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000058 if (OwnsDiagClient)
59 delete Client;
Chris Lattner182745a2007-12-02 01:09:57 +000060}
61
Douglas Gregor4f5e21e2011-01-31 22:04:05 +000062void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
63 if (OwnsDiagClient && Client)
64 delete Client;
65
66 Client = client;
67 OwnsDiagClient = ShouldOwnClient;
68}
Chris Lattner04ae2df2009-07-12 21:18:45 +000069
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000070void Diagnostic::pushMappings(SourceLocation Loc) {
71 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattner04ae2df2009-07-12 21:18:45 +000072}
73
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000074bool Diagnostic::popMappings(SourceLocation Loc) {
75 if (DiagStateOnPushStack.empty())
Chris Lattner04ae2df2009-07-12 21:18:45 +000076 return false;
77
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000078 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
79 // State changed at some point between push/pop.
80 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
81 }
82 DiagStateOnPushStack.pop_back();
Chris Lattner04ae2df2009-07-12 21:18:45 +000083 return true;
84}
85
Douglas Gregorabc563f2010-07-19 21:46:24 +000086void Diagnostic::Reset() {
Douglas Gregorabc563f2010-07-19 21:46:24 +000087 ErrorOccurred = false;
88 FatalErrorOccurred = false;
Douglas Gregorabc563f2010-07-19 21:46:24 +000089
90 NumWarnings = 0;
91 NumErrors = 0;
92 NumErrorsSuppressed = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +000093 CurDiagID = ~0U;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +000094 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
95 // using a Diagnostic associated to a translation unit that follow
96 // diagnostics from a Diagnostic associated to anoter t.u. will not be
97 // displayed.
98 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregorabc563f2010-07-19 21:46:24 +000099 DelayedDiagID = 0;
Argyrios Kyrtzidisdc0a2da2011-03-26 18:58:17 +0000100
101 // Clear state related to #pragma diagnostic.
102 DiagStates.clear();
103 DiagStatePoints.clear();
104 DiagStateOnPushStack.clear();
105
106 // Create a DiagState and DiagStatePoint representing diagnostic changes
107 // through command-line.
108 DiagStates.push_back(DiagState());
109 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000110}
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000112void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
113 llvm::StringRef Arg2) {
114 if (DelayedDiagID)
115 return;
116
117 DelayedDiagID = DiagID;
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000118 DelayedDiagArg1 = Arg1.str();
119 DelayedDiagArg2 = Arg2.str();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000120}
121
122void Diagnostic::ReportDelayed() {
123 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
124 DelayedDiagID = 0;
125 DelayedDiagArg1.clear();
126 DelayedDiagArg2.clear();
127}
128
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000129Diagnostic::DiagStatePointsTy::iterator
130Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
131 assert(!DiagStatePoints.empty());
132 assert(DiagStatePoints.front().Loc.isInvalid() &&
133 "Should have created a DiagStatePoint for command-line");
134
135 FullSourceLoc Loc(L, *SourceMgr);
136 if (Loc.isInvalid())
137 return DiagStatePoints.end() - 1;
138
139 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
140 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
141 if (LastStateChangePos.isValid() &&
142 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
143 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
144 DiagStatePoint(0, Loc));
145 --Pos;
146 return Pos;
147}
148
149/// \brief This allows the client to specify that certain
150/// warnings are ignored. Notes can never be mapped, errors can only be
151/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
152///
153/// \param The source location that this change of diagnostic state should
154/// take affect. It can be null if we are setting the latest state.
155void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
156 SourceLocation L) {
157 assert(Diag < diag::DIAG_UPPER_LIMIT &&
158 "Can only map builtin diagnostics");
159 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
160 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
161 "Cannot map errors into warnings!");
162 assert(!DiagStatePoints.empty());
163
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000164 bool isPragma = L.isValid();
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000165 FullSourceLoc Loc(L, *SourceMgr);
166 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
167
168 // Common case; setting all the diagnostics of a group in one place.
169 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000170 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000171 return;
172 }
173
174 // Another common case; modifying diagnostic state in a source location
175 // after the previous one.
176 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
177 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000178 // A diagnostic pragma occurred, create a new DiagState initialized with
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000179 // the current one and a new DiagStatePoint to record at which location
180 // the new state became active.
181 DiagStates.push_back(*GetCurDiagState());
182 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000183 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000184 return;
185 }
186
187 // We allow setting the diagnostic state in random source order for
188 // completeness but it should not be actually happening in normal practice.
189
190 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
191 assert(Pos != DiagStatePoints.end());
192
193 // Update all diagnostic states that are active after the given location.
194 for (DiagStatePointsTy::iterator
195 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000196 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000197 }
198
199 // If the location corresponds to an existing point, just update its state.
200 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000201 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000202 return;
203 }
204
205 // Create a new state/point and fit it into the vector of DiagStatePoints
206 // so that the vector is always ordered according to location.
207 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
208 DiagStates.push_back(*Pos->State);
209 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +0000210 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000211 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
212 FullSourceLoc(Loc, *SourceMgr)));
213}
214
Argyrios Kyrtzidise59abb52011-05-05 07:54:59 +0000215void Diagnostic::Report(const StoredDiagnostic &storedDiag) {
216 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
217
218 CurDiagLoc = storedDiag.getLocation();
219 CurDiagID = storedDiag.getID();
220 NumDiagArgs = 0;
221
222 NumDiagRanges = storedDiag.range_size();
223 assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
224 "Too many arguments to diagnostic!");
225 unsigned i = 0;
226 for (StoredDiagnostic::range_iterator
227 RI = storedDiag.range_begin(),
228 RE = storedDiag.range_end(); RI != RE; ++RI)
229 DiagRanges[i++] = *RI;
230
231 NumFixItHints = storedDiag.fixit_size();
232 assert(NumFixItHints < Diagnostic::MaxFixItHints && "Too many fix-it hints!");
233 i = 0;
234 for (StoredDiagnostic::fixit_iterator
235 FI = storedDiag.fixit_begin(),
236 FE = storedDiag.fixit_end(); FI != FE; ++FI)
237 FixItHints[i++] = *FI;
238
239 assert(Client && "DiagnosticClient not set!");
240 Level DiagLevel = storedDiag.getLevel();
241 DiagnosticInfo Info(this, storedDiag.getMessage());
242 Client->HandleDiagnostic(DiagLevel, Info);
243 if (Client->IncludeInDiagnosticCounts()) {
244 if (DiagLevel == Diagnostic::Warning)
245 ++NumWarnings;
246 }
247
248 CurDiagID = ~0U;
249}
250
Douglas Gregorb5350412010-10-13 17:22:14 +0000251void DiagnosticBuilder::FlushCounts() {
252 DiagObj->NumDiagArgs = NumArgs;
253 DiagObj->NumDiagRanges = NumRanges;
254 DiagObj->NumFixItHints = NumFixItHints;
255}
256
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000257bool DiagnosticBuilder::Emit() {
258 // If DiagObj is null, then its soul was stolen by the copy ctor
259 // or the user called Emit().
260 if (DiagObj == 0) return false;
261
262 // When emitting diagnostics, we set the final argument count into
263 // the Diagnostic object.
Douglas Gregorb5350412010-10-13 17:22:14 +0000264 FlushCounts();
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000265
266 // Process the diagnostic, sending the accumulated information to the
267 // DiagnosticClient.
268 bool Emitted = DiagObj->ProcessDiag();
269
270 // Clear out the current diagnostic object.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000271 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000272 DiagObj->Clear();
273
274 // If there was a delayed diagnostic, emit it now.
Douglas Gregor9e2dac92010-03-22 15:47:45 +0000275 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000276 DiagObj->ReportDelayed();
277
278 // This diagnostic is dead.
279 DiagObj = 0;
280
281 return Emitted;
282}
283
Nico Weber7bfaaae2008-08-10 19:59:06 +0000284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285DiagnosticClient::~DiagnosticClient() {}
Nico Weber7bfaaae2008-08-10 19:59:06 +0000286
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000287void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
288 const DiagnosticInfo &Info) {
289 if (!IncludeInDiagnosticCounts())
290 return;
291
292 if (DiagLevel == Diagnostic::Warning)
293 ++NumWarnings;
294 else if (DiagLevel >= Diagnostic::Error)
295 ++NumErrors;
296}
Chris Lattnerf4c83962008-11-19 06:51:40 +0000297
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000298/// ModifierIs - Return true if the specified modifier matches specified string.
299template <std::size_t StrLen>
300static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
301 const char (&Str)[StrLen]) {
302 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
303}
304
John McCall909c1822010-01-14 20:11:39 +0000305/// ScanForward - Scans forward, looking for the given character, skipping
306/// nested clauses and escaped characters.
307static const char *ScanFormat(const char *I, const char *E, char Target) {
308 unsigned Depth = 0;
309
310 for ( ; I != E; ++I) {
311 if (Depth == 0 && *I == Target) return I;
312 if (Depth != 0 && *I == '}') Depth--;
313
314 if (*I == '%') {
315 I++;
316 if (I == E) break;
317
318 // Escaped characters get implicitly skipped here.
319
320 // Format specifier.
321 if (!isdigit(*I) && !ispunct(*I)) {
322 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
323 if (I == E) break;
324 if (*I == '{')
325 Depth++;
326 }
327 }
328 }
329 return E;
330}
331
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000332/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
333/// like this: %select{foo|bar|baz}2. This means that the integer argument
334/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
335/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
336/// This is very useful for certain classes of variant diagnostics.
John McCall9f286142010-01-13 23:58:20 +0000337static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000338 const char *Argument, unsigned ArgumentLen,
339 llvm::SmallVectorImpl<char> &OutStr) {
340 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000342 // Skip over 'ValNo' |'s.
343 while (ValNo) {
John McCall909c1822010-01-14 20:11:39 +0000344 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000345 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
346 " larger than the number of options in the diagnostic string!");
347 Argument = NextVal+1; // Skip this string.
348 --ValNo;
349 }
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000351 // Get the end of the value. This is either the } or the |.
John McCall909c1822010-01-14 20:11:39 +0000352 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCall9f286142010-01-13 23:58:20 +0000353
354 // Recursively format the result of the select clause into the output string.
355 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000356}
357
358/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
359/// letter 's' to the string if the value is not 1. This is used in cases like
360/// this: "you idiot, you have %4 parameter%s4!".
361static void HandleIntegerSModifier(unsigned ValNo,
362 llvm::SmallVectorImpl<char> &OutStr) {
363 if (ValNo != 1)
364 OutStr.push_back('s');
365}
366
John McCall3be16b72010-01-14 00:50:32 +0000367/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
368/// prints the ordinal form of the given integer, with 1 corresponding
369/// to the first ordinal. Currently this is hard-coded to use the
370/// English form.
371static void HandleOrdinalModifier(unsigned ValNo,
372 llvm::SmallVectorImpl<char> &OutStr) {
373 assert(ValNo != 0 && "ValNo must be strictly positive!");
374
375 llvm::raw_svector_ostream Out(OutStr);
376
377 // We could use text forms for the first N ordinals, but the numeric
378 // forms are actually nicer in diagnostics because they stand out.
379 Out << ValNo;
380
381 // It is critically important that we do this perfectly for
382 // user-written sequences with over 100 elements.
383 switch (ValNo % 100) {
384 case 11:
385 case 12:
386 case 13:
387 Out << "th"; return;
388 default:
389 switch (ValNo % 10) {
390 case 1: Out << "st"; return;
391 case 2: Out << "nd"; return;
392 case 3: Out << "rd"; return;
393 default: Out << "th"; return;
394 }
395 }
396}
397
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000398
Sebastian Redle4c452c2008-11-22 13:44:36 +0000399/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000400static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000401 // Programming 101: Parse a decimal number :-)
402 unsigned Val = 0;
403 while (Start != End && *Start >= '0' && *Start <= '9') {
404 Val *= 10;
405 Val += *Start - '0';
406 ++Start;
407 }
408 return Val;
409}
410
411/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000412static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000413 if (*Start != '[') {
414 unsigned Ref = PluralNumber(Start, End);
415 return Ref == Val;
416 }
417
418 ++Start;
419 unsigned Low = PluralNumber(Start, End);
420 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
421 ++Start;
422 unsigned High = PluralNumber(Start, End);
423 assert(*Start == ']' && "Bad plural expression syntax: expected )");
424 ++Start;
425 return Low <= Val && Val <= High;
426}
427
428/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattnerd2aa7c92009-04-15 17:13:42 +0000429static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000430 // Empty condition?
431 if (*Start == ':')
432 return true;
433
434 while (1) {
435 char C = *Start;
436 if (C == '%') {
437 // Modulo expression
438 ++Start;
439 unsigned Arg = PluralNumber(Start, End);
440 assert(*Start == '=' && "Bad plural expression syntax: expected =");
441 ++Start;
442 unsigned ValMod = ValNo % Arg;
443 if (TestPluralRange(ValMod, Start, End))
444 return true;
445 } else {
Sebastian Redle2065322008-11-27 07:28:14 +0000446 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redle4c452c2008-11-22 13:44:36 +0000447 "Bad plural expression syntax: unexpected character");
448 // Range expression
449 if (TestPluralRange(ValNo, Start, End))
450 return true;
451 }
452
453 // Scan for next or-expr part.
454 Start = std::find(Start, End, ',');
Mike Stump1eb44332009-09-09 15:08:12 +0000455 if (Start == End)
Sebastian Redle4c452c2008-11-22 13:44:36 +0000456 break;
457 ++Start;
458 }
459 return false;
460}
461
462/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
463/// for complex plural forms, or in languages where all plurals are complex.
464/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
465/// conditions that are tested in order, the form corresponding to the first
466/// that applies being emitted. The empty condition is always true, making the
467/// last form a default case.
468/// Conditions are simple boolean expressions, where n is the number argument.
469/// Here are the rules.
470/// condition := expression | empty
471/// empty := -> always true
472/// expression := numeric [',' expression] -> logical or
473/// numeric := range -> true if n in range
474/// | '%' number '=' range -> true if n % number in range
475/// range := number
476/// | '[' number ',' number ']' -> ranges are inclusive both ends
477///
478/// Here are some examples from the GNU gettext manual written in this form:
479/// English:
480/// {1:form0|:form1}
481/// Latvian:
482/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
483/// Gaeilge:
484/// {1:form0|2:form1|:form2}
485/// Romanian:
486/// {1:form0|0,%100=[1,19]:form1|:form2}
487/// Lithuanian:
488/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
489/// Russian (requires repeated form):
490/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
491/// Slovak
492/// {1:form0|[2,4]:form1|:form2}
493/// Polish (requires repeated form):
494/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCalle53a44b2010-10-14 01:55:31 +0000495static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redle4c452c2008-11-22 13:44:36 +0000496 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb54b2762009-04-16 05:04:32 +0000497 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redle4c452c2008-11-22 13:44:36 +0000498 const char *ArgumentEnd = Argument + ArgumentLen;
499 while (1) {
500 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
501 const char *ExprEnd = Argument;
502 while (*ExprEnd != ':') {
503 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
504 ++ExprEnd;
505 }
506 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
507 Argument = ExprEnd + 1;
John McCall909c1822010-01-14 20:11:39 +0000508 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle53a44b2010-10-14 01:55:31 +0000509
510 // Recursively format the result of the plural clause into the
511 // output string.
512 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000513 return;
514 }
John McCall909c1822010-01-14 20:11:39 +0000515 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redle4c452c2008-11-22 13:44:36 +0000516 }
517}
518
519
Chris Lattnerf4c83962008-11-19 06:51:40 +0000520/// FormatDiagnostic - Format this diagnostic into a string, substituting the
521/// formal arguments into the %0 slots. The result is appended onto the Str
522/// array.
523void DiagnosticInfo::
524FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidise59abb52011-05-05 07:54:59 +0000525 if (!StoredDiagMessage.empty()) {
526 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
527 return;
528 }
529
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000530 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
Chris Lattnerf4c83962008-11-19 06:51:40 +0000531 const char *DiagEnd = DiagStr+strlen(DiagStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000532
John McCall9f286142010-01-13 23:58:20 +0000533 FormatDiagnostic(DiagStr, DiagEnd, OutStr);
534}
535
536void DiagnosticInfo::
537FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
538 llvm::SmallVectorImpl<char> &OutStr) const {
539
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000540 /// FormattedArgs - Keep track of all of the arguments formatted by
541 /// ConvertArgToString and pass them into subsequent calls to
542 /// ConvertArgToString, allowing the implementation to avoid redundancies in
543 /// obvious cases.
544 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
545
Chris Lattnerf4c83962008-11-19 06:51:40 +0000546 while (DiagStr != DiagEnd) {
547 if (DiagStr[0] != '%') {
548 // Append non-%0 substrings to Str if we have one.
549 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
550 OutStr.append(DiagStr, StrEnd);
551 DiagStr = StrEnd;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000552 continue;
John McCall909c1822010-01-14 20:11:39 +0000553 } else if (ispunct(DiagStr[1])) {
554 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000555 DiagStr += 2;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000556 continue;
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000559 // Skip the %.
560 ++DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000562 // This must be a placeholder for a diagnostic argument. The format for a
563 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
564 // The digit is a number from 0-9 indicating which argument this comes from.
565 // The modifier is a string of digits from the set [-a-z]+, arguments is a
566 // brace enclosed string.
567 const char *Modifier = 0, *Argument = 0;
568 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000570 // Check to see if we have a modifier. If so eat it.
571 if (!isdigit(DiagStr[0])) {
572 Modifier = DiagStr;
573 while (DiagStr[0] == '-' ||
574 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
575 ++DiagStr;
576 ModifierLen = DiagStr-Modifier;
Chris Lattnerf4c83962008-11-19 06:51:40 +0000577
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000578 // If we have an argument, get it next.
579 if (DiagStr[0] == '{') {
580 ++DiagStr; // Skip {.
581 Argument = DiagStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
John McCall909c1822010-01-14 20:11:39 +0000583 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
584 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000585 ArgumentLen = DiagStr-Argument;
586 ++DiagStr; // Skip }.
Chris Lattnerf4c83962008-11-19 06:51:40 +0000587 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000588 }
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000590 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner22caddc2008-11-23 09:13:29 +0000591 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000592
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000593 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
594
595 switch (Kind) {
Chris Lattner08631c52008-11-23 21:45:46 +0000596 // ---- STRINGS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000597 case Diagnostic::ak_std_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000598 const std::string &S = getArgStdStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000599 assert(ModifierLen == 0 && "No modifiers for strings yet");
600 OutStr.append(S.begin(), S.end());
601 break;
602 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000603 case Diagnostic::ak_c_string: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000604 const char *S = getArgCStr(ArgNo);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000605 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000606
607 // Don't crash if get passed a null pointer by accident.
608 if (!S)
609 S = "(null)";
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000611 OutStr.append(S, S + strlen(S));
612 break;
613 }
Chris Lattner08631c52008-11-23 21:45:46 +0000614 // ---- INTEGERS ----
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000615 case Diagnostic::ak_sint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000616 int Val = getArgSInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000618 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle53a44b2010-10-14 01:55:31 +0000619 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
620 OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000621 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
622 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000623 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCalle53a44b2010-10-14 01:55:31 +0000624 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
625 OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000626 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
627 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000628 } else {
629 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000630 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000631 }
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000632 break;
633 }
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000634 case Diagnostic::ak_uint: {
Chris Lattner22caddc2008-11-23 09:13:29 +0000635 unsigned Val = getArgUInt(ArgNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000637 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall9f286142010-01-13 23:58:20 +0000638 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000639 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
640 HandleIntegerSModifier(Val, OutStr);
Sebastian Redle4c452c2008-11-22 13:44:36 +0000641 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCalle53a44b2010-10-14 01:55:31 +0000642 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
643 OutStr);
John McCall3be16b72010-01-14 00:50:32 +0000644 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
645 HandleOrdinalModifier(Val, OutStr);
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000646 } else {
647 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbar23e47c62009-10-17 18:12:14 +0000648 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner30bc9652008-11-19 07:22:31 +0000649 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000650 break;
Chris Lattneraf7ae4e2008-11-21 07:50:02 +0000651 }
Chris Lattner08631c52008-11-23 21:45:46 +0000652 // ---- NAMES and TYPES ----
653 case Diagnostic::ak_identifierinfo: {
Chris Lattner08631c52008-11-23 21:45:46 +0000654 const IdentifierInfo *II = getArgIdentifier(ArgNo);
655 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbare46e3542009-04-20 06:13:16 +0000656
657 // Don't crash if get passed a null pointer by accident.
658 if (!II) {
659 const char *S = "(null)";
660 OutStr.append(S, S + strlen(S));
661 continue;
662 }
663
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000664 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattner08631c52008-11-23 21:45:46 +0000665 break;
666 }
Chris Lattner22caddc2008-11-23 09:13:29 +0000667 case Diagnostic::ak_qualtype:
Chris Lattner011bb4e2008-11-23 20:28:15 +0000668 case Diagnostic::ak_declarationname:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000669 case Diagnostic::ak_nameddecl:
Douglas Gregordacd4342009-08-26 00:04:55 +0000670 case Diagnostic::ak_nestednamespec:
Douglas Gregor3f093272009-10-13 21:16:44 +0000671 case Diagnostic::ak_declcontext:
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000672 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner3fdf4b02008-11-23 09:21:17 +0000673 Modifier, ModifierLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000674 Argument, ArgumentLen,
675 FormattedArgs.data(), FormattedArgs.size(),
676 OutStr);
Chris Lattner22caddc2008-11-23 09:13:29 +0000677 break;
Nico Weber7bfaaae2008-08-10 19:59:06 +0000678 }
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000679
680 // Remember this argument info for subsequent formatting operations. Turn
681 // std::strings into a null terminated string to make it be the same case as
682 // all the other ones.
683 if (Kind != Diagnostic::ak_std_string)
684 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
685 else
686 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
687 (intptr_t)getArgStdStr(ArgNo).c_str()));
688
Nico Weber7bfaaae2008-08-10 19:59:06 +0000689 }
Nico Weber7bfaaae2008-08-10 19:59:06 +0000690}
Ted Kremenekcabe6682009-01-23 20:28:53 +0000691
Douglas Gregora88084b2010-02-18 18:08:43 +0000692StoredDiagnostic::StoredDiagnostic() { }
693
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000694StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregora88084b2010-02-18 18:08:43 +0000695 llvm::StringRef Message)
Benjamin Kramera6a32e22010-11-19 17:36:51 +0000696 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregora88084b2010-02-18 18:08:43 +0000697
698StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
699 const DiagnosticInfo &Info)
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000700 : ID(Info.getID()), Level(Level)
701{
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000702 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
703 "Valid source location without setting a source manager for diagnostic");
704 if (Info.getLocation().isValid())
705 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregora88084b2010-02-18 18:08:43 +0000706 llvm::SmallString<64> Message;
707 Info.FormatDiagnostic(Message);
708 this->Message.assign(Message.begin(), Message.end());
709
710 Ranges.reserve(Info.getNumRanges());
711 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
712 Ranges.push_back(Info.getRange(I));
713
Douglas Gregor849b2432010-03-31 17:46:05 +0000714 FixIts.reserve(Info.getNumFixItHints());
715 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
716 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregora88084b2010-02-18 18:08:43 +0000717}
718
719StoredDiagnostic::~StoredDiagnostic() { }
720
Ted Kremenekcabe6682009-01-23 20:28:53 +0000721/// IncludeInDiagnosticCounts - This method (whose default implementation
722/// returns true) indicates whether the diagnostics handled by this
723/// DiagnosticClient should be included in the number of diagnostics
724/// reported by Diagnostic.
725bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000726
727PartialDiagnostic::StorageAllocator::StorageAllocator() {
728 for (unsigned I = 0; I != NumCached; ++I)
729 FreeList[I] = Cached + I;
730 NumFreeListEntries = NumCached;
731}
732
733PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Ted Kremenek03201fb2011-03-21 18:40:07 +0000734 // Don't assert if we are in a CrashRecovery context, as this
735 // invariant may be invalidated during a crash.
Ted Kremenekcd1eecf2011-03-21 18:40:10 +0000736 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000737}