1 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the Diagnostic-related interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/PartialDiagnostic.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/Locale.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 using namespace clang;
26 
DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK,intptr_t QT,StringRef Modifier,StringRef Argument,ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,SmallVectorImpl<char> & Output,void * Cookie,ArrayRef<intptr_t> QualTypeVals)27 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
28                             StringRef Modifier, StringRef Argument,
29                             ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
30                             SmallVectorImpl<char> &Output,
31                             void *Cookie,
32                             ArrayRef<intptr_t> QualTypeVals) {
33   StringRef Str = "<can't format argument>";
34   Output.append(Str.begin(), Str.end());
35 }
36 
DiagnosticsEngine(const IntrusiveRefCntPtr<DiagnosticIDs> & diags,DiagnosticOptions * DiagOpts,DiagnosticConsumer * client,bool ShouldOwnClient)37 DiagnosticsEngine::DiagnosticsEngine(
38     const IntrusiveRefCntPtr<DiagnosticIDs> &diags, DiagnosticOptions *DiagOpts,
39     DiagnosticConsumer *client, bool ShouldOwnClient)
40     : Diags(diags), DiagOpts(DiagOpts), Client(nullptr), SourceMgr(nullptr) {
41   setClient(client, ShouldOwnClient);
42   ArgToStringFn = DummyArgToStringFn;
43   ArgToStringCookie = nullptr;
44 
45   AllExtensionsSilenced = 0;
46   IgnoreAllWarnings = false;
47   WarningsAsErrors = false;
48   EnableAllWarnings = false;
49   ErrorsAsFatal = false;
50   SuppressSystemWarnings = false;
51   SuppressAllDiagnostics = false;
52   ElideType = true;
53   PrintTemplateTree = false;
54   ShowColors = false;
55   ShowOverloads = Ovl_All;
56   ExtBehavior = diag::Severity::Ignored;
57 
58   ErrorLimit = 0;
59   TemplateBacktraceLimit = 0;
60   ConstexprBacktraceLimit = 0;
61 
62   Reset();
63 }
64 
~DiagnosticsEngine()65 DiagnosticsEngine::~DiagnosticsEngine() {
66   // If we own the diagnostic client, destroy it first so that it can access the
67   // engine from its destructor.
68   setClient(nullptr);
69 }
70 
setClient(DiagnosticConsumer * client,bool ShouldOwnClient)71 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
72                                   bool ShouldOwnClient) {
73   Owner.reset(ShouldOwnClient ? client : nullptr);
74   Client = client;
75 }
76 
pushMappings(SourceLocation Loc)77 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
78   DiagStateOnPushStack.push_back(GetCurDiagState());
79 }
80 
popMappings(SourceLocation Loc)81 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
82   if (DiagStateOnPushStack.empty())
83     return false;
84 
85   if (DiagStateOnPushStack.back() != GetCurDiagState()) {
86     // State changed at some point between push/pop.
87     PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
88   }
89   DiagStateOnPushStack.pop_back();
90   return true;
91 }
92 
Reset()93 void DiagnosticsEngine::Reset() {
94   ErrorOccurred = false;
95   UncompilableErrorOccurred = false;
96   FatalErrorOccurred = false;
97   UnrecoverableErrorOccurred = false;
98 
99   NumWarnings = 0;
100   NumErrors = 0;
101   TrapNumErrorsOccurred = 0;
102   TrapNumUnrecoverableErrorsOccurred = 0;
103 
104   CurDiagID = ~0U;
105   LastDiagLevel = DiagnosticIDs::Ignored;
106   DelayedDiagID = 0;
107 
108   // Clear state related to #pragma diagnostic.
109   DiagStates.clear();
110   DiagStatePoints.clear();
111   DiagStateOnPushStack.clear();
112 
113   // Create a DiagState and DiagStatePoint representing diagnostic changes
114   // through command-line.
115   DiagStates.push_back(DiagState());
116   DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
117 }
118 
SetDelayedDiagnostic(unsigned DiagID,StringRef Arg1,StringRef Arg2)119 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
120                                              StringRef Arg2) {
121   if (DelayedDiagID)
122     return;
123 
124   DelayedDiagID = DiagID;
125   DelayedDiagArg1 = Arg1.str();
126   DelayedDiagArg2 = Arg2.str();
127 }
128 
ReportDelayed()129 void DiagnosticsEngine::ReportDelayed() {
130   Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
131   DelayedDiagID = 0;
132   DelayedDiagArg1.clear();
133   DelayedDiagArg2.clear();
134 }
135 
136 DiagnosticsEngine::DiagStatePointsTy::iterator
GetDiagStatePointForLoc(SourceLocation L) const137 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
138   assert(!DiagStatePoints.empty());
139   assert(DiagStatePoints.front().Loc.isInvalid() &&
140          "Should have created a DiagStatePoint for command-line");
141 
142   if (!SourceMgr)
143     return DiagStatePoints.end() - 1;
144 
145   FullSourceLoc Loc(L, *SourceMgr);
146   if (Loc.isInvalid())
147     return DiagStatePoints.end() - 1;
148 
149   DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
150   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
151   if (LastStateChangePos.isValid() &&
152       Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
153     Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
154                            DiagStatePoint(nullptr, Loc));
155   --Pos;
156   return Pos;
157 }
158 
setSeverity(diag::kind Diag,diag::Severity Map,SourceLocation L)159 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
160                                     SourceLocation L) {
161   assert(Diag < diag::DIAG_UPPER_LIMIT &&
162          "Can only map builtin diagnostics");
163   assert((Diags->isBuiltinWarningOrExtension(Diag) ||
164           (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
165          "Cannot map errors into warnings!");
166   assert(!DiagStatePoints.empty());
167   assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
168 
169   FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc();
170   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
171   // Don't allow a mapping to a warning override an error/fatal mapping.
172   if (Map == diag::Severity::Warning) {
173     DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
174     if (Info.getSeverity() == diag::Severity::Error ||
175         Info.getSeverity() == diag::Severity::Fatal)
176       Map = Info.getSeverity();
177   }
178   DiagnosticMapping Mapping = makeUserMapping(Map, L);
179 
180   // Common case; setting all the diagnostics of a group in one place.
181   if (Loc.isInvalid() || Loc == LastStateChangePos) {
182     GetCurDiagState()->setMapping(Diag, Mapping);
183     return;
184   }
185 
186   // Another common case; modifying diagnostic state in a source location
187   // after the previous one.
188   if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
189       LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
190     // A diagnostic pragma occurred, create a new DiagState initialized with
191     // the current one and a new DiagStatePoint to record at which location
192     // the new state became active.
193     DiagStates.push_back(*GetCurDiagState());
194     PushDiagStatePoint(&DiagStates.back(), Loc);
195     GetCurDiagState()->setMapping(Diag, Mapping);
196     return;
197   }
198 
199   // We allow setting the diagnostic state in random source order for
200   // completeness but it should not be actually happening in normal practice.
201 
202   DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
203   assert(Pos != DiagStatePoints.end());
204 
205   // Update all diagnostic states that are active after the given location.
206   for (DiagStatePointsTy::iterator
207          I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
208     GetCurDiagState()->setMapping(Diag, Mapping);
209   }
210 
211   // If the location corresponds to an existing point, just update its state.
212   if (Pos->Loc == Loc) {
213     GetCurDiagState()->setMapping(Diag, Mapping);
214     return;
215   }
216 
217   // Create a new state/point and fit it into the vector of DiagStatePoints
218   // so that the vector is always ordered according to location.
219   assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc));
220   DiagStates.push_back(*Pos->State);
221   DiagState *NewState = &DiagStates.back();
222   GetCurDiagState()->setMapping(Diag, Mapping);
223   DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
224                                                FullSourceLoc(Loc, *SourceMgr)));
225 }
226 
setSeverityForGroup(diag::Flavor Flavor,StringRef Group,diag::Severity Map,SourceLocation Loc)227 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
228                                             StringRef Group, diag::Severity Map,
229                                             SourceLocation Loc) {
230   // Get the diagnostics in this group.
231   SmallVector<diag::kind, 256> GroupDiags;
232   if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
233     return true;
234 
235   // Set the mapping.
236   for (diag::kind Diag : GroupDiags)
237     setSeverity(Diag, Map, Loc);
238 
239   return false;
240 }
241 
setDiagnosticGroupWarningAsError(StringRef Group,bool Enabled)242 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
243                                                          bool Enabled) {
244   // If we are enabling this feature, just set the diagnostic mappings to map to
245   // errors.
246   if (Enabled)
247     return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
248                                diag::Severity::Error);
249 
250   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
251   // potentially downgrade anything already mapped to be a warning.
252 
253   // Get the diagnostics in this group.
254   SmallVector<diag::kind, 8> GroupDiags;
255   if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
256                                    GroupDiags))
257     return true;
258 
259   // Perform the mapping change.
260   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
261     DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]);
262 
263     if (Info.getSeverity() == diag::Severity::Error ||
264         Info.getSeverity() == diag::Severity::Fatal)
265       Info.setSeverity(diag::Severity::Warning);
266 
267     Info.setNoWarningAsError(true);
268   }
269 
270   return false;
271 }
272 
setDiagnosticGroupErrorAsFatal(StringRef Group,bool Enabled)273 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
274                                                        bool Enabled) {
275   // If we are enabling this feature, just set the diagnostic mappings to map to
276   // fatal errors.
277   if (Enabled)
278     return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
279                                diag::Severity::Fatal);
280 
281   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
282   // potentially downgrade anything already mapped to be an error.
283 
284   // Get the diagnostics in this group.
285   SmallVector<diag::kind, 8> GroupDiags;
286   if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
287                                    GroupDiags))
288     return true;
289 
290   // Perform the mapping change.
291   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
292     DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]);
293 
294     if (Info.getSeverity() == diag::Severity::Fatal)
295       Info.setSeverity(diag::Severity::Error);
296 
297     Info.setNoErrorAsFatal(true);
298   }
299 
300   return false;
301 }
302 
setSeverityForAll(diag::Flavor Flavor,diag::Severity Map,SourceLocation Loc)303 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
304                                           diag::Severity Map,
305                                           SourceLocation Loc) {
306   // Get all the diagnostics.
307   SmallVector<diag::kind, 64> AllDiags;
308   Diags->getAllDiagnostics(Flavor, AllDiags);
309 
310   // Set the mapping.
311   for (unsigned i = 0, e = AllDiags.size(); i != e; ++i)
312     if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
313       setSeverity(AllDiags[i], Map, Loc);
314 }
315 
Report(const StoredDiagnostic & storedDiag)316 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
317   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
318 
319   CurDiagLoc = storedDiag.getLocation();
320   CurDiagID = storedDiag.getID();
321   NumDiagArgs = 0;
322 
323   DiagRanges.clear();
324   DiagRanges.reserve(storedDiag.range_size());
325   for (StoredDiagnostic::range_iterator
326          RI = storedDiag.range_begin(),
327          RE = storedDiag.range_end(); RI != RE; ++RI)
328     DiagRanges.push_back(*RI);
329 
330   DiagFixItHints.clear();
331   DiagFixItHints.reserve(storedDiag.fixit_size());
332   for (StoredDiagnostic::fixit_iterator
333          FI = storedDiag.fixit_begin(),
334          FE = storedDiag.fixit_end(); FI != FE; ++FI)
335     DiagFixItHints.push_back(*FI);
336 
337   assert(Client && "DiagnosticConsumer not set!");
338   Level DiagLevel = storedDiag.getLevel();
339   Diagnostic Info(this, storedDiag.getMessage());
340   Client->HandleDiagnostic(DiagLevel, Info);
341   if (Client->IncludeInDiagnosticCounts()) {
342     if (DiagLevel == DiagnosticsEngine::Warning)
343       ++NumWarnings;
344   }
345 
346   CurDiagID = ~0U;
347 }
348 
EmitCurrentDiagnostic(bool Force)349 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
350   assert(getClient() && "DiagnosticClient not set!");
351 
352   bool Emitted;
353   if (Force) {
354     Diagnostic Info(this);
355 
356     // Figure out the diagnostic level of this message.
357     DiagnosticIDs::Level DiagLevel
358       = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
359 
360     Emitted = (DiagLevel != DiagnosticIDs::Ignored);
361     if (Emitted) {
362       // Emit the diagnostic regardless of suppression level.
363       Diags->EmitDiag(*this, DiagLevel);
364     }
365   } else {
366     // Process the diagnostic, sending the accumulated information to the
367     // DiagnosticConsumer.
368     Emitted = ProcessDiag();
369   }
370 
371   // Clear out the current diagnostic object.
372   unsigned DiagID = CurDiagID;
373   Clear();
374 
375   // If there was a delayed diagnostic, emit it now.
376   if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
377     ReportDelayed();
378 
379   return Emitted;
380 }
381 
382 
~DiagnosticConsumer()383 DiagnosticConsumer::~DiagnosticConsumer() {}
384 
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const Diagnostic & Info)385 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
386                                         const Diagnostic &Info) {
387   if (!IncludeInDiagnosticCounts())
388     return;
389 
390   if (DiagLevel == DiagnosticsEngine::Warning)
391     ++NumWarnings;
392   else if (DiagLevel >= DiagnosticsEngine::Error)
393     ++NumErrors;
394 }
395 
396 /// ModifierIs - Return true if the specified modifier matches specified string.
397 template <std::size_t StrLen>
ModifierIs(const char * Modifier,unsigned ModifierLen,const char (& Str)[StrLen])398 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
399                        const char (&Str)[StrLen]) {
400   return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
401 }
402 
403 /// ScanForward - Scans forward, looking for the given character, skipping
404 /// nested clauses and escaped characters.
ScanFormat(const char * I,const char * E,char Target)405 static const char *ScanFormat(const char *I, const char *E, char Target) {
406   unsigned Depth = 0;
407 
408   for ( ; I != E; ++I) {
409     if (Depth == 0 && *I == Target) return I;
410     if (Depth != 0 && *I == '}') Depth--;
411 
412     if (*I == '%') {
413       I++;
414       if (I == E) break;
415 
416       // Escaped characters get implicitly skipped here.
417 
418       // Format specifier.
419       if (!isDigit(*I) && !isPunctuation(*I)) {
420         for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
421         if (I == E) break;
422         if (*I == '{')
423           Depth++;
424       }
425     }
426   }
427   return E;
428 }
429 
430 /// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
431 /// like this:  %select{foo|bar|baz}2.  This means that the integer argument
432 /// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
433 /// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
434 /// This is very useful for certain classes of variant diagnostics.
HandleSelectModifier(const Diagnostic & DInfo,unsigned ValNo,const char * Argument,unsigned ArgumentLen,SmallVectorImpl<char> & OutStr)435 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
436                                  const char *Argument, unsigned ArgumentLen,
437                                  SmallVectorImpl<char> &OutStr) {
438   const char *ArgumentEnd = Argument+ArgumentLen;
439 
440   // Skip over 'ValNo' |'s.
441   while (ValNo) {
442     const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
443     assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
444            " larger than the number of options in the diagnostic string!");
445     Argument = NextVal+1;  // Skip this string.
446     --ValNo;
447   }
448 
449   // Get the end of the value.  This is either the } or the |.
450   const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
451 
452   // Recursively format the result of the select clause into the output string.
453   DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
454 }
455 
456 /// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
457 /// letter 's' to the string if the value is not 1.  This is used in cases like
458 /// this:  "you idiot, you have %4 parameter%s4!".
HandleIntegerSModifier(unsigned ValNo,SmallVectorImpl<char> & OutStr)459 static void HandleIntegerSModifier(unsigned ValNo,
460                                    SmallVectorImpl<char> &OutStr) {
461   if (ValNo != 1)
462     OutStr.push_back('s');
463 }
464 
465 /// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
466 /// prints the ordinal form of the given integer, with 1 corresponding
467 /// to the first ordinal.  Currently this is hard-coded to use the
468 /// English form.
HandleOrdinalModifier(unsigned ValNo,SmallVectorImpl<char> & OutStr)469 static void HandleOrdinalModifier(unsigned ValNo,
470                                   SmallVectorImpl<char> &OutStr) {
471   assert(ValNo != 0 && "ValNo must be strictly positive!");
472 
473   llvm::raw_svector_ostream Out(OutStr);
474 
475   // We could use text forms for the first N ordinals, but the numeric
476   // forms are actually nicer in diagnostics because they stand out.
477   Out << ValNo << llvm::getOrdinalSuffix(ValNo);
478 }
479 
480 
481 /// PluralNumber - Parse an unsigned integer and advance Start.
PluralNumber(const char * & Start,const char * End)482 static unsigned PluralNumber(const char *&Start, const char *End) {
483   // Programming 101: Parse a decimal number :-)
484   unsigned Val = 0;
485   while (Start != End && *Start >= '0' && *Start <= '9') {
486     Val *= 10;
487     Val += *Start - '0';
488     ++Start;
489   }
490   return Val;
491 }
492 
493 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
TestPluralRange(unsigned Val,const char * & Start,const char * End)494 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
495   if (*Start != '[') {
496     unsigned Ref = PluralNumber(Start, End);
497     return Ref == Val;
498   }
499 
500   ++Start;
501   unsigned Low = PluralNumber(Start, End);
502   assert(*Start == ',' && "Bad plural expression syntax: expected ,");
503   ++Start;
504   unsigned High = PluralNumber(Start, End);
505   assert(*Start == ']' && "Bad plural expression syntax: expected )");
506   ++Start;
507   return Low <= Val && Val <= High;
508 }
509 
510 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
EvalPluralExpr(unsigned ValNo,const char * Start,const char * End)511 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
512   // Empty condition?
513   if (*Start == ':')
514     return true;
515 
516   while (1) {
517     char C = *Start;
518     if (C == '%') {
519       // Modulo expression
520       ++Start;
521       unsigned Arg = PluralNumber(Start, End);
522       assert(*Start == '=' && "Bad plural expression syntax: expected =");
523       ++Start;
524       unsigned ValMod = ValNo % Arg;
525       if (TestPluralRange(ValMod, Start, End))
526         return true;
527     } else {
528       assert((C == '[' || (C >= '0' && C <= '9')) &&
529              "Bad plural expression syntax: unexpected character");
530       // Range expression
531       if (TestPluralRange(ValNo, Start, End))
532         return true;
533     }
534 
535     // Scan for next or-expr part.
536     Start = std::find(Start, End, ',');
537     if (Start == End)
538       break;
539     ++Start;
540   }
541   return false;
542 }
543 
544 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
545 /// for complex plural forms, or in languages where all plurals are complex.
546 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
547 /// conditions that are tested in order, the form corresponding to the first
548 /// that applies being emitted. The empty condition is always true, making the
549 /// last form a default case.
550 /// Conditions are simple boolean expressions, where n is the number argument.
551 /// Here are the rules.
552 /// condition  := expression | empty
553 /// empty      :=                             -> always true
554 /// expression := numeric [',' expression]    -> logical or
555 /// numeric    := range                       -> true if n in range
556 ///             | '%' number '=' range        -> true if n % number in range
557 /// range      := number
558 ///             | '[' number ',' number ']'   -> ranges are inclusive both ends
559 ///
560 /// Here are some examples from the GNU gettext manual written in this form:
561 /// English:
562 /// {1:form0|:form1}
563 /// Latvian:
564 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
565 /// Gaeilge:
566 /// {1:form0|2:form1|:form2}
567 /// Romanian:
568 /// {1:form0|0,%100=[1,19]:form1|:form2}
569 /// Lithuanian:
570 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
571 /// Russian (requires repeated form):
572 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
573 /// Slovak
574 /// {1:form0|[2,4]:form1|:form2}
575 /// Polish (requires repeated form):
576 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
HandlePluralModifier(const Diagnostic & DInfo,unsigned ValNo,const char * Argument,unsigned ArgumentLen,SmallVectorImpl<char> & OutStr)577 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
578                                  const char *Argument, unsigned ArgumentLen,
579                                  SmallVectorImpl<char> &OutStr) {
580   const char *ArgumentEnd = Argument + ArgumentLen;
581   while (1) {
582     assert(Argument < ArgumentEnd && "Plural expression didn't match.");
583     const char *ExprEnd = Argument;
584     while (*ExprEnd != ':') {
585       assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
586       ++ExprEnd;
587     }
588     if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
589       Argument = ExprEnd + 1;
590       ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
591 
592       // Recursively format the result of the plural clause into the
593       // output string.
594       DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
595       return;
596     }
597     Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
598   }
599 }
600 
601 /// \brief Returns the friendly description for a token kind that will appear
602 /// without quotes in diagnostic messages. These strings may be translatable in
603 /// future.
getTokenDescForDiagnostic(tok::TokenKind Kind)604 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
605   switch (Kind) {
606   case tok::identifier:
607     return "identifier";
608   default:
609     return nullptr;
610   }
611 }
612 
613 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
614 /// formal arguments into the %0 slots.  The result is appended onto the Str
615 /// array.
616 void Diagnostic::
FormatDiagnostic(SmallVectorImpl<char> & OutStr) const617 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
618   if (!StoredDiagMessage.empty()) {
619     OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
620     return;
621   }
622 
623   StringRef Diag =
624     getDiags()->getDiagnosticIDs()->getDescription(getID());
625 
626   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
627 }
628 
629 void Diagnostic::
FormatDiagnostic(const char * DiagStr,const char * DiagEnd,SmallVectorImpl<char> & OutStr) const630 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
631                  SmallVectorImpl<char> &OutStr) const {
632 
633   // When the diagnostic string is only "%0", the entire string is being given
634   // by an outside source.  Remove unprintable characters from this string
635   // and skip all the other string processing.
636   if (DiagEnd - DiagStr == 2 &&
637       StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
638       getArgKind(0) == DiagnosticsEngine::ak_std_string) {
639     const std::string &S = getArgStdStr(0);
640     for (char c : S) {
641       if (llvm::sys::locale::isPrint(c) || c == '\t') {
642         OutStr.push_back(c);
643       }
644     }
645     return;
646   }
647 
648   /// FormattedArgs - Keep track of all of the arguments formatted by
649   /// ConvertArgToString and pass them into subsequent calls to
650   /// ConvertArgToString, allowing the implementation to avoid redundancies in
651   /// obvious cases.
652   SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
653 
654   /// QualTypeVals - Pass a vector of arrays so that QualType names can be
655   /// compared to see if more information is needed to be printed.
656   SmallVector<intptr_t, 2> QualTypeVals;
657   SmallVector<char, 64> Tree;
658 
659   for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
660     if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
661       QualTypeVals.push_back(getRawArg(i));
662 
663   while (DiagStr != DiagEnd) {
664     if (DiagStr[0] != '%') {
665       // Append non-%0 substrings to Str if we have one.
666       const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
667       OutStr.append(DiagStr, StrEnd);
668       DiagStr = StrEnd;
669       continue;
670     } else if (isPunctuation(DiagStr[1])) {
671       OutStr.push_back(DiagStr[1]);  // %% -> %.
672       DiagStr += 2;
673       continue;
674     }
675 
676     // Skip the %.
677     ++DiagStr;
678 
679     // This must be a placeholder for a diagnostic argument.  The format for a
680     // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
681     // The digit is a number from 0-9 indicating which argument this comes from.
682     // The modifier is a string of digits from the set [-a-z]+, arguments is a
683     // brace enclosed string.
684     const char *Modifier = nullptr, *Argument = nullptr;
685     unsigned ModifierLen = 0, ArgumentLen = 0;
686 
687     // Check to see if we have a modifier.  If so eat it.
688     if (!isDigit(DiagStr[0])) {
689       Modifier = DiagStr;
690       while (DiagStr[0] == '-' ||
691              (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
692         ++DiagStr;
693       ModifierLen = DiagStr-Modifier;
694 
695       // If we have an argument, get it next.
696       if (DiagStr[0] == '{') {
697         ++DiagStr; // Skip {.
698         Argument = DiagStr;
699 
700         DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
701         assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
702         ArgumentLen = DiagStr-Argument;
703         ++DiagStr;  // Skip }.
704       }
705     }
706 
707     assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
708     unsigned ArgNo = *DiagStr++ - '0';
709 
710     // Only used for type diffing.
711     unsigned ArgNo2 = ArgNo;
712 
713     DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
714     if (ModifierIs(Modifier, ModifierLen, "diff")) {
715       assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
716              "Invalid format for diff modifier");
717       ++DiagStr;  // Comma.
718       ArgNo2 = *DiagStr++ - '0';
719       DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
720       if (Kind == DiagnosticsEngine::ak_qualtype &&
721           Kind2 == DiagnosticsEngine::ak_qualtype)
722         Kind = DiagnosticsEngine::ak_qualtype_pair;
723       else {
724         // %diff only supports QualTypes.  For other kinds of arguments,
725         // use the default printing.  For example, if the modifier is:
726         //   "%diff{compare $ to $|other text}1,2"
727         // treat it as:
728         //   "compare %1 to %2"
729         const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|');
730         const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
731         const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
732         const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
733         const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
734         FormatDiagnostic(Argument, FirstDollar, OutStr);
735         FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
736         FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
737         FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
738         FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
739         continue;
740       }
741     }
742 
743     switch (Kind) {
744     // ---- STRINGS ----
745     case DiagnosticsEngine::ak_std_string: {
746       const std::string &S = getArgStdStr(ArgNo);
747       assert(ModifierLen == 0 && "No modifiers for strings yet");
748       OutStr.append(S.begin(), S.end());
749       break;
750     }
751     case DiagnosticsEngine::ak_c_string: {
752       const char *S = getArgCStr(ArgNo);
753       assert(ModifierLen == 0 && "No modifiers for strings yet");
754 
755       // Don't crash if get passed a null pointer by accident.
756       if (!S)
757         S = "(null)";
758 
759       OutStr.append(S, S + strlen(S));
760       break;
761     }
762     // ---- INTEGERS ----
763     case DiagnosticsEngine::ak_sint: {
764       int Val = getArgSInt(ArgNo);
765 
766       if (ModifierIs(Modifier, ModifierLen, "select")) {
767         HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
768                              OutStr);
769       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
770         HandleIntegerSModifier(Val, OutStr);
771       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
772         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
773                              OutStr);
774       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
775         HandleOrdinalModifier((unsigned)Val, OutStr);
776       } else {
777         assert(ModifierLen == 0 && "Unknown integer modifier");
778         llvm::raw_svector_ostream(OutStr) << Val;
779       }
780       break;
781     }
782     case DiagnosticsEngine::ak_uint: {
783       unsigned Val = getArgUInt(ArgNo);
784 
785       if (ModifierIs(Modifier, ModifierLen, "select")) {
786         HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
787       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
788         HandleIntegerSModifier(Val, OutStr);
789       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
790         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
791                              OutStr);
792       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
793         HandleOrdinalModifier(Val, OutStr);
794       } else {
795         assert(ModifierLen == 0 && "Unknown integer modifier");
796         llvm::raw_svector_ostream(OutStr) << Val;
797       }
798       break;
799     }
800     // ---- TOKEN SPELLINGS ----
801     case DiagnosticsEngine::ak_tokenkind: {
802       tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
803       assert(ModifierLen == 0 && "No modifiers for token kinds yet");
804 
805       llvm::raw_svector_ostream Out(OutStr);
806       if (const char *S = tok::getPunctuatorSpelling(Kind))
807         // Quoted token spelling for punctuators.
808         Out << '\'' << S << '\'';
809       else if (const char *S = tok::getKeywordSpelling(Kind))
810         // Unquoted token spelling for keywords.
811         Out << S;
812       else if (const char *S = getTokenDescForDiagnostic(Kind))
813         // Unquoted translatable token name.
814         Out << S;
815       else if (const char *S = tok::getTokenName(Kind))
816         // Debug name, shouldn't appear in user-facing diagnostics.
817         Out << '<' << S << '>';
818       else
819         Out << "(null)";
820       break;
821     }
822     // ---- NAMES and TYPES ----
823     case DiagnosticsEngine::ak_identifierinfo: {
824       const IdentifierInfo *II = getArgIdentifier(ArgNo);
825       assert(ModifierLen == 0 && "No modifiers for strings yet");
826 
827       // Don't crash if get passed a null pointer by accident.
828       if (!II) {
829         const char *S = "(null)";
830         OutStr.append(S, S + strlen(S));
831         continue;
832       }
833 
834       llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
835       break;
836     }
837     case DiagnosticsEngine::ak_qualtype:
838     case DiagnosticsEngine::ak_declarationname:
839     case DiagnosticsEngine::ak_nameddecl:
840     case DiagnosticsEngine::ak_nestednamespec:
841     case DiagnosticsEngine::ak_declcontext:
842     case DiagnosticsEngine::ak_attr:
843       getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
844                                      StringRef(Modifier, ModifierLen),
845                                      StringRef(Argument, ArgumentLen),
846                                      FormattedArgs,
847                                      OutStr, QualTypeVals);
848       break;
849     case DiagnosticsEngine::ak_qualtype_pair:
850       // Create a struct with all the info needed for printing.
851       TemplateDiffTypes TDT;
852       TDT.FromType = getRawArg(ArgNo);
853       TDT.ToType = getRawArg(ArgNo2);
854       TDT.ElideType = getDiags()->ElideType;
855       TDT.ShowColors = getDiags()->ShowColors;
856       TDT.TemplateDiffUsed = false;
857       intptr_t val = reinterpret_cast<intptr_t>(&TDT);
858 
859       const char *ArgumentEnd = Argument + ArgumentLen;
860       const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
861 
862       // Print the tree.  If this diagnostic already has a tree, skip the
863       // second tree.
864       if (getDiags()->PrintTemplateTree && Tree.empty()) {
865         TDT.PrintFromType = true;
866         TDT.PrintTree = true;
867         getDiags()->ConvertArgToString(Kind, val,
868                                        StringRef(Modifier, ModifierLen),
869                                        StringRef(Argument, ArgumentLen),
870                                        FormattedArgs,
871                                        Tree, QualTypeVals);
872         // If there is no tree information, fall back to regular printing.
873         if (!Tree.empty()) {
874           FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
875           break;
876         }
877       }
878 
879       // Non-tree printing, also the fall-back when tree printing fails.
880       // The fall-back is triggered when the types compared are not templates.
881       const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
882       const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
883 
884       // Append before text
885       FormatDiagnostic(Argument, FirstDollar, OutStr);
886 
887       // Append first type
888       TDT.PrintTree = false;
889       TDT.PrintFromType = true;
890       getDiags()->ConvertArgToString(Kind, val,
891                                      StringRef(Modifier, ModifierLen),
892                                      StringRef(Argument, ArgumentLen),
893                                      FormattedArgs,
894                                      OutStr, QualTypeVals);
895       if (!TDT.TemplateDiffUsed)
896         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
897                                                TDT.FromType));
898 
899       // Append middle text
900       FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
901 
902       // Append second type
903       TDT.PrintFromType = false;
904       getDiags()->ConvertArgToString(Kind, val,
905                                      StringRef(Modifier, ModifierLen),
906                                      StringRef(Argument, ArgumentLen),
907                                      FormattedArgs,
908                                      OutStr, QualTypeVals);
909       if (!TDT.TemplateDiffUsed)
910         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
911                                                TDT.ToType));
912 
913       // Append end text
914       FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
915       break;
916     }
917 
918     // Remember this argument info for subsequent formatting operations.  Turn
919     // std::strings into a null terminated string to make it be the same case as
920     // all the other ones.
921     if (Kind == DiagnosticsEngine::ak_qualtype_pair)
922       continue;
923     else if (Kind != DiagnosticsEngine::ak_std_string)
924       FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
925     else
926       FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
927                                         (intptr_t)getArgStdStr(ArgNo).c_str()));
928 
929   }
930 
931   // Append the type tree to the end of the diagnostics.
932   OutStr.append(Tree.begin(), Tree.end());
933 }
934 
StoredDiagnostic()935 StoredDiagnostic::StoredDiagnostic() { }
936 
StoredDiagnostic(DiagnosticsEngine::Level Level,unsigned ID,StringRef Message)937 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
938                                    StringRef Message)
939   : ID(ID), Level(Level), Loc(), Message(Message) { }
940 
StoredDiagnostic(DiagnosticsEngine::Level Level,const Diagnostic & Info)941 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
942                                    const Diagnostic &Info)
943   : ID(Info.getID()), Level(Level)
944 {
945   assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
946        "Valid source location without setting a source manager for diagnostic");
947   if (Info.getLocation().isValid())
948     Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
949   SmallString<64> Message;
950   Info.FormatDiagnostic(Message);
951   this->Message.assign(Message.begin(), Message.end());
952   this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
953   this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
954 }
955 
StoredDiagnostic(DiagnosticsEngine::Level Level,unsigned ID,StringRef Message,FullSourceLoc Loc,ArrayRef<CharSourceRange> Ranges,ArrayRef<FixItHint> FixIts)956 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
957                                    StringRef Message, FullSourceLoc Loc,
958                                    ArrayRef<CharSourceRange> Ranges,
959                                    ArrayRef<FixItHint> FixIts)
960   : ID(ID), Level(Level), Loc(Loc), Message(Message),
961     Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
962 {
963 }
964 
~StoredDiagnostic()965 StoredDiagnostic::~StoredDiagnostic() { }
966 
967 /// IncludeInDiagnosticCounts - This method (whose default implementation
968 ///  returns true) indicates whether the diagnostics handled by this
969 ///  DiagnosticConsumer should be included in the number of diagnostics
970 ///  reported by DiagnosticsEngine.
IncludeInDiagnosticCounts() const971 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
972 
anchor()973 void IgnoringDiagConsumer::anchor() { }
974 
~ForwardingDiagnosticConsumer()975 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
976 
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const Diagnostic & Info)977 void ForwardingDiagnosticConsumer::HandleDiagnostic(
978        DiagnosticsEngine::Level DiagLevel,
979        const Diagnostic &Info) {
980   Target.HandleDiagnostic(DiagLevel, Info);
981 }
982 
clear()983 void ForwardingDiagnosticConsumer::clear() {
984   DiagnosticConsumer::clear();
985   Target.clear();
986 }
987 
IncludeInDiagnosticCounts() const988 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
989   return Target.IncludeInDiagnosticCounts();
990 }
991 
StorageAllocator()992 PartialDiagnostic::StorageAllocator::StorageAllocator() {
993   for (unsigned I = 0; I != NumCached; ++I)
994     FreeList[I] = Cached + I;
995   NumFreeListEntries = NumCached;
996 }
997 
~StorageAllocator()998 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
999   // Don't assert if we are in a CrashRecovery context, as this invariant may
1000   // be invalidated during a crash.
1001   assert((NumFreeListEntries == NumCached ||
1002           llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1003          "A partial is on the lamb");
1004 }
1005