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