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