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 
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 
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 
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 
71 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
72                                   bool ShouldOwnClient) {
73   Owner.reset(ShouldOwnClient ? client : nullptr);
74   Client = client;
75 }
76 
77 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
78   DiagStateOnPushStack.push_back(GetCurDiagState());
79 }
80 
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 
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.emplace_back();
116   DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
117 }
118 
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 
129 void DiagnosticsEngine::ReportDelayed() {
130   Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
131   DelayedDiagID = 0;
132   DelayedDiagArg1.clear();
133   DelayedDiagArg2.clear();
134 }
135 
136 DiagnosticsEngine::DiagStatePointsTy::iterator
137 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 
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 
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 
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 
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 
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 
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.append(storedDiag.range_begin(), storedDiag.range_end());
325 
326   DiagFixItHints.clear();
327   DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
328 
329   assert(Client && "DiagnosticConsumer not set!");
330   Level DiagLevel = storedDiag.getLevel();
331   Diagnostic Info(this, storedDiag.getMessage());
332   Client->HandleDiagnostic(DiagLevel, Info);
333   if (Client->IncludeInDiagnosticCounts()) {
334     if (DiagLevel == DiagnosticsEngine::Warning)
335       ++NumWarnings;
336   }
337 
338   CurDiagID = ~0U;
339 }
340 
341 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
342   assert(getClient() && "DiagnosticClient not set!");
343 
344   bool Emitted;
345   if (Force) {
346     Diagnostic Info(this);
347 
348     // Figure out the diagnostic level of this message.
349     DiagnosticIDs::Level DiagLevel
350       = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
351 
352     Emitted = (DiagLevel != DiagnosticIDs::Ignored);
353     if (Emitted) {
354       // Emit the diagnostic regardless of suppression level.
355       Diags->EmitDiag(*this, DiagLevel);
356     }
357   } else {
358     // Process the diagnostic, sending the accumulated information to the
359     // DiagnosticConsumer.
360     Emitted = ProcessDiag();
361   }
362 
363   // Clear out the current diagnostic object.
364   unsigned DiagID = CurDiagID;
365   Clear();
366 
367   // If there was a delayed diagnostic, emit it now.
368   if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
369     ReportDelayed();
370 
371   return Emitted;
372 }
373 
374 
375 DiagnosticConsumer::~DiagnosticConsumer() {}
376 
377 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
378                                         const Diagnostic &Info) {
379   if (!IncludeInDiagnosticCounts())
380     return;
381 
382   if (DiagLevel == DiagnosticsEngine::Warning)
383     ++NumWarnings;
384   else if (DiagLevel >= DiagnosticsEngine::Error)
385     ++NumErrors;
386 }
387 
388 /// ModifierIs - Return true if the specified modifier matches specified string.
389 template <std::size_t StrLen>
390 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
391                        const char (&Str)[StrLen]) {
392   return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
393 }
394 
395 /// ScanForward - Scans forward, looking for the given character, skipping
396 /// nested clauses and escaped characters.
397 static const char *ScanFormat(const char *I, const char *E, char Target) {
398   unsigned Depth = 0;
399 
400   for ( ; I != E; ++I) {
401     if (Depth == 0 && *I == Target) return I;
402     if (Depth != 0 && *I == '}') Depth--;
403 
404     if (*I == '%') {
405       I++;
406       if (I == E) break;
407 
408       // Escaped characters get implicitly skipped here.
409 
410       // Format specifier.
411       if (!isDigit(*I) && !isPunctuation(*I)) {
412         for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
413         if (I == E) break;
414         if (*I == '{')
415           Depth++;
416       }
417     }
418   }
419   return E;
420 }
421 
422 /// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
423 /// like this:  %select{foo|bar|baz}2.  This means that the integer argument
424 /// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
425 /// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
426 /// This is very useful for certain classes of variant diagnostics.
427 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
428                                  const char *Argument, unsigned ArgumentLen,
429                                  SmallVectorImpl<char> &OutStr) {
430   const char *ArgumentEnd = Argument+ArgumentLen;
431 
432   // Skip over 'ValNo' |'s.
433   while (ValNo) {
434     const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
435     assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
436            " larger than the number of options in the diagnostic string!");
437     Argument = NextVal+1;  // Skip this string.
438     --ValNo;
439   }
440 
441   // Get the end of the value.  This is either the } or the |.
442   const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
443 
444   // Recursively format the result of the select clause into the output string.
445   DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
446 }
447 
448 /// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
449 /// letter 's' to the string if the value is not 1.  This is used in cases like
450 /// this:  "you idiot, you have %4 parameter%s4!".
451 static void HandleIntegerSModifier(unsigned ValNo,
452                                    SmallVectorImpl<char> &OutStr) {
453   if (ValNo != 1)
454     OutStr.push_back('s');
455 }
456 
457 /// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
458 /// prints the ordinal form of the given integer, with 1 corresponding
459 /// to the first ordinal.  Currently this is hard-coded to use the
460 /// English form.
461 static void HandleOrdinalModifier(unsigned ValNo,
462                                   SmallVectorImpl<char> &OutStr) {
463   assert(ValNo != 0 && "ValNo must be strictly positive!");
464 
465   llvm::raw_svector_ostream Out(OutStr);
466 
467   // We could use text forms for the first N ordinals, but the numeric
468   // forms are actually nicer in diagnostics because they stand out.
469   Out << ValNo << llvm::getOrdinalSuffix(ValNo);
470 }
471 
472 
473 /// PluralNumber - Parse an unsigned integer and advance Start.
474 static unsigned PluralNumber(const char *&Start, const char *End) {
475   // Programming 101: Parse a decimal number :-)
476   unsigned Val = 0;
477   while (Start != End && *Start >= '0' && *Start <= '9') {
478     Val *= 10;
479     Val += *Start - '0';
480     ++Start;
481   }
482   return Val;
483 }
484 
485 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
486 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
487   if (*Start != '[') {
488     unsigned Ref = PluralNumber(Start, End);
489     return Ref == Val;
490   }
491 
492   ++Start;
493   unsigned Low = PluralNumber(Start, End);
494   assert(*Start == ',' && "Bad plural expression syntax: expected ,");
495   ++Start;
496   unsigned High = PluralNumber(Start, End);
497   assert(*Start == ']' && "Bad plural expression syntax: expected )");
498   ++Start;
499   return Low <= Val && Val <= High;
500 }
501 
502 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
503 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
504   // Empty condition?
505   if (*Start == ':')
506     return true;
507 
508   while (1) {
509     char C = *Start;
510     if (C == '%') {
511       // Modulo expression
512       ++Start;
513       unsigned Arg = PluralNumber(Start, End);
514       assert(*Start == '=' && "Bad plural expression syntax: expected =");
515       ++Start;
516       unsigned ValMod = ValNo % Arg;
517       if (TestPluralRange(ValMod, Start, End))
518         return true;
519     } else {
520       assert((C == '[' || (C >= '0' && C <= '9')) &&
521              "Bad plural expression syntax: unexpected character");
522       // Range expression
523       if (TestPluralRange(ValNo, Start, End))
524         return true;
525     }
526 
527     // Scan for next or-expr part.
528     Start = std::find(Start, End, ',');
529     if (Start == End)
530       break;
531     ++Start;
532   }
533   return false;
534 }
535 
536 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
537 /// for complex plural forms, or in languages where all plurals are complex.
538 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
539 /// conditions that are tested in order, the form corresponding to the first
540 /// that applies being emitted. The empty condition is always true, making the
541 /// last form a default case.
542 /// Conditions are simple boolean expressions, where n is the number argument.
543 /// Here are the rules.
544 /// condition  := expression | empty
545 /// empty      :=                             -> always true
546 /// expression := numeric [',' expression]    -> logical or
547 /// numeric    := range                       -> true if n in range
548 ///             | '%' number '=' range        -> true if n % number in range
549 /// range      := number
550 ///             | '[' number ',' number ']'   -> ranges are inclusive both ends
551 ///
552 /// Here are some examples from the GNU gettext manual written in this form:
553 /// English:
554 /// {1:form0|:form1}
555 /// Latvian:
556 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
557 /// Gaeilge:
558 /// {1:form0|2:form1|:form2}
559 /// Romanian:
560 /// {1:form0|0,%100=[1,19]:form1|:form2}
561 /// Lithuanian:
562 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
563 /// Russian (requires repeated form):
564 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
565 /// Slovak
566 /// {1:form0|[2,4]:form1|:form2}
567 /// Polish (requires repeated form):
568 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
569 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
570                                  const char *Argument, unsigned ArgumentLen,
571                                  SmallVectorImpl<char> &OutStr) {
572   const char *ArgumentEnd = Argument + ArgumentLen;
573   while (1) {
574     assert(Argument < ArgumentEnd && "Plural expression didn't match.");
575     const char *ExprEnd = Argument;
576     while (*ExprEnd != ':') {
577       assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
578       ++ExprEnd;
579     }
580     if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
581       Argument = ExprEnd + 1;
582       ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
583 
584       // Recursively format the result of the plural clause into the
585       // output string.
586       DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
587       return;
588     }
589     Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
590   }
591 }
592 
593 /// \brief Returns the friendly description for a token kind that will appear
594 /// without quotes in diagnostic messages. These strings may be translatable in
595 /// future.
596 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
597   switch (Kind) {
598   case tok::identifier:
599     return "identifier";
600   default:
601     return nullptr;
602   }
603 }
604 
605 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
606 /// formal arguments into the %0 slots.  The result is appended onto the Str
607 /// array.
608 void Diagnostic::
609 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
610   if (!StoredDiagMessage.empty()) {
611     OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
612     return;
613   }
614 
615   StringRef Diag =
616     getDiags()->getDiagnosticIDs()->getDescription(getID());
617 
618   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
619 }
620 
621 void Diagnostic::
622 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
623                  SmallVectorImpl<char> &OutStr) const {
624 
625   // When the diagnostic string is only "%0", the entire string is being given
626   // by an outside source.  Remove unprintable characters from this string
627   // and skip all the other string processing.
628   if (DiagEnd - DiagStr == 2 &&
629       StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
630       getArgKind(0) == DiagnosticsEngine::ak_std_string) {
631     const std::string &S = getArgStdStr(0);
632     for (char c : S) {
633       if (llvm::sys::locale::isPrint(c) || c == '\t') {
634         OutStr.push_back(c);
635       }
636     }
637     return;
638   }
639 
640   /// FormattedArgs - Keep track of all of the arguments formatted by
641   /// ConvertArgToString and pass them into subsequent calls to
642   /// ConvertArgToString, allowing the implementation to avoid redundancies in
643   /// obvious cases.
644   SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
645 
646   /// QualTypeVals - Pass a vector of arrays so that QualType names can be
647   /// compared to see if more information is needed to be printed.
648   SmallVector<intptr_t, 2> QualTypeVals;
649   SmallVector<char, 64> Tree;
650 
651   for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
652     if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
653       QualTypeVals.push_back(getRawArg(i));
654 
655   while (DiagStr != DiagEnd) {
656     if (DiagStr[0] != '%') {
657       // Append non-%0 substrings to Str if we have one.
658       const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
659       OutStr.append(DiagStr, StrEnd);
660       DiagStr = StrEnd;
661       continue;
662     } else if (isPunctuation(DiagStr[1])) {
663       OutStr.push_back(DiagStr[1]);  // %% -> %.
664       DiagStr += 2;
665       continue;
666     }
667 
668     // Skip the %.
669     ++DiagStr;
670 
671     // This must be a placeholder for a diagnostic argument.  The format for a
672     // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
673     // The digit is a number from 0-9 indicating which argument this comes from.
674     // The modifier is a string of digits from the set [-a-z]+, arguments is a
675     // brace enclosed string.
676     const char *Modifier = nullptr, *Argument = nullptr;
677     unsigned ModifierLen = 0, ArgumentLen = 0;
678 
679     // Check to see if we have a modifier.  If so eat it.
680     if (!isDigit(DiagStr[0])) {
681       Modifier = DiagStr;
682       while (DiagStr[0] == '-' ||
683              (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
684         ++DiagStr;
685       ModifierLen = DiagStr-Modifier;
686 
687       // If we have an argument, get it next.
688       if (DiagStr[0] == '{') {
689         ++DiagStr; // Skip {.
690         Argument = DiagStr;
691 
692         DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
693         assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
694         ArgumentLen = DiagStr-Argument;
695         ++DiagStr;  // Skip }.
696       }
697     }
698 
699     assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
700     unsigned ArgNo = *DiagStr++ - '0';
701 
702     // Only used for type diffing.
703     unsigned ArgNo2 = ArgNo;
704 
705     DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
706     if (ModifierIs(Modifier, ModifierLen, "diff")) {
707       assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
708              "Invalid format for diff modifier");
709       ++DiagStr;  // Comma.
710       ArgNo2 = *DiagStr++ - '0';
711       DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
712       if (Kind == DiagnosticsEngine::ak_qualtype &&
713           Kind2 == DiagnosticsEngine::ak_qualtype)
714         Kind = DiagnosticsEngine::ak_qualtype_pair;
715       else {
716         // %diff only supports QualTypes.  For other kinds of arguments,
717         // use the default printing.  For example, if the modifier is:
718         //   "%diff{compare $ to $|other text}1,2"
719         // treat it as:
720         //   "compare %1 to %2"
721         const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|');
722         const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
723         const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
724         const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
725         const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
726         FormatDiagnostic(Argument, FirstDollar, OutStr);
727         FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
728         FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
729         FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
730         FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
731         continue;
732       }
733     }
734 
735     switch (Kind) {
736     // ---- STRINGS ----
737     case DiagnosticsEngine::ak_std_string: {
738       const std::string &S = getArgStdStr(ArgNo);
739       assert(ModifierLen == 0 && "No modifiers for strings yet");
740       OutStr.append(S.begin(), S.end());
741       break;
742     }
743     case DiagnosticsEngine::ak_c_string: {
744       const char *S = getArgCStr(ArgNo);
745       assert(ModifierLen == 0 && "No modifiers for strings yet");
746 
747       // Don't crash if get passed a null pointer by accident.
748       if (!S)
749         S = "(null)";
750 
751       OutStr.append(S, S + strlen(S));
752       break;
753     }
754     // ---- INTEGERS ----
755     case DiagnosticsEngine::ak_sint: {
756       int Val = getArgSInt(ArgNo);
757 
758       if (ModifierIs(Modifier, ModifierLen, "select")) {
759         HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
760                              OutStr);
761       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
762         HandleIntegerSModifier(Val, OutStr);
763       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
764         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
765                              OutStr);
766       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
767         HandleOrdinalModifier((unsigned)Val, OutStr);
768       } else {
769         assert(ModifierLen == 0 && "Unknown integer modifier");
770         llvm::raw_svector_ostream(OutStr) << Val;
771       }
772       break;
773     }
774     case DiagnosticsEngine::ak_uint: {
775       unsigned Val = getArgUInt(ArgNo);
776 
777       if (ModifierIs(Modifier, ModifierLen, "select")) {
778         HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
779       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
780         HandleIntegerSModifier(Val, OutStr);
781       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
782         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
783                              OutStr);
784       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
785         HandleOrdinalModifier(Val, OutStr);
786       } else {
787         assert(ModifierLen == 0 && "Unknown integer modifier");
788         llvm::raw_svector_ostream(OutStr) << Val;
789       }
790       break;
791     }
792     // ---- TOKEN SPELLINGS ----
793     case DiagnosticsEngine::ak_tokenkind: {
794       tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
795       assert(ModifierLen == 0 && "No modifiers for token kinds yet");
796 
797       llvm::raw_svector_ostream Out(OutStr);
798       if (const char *S = tok::getPunctuatorSpelling(Kind))
799         // Quoted token spelling for punctuators.
800         Out << '\'' << S << '\'';
801       else if (const char *S = tok::getKeywordSpelling(Kind))
802         // Unquoted token spelling for keywords.
803         Out << S;
804       else if (const char *S = getTokenDescForDiagnostic(Kind))
805         // Unquoted translatable token name.
806         Out << S;
807       else if (const char *S = tok::getTokenName(Kind))
808         // Debug name, shouldn't appear in user-facing diagnostics.
809         Out << '<' << S << '>';
810       else
811         Out << "(null)";
812       break;
813     }
814     // ---- NAMES and TYPES ----
815     case DiagnosticsEngine::ak_identifierinfo: {
816       const IdentifierInfo *II = getArgIdentifier(ArgNo);
817       assert(ModifierLen == 0 && "No modifiers for strings yet");
818 
819       // Don't crash if get passed a null pointer by accident.
820       if (!II) {
821         const char *S = "(null)";
822         OutStr.append(S, S + strlen(S));
823         continue;
824       }
825 
826       llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
827       break;
828     }
829     case DiagnosticsEngine::ak_qualtype:
830     case DiagnosticsEngine::ak_declarationname:
831     case DiagnosticsEngine::ak_nameddecl:
832     case DiagnosticsEngine::ak_nestednamespec:
833     case DiagnosticsEngine::ak_declcontext:
834     case DiagnosticsEngine::ak_attr:
835       getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
836                                      StringRef(Modifier, ModifierLen),
837                                      StringRef(Argument, ArgumentLen),
838                                      FormattedArgs,
839                                      OutStr, QualTypeVals);
840       break;
841     case DiagnosticsEngine::ak_qualtype_pair:
842       // Create a struct with all the info needed for printing.
843       TemplateDiffTypes TDT;
844       TDT.FromType = getRawArg(ArgNo);
845       TDT.ToType = getRawArg(ArgNo2);
846       TDT.ElideType = getDiags()->ElideType;
847       TDT.ShowColors = getDiags()->ShowColors;
848       TDT.TemplateDiffUsed = false;
849       intptr_t val = reinterpret_cast<intptr_t>(&TDT);
850 
851       const char *ArgumentEnd = Argument + ArgumentLen;
852       const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
853 
854       // Print the tree.  If this diagnostic already has a tree, skip the
855       // second tree.
856       if (getDiags()->PrintTemplateTree && Tree.empty()) {
857         TDT.PrintFromType = true;
858         TDT.PrintTree = true;
859         getDiags()->ConvertArgToString(Kind, val,
860                                        StringRef(Modifier, ModifierLen),
861                                        StringRef(Argument, ArgumentLen),
862                                        FormattedArgs,
863                                        Tree, QualTypeVals);
864         // If there is no tree information, fall back to regular printing.
865         if (!Tree.empty()) {
866           FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
867           break;
868         }
869       }
870 
871       // Non-tree printing, also the fall-back when tree printing fails.
872       // The fall-back is triggered when the types compared are not templates.
873       const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
874       const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
875 
876       // Append before text
877       FormatDiagnostic(Argument, FirstDollar, OutStr);
878 
879       // Append first type
880       TDT.PrintTree = false;
881       TDT.PrintFromType = true;
882       getDiags()->ConvertArgToString(Kind, val,
883                                      StringRef(Modifier, ModifierLen),
884                                      StringRef(Argument, ArgumentLen),
885                                      FormattedArgs,
886                                      OutStr, QualTypeVals);
887       if (!TDT.TemplateDiffUsed)
888         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
889                                                TDT.FromType));
890 
891       // Append middle text
892       FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
893 
894       // Append second type
895       TDT.PrintFromType = false;
896       getDiags()->ConvertArgToString(Kind, val,
897                                      StringRef(Modifier, ModifierLen),
898                                      StringRef(Argument, ArgumentLen),
899                                      FormattedArgs,
900                                      OutStr, QualTypeVals);
901       if (!TDT.TemplateDiffUsed)
902         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
903                                                TDT.ToType));
904 
905       // Append end text
906       FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
907       break;
908     }
909 
910     // Remember this argument info for subsequent formatting operations.  Turn
911     // std::strings into a null terminated string to make it be the same case as
912     // all the other ones.
913     if (Kind == DiagnosticsEngine::ak_qualtype_pair)
914       continue;
915     else if (Kind != DiagnosticsEngine::ak_std_string)
916       FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
917     else
918       FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
919                                         (intptr_t)getArgStdStr(ArgNo).c_str()));
920 
921   }
922 
923   // Append the type tree to the end of the diagnostics.
924   OutStr.append(Tree.begin(), Tree.end());
925 }
926 
927 StoredDiagnostic::StoredDiagnostic() { }
928 
929 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
930                                    StringRef Message)
931   : ID(ID), Level(Level), Loc(), Message(Message) { }
932 
933 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
934                                    const Diagnostic &Info)
935   : ID(Info.getID()), Level(Level)
936 {
937   assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
938        "Valid source location without setting a source manager for diagnostic");
939   if (Info.getLocation().isValid())
940     Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
941   SmallString<64> Message;
942   Info.FormatDiagnostic(Message);
943   this->Message.assign(Message.begin(), Message.end());
944   this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
945   this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
946 }
947 
948 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
949                                    StringRef Message, FullSourceLoc Loc,
950                                    ArrayRef<CharSourceRange> Ranges,
951                                    ArrayRef<FixItHint> FixIts)
952   : ID(ID), Level(Level), Loc(Loc), Message(Message),
953     Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
954 {
955 }
956 
957 StoredDiagnostic::~StoredDiagnostic() { }
958 
959 /// IncludeInDiagnosticCounts - This method (whose default implementation
960 ///  returns true) indicates whether the diagnostics handled by this
961 ///  DiagnosticConsumer should be included in the number of diagnostics
962 ///  reported by DiagnosticsEngine.
963 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
964 
965 void IgnoringDiagConsumer::anchor() { }
966 
967 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
968 
969 void ForwardingDiagnosticConsumer::HandleDiagnostic(
970        DiagnosticsEngine::Level DiagLevel,
971        const Diagnostic &Info) {
972   Target.HandleDiagnostic(DiagLevel, Info);
973 }
974 
975 void ForwardingDiagnosticConsumer::clear() {
976   DiagnosticConsumer::clear();
977   Target.clear();
978 }
979 
980 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
981   return Target.IncludeInDiagnosticCounts();
982 }
983 
984 PartialDiagnostic::StorageAllocator::StorageAllocator() {
985   for (unsigned I = 0; I != NumCached; ++I)
986     FreeList[I] = Cached + I;
987   NumFreeListEntries = NumCached;
988 }
989 
990 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
991   // Don't assert if we are in a CrashRecovery context, as this invariant may
992   // be invalidated during a crash.
993   assert((NumFreeListEntries == NumCached ||
994           llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
995          "A partial is on the lamb");
996 }
997