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