blob: e0ef53d00de630eb41e95950967297f19536842a [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek39a76652010-04-12 19:54:17 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattnerb91fd172008-11-19 07:32:16 +000015#include "clang/Basic/IdentifierTable.h"
Ted Kremenek39a76652010-04-12 19:54:17 +000016#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner23be0672008-11-19 06:51:40 +000017#include "llvm/ADT/SmallVector.h"
Daniel Dunbare3633792009-10-17 18:12:14 +000018#include "llvm/Support/raw_ostream.h"
Ted Kremenek84de4a12011-03-21 18:40:07 +000019#include "llvm/Support/CrashRecoveryContext.h"
20
Chris Lattner22eb9722006-06-18 05:43:12 +000021using namespace clang;
22
Chris Lattner63ecc502008-11-23 09:21:17 +000023static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
24 const char *Modifier, unsigned ML,
25 const char *Argument, unsigned ArgLen,
Chris Lattnerc243f292009-10-20 05:25:22 +000026 const Diagnostic::ArgumentValue *PrevArgs,
27 unsigned NumPrevArgs,
Chris Lattnercf868c42009-02-19 23:53:20 +000028 llvm::SmallVectorImpl<char> &Output,
29 void *Cookie) {
Chris Lattner63ecc502008-11-23 09:21:17 +000030 const char *Str = "<can't format argument>";
Chris Lattner6a2ed6f2008-11-23 09:13:29 +000031 Output.append(Str, Str+strlen(Str));
32}
33
34
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000035Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
36 DiagnosticClient *client, bool ShouldOwnClient)
37 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
38 SourceMgr(0) {
Chris Lattner63ecc502008-11-23 09:21:17 +000039 ArgToStringFn = DummyArgToStringFn;
Chris Lattnercf868c42009-02-19 23:53:20 +000040 ArgToStringCookie = 0;
Mike Stump11289f42009-09-09 15:08:12 +000041
Douglas Gregor0e119552010-07-31 00:40:00 +000042 AllExtensionsSilenced = 0;
43 IgnoreAllWarnings = false;
44 WarningsAsErrors = false;
45 ErrorsAsFatal = false;
46 SuppressSystemWarnings = false;
47 SuppressAllDiagnostics = false;
48 ShowOverloads = Ovl_All;
49 ExtBehavior = Ext_Ignore;
50
51 ErrorLimit = 0;
52 TemplateBacktraceLimit = 0;
Douglas Gregor0e119552010-07-31 00:40:00 +000053
Douglas Gregoraa21cc42010-07-19 21:46:24 +000054 Reset();
Chris Lattnerae411572006-07-05 00:55:08 +000055}
56
Chris Lattnere6535cf2007-12-02 01:09:57 +000057Diagnostic::~Diagnostic() {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000058 if (OwnsDiagClient)
59 delete Client;
Chris Lattnere6535cf2007-12-02 01:09:57 +000060}
61
Douglas Gregor7a964ad2011-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 Lattnerfb42a182009-07-12 21:18:45 +000069
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000070void Diagnostic::pushMappings(SourceLocation Loc) {
71 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000072}
73
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000074bool Diagnostic::popMappings(SourceLocation Loc) {
75 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +000076 return false;
77
Argyrios Kyrtzidis1cb0de12010-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 Lattnerfb42a182009-07-12 21:18:45 +000083 return true;
84}
85
Douglas Gregoraa21cc42010-07-19 21:46:24 +000086void Diagnostic::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +000087 ErrorOccurred = false;
88 FatalErrorOccurred = false;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +000089 UnrecoverableErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000090
91 NumWarnings = 0;
92 NumErrors = 0;
93 NumErrorsSuppressed = 0;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +000094
Douglas Gregoraa21cc42010-07-19 21:46:24 +000095 CurDiagID = ~0U;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +000096 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
97 // using a Diagnostic associated to a translation unit that follow
98 // diagnostics from a Diagnostic associated to anoter t.u. will not be
99 // displayed.
100 LastDiagLevel = (DiagnosticIDs::Level)-1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000101 DelayedDiagID = 0;
Argyrios Kyrtzidisbbbeea12011-03-26 18:58:17 +0000102
103 // Clear state related to #pragma diagnostic.
104 DiagStates.clear();
105 DiagStatePoints.clear();
106 DiagStateOnPushStack.clear();
107
108 // Create a DiagState and DiagStatePoint representing diagnostic changes
109 // through command-line.
110 DiagStates.push_back(DiagState());
111 PushDiagStatePoint(&DiagStates.back(), SourceLocation());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000112}
Chris Lattner22eb9722006-06-18 05:43:12 +0000113
Douglas Gregor85795312010-03-22 15:10:57 +0000114void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
115 llvm::StringRef Arg2) {
116 if (DelayedDiagID)
117 return;
118
119 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000120 DelayedDiagArg1 = Arg1.str();
121 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000122}
123
124void Diagnostic::ReportDelayed() {
125 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
126 DelayedDiagID = 0;
127 DelayedDiagArg1.clear();
128 DelayedDiagArg2.clear();
129}
130
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000131Diagnostic::DiagStatePointsTy::iterator
132Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
133 assert(!DiagStatePoints.empty());
134 assert(DiagStatePoints.front().Loc.isInvalid() &&
135 "Should have created a DiagStatePoint for command-line");
136
137 FullSourceLoc Loc(L, *SourceMgr);
138 if (Loc.isInvalid())
139 return DiagStatePoints.end() - 1;
140
141 DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
142 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
143 if (LastStateChangePos.isValid() &&
144 Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
145 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
146 DiagStatePoint(0, Loc));
147 --Pos;
148 return Pos;
149}
150
151/// \brief This allows the client to specify that certain
152/// warnings are ignored. Notes can never be mapped, errors can only be
153/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
154///
155/// \param The source location that this change of diagnostic state should
156/// take affect. It can be null if we are setting the latest state.
157void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
158 SourceLocation L) {
159 assert(Diag < diag::DIAG_UPPER_LIMIT &&
160 "Can only map builtin diagnostics");
161 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
162 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
163 "Cannot map errors into warnings!");
164 assert(!DiagStatePoints.empty());
165
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000166 bool isPragma = L.isValid();
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000167 FullSourceLoc Loc(L, *SourceMgr);
168 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
169
170 // Common case; setting all the diagnostics of a group in one place.
171 if (Loc.isInvalid() || Loc == LastStateChangePos) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000172 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000173 return;
174 }
175
176 // Another common case; modifying diagnostic state in a source location
177 // after the previous one.
178 if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
179 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
Chris Lattner57540c52011-04-15 05:22:18 +0000180 // A diagnostic pragma occurred, create a new DiagState initialized with
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000181 // the current one and a new DiagStatePoint to record at which location
182 // the new state became active.
183 DiagStates.push_back(*GetCurDiagState());
184 PushDiagStatePoint(&DiagStates.back(), Loc);
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000185 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000186 return;
187 }
188
189 // We allow setting the diagnostic state in random source order for
190 // completeness but it should not be actually happening in normal practice.
191
192 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
193 assert(Pos != DiagStatePoints.end());
194
195 // Update all diagnostic states that are active after the given location.
196 for (DiagStatePointsTy::iterator
197 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000198 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000199 }
200
201 // If the location corresponds to an existing point, just update its state.
202 if (Pos->Loc == Loc) {
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000203 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000204 return;
205 }
206
207 // Create a new state/point and fit it into the vector of DiagStatePoints
208 // so that the vector is always ordered according to location.
209 Pos->Loc.isBeforeInTranslationUnitThan(Loc);
210 DiagStates.push_back(*Pos->State);
211 DiagState *NewState = &DiagStates.back();
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +0000212 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000213 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
214 FullSourceLoc(Loc, *SourceMgr)));
215}
216
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000217void Diagnostic::Report(const StoredDiagnostic &storedDiag) {
218 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
219
220 CurDiagLoc = storedDiag.getLocation();
221 CurDiagID = storedDiag.getID();
222 NumDiagArgs = 0;
223
224 NumDiagRanges = storedDiag.range_size();
225 assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
226 "Too many arguments to diagnostic!");
227 unsigned i = 0;
228 for (StoredDiagnostic::range_iterator
229 RI = storedDiag.range_begin(),
230 RE = storedDiag.range_end(); RI != RE; ++RI)
231 DiagRanges[i++] = *RI;
232
233 NumFixItHints = storedDiag.fixit_size();
234 assert(NumFixItHints < Diagnostic::MaxFixItHints && "Too many fix-it hints!");
235 i = 0;
236 for (StoredDiagnostic::fixit_iterator
237 FI = storedDiag.fixit_begin(),
238 FE = storedDiag.fixit_end(); FI != FE; ++FI)
239 FixItHints[i++] = *FI;
240
241 assert(Client && "DiagnosticClient not set!");
242 Level DiagLevel = storedDiag.getLevel();
243 DiagnosticInfo Info(this, storedDiag.getMessage());
244 Client->HandleDiagnostic(DiagLevel, Info);
245 if (Client->IncludeInDiagnosticCounts()) {
246 if (DiagLevel == Diagnostic::Warning)
247 ++NumWarnings;
248 }
249
250 CurDiagID = ~0U;
251}
252
Douglas Gregorb3921592010-10-13 17:22:14 +0000253void DiagnosticBuilder::FlushCounts() {
254 DiagObj->NumDiagArgs = NumArgs;
255 DiagObj->NumDiagRanges = NumRanges;
256 DiagObj->NumFixItHints = NumFixItHints;
257}
258
Douglas Gregor85795312010-03-22 15:10:57 +0000259bool DiagnosticBuilder::Emit() {
260 // If DiagObj is null, then its soul was stolen by the copy ctor
261 // or the user called Emit().
262 if (DiagObj == 0) return false;
263
264 // When emitting diagnostics, we set the final argument count into
265 // the Diagnostic object.
Douglas Gregorb3921592010-10-13 17:22:14 +0000266 FlushCounts();
Douglas Gregor85795312010-03-22 15:10:57 +0000267
268 // Process the diagnostic, sending the accumulated information to the
269 // DiagnosticClient.
270 bool Emitted = DiagObj->ProcessDiag();
271
272 // Clear out the current diagnostic object.
Douglas Gregor96380982010-03-22 15:47:45 +0000273 unsigned DiagID = DiagObj->CurDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000274 DiagObj->Clear();
275
276 // If there was a delayed diagnostic, emit it now.
Douglas Gregor96380982010-03-22 15:47:45 +0000277 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
Douglas Gregor85795312010-03-22 15:10:57 +0000278 DiagObj->ReportDelayed();
279
280 // This diagnostic is dead.
281 DiagObj = 0;
282
283 return Emitted;
284}
285
Nico Weber4c311642008-08-10 19:59:06 +0000286
Chris Lattner22eb9722006-06-18 05:43:12 +0000287DiagnosticClient::~DiagnosticClient() {}
Nico Weber4c311642008-08-10 19:59:06 +0000288
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000289void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
290 const DiagnosticInfo &Info) {
291 if (!IncludeInDiagnosticCounts())
292 return;
293
294 if (DiagLevel == Diagnostic::Warning)
295 ++NumWarnings;
296 else if (DiagLevel >= Diagnostic::Error)
297 ++NumErrors;
298}
Chris Lattner23be0672008-11-19 06:51:40 +0000299
Chris Lattner2b786902008-11-21 07:50:02 +0000300/// ModifierIs - Return true if the specified modifier matches specified string.
301template <std::size_t StrLen>
302static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
303 const char (&Str)[StrLen]) {
304 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
305}
306
John McCall8cb7a8a32010-01-14 20:11:39 +0000307/// ScanForward - Scans forward, looking for the given character, skipping
308/// nested clauses and escaped characters.
309static const char *ScanFormat(const char *I, const char *E, char Target) {
310 unsigned Depth = 0;
311
312 for ( ; I != E; ++I) {
313 if (Depth == 0 && *I == Target) return I;
314 if (Depth != 0 && *I == '}') Depth--;
315
316 if (*I == '%') {
317 I++;
318 if (I == E) break;
319
320 // Escaped characters get implicitly skipped here.
321
322 // Format specifier.
323 if (!isdigit(*I) && !ispunct(*I)) {
324 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
325 if (I == E) break;
326 if (*I == '{')
327 Depth++;
328 }
329 }
330 }
331 return E;
332}
333
Chris Lattner2b786902008-11-21 07:50:02 +0000334/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
335/// like this: %select{foo|bar|baz}2. This means that the integer argument
336/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
337/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
338/// This is very useful for certain classes of variant diagnostics.
John McCalle4d54322010-01-13 23:58:20 +0000339static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000340 const char *Argument, unsigned ArgumentLen,
341 llvm::SmallVectorImpl<char> &OutStr) {
342 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner2b786902008-11-21 07:50:02 +0000344 // Skip over 'ValNo' |'s.
345 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000346 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000347 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
348 " larger than the number of options in the diagnostic string!");
349 Argument = NextVal+1; // Skip this string.
350 --ValNo;
351 }
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattner2b786902008-11-21 07:50:02 +0000353 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000354 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000355
356 // Recursively format the result of the select clause into the output string.
357 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000358}
359
360/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
361/// letter 's' to the string if the value is not 1. This is used in cases like
362/// this: "you idiot, you have %4 parameter%s4!".
363static void HandleIntegerSModifier(unsigned ValNo,
364 llvm::SmallVectorImpl<char> &OutStr) {
365 if (ValNo != 1)
366 OutStr.push_back('s');
367}
368
John McCall9015cde2010-01-14 00:50:32 +0000369/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
370/// prints the ordinal form of the given integer, with 1 corresponding
371/// to the first ordinal. Currently this is hard-coded to use the
372/// English form.
373static void HandleOrdinalModifier(unsigned ValNo,
374 llvm::SmallVectorImpl<char> &OutStr) {
375 assert(ValNo != 0 && "ValNo must be strictly positive!");
376
377 llvm::raw_svector_ostream Out(OutStr);
378
379 // We could use text forms for the first N ordinals, but the numeric
380 // forms are actually nicer in diagnostics because they stand out.
381 Out << ValNo;
382
383 // It is critically important that we do this perfectly for
384 // user-written sequences with over 100 elements.
385 switch (ValNo % 100) {
386 case 11:
387 case 12:
388 case 13:
389 Out << "th"; return;
390 default:
391 switch (ValNo % 10) {
392 case 1: Out << "st"; return;
393 case 2: Out << "nd"; return;
394 case 3: Out << "rd"; return;
395 default: Out << "th"; return;
396 }
397 }
398}
399
Chris Lattner2b786902008-11-21 07:50:02 +0000400
Sebastian Redl15b02d22008-11-22 13:44:36 +0000401/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000402static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000403 // Programming 101: Parse a decimal number :-)
404 unsigned Val = 0;
405 while (Start != End && *Start >= '0' && *Start <= '9') {
406 Val *= 10;
407 Val += *Start - '0';
408 ++Start;
409 }
410 return Val;
411}
412
413/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000414static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000415 if (*Start != '[') {
416 unsigned Ref = PluralNumber(Start, End);
417 return Ref == Val;
418 }
419
420 ++Start;
421 unsigned Low = PluralNumber(Start, End);
422 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
423 ++Start;
424 unsigned High = PluralNumber(Start, End);
425 assert(*Start == ']' && "Bad plural expression syntax: expected )");
426 ++Start;
427 return Low <= Val && Val <= High;
428}
429
430/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000431static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000432 // Empty condition?
433 if (*Start == ':')
434 return true;
435
436 while (1) {
437 char C = *Start;
438 if (C == '%') {
439 // Modulo expression
440 ++Start;
441 unsigned Arg = PluralNumber(Start, End);
442 assert(*Start == '=' && "Bad plural expression syntax: expected =");
443 ++Start;
444 unsigned ValMod = ValNo % Arg;
445 if (TestPluralRange(ValMod, Start, End))
446 return true;
447 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000448 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000449 "Bad plural expression syntax: unexpected character");
450 // Range expression
451 if (TestPluralRange(ValNo, Start, End))
452 return true;
453 }
454
455 // Scan for next or-expr part.
456 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000457 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000458 break;
459 ++Start;
460 }
461 return false;
462}
463
464/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
465/// for complex plural forms, or in languages where all plurals are complex.
466/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
467/// conditions that are tested in order, the form corresponding to the first
468/// that applies being emitted. The empty condition is always true, making the
469/// last form a default case.
470/// Conditions are simple boolean expressions, where n is the number argument.
471/// Here are the rules.
472/// condition := expression | empty
473/// empty := -> always true
474/// expression := numeric [',' expression] -> logical or
475/// numeric := range -> true if n in range
476/// | '%' number '=' range -> true if n % number in range
477/// range := number
478/// | '[' number ',' number ']' -> ranges are inclusive both ends
479///
480/// Here are some examples from the GNU gettext manual written in this form:
481/// English:
482/// {1:form0|:form1}
483/// Latvian:
484/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
485/// Gaeilge:
486/// {1:form0|2:form1|:form2}
487/// Romanian:
488/// {1:form0|0,%100=[1,19]:form1|:form2}
489/// Lithuanian:
490/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
491/// Russian (requires repeated form):
492/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
493/// Slovak
494/// {1:form0|[2,4]:form1|:form2}
495/// Polish (requires repeated form):
496/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
John McCall43b61682010-10-14 01:55:31 +0000497static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000498 const char *Argument, unsigned ArgumentLen,
Chris Lattnerb8e73152009-04-16 05:04:32 +0000499 llvm::SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000500 const char *ArgumentEnd = Argument + ArgumentLen;
501 while (1) {
502 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
503 const char *ExprEnd = Argument;
504 while (*ExprEnd != ':') {
505 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
506 ++ExprEnd;
507 }
508 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
509 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000510 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000511
512 // Recursively format the result of the plural clause into the
513 // output string.
514 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000515 return;
516 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000517 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000518 }
519}
520
521
Chris Lattner23be0672008-11-19 06:51:40 +0000522/// FormatDiagnostic - Format this diagnostic into a string, substituting the
523/// formal arguments into the %0 slots. The result is appended onto the Str
524/// array.
525void DiagnosticInfo::
526FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000527 if (!StoredDiagMessage.empty()) {
528 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
529 return;
530 }
531
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000532 llvm::StringRef Diag =
533 getDiags()->getDiagnosticIDs()->getDescription(getID());
Mike Stump11289f42009-09-09 15:08:12 +0000534
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000535 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
John McCalle4d54322010-01-13 23:58:20 +0000536}
537
538void DiagnosticInfo::
539FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
540 llvm::SmallVectorImpl<char> &OutStr) const {
541
Chris Lattnerc243f292009-10-20 05:25:22 +0000542 /// FormattedArgs - Keep track of all of the arguments formatted by
543 /// ConvertArgToString and pass them into subsequent calls to
544 /// ConvertArgToString, allowing the implementation to avoid redundancies in
545 /// obvious cases.
546 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
547
Chris Lattner23be0672008-11-19 06:51:40 +0000548 while (DiagStr != DiagEnd) {
549 if (DiagStr[0] != '%') {
550 // Append non-%0 substrings to Str if we have one.
551 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
552 OutStr.append(DiagStr, StrEnd);
553 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000554 continue;
John McCall8cb7a8a32010-01-14 20:11:39 +0000555 } else if (ispunct(DiagStr[1])) {
556 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000557 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000558 continue;
559 }
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattner2b786902008-11-21 07:50:02 +0000561 // Skip the %.
562 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner2b786902008-11-21 07:50:02 +0000564 // This must be a placeholder for a diagnostic argument. The format for a
565 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
566 // The digit is a number from 0-9 indicating which argument this comes from.
567 // The modifier is a string of digits from the set [-a-z]+, arguments is a
568 // brace enclosed string.
569 const char *Modifier = 0, *Argument = 0;
570 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattner2b786902008-11-21 07:50:02 +0000572 // Check to see if we have a modifier. If so eat it.
573 if (!isdigit(DiagStr[0])) {
574 Modifier = DiagStr;
575 while (DiagStr[0] == '-' ||
576 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
577 ++DiagStr;
578 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000579
Chris Lattner2b786902008-11-21 07:50:02 +0000580 // If we have an argument, get it next.
581 if (DiagStr[0] == '{') {
582 ++DiagStr; // Skip {.
583 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000584
John McCall8cb7a8a32010-01-14 20:11:39 +0000585 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
586 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000587 ArgumentLen = DiagStr-Argument;
588 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000589 }
Chris Lattner2b786902008-11-21 07:50:02 +0000590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattner2b786902008-11-21 07:50:02 +0000592 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000593 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000594
Chris Lattnerc243f292009-10-20 05:25:22 +0000595 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
596
597 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000598 // ---- STRINGS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000599 case Diagnostic::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000600 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000601 assert(ModifierLen == 0 && "No modifiers for strings yet");
602 OutStr.append(S.begin(), S.end());
603 break;
604 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000605 case Diagnostic::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000606 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000607 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 (!S)
611 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000612
Chris Lattner2b786902008-11-21 07:50:02 +0000613 OutStr.append(S, S + strlen(S));
614 break;
615 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000616 // ---- INTEGERS ----
Chris Lattner427c9c12008-11-22 00:59:29 +0000617 case Diagnostic::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000618 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattner2b786902008-11-21 07:50:02 +0000620 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000621 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
622 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000623 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
624 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000625 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000626 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
627 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000628 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
629 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000630 } else {
631 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000632 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000633 }
Chris Lattner2b786902008-11-21 07:50:02 +0000634 break;
635 }
Chris Lattner427c9c12008-11-22 00:59:29 +0000636 case Diagnostic::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000637 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000638
Chris Lattner2b786902008-11-21 07:50:02 +0000639 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000640 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000641 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
642 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000643 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000644 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
645 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000646 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
647 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000648 } else {
649 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000650 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000651 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000652 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000653 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000654 // ---- NAMES and TYPES ----
655 case Diagnostic::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000656 const IdentifierInfo *II = getArgIdentifier(ArgNo);
657 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000658
659 // Don't crash if get passed a null pointer by accident.
660 if (!II) {
661 const char *S = "(null)";
662 OutStr.append(S, S + strlen(S));
663 continue;
664 }
665
Daniel Dunbar07d07852009-10-18 21:17:35 +0000666 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000667 break;
668 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000669 case Diagnostic::ak_qualtype:
Chris Lattnerf7e69d52008-11-23 20:28:15 +0000670 case Diagnostic::ak_declarationname:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000671 case Diagnostic::ak_nameddecl:
Douglas Gregor053f6912009-08-26 00:04:55 +0000672 case Diagnostic::ak_nestednamespec:
Douglas Gregore40876a2009-10-13 21:16:44 +0000673 case Diagnostic::ak_declcontext:
Chris Lattnerc243f292009-10-20 05:25:22 +0000674 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Chris Lattner63ecc502008-11-23 09:21:17 +0000675 Modifier, ModifierLen,
Chris Lattnerc243f292009-10-20 05:25:22 +0000676 Argument, ArgumentLen,
677 FormattedArgs.data(), FormattedArgs.size(),
678 OutStr);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000679 break;
Nico Weber4c311642008-08-10 19:59:06 +0000680 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000681
682 // Remember this argument info for subsequent formatting operations. Turn
683 // std::strings into a null terminated string to make it be the same case as
684 // all the other ones.
685 if (Kind != Diagnostic::ak_std_string)
686 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
687 else
688 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
689 (intptr_t)getArgStdStr(ArgNo).c_str()));
690
Nico Weber4c311642008-08-10 19:59:06 +0000691 }
Nico Weber4c311642008-08-10 19:59:06 +0000692}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000693
Douglas Gregor33cdd812010-02-18 18:08:43 +0000694StoredDiagnostic::StoredDiagnostic() { }
695
Douglas Gregora750e8e2010-11-19 16:18:16 +0000696StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000697 llvm::StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000698 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000699
700StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
701 const DiagnosticInfo &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000702 : ID(Info.getID()), Level(Level)
703{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000704 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
705 "Valid source location without setting a source manager for diagnostic");
706 if (Info.getLocation().isValid())
707 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000708 llvm::SmallString<64> Message;
709 Info.FormatDiagnostic(Message);
710 this->Message.assign(Message.begin(), Message.end());
711
712 Ranges.reserve(Info.getNumRanges());
713 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
714 Ranges.push_back(Info.getRange(I));
715
Douglas Gregora771f462010-03-31 17:46:05 +0000716 FixIts.reserve(Info.getNumFixItHints());
717 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
718 FixIts.push_back(Info.getFixItHint(I));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000719}
720
721StoredDiagnostic::~StoredDiagnostic() { }
722
Ted Kremenekea06ec12009-01-23 20:28:53 +0000723/// IncludeInDiagnosticCounts - This method (whose default implementation
724/// returns true) indicates whether the diagnostics handled by this
725/// DiagnosticClient should be included in the number of diagnostics
726/// reported by Diagnostic.
727bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +0000728
729PartialDiagnostic::StorageAllocator::StorageAllocator() {
730 for (unsigned I = 0; I != NumCached; ++I)
731 FreeList[I] = Cached + I;
732 NumFreeListEntries = NumCached;
733}
734
735PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Ted Kremenek84de4a12011-03-21 18:40:07 +0000736 // Don't assert if we are in a CrashRecovery context, as this
737 // invariant may be invalidated during a crash.
Ted Kremenek0aaa67b2011-03-21 18:40:10 +0000738 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
Douglas Gregor89336232010-03-29 23:34:08 +0000739}