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