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