Diagnostic.cpp revision 27b0f510d1d4f9ed5668eec1195f04b4a74a4426
1//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTDiagnostic.h"
15#include "clang/Analysis/AnalysisDiagnostic.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/FileManager.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/Driver/DriverDiagnostic.h"
23#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Lex/LexDiagnostic.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Sema/SemaDiagnostic.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
31
32#include <vector>
33#include <map>
34#include <cstring>
35using namespace clang;
36
37//===----------------------------------------------------------------------===//
38// Builtin Diagnostic information
39//===----------------------------------------------------------------------===//
40
41// Diagnostic classes.
42enum {
43  CLASS_NOTE       = 0x01,
44  CLASS_WARNING    = 0x02,
45  CLASS_EXTENSION  = 0x03,
46  CLASS_ERROR      = 0x04
47};
48
49struct StaticDiagInfoRec {
50  unsigned short DiagID;
51  unsigned Mapping : 3;
52  unsigned Class : 3;
53  bool SFINAE : 1;
54  unsigned Category : 5;
55
56  const char *Description;
57  const char *OptionGroup;
58
59  bool operator<(const StaticDiagInfoRec &RHS) const {
60    return DiagID < RHS.DiagID;
61  }
62  bool operator>(const StaticDiagInfoRec &RHS) const {
63    return DiagID > RHS.DiagID;
64  }
65};
66
67static const StaticDiagInfoRec StaticDiagInfo[] = {
68#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY)    \
69  { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP },
70#include "clang/Basic/DiagnosticCommonKinds.inc"
71#include "clang/Basic/DiagnosticDriverKinds.inc"
72#include "clang/Basic/DiagnosticFrontendKinds.inc"
73#include "clang/Basic/DiagnosticLexKinds.inc"
74#include "clang/Basic/DiagnosticParseKinds.inc"
75#include "clang/Basic/DiagnosticASTKinds.inc"
76#include "clang/Basic/DiagnosticSemaKinds.inc"
77#include "clang/Basic/DiagnosticAnalysisKinds.inc"
78  { 0, 0, 0, 0, 0, 0, 0}
79};
80#undef DIAG
81
82/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
83/// or null if the ID is invalid.
84static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
85  unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
86
87  // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
88#ifndef NDEBUG
89  static bool IsFirst = true;
90  if (IsFirst) {
91    for (unsigned i = 1; i != NumDiagEntries; ++i) {
92      assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
93             "Diag ID conflict, the enums at the start of clang::diag (in "
94             "Diagnostic.h) probably need to be increased");
95
96      assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
97             "Improperly sorted diag info");
98    }
99    IsFirst = false;
100  }
101#endif
102
103  // Search the diagnostic table with a binary search.
104  StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 };
105
106  const StaticDiagInfoRec *Found =
107    std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
108  if (Found == StaticDiagInfo + NumDiagEntries ||
109      Found->DiagID != DiagID)
110    return 0;
111
112  return Found;
113}
114
115static unsigned GetDefaultDiagMapping(unsigned DiagID) {
116  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
117    return Info->Mapping;
118  return diag::MAP_FATAL;
119}
120
121/// getWarningOptionForDiag - Return the lowest-level warning option that
122/// enables the specified diagnostic.  If there is no -Wfoo flag that controls
123/// the diagnostic, this returns null.
124const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
125  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
126    return Info->OptionGroup;
127  return 0;
128}
129
130Diagnostic::SFINAEResponse
131Diagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) {
132  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) {
133    if (!Info->SFINAE)
134      return SFINAE_Report;
135
136    if (Info->Class == CLASS_ERROR)
137      return SFINAE_SubstitutionFailure;
138
139    // Suppress notes, warnings, and extensions;
140    return SFINAE_Suppress;
141  }
142
143  return SFINAE_Report;
144}
145
146/// getDiagClass - Return the class field of the diagnostic.
147///
148static unsigned getBuiltinDiagClass(unsigned DiagID) {
149  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
150    return Info->Class;
151  return ~0U;
152}
153
154//===----------------------------------------------------------------------===//
155// Custom Diagnostic information
156//===----------------------------------------------------------------------===//
157
158namespace clang {
159  namespace diag {
160    class CustomDiagInfo {
161      typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
162      std::vector<DiagDesc> DiagInfo;
163      std::map<DiagDesc, unsigned> DiagIDs;
164    public:
165
166      /// getDescription - Return the description of the specified custom
167      /// diagnostic.
168      const char *getDescription(unsigned DiagID) const {
169        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
170               "Invalid diagnosic ID");
171        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
172      }
173
174      /// getLevel - Return the level of the specified custom diagnostic.
175      Diagnostic::Level getLevel(unsigned DiagID) const {
176        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
177               "Invalid diagnosic ID");
178        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
179      }
180
181      unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
182                                 Diagnostic &Diags) {
183        DiagDesc D(L, Message);
184        // Check to see if it already exists.
185        std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
186        if (I != DiagIDs.end() && I->first == D)
187          return I->second;
188
189        // If not, assign a new ID.
190        unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
191        DiagIDs.insert(std::make_pair(D, ID));
192        DiagInfo.push_back(D);
193        return ID;
194      }
195    };
196
197  } // end diag namespace
198} // end clang namespace
199
200
201//===----------------------------------------------------------------------===//
202// Common Diagnostic implementation
203//===----------------------------------------------------------------------===//
204
205static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
206                               const char *Modifier, unsigned ML,
207                               const char *Argument, unsigned ArgLen,
208                               const Diagnostic::ArgumentValue *PrevArgs,
209                               unsigned NumPrevArgs,
210                               llvm::SmallVectorImpl<char> &Output,
211                               void *Cookie) {
212  const char *Str = "<can't format argument>";
213  Output.append(Str, Str+strlen(Str));
214}
215
216
217Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
218  AllExtensionsSilenced = 0;
219  IgnoreAllWarnings = false;
220  WarningsAsErrors = false;
221  ErrorsAsFatal = false;
222  SuppressSystemWarnings = false;
223  SuppressAllDiagnostics = false;
224  ExtBehavior = Ext_Ignore;
225
226  ErrorOccurred = false;
227  FatalErrorOccurred = false;
228  ErrorLimit = 0;
229  TemplateBacktraceLimit = 0;
230
231  NumWarnings = 0;
232  NumErrors = 0;
233  NumErrorsSuppressed = 0;
234  CustomDiagInfo = 0;
235  CurDiagID = ~0U;
236  LastDiagLevel = Ignored;
237
238  ArgToStringFn = DummyArgToStringFn;
239  ArgToStringCookie = 0;
240
241  DelayedDiagID = 0;
242
243  // Set all mappings to 'unset'.
244  DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
245  DiagMappingsStack.push_back(BlankDiags);
246}
247
248Diagnostic::~Diagnostic() {
249  delete CustomDiagInfo;
250}
251
252
253void Diagnostic::pushMappings() {
254  // Avoids undefined behavior when the stack has to resize.
255  DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
256  DiagMappingsStack.push_back(DiagMappingsStack.back());
257}
258
259bool Diagnostic::popMappings() {
260  if (DiagMappingsStack.size() == 1)
261    return false;
262
263  DiagMappingsStack.pop_back();
264  return true;
265}
266
267/// getCustomDiagID - Return an ID for a diagnostic with the specified message
268/// and level.  If this is the first request for this diagnosic, it is
269/// registered and created, otherwise the existing ID is returned.
270unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
271  if (CustomDiagInfo == 0)
272    CustomDiagInfo = new diag::CustomDiagInfo();
273  return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
274}
275
276
277/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
278/// level of the specified diagnostic ID is a Warning or Extension.
279/// This only works on builtin diagnostics, not custom ones, and is not legal to
280/// call on NOTEs.
281bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
282  return DiagID < diag::DIAG_UPPER_LIMIT &&
283         getBuiltinDiagClass(DiagID) != CLASS_ERROR;
284}
285
286/// \brief Determine whether the given built-in diagnostic ID is a
287/// Note.
288bool Diagnostic::isBuiltinNote(unsigned DiagID) {
289  return DiagID < diag::DIAG_UPPER_LIMIT &&
290    getBuiltinDiagClass(DiagID) == CLASS_NOTE;
291}
292
293/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
294/// ID is for an extension of some sort.  This also returns EnabledByDefault,
295/// which is set to indicate whether the diagnostic is ignored by default (in
296/// which case -pedantic enables it) or treated as a warning/error by default.
297///
298bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID,
299                                        bool &EnabledByDefault) {
300  if (DiagID >= diag::DIAG_UPPER_LIMIT ||
301      getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
302    return false;
303
304  EnabledByDefault = StaticDiagInfo[DiagID].Mapping != diag::MAP_IGNORE;
305  return true;
306}
307
308
309/// getDescription - Given a diagnostic ID, return a description of the
310/// issue.
311const char *Diagnostic::getDescription(unsigned DiagID) const {
312  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
313    return Info->Description;
314  return CustomDiagInfo->getDescription(DiagID);
315}
316
317void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
318                                      llvm::StringRef Arg2) {
319  if (DelayedDiagID)
320    return;
321
322  DelayedDiagID = DiagID;
323  DelayedDiagArg1 = Arg1.str();
324  DelayedDiagArg2 = Arg2.str();
325}
326
327void Diagnostic::ReportDelayed() {
328  Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
329  DelayedDiagID = 0;
330  DelayedDiagArg1.clear();
331  DelayedDiagArg2.clear();
332}
333
334/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
335/// object, classify the specified diagnostic ID into a Level, consumable by
336/// the DiagnosticClient.
337Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
338  // Handle custom diagnostics, which cannot be mapped.
339  if (DiagID >= diag::DIAG_UPPER_LIMIT)
340    return CustomDiagInfo->getLevel(DiagID);
341
342  unsigned DiagClass = getBuiltinDiagClass(DiagID);
343  assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
344  return getDiagnosticLevel(DiagID, DiagClass);
345}
346
347/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
348/// object, classify the specified diagnostic ID into a Level, consumable by
349/// the DiagnosticClient.
350Diagnostic::Level
351Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
352  // Specific non-error diagnostics may be mapped to various levels from ignored
353  // to error.  Errors can only be mapped to fatal.
354  Diagnostic::Level Result = Diagnostic::Fatal;
355
356  // Get the mapping information, if unset, compute it lazily.
357  unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
358  if (MappingInfo == 0) {
359    MappingInfo = GetDefaultDiagMapping(DiagID);
360    setDiagnosticMappingInternal(DiagID, MappingInfo, false);
361  }
362
363  switch (MappingInfo & 7) {
364  default: assert(0 && "Unknown mapping!");
365  case diag::MAP_IGNORE:
366    // Ignore this, unless this is an extension diagnostic and we're mapping
367    // them onto warnings or errors.
368    if (!isBuiltinExtensionDiag(DiagID) ||  // Not an extension
369        ExtBehavior == Ext_Ignore ||        // Extensions ignored anyway
370        (MappingInfo & 8) != 0)             // User explicitly mapped it.
371      return Diagnostic::Ignored;
372    Result = Diagnostic::Warning;
373    if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
374    if (Result == Diagnostic::Error && ErrorsAsFatal)
375      Result = Diagnostic::Fatal;
376    break;
377  case diag::MAP_ERROR:
378    Result = Diagnostic::Error;
379    if (ErrorsAsFatal)
380      Result = Diagnostic::Fatal;
381    break;
382  case diag::MAP_FATAL:
383    Result = Diagnostic::Fatal;
384    break;
385  case diag::MAP_WARNING:
386    // If warnings are globally mapped to ignore or error, do it.
387    if (IgnoreAllWarnings)
388      return Diagnostic::Ignored;
389
390    Result = Diagnostic::Warning;
391
392    // If this is an extension diagnostic and we're in -pedantic-error mode, and
393    // if the user didn't explicitly map it, upgrade to an error.
394    if (ExtBehavior == Ext_Error &&
395        (MappingInfo & 8) == 0 &&
396        isBuiltinExtensionDiag(DiagID))
397      Result = Diagnostic::Error;
398
399    if (WarningsAsErrors)
400      Result = Diagnostic::Error;
401    if (Result == Diagnostic::Error && ErrorsAsFatal)
402      Result = Diagnostic::Fatal;
403    break;
404
405  case diag::MAP_WARNING_NO_WERROR:
406    // Diagnostics specified with -Wno-error=foo should be set to warnings, but
407    // not be adjusted by -Werror or -pedantic-errors.
408    Result = Diagnostic::Warning;
409
410    // If warnings are globally mapped to ignore or error, do it.
411    if (IgnoreAllWarnings)
412      return Diagnostic::Ignored;
413
414    break;
415
416  case diag::MAP_ERROR_NO_WFATAL:
417    // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
418    // unaffected by -Wfatal-errors.
419    Result = Diagnostic::Error;
420    break;
421  }
422
423  // Okay, we're about to return this as a "diagnostic to emit" one last check:
424  // if this is any sort of extension warning, and if we're in an __extension__
425  // block, silence it.
426  if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
427    return Diagnostic::Ignored;
428
429  return Result;
430}
431
432struct WarningOption {
433  const char  *Name;
434  const short *Members;
435  const char  *SubGroups;
436};
437
438#define GET_DIAG_ARRAYS
439#include "clang/Basic/DiagnosticGroups.inc"
440#undef GET_DIAG_ARRAYS
441
442// Second the table of options, sorted by name for fast binary lookup.
443static const WarningOption OptionTable[] = {
444#define GET_DIAG_TABLE
445#include "clang/Basic/DiagnosticGroups.inc"
446#undef GET_DIAG_TABLE
447};
448static const size_t OptionTableSize =
449sizeof(OptionTable) / sizeof(OptionTable[0]);
450
451static bool WarningOptionCompare(const WarningOption &LHS,
452                                 const WarningOption &RHS) {
453  return strcmp(LHS.Name, RHS.Name) < 0;
454}
455
456static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
457                            Diagnostic &Diags) {
458  // Option exists, poke all the members of its diagnostic set.
459  if (const short *Member = Group->Members) {
460    for (; *Member != -1; ++Member)
461      Diags.setDiagnosticMapping(*Member, Mapping);
462  }
463
464  // Enable/disable all subgroups along with this one.
465  if (const char *SubGroups = Group->SubGroups) {
466    for (; *SubGroups != (char)-1; ++SubGroups)
467      MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
468  }
469}
470
471/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
472/// "unknown-pragmas" to have the specified mapping.  This returns true and
473/// ignores the request if "Group" was unknown, false otherwise.
474bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
475                                           diag::Mapping Map) {
476
477  WarningOption Key = { Group, 0, 0 };
478  const WarningOption *Found =
479  std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
480                   WarningOptionCompare);
481  if (Found == OptionTable + OptionTableSize ||
482      strcmp(Found->Name, Group) != 0)
483    return true;  // Option not found.
484
485  MapGroupMembers(Found, Map, *this);
486  return false;
487}
488
489
490/// ProcessDiag - This is the method used to report a diagnostic that is
491/// finally fully formed.
492bool Diagnostic::ProcessDiag() {
493  DiagnosticInfo Info(this);
494
495  if (SuppressAllDiagnostics)
496    return false;
497
498  // Figure out the diagnostic level of this message.
499  Diagnostic::Level DiagLevel;
500  unsigned DiagID = Info.getID();
501
502  // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
503  // in a system header.
504  bool ShouldEmitInSystemHeader;
505
506  if (DiagID >= diag::DIAG_UPPER_LIMIT) {
507    // Handle custom diagnostics, which cannot be mapped.
508    DiagLevel = CustomDiagInfo->getLevel(DiagID);
509
510    // Custom diagnostics always are emitted in system headers.
511    ShouldEmitInSystemHeader = true;
512  } else {
513    // Get the class of the diagnostic.  If this is a NOTE, map it onto whatever
514    // the diagnostic level was for the previous diagnostic so that it is
515    // filtered the same as the previous diagnostic.
516    unsigned DiagClass = getBuiltinDiagClass(DiagID);
517    if (DiagClass == CLASS_NOTE) {
518      DiagLevel = Diagnostic::Note;
519      ShouldEmitInSystemHeader = false;  // extra consideration is needed
520    } else {
521      // If this is not an error and we are in a system header, we ignore it.
522      // Check the original Diag ID here, because we also want to ignore
523      // extensions and warnings in -Werror and -pedantic-errors modes, which
524      // *map* warnings/extensions to errors.
525      ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
526
527      DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
528    }
529  }
530
531  if (DiagLevel != Diagnostic::Note) {
532    // Record that a fatal error occurred only when we see a second
533    // non-note diagnostic. This allows notes to be attached to the
534    // fatal error, but suppresses any diagnostics that follow those
535    // notes.
536    if (LastDiagLevel == Diagnostic::Fatal)
537      FatalErrorOccurred = true;
538
539    LastDiagLevel = DiagLevel;
540  }
541
542  // If a fatal error has already been emitted, silence all subsequent
543  // diagnostics.
544  if (FatalErrorOccurred) {
545    if (DiagLevel >= Diagnostic::Error) {
546      ++NumErrors;
547      ++NumErrorsSuppressed;
548    }
549
550    return false;
551  }
552
553  // If the client doesn't care about this message, don't issue it.  If this is
554  // a note and the last real diagnostic was ignored, ignore it too.
555  if (DiagLevel == Diagnostic::Ignored ||
556      (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
557    return false;
558
559  // If this diagnostic is in a system header and is not a clang error, suppress
560  // it.
561  if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
562      Info.getLocation().isValid() &&
563      Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
564      (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
565    LastDiagLevel = Diagnostic::Ignored;
566    return false;
567  }
568
569  if (DiagLevel >= Diagnostic::Error) {
570    ErrorOccurred = true;
571    ++NumErrors;
572
573    // If we've emitted a lot of errors, emit a fatal error after it to stop a
574    // flood of bogus errors.
575    if (ErrorLimit && NumErrors >= ErrorLimit &&
576        DiagLevel == Diagnostic::Error)
577      SetDelayedDiagnostic(diag::fatal_too_many_errors);
578  }
579
580  // Finally, report it.
581  Client->HandleDiagnostic(DiagLevel, Info);
582  if (Client->IncludeInDiagnosticCounts()) {
583    if (DiagLevel == Diagnostic::Warning)
584      ++NumWarnings;
585  }
586
587  CurDiagID = ~0U;
588
589  return true;
590}
591
592bool DiagnosticBuilder::Emit() {
593  // If DiagObj is null, then its soul was stolen by the copy ctor
594  // or the user called Emit().
595  if (DiagObj == 0) return false;
596
597  // When emitting diagnostics, we set the final argument count into
598  // the Diagnostic object.
599  DiagObj->NumDiagArgs = NumArgs;
600  DiagObj->NumDiagRanges = NumRanges;
601  DiagObj->NumFixItHints = NumFixItHints;
602
603  // Process the diagnostic, sending the accumulated information to the
604  // DiagnosticClient.
605  bool Emitted = DiagObj->ProcessDiag();
606
607  // Clear out the current diagnostic object.
608  unsigned DiagID = DiagObj->CurDiagID;
609  DiagObj->Clear();
610
611  // If there was a delayed diagnostic, emit it now.
612  if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
613    DiagObj->ReportDelayed();
614
615  // This diagnostic is dead.
616  DiagObj = 0;
617
618  return Emitted;
619}
620
621
622DiagnosticClient::~DiagnosticClient() {}
623
624
625/// ModifierIs - Return true if the specified modifier matches specified string.
626template <std::size_t StrLen>
627static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
628                       const char (&Str)[StrLen]) {
629  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
630}
631
632/// ScanForward - Scans forward, looking for the given character, skipping
633/// nested clauses and escaped characters.
634static const char *ScanFormat(const char *I, const char *E, char Target) {
635  unsigned Depth = 0;
636
637  for ( ; I != E; ++I) {
638    if (Depth == 0 && *I == Target) return I;
639    if (Depth != 0 && *I == '}') Depth--;
640
641    if (*I == '%') {
642      I++;
643      if (I == E) break;
644
645      // Escaped characters get implicitly skipped here.
646
647      // Format specifier.
648      if (!isdigit(*I) && !ispunct(*I)) {
649        for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
650        if (I == E) break;
651        if (*I == '{')
652          Depth++;
653      }
654    }
655  }
656  return E;
657}
658
659/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
660/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
661/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
662/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
663/// This is very useful for certain classes of variant diagnostics.
664static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
665                                 const char *Argument, unsigned ArgumentLen,
666                                 llvm::SmallVectorImpl<char> &OutStr) {
667  const char *ArgumentEnd = Argument+ArgumentLen;
668
669  // Skip over 'ValNo' |'s.
670  while (ValNo) {
671    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
672    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
673           " larger than the number of options in the diagnostic string!");
674    Argument = NextVal+1;  // Skip this string.
675    --ValNo;
676  }
677
678  // Get the end of the value.  This is either the } or the |.
679  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
680
681  // Recursively format the result of the select clause into the output string.
682  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
683}
684
685/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
686/// letter 's' to the string if the value is not 1.  This is used in cases like
687/// this:  "you idiot, you have %4 parameter%s4!".
688static void HandleIntegerSModifier(unsigned ValNo,
689                                   llvm::SmallVectorImpl<char> &OutStr) {
690  if (ValNo != 1)
691    OutStr.push_back('s');
692}
693
694/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
695/// prints the ordinal form of the given integer, with 1 corresponding
696/// to the first ordinal.  Currently this is hard-coded to use the
697/// English form.
698static void HandleOrdinalModifier(unsigned ValNo,
699                                  llvm::SmallVectorImpl<char> &OutStr) {
700  assert(ValNo != 0 && "ValNo must be strictly positive!");
701
702  llvm::raw_svector_ostream Out(OutStr);
703
704  // We could use text forms for the first N ordinals, but the numeric
705  // forms are actually nicer in diagnostics because they stand out.
706  Out << ValNo;
707
708  // It is critically important that we do this perfectly for
709  // user-written sequences with over 100 elements.
710  switch (ValNo % 100) {
711  case 11:
712  case 12:
713  case 13:
714    Out << "th"; return;
715  default:
716    switch (ValNo % 10) {
717    case 1: Out << "st"; return;
718    case 2: Out << "nd"; return;
719    case 3: Out << "rd"; return;
720    default: Out << "th"; return;
721    }
722  }
723}
724
725
726/// PluralNumber - Parse an unsigned integer and advance Start.
727static unsigned PluralNumber(const char *&Start, const char *End) {
728  // Programming 101: Parse a decimal number :-)
729  unsigned Val = 0;
730  while (Start != End && *Start >= '0' && *Start <= '9') {
731    Val *= 10;
732    Val += *Start - '0';
733    ++Start;
734  }
735  return Val;
736}
737
738/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
739static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
740  if (*Start != '[') {
741    unsigned Ref = PluralNumber(Start, End);
742    return Ref == Val;
743  }
744
745  ++Start;
746  unsigned Low = PluralNumber(Start, End);
747  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
748  ++Start;
749  unsigned High = PluralNumber(Start, End);
750  assert(*Start == ']' && "Bad plural expression syntax: expected )");
751  ++Start;
752  return Low <= Val && Val <= High;
753}
754
755/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
756static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
757  // Empty condition?
758  if (*Start == ':')
759    return true;
760
761  while (1) {
762    char C = *Start;
763    if (C == '%') {
764      // Modulo expression
765      ++Start;
766      unsigned Arg = PluralNumber(Start, End);
767      assert(*Start == '=' && "Bad plural expression syntax: expected =");
768      ++Start;
769      unsigned ValMod = ValNo % Arg;
770      if (TestPluralRange(ValMod, Start, End))
771        return true;
772    } else {
773      assert((C == '[' || (C >= '0' && C <= '9')) &&
774             "Bad plural expression syntax: unexpected character");
775      // Range expression
776      if (TestPluralRange(ValNo, Start, End))
777        return true;
778    }
779
780    // Scan for next or-expr part.
781    Start = std::find(Start, End, ',');
782    if (Start == End)
783      break;
784    ++Start;
785  }
786  return false;
787}
788
789/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
790/// for complex plural forms, or in languages where all plurals are complex.
791/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
792/// conditions that are tested in order, the form corresponding to the first
793/// that applies being emitted. The empty condition is always true, making the
794/// last form a default case.
795/// Conditions are simple boolean expressions, where n is the number argument.
796/// Here are the rules.
797/// condition  := expression | empty
798/// empty      :=                             -> always true
799/// expression := numeric [',' expression]    -> logical or
800/// numeric    := range                       -> true if n in range
801///             | '%' number '=' range        -> true if n % number in range
802/// range      := number
803///             | '[' number ',' number ']'   -> ranges are inclusive both ends
804///
805/// Here are some examples from the GNU gettext manual written in this form:
806/// English:
807/// {1:form0|:form1}
808/// Latvian:
809/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
810/// Gaeilge:
811/// {1:form0|2:form1|:form2}
812/// Romanian:
813/// {1:form0|0,%100=[1,19]:form1|:form2}
814/// Lithuanian:
815/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
816/// Russian (requires repeated form):
817/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
818/// Slovak
819/// {1:form0|[2,4]:form1|:form2}
820/// Polish (requires repeated form):
821/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
822static void HandlePluralModifier(unsigned ValNo,
823                                 const char *Argument, unsigned ArgumentLen,
824                                 llvm::SmallVectorImpl<char> &OutStr) {
825  const char *ArgumentEnd = Argument + ArgumentLen;
826  while (1) {
827    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
828    const char *ExprEnd = Argument;
829    while (*ExprEnd != ':') {
830      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
831      ++ExprEnd;
832    }
833    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
834      Argument = ExprEnd + 1;
835      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
836      OutStr.append(Argument, ExprEnd);
837      return;
838    }
839    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
840  }
841}
842
843
844/// FormatDiagnostic - Format this diagnostic into a string, substituting the
845/// formal arguments into the %0 slots.  The result is appended onto the Str
846/// array.
847void DiagnosticInfo::
848FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
849  const char *DiagStr = getDiags()->getDescription(getID());
850  const char *DiagEnd = DiagStr+strlen(DiagStr);
851
852  FormatDiagnostic(DiagStr, DiagEnd, OutStr);
853}
854
855void DiagnosticInfo::
856FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
857                 llvm::SmallVectorImpl<char> &OutStr) const {
858
859  /// FormattedArgs - Keep track of all of the arguments formatted by
860  /// ConvertArgToString and pass them into subsequent calls to
861  /// ConvertArgToString, allowing the implementation to avoid redundancies in
862  /// obvious cases.
863  llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
864
865  while (DiagStr != DiagEnd) {
866    if (DiagStr[0] != '%') {
867      // Append non-%0 substrings to Str if we have one.
868      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
869      OutStr.append(DiagStr, StrEnd);
870      DiagStr = StrEnd;
871      continue;
872    } else if (ispunct(DiagStr[1])) {
873      OutStr.push_back(DiagStr[1]);  // %% -> %.
874      DiagStr += 2;
875      continue;
876    }
877
878    // Skip the %.
879    ++DiagStr;
880
881    // This must be a placeholder for a diagnostic argument.  The format for a
882    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
883    // The digit is a number from 0-9 indicating which argument this comes from.
884    // The modifier is a string of digits from the set [-a-z]+, arguments is a
885    // brace enclosed string.
886    const char *Modifier = 0, *Argument = 0;
887    unsigned ModifierLen = 0, ArgumentLen = 0;
888
889    // Check to see if we have a modifier.  If so eat it.
890    if (!isdigit(DiagStr[0])) {
891      Modifier = DiagStr;
892      while (DiagStr[0] == '-' ||
893             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
894        ++DiagStr;
895      ModifierLen = DiagStr-Modifier;
896
897      // If we have an argument, get it next.
898      if (DiagStr[0] == '{') {
899        ++DiagStr; // Skip {.
900        Argument = DiagStr;
901
902        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
903        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
904        ArgumentLen = DiagStr-Argument;
905        ++DiagStr;  // Skip }.
906      }
907    }
908
909    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
910    unsigned ArgNo = *DiagStr++ - '0';
911
912    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
913
914    switch (Kind) {
915    // ---- STRINGS ----
916    case Diagnostic::ak_std_string: {
917      const std::string &S = getArgStdStr(ArgNo);
918      assert(ModifierLen == 0 && "No modifiers for strings yet");
919      OutStr.append(S.begin(), S.end());
920      break;
921    }
922    case Diagnostic::ak_c_string: {
923      const char *S = getArgCStr(ArgNo);
924      assert(ModifierLen == 0 && "No modifiers for strings yet");
925
926      // Don't crash if get passed a null pointer by accident.
927      if (!S)
928        S = "(null)";
929
930      OutStr.append(S, S + strlen(S));
931      break;
932    }
933    // ---- INTEGERS ----
934    case Diagnostic::ak_sint: {
935      int Val = getArgSInt(ArgNo);
936
937      if (ModifierIs(Modifier, ModifierLen, "select")) {
938        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
939      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
940        HandleIntegerSModifier(Val, OutStr);
941      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
942        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
943      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
944        HandleOrdinalModifier((unsigned)Val, OutStr);
945      } else {
946        assert(ModifierLen == 0 && "Unknown integer modifier");
947        llvm::raw_svector_ostream(OutStr) << Val;
948      }
949      break;
950    }
951    case Diagnostic::ak_uint: {
952      unsigned Val = getArgUInt(ArgNo);
953
954      if (ModifierIs(Modifier, ModifierLen, "select")) {
955        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
956      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
957        HandleIntegerSModifier(Val, OutStr);
958      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
959        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
960      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
961        HandleOrdinalModifier(Val, OutStr);
962      } else {
963        assert(ModifierLen == 0 && "Unknown integer modifier");
964        llvm::raw_svector_ostream(OutStr) << Val;
965      }
966      break;
967    }
968    // ---- NAMES and TYPES ----
969    case Diagnostic::ak_identifierinfo: {
970      const IdentifierInfo *II = getArgIdentifier(ArgNo);
971      assert(ModifierLen == 0 && "No modifiers for strings yet");
972
973      // Don't crash if get passed a null pointer by accident.
974      if (!II) {
975        const char *S = "(null)";
976        OutStr.append(S, S + strlen(S));
977        continue;
978      }
979
980      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
981      break;
982    }
983    case Diagnostic::ak_qualtype:
984    case Diagnostic::ak_declarationname:
985    case Diagnostic::ak_nameddecl:
986    case Diagnostic::ak_nestednamespec:
987    case Diagnostic::ak_declcontext:
988      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
989                                     Modifier, ModifierLen,
990                                     Argument, ArgumentLen,
991                                     FormattedArgs.data(), FormattedArgs.size(),
992                                     OutStr);
993      break;
994    }
995
996    // Remember this argument info for subsequent formatting operations.  Turn
997    // std::strings into a null terminated string to make it be the same case as
998    // all the other ones.
999    if (Kind != Diagnostic::ak_std_string)
1000      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1001    else
1002      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1003                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
1004
1005  }
1006}
1007
1008StoredDiagnostic::StoredDiagnostic() { }
1009
1010StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1011                                   llvm::StringRef Message)
1012  : Level(Level), Loc(), Message(Message) { }
1013
1014StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1015                                   const DiagnosticInfo &Info)
1016  : Level(Level), Loc(Info.getLocation())
1017{
1018  llvm::SmallString<64> Message;
1019  Info.FormatDiagnostic(Message);
1020  this->Message.assign(Message.begin(), Message.end());
1021
1022  Ranges.reserve(Info.getNumRanges());
1023  for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
1024    Ranges.push_back(Info.getRange(I));
1025
1026  FixIts.reserve(Info.getNumFixItHints());
1027  for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
1028    FixIts.push_back(Info.getFixItHint(I));
1029}
1030
1031StoredDiagnostic::~StoredDiagnostic() { }
1032
1033static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1034  OS.write((const char *)&Value, sizeof(unsigned));
1035}
1036
1037static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1038  WriteUnsigned(OS, String.size());
1039  OS.write(String.data(), String.size());
1040}
1041
1042static void WriteSourceLocation(llvm::raw_ostream &OS,
1043                                SourceManager *SM,
1044                                SourceLocation Location) {
1045  if (!SM || Location.isInvalid()) {
1046    // If we don't have a source manager or this location is invalid,
1047    // just write an invalid location.
1048    WriteUnsigned(OS, 0);
1049    WriteUnsigned(OS, 0);
1050    WriteUnsigned(OS, 0);
1051    return;
1052  }
1053
1054  Location = SM->getInstantiationLoc(Location);
1055  std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
1056
1057  const FileEntry *FE = SM->getFileEntryForID(Decomposed.first);
1058  if (FE)
1059    WriteString(OS, FE->getName());
1060  else {
1061    // Fallback to using the buffer name when there is no entry.
1062    WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier());
1063  }
1064
1065  WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1066  WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1067}
1068
1069void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
1070  SourceManager *SM = 0;
1071  if (getLocation().isValid())
1072    SM = &const_cast<SourceManager &>(getLocation().getManager());
1073
1074  // Write a short header to help identify diagnostics.
1075  OS << (char)0x06 << (char)0x07;
1076
1077  // Write the diagnostic level and location.
1078  WriteUnsigned(OS, (unsigned)Level);
1079  WriteSourceLocation(OS, SM, getLocation());
1080
1081  // Write the diagnostic message.
1082  llvm::SmallString<64> Message;
1083  WriteString(OS, getMessage());
1084
1085  // Count the number of ranges that don't point into macros, since
1086  // only simple file ranges serialize well.
1087  unsigned NumNonMacroRanges = 0;
1088  for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1089    if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1090      continue;
1091
1092    ++NumNonMacroRanges;
1093  }
1094
1095  // Write the ranges.
1096  WriteUnsigned(OS, NumNonMacroRanges);
1097  if (NumNonMacroRanges) {
1098    for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1099      if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1100        continue;
1101
1102      WriteSourceLocation(OS, SM, R->getBegin());
1103      WriteSourceLocation(OS, SM, R->getEnd());
1104    }
1105  }
1106
1107  // Determine if all of the fix-its involve rewrites with simple file
1108  // locations (not in macro instantiations). If so, we can write
1109  // fix-it information.
1110  unsigned NumFixIts = 0;
1111  for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1112    if (F->RemoveRange.isValid() &&
1113        (F->RemoveRange.getBegin().isMacroID() ||
1114         F->RemoveRange.getEnd().isMacroID())) {
1115      NumFixIts = 0;
1116      break;
1117    }
1118
1119    if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) {
1120      NumFixIts = 0;
1121      break;
1122    }
1123
1124    ++NumFixIts;
1125  }
1126
1127  // Write the fix-its.
1128  WriteUnsigned(OS, NumFixIts);
1129  for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1130    WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1131    WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
1132    WriteSourceLocation(OS, SM, F->InsertionLoc);
1133    WriteString(OS, F->CodeToInsert);
1134  }
1135}
1136
1137static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1138                         unsigned &Value) {
1139  if (Memory + sizeof(unsigned) > MemoryEnd)
1140    return true;
1141
1142  memmove(&Value, Memory, sizeof(unsigned));
1143  Memory += sizeof(unsigned);
1144  return false;
1145}
1146
1147static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1148                               const char *&Memory, const char *MemoryEnd,
1149                               SourceLocation &Location) {
1150  // Read the filename.
1151  unsigned FileNameLen = 0;
1152  if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1153      Memory + FileNameLen > MemoryEnd)
1154    return true;
1155
1156  llvm::StringRef FileName(Memory, FileNameLen);
1157  Memory += FileNameLen;
1158
1159  // Read the line, column.
1160  unsigned Line = 0, Column = 0;
1161  if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1162      ReadUnsigned(Memory, MemoryEnd, Column))
1163    return true;
1164
1165  if (FileName.empty()) {
1166    Location = SourceLocation();
1167    return false;
1168  }
1169
1170  const FileEntry *File = FM.getFile(FileName);
1171  if (!File)
1172    return true;
1173
1174  // Make sure that this file has an entry in the source manager.
1175  if (!SM.hasFileInfo(File))
1176    SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1177
1178  Location = SM.getLocation(File, Line, Column);
1179  return false;
1180}
1181
1182StoredDiagnostic
1183StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1184                              const char *&Memory, const char *MemoryEnd) {
1185  while (true) {
1186    if (Memory == MemoryEnd)
1187      return StoredDiagnostic();
1188
1189    if (*Memory != 0x06) {
1190      ++Memory;
1191      continue;
1192    }
1193
1194    ++Memory;
1195    if (Memory == MemoryEnd)
1196      return StoredDiagnostic();
1197
1198    if (*Memory != 0x07) {
1199      ++Memory;
1200      continue;
1201    }
1202
1203    // We found the header. We're done.
1204    ++Memory;
1205    break;
1206  }
1207
1208  // Read the severity level.
1209  unsigned Level = 0;
1210  if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1211    return StoredDiagnostic();
1212
1213  // Read the source location.
1214  SourceLocation Location;
1215  if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1216    return StoredDiagnostic();
1217
1218  // Read the diagnostic text.
1219  if (Memory == MemoryEnd)
1220    return StoredDiagnostic();
1221
1222  unsigned MessageLen = 0;
1223  if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1224      Memory + MessageLen > MemoryEnd)
1225    return StoredDiagnostic();
1226
1227  llvm::StringRef Message(Memory, MessageLen);
1228  Memory += MessageLen;
1229
1230
1231  // At this point, we have enough information to form a diagnostic. Do so.
1232  StoredDiagnostic Diag;
1233  Diag.Level = (Diagnostic::Level)Level;
1234  Diag.Loc = FullSourceLoc(Location, SM);
1235  Diag.Message = Message;
1236  if (Memory == MemoryEnd)
1237    return Diag;
1238
1239  // Read the source ranges.
1240  unsigned NumSourceRanges = 0;
1241  if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1242    return Diag;
1243  for (unsigned I = 0; I != NumSourceRanges; ++I) {
1244    SourceLocation Begin, End;
1245    if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
1246        ReadSourceLocation(FM, SM, Memory, MemoryEnd, End))
1247      return Diag;
1248
1249    Diag.Ranges.push_back(SourceRange(Begin, End));
1250  }
1251
1252  // Read the fix-it hints.
1253  unsigned NumFixIts = 0;
1254  if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1255    return Diag;
1256  for (unsigned I = 0; I != NumFixIts; ++I) {
1257    SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
1258    unsigned InsertLen = 0;
1259    if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1260        ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
1261        ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
1262        ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1263        Memory + InsertLen > MemoryEnd) {
1264      Diag.FixIts.clear();
1265      return Diag;
1266    }
1267
1268    FixItHint Hint;
1269    Hint.RemoveRange = SourceRange(RemoveBegin, RemoveEnd);
1270    Hint.InsertionLoc = InsertionLoc;
1271    Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1272    Memory += InsertLen;
1273    Diag.FixIts.push_back(Hint);
1274  }
1275
1276  return Diag;
1277}
1278
1279/// IncludeInDiagnosticCounts - This method (whose default implementation
1280///  returns true) indicates whether the diagnostics handled by this
1281///  DiagnosticClient should be included in the number of diagnostics
1282///  reported by Diagnostic.
1283bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
1284
1285PartialDiagnostic::StorageAllocator::StorageAllocator() {
1286  for (unsigned I = 0; I != NumCached; ++I)
1287    FreeList[I] = Cached + I;
1288  NumFreeListEntries = NumCached;
1289}
1290
1291PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1292  assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
1293}
1294