Diagnostic.cpp revision 9f28614bf1a8387000d8df57a713fcf69e198145
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/IdentifierTable.h"
25#include "clang/Basic/SourceLocation.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/raw_ostream.h"
29#include <vector>
30#include <map>
31#include <cstring>
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Builtin Diagnostic information
36//===----------------------------------------------------------------------===//
37
38// Diagnostic classes.
39enum {
40  CLASS_NOTE       = 0x01,
41  CLASS_WARNING    = 0x02,
42  CLASS_EXTENSION  = 0x03,
43  CLASS_ERROR      = 0x04
44};
45
46struct StaticDiagInfoRec {
47  unsigned short DiagID;
48  unsigned Mapping : 3;
49  unsigned Class : 3;
50  bool SFINAE : 1;
51  const char *Description;
52  const char *OptionGroup;
53
54  bool operator<(const StaticDiagInfoRec &RHS) const {
55    return DiagID < RHS.DiagID;
56  }
57  bool operator>(const StaticDiagInfoRec &RHS) const {
58    return DiagID > RHS.DiagID;
59  }
60};
61
62static const StaticDiagInfoRec StaticDiagInfo[] = {
63#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE)    \
64  { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, DESC, GROUP },
65#include "clang/Basic/DiagnosticCommonKinds.inc"
66#include "clang/Basic/DiagnosticDriverKinds.inc"
67#include "clang/Basic/DiagnosticFrontendKinds.inc"
68#include "clang/Basic/DiagnosticLexKinds.inc"
69#include "clang/Basic/DiagnosticParseKinds.inc"
70#include "clang/Basic/DiagnosticASTKinds.inc"
71#include "clang/Basic/DiagnosticSemaKinds.inc"
72#include "clang/Basic/DiagnosticAnalysisKinds.inc"
73  { 0, 0, 0, 0, 0, 0}
74};
75#undef DIAG
76
77/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
78/// or null if the ID is invalid.
79static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
80  unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
81
82  // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
83#ifndef NDEBUG
84  static bool IsFirst = true;
85  if (IsFirst) {
86    for (unsigned i = 1; i != NumDiagEntries; ++i) {
87      assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
88             "Diag ID conflict, the enums at the start of clang::diag (in "
89             "Diagnostic.h) probably need to be increased");
90
91      assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
92             "Improperly sorted diag info");
93    }
94    IsFirst = false;
95  }
96#endif
97
98  // Search the diagnostic table with a binary search.
99  StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 };
100
101  const StaticDiagInfoRec *Found =
102    std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
103  if (Found == StaticDiagInfo + NumDiagEntries ||
104      Found->DiagID != DiagID)
105    return 0;
106
107  return Found;
108}
109
110static unsigned GetDefaultDiagMapping(unsigned DiagID) {
111  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
112    return Info->Mapping;
113  return diag::MAP_FATAL;
114}
115
116/// getWarningOptionForDiag - Return the lowest-level warning option that
117/// enables the specified diagnostic.  If there is no -Wfoo flag that controls
118/// the diagnostic, this returns null.
119const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
120  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
121    return Info->OptionGroup;
122  return 0;
123}
124
125bool Diagnostic::isBuiltinSFINAEDiag(unsigned DiagID) {
126  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
127    return Info->SFINAE && Info->Class == CLASS_ERROR;
128  return false;
129}
130
131/// getDiagClass - Return the class field of the diagnostic.
132///
133static unsigned getBuiltinDiagClass(unsigned DiagID) {
134  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
135    return Info->Class;
136  return ~0U;
137}
138
139//===----------------------------------------------------------------------===//
140// Custom Diagnostic information
141//===----------------------------------------------------------------------===//
142
143namespace clang {
144  namespace diag {
145    class CustomDiagInfo {
146      typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
147      std::vector<DiagDesc> DiagInfo;
148      std::map<DiagDesc, unsigned> DiagIDs;
149    public:
150
151      /// getDescription - Return the description of the specified custom
152      /// diagnostic.
153      const char *getDescription(unsigned DiagID) const {
154        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
155               "Invalid diagnosic ID");
156        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
157      }
158
159      /// getLevel - Return the level of the specified custom diagnostic.
160      Diagnostic::Level getLevel(unsigned DiagID) const {
161        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
162               "Invalid diagnosic ID");
163        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
164      }
165
166      unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
167                                 Diagnostic &Diags) {
168        DiagDesc D(L, Message);
169        // Check to see if it already exists.
170        std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
171        if (I != DiagIDs.end() && I->first == D)
172          return I->second;
173
174        // If not, assign a new ID.
175        unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
176        DiagIDs.insert(std::make_pair(D, ID));
177        DiagInfo.push_back(D);
178        return ID;
179      }
180    };
181
182  } // end diag namespace
183} // end clang namespace
184
185
186//===----------------------------------------------------------------------===//
187// Common Diagnostic implementation
188//===----------------------------------------------------------------------===//
189
190static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
191                               const char *Modifier, unsigned ML,
192                               const char *Argument, unsigned ArgLen,
193                               const Diagnostic::ArgumentValue *PrevArgs,
194                               unsigned NumPrevArgs,
195                               llvm::SmallVectorImpl<char> &Output,
196                               void *Cookie) {
197  const char *Str = "<can't format argument>";
198  Output.append(Str, Str+strlen(Str));
199}
200
201
202Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
203  AllExtensionsSilenced = 0;
204  IgnoreAllWarnings = false;
205  WarningsAsErrors = false;
206  ErrorsAsFatal = false;
207  SuppressSystemWarnings = false;
208  SuppressAllDiagnostics = false;
209  ExtBehavior = Ext_Ignore;
210
211  ErrorOccurred = false;
212  FatalErrorOccurred = false;
213  NumDiagnostics = 0;
214
215  NumErrors = 0;
216  CustomDiagInfo = 0;
217  CurDiagID = ~0U;
218  LastDiagLevel = Ignored;
219
220  ArgToStringFn = DummyArgToStringFn;
221  ArgToStringCookie = 0;
222
223  // Set all mappings to 'unset'.
224  DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
225  DiagMappingsStack.push_back(BlankDiags);
226}
227
228Diagnostic::~Diagnostic() {
229  delete CustomDiagInfo;
230}
231
232
233void Diagnostic::pushMappings() {
234  // Avoids undefined behavior when the stack has to resize.
235  DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
236  DiagMappingsStack.push_back(DiagMappingsStack.back());
237}
238
239bool Diagnostic::popMappings() {
240  if (DiagMappingsStack.size() == 1)
241    return false;
242
243  DiagMappingsStack.pop_back();
244  return true;
245}
246
247/// getCustomDiagID - Return an ID for a diagnostic with the specified message
248/// and level.  If this is the first request for this diagnosic, it is
249/// registered and created, otherwise the existing ID is returned.
250unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
251  if (CustomDiagInfo == 0)
252    CustomDiagInfo = new diag::CustomDiagInfo();
253  return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
254}
255
256
257/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
258/// level of the specified diagnostic ID is a Warning or Extension.
259/// This only works on builtin diagnostics, not custom ones, and is not legal to
260/// call on NOTEs.
261bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
262  return DiagID < diag::DIAG_UPPER_LIMIT &&
263         getBuiltinDiagClass(DiagID) != CLASS_ERROR;
264}
265
266/// \brief Determine whether the given built-in diagnostic ID is a
267/// Note.
268bool Diagnostic::isBuiltinNote(unsigned DiagID) {
269  return DiagID < diag::DIAG_UPPER_LIMIT &&
270    getBuiltinDiagClass(DiagID) == CLASS_NOTE;
271}
272
273/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
274/// ID is for an extension of some sort.
275///
276bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) {
277  return DiagID < diag::DIAG_UPPER_LIMIT &&
278         getBuiltinDiagClass(DiagID) == CLASS_EXTENSION;
279}
280
281
282/// getDescription - Given a diagnostic ID, return a description of the
283/// issue.
284const char *Diagnostic::getDescription(unsigned DiagID) const {
285  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
286    return Info->Description;
287  return CustomDiagInfo->getDescription(DiagID);
288}
289
290/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
291/// object, classify the specified diagnostic ID into a Level, consumable by
292/// the DiagnosticClient.
293Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
294  // Handle custom diagnostics, which cannot be mapped.
295  if (DiagID >= diag::DIAG_UPPER_LIMIT)
296    return CustomDiagInfo->getLevel(DiagID);
297
298  unsigned DiagClass = getBuiltinDiagClass(DiagID);
299  assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
300  return getDiagnosticLevel(DiagID, DiagClass);
301}
302
303/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
304/// object, classify the specified diagnostic ID into a Level, consumable by
305/// the DiagnosticClient.
306Diagnostic::Level
307Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
308  // Specific non-error diagnostics may be mapped to various levels from ignored
309  // to error.  Errors can only be mapped to fatal.
310  Diagnostic::Level Result = Diagnostic::Fatal;
311
312  // Get the mapping information, if unset, compute it lazily.
313  unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
314  if (MappingInfo == 0) {
315    MappingInfo = GetDefaultDiagMapping(DiagID);
316    setDiagnosticMappingInternal(DiagID, MappingInfo, false);
317  }
318
319  switch (MappingInfo & 7) {
320  default: assert(0 && "Unknown mapping!");
321  case diag::MAP_IGNORE:
322    // Ignore this, unless this is an extension diagnostic and we're mapping
323    // them onto warnings or errors.
324    if (!isBuiltinExtensionDiag(DiagID) ||  // Not an extension
325        ExtBehavior == Ext_Ignore ||        // Extensions ignored anyway
326        (MappingInfo & 8) != 0)             // User explicitly mapped it.
327      return Diagnostic::Ignored;
328    Result = Diagnostic::Warning;
329    if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
330    if (Result == Diagnostic::Error && ErrorsAsFatal)
331      Result = Diagnostic::Fatal;
332    break;
333  case diag::MAP_ERROR:
334    Result = Diagnostic::Error;
335    if (ErrorsAsFatal)
336      Result = Diagnostic::Fatal;
337    break;
338  case diag::MAP_FATAL:
339    Result = Diagnostic::Fatal;
340    break;
341  case diag::MAP_WARNING:
342    // If warnings are globally mapped to ignore or error, do it.
343    if (IgnoreAllWarnings)
344      return Diagnostic::Ignored;
345
346    Result = Diagnostic::Warning;
347
348    // If this is an extension diagnostic and we're in -pedantic-error mode, and
349    // if the user didn't explicitly map it, upgrade to an error.
350    if (ExtBehavior == Ext_Error &&
351        (MappingInfo & 8) == 0 &&
352        isBuiltinExtensionDiag(DiagID))
353      Result = Diagnostic::Error;
354
355    if (WarningsAsErrors)
356      Result = Diagnostic::Error;
357    if (Result == Diagnostic::Error && ErrorsAsFatal)
358      Result = Diagnostic::Fatal;
359    break;
360
361  case diag::MAP_WARNING_NO_WERROR:
362    // Diagnostics specified with -Wno-error=foo should be set to warnings, but
363    // not be adjusted by -Werror or -pedantic-errors.
364    Result = Diagnostic::Warning;
365
366    // If warnings are globally mapped to ignore or error, do it.
367    if (IgnoreAllWarnings)
368      return Diagnostic::Ignored;
369
370    break;
371
372  case diag::MAP_ERROR_NO_WFATAL:
373    // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
374    // unaffected by -Wfatal-errors.
375    Result = Diagnostic::Error;
376    break;
377  }
378
379  // Okay, we're about to return this as a "diagnostic to emit" one last check:
380  // if this is any sort of extension warning, and if we're in an __extension__
381  // block, silence it.
382  if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
383    return Diagnostic::Ignored;
384
385  return Result;
386}
387
388struct WarningOption {
389  const char  *Name;
390  const short *Members;
391  const char  *SubGroups;
392};
393
394#define GET_DIAG_ARRAYS
395#include "clang/Basic/DiagnosticGroups.inc"
396#undef GET_DIAG_ARRAYS
397
398// Second the table of options, sorted by name for fast binary lookup.
399static const WarningOption OptionTable[] = {
400#define GET_DIAG_TABLE
401#include "clang/Basic/DiagnosticGroups.inc"
402#undef GET_DIAG_TABLE
403};
404static const size_t OptionTableSize =
405sizeof(OptionTable) / sizeof(OptionTable[0]);
406
407static bool WarningOptionCompare(const WarningOption &LHS,
408                                 const WarningOption &RHS) {
409  return strcmp(LHS.Name, RHS.Name) < 0;
410}
411
412static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
413                            Diagnostic &Diags) {
414  // Option exists, poke all the members of its diagnostic set.
415  if (const short *Member = Group->Members) {
416    for (; *Member != -1; ++Member)
417      Diags.setDiagnosticMapping(*Member, Mapping);
418  }
419
420  // Enable/disable all subgroups along with this one.
421  if (const char *SubGroups = Group->SubGroups) {
422    for (; *SubGroups != (char)-1; ++SubGroups)
423      MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
424  }
425}
426
427/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
428/// "unknown-pragmas" to have the specified mapping.  This returns true and
429/// ignores the request if "Group" was unknown, false otherwise.
430bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
431                                           diag::Mapping Map) {
432
433  WarningOption Key = { Group, 0, 0 };
434  const WarningOption *Found =
435  std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
436                   WarningOptionCompare);
437  if (Found == OptionTable + OptionTableSize ||
438      strcmp(Found->Name, Group) != 0)
439    return true;  // Option not found.
440
441  MapGroupMembers(Found, Map, *this);
442  return false;
443}
444
445
446/// ProcessDiag - This is the method used to report a diagnostic that is
447/// finally fully formed.
448bool Diagnostic::ProcessDiag() {
449  DiagnosticInfo Info(this);
450
451  if (SuppressAllDiagnostics)
452    return false;
453
454  // Figure out the diagnostic level of this message.
455  Diagnostic::Level DiagLevel;
456  unsigned DiagID = Info.getID();
457
458  // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
459  // in a system header.
460  bool ShouldEmitInSystemHeader;
461
462  if (DiagID >= diag::DIAG_UPPER_LIMIT) {
463    // Handle custom diagnostics, which cannot be mapped.
464    DiagLevel = CustomDiagInfo->getLevel(DiagID);
465
466    // Custom diagnostics always are emitted in system headers.
467    ShouldEmitInSystemHeader = true;
468  } else {
469    // Get the class of the diagnostic.  If this is a NOTE, map it onto whatever
470    // the diagnostic level was for the previous diagnostic so that it is
471    // filtered the same as the previous diagnostic.
472    unsigned DiagClass = getBuiltinDiagClass(DiagID);
473    if (DiagClass == CLASS_NOTE) {
474      DiagLevel = Diagnostic::Note;
475      ShouldEmitInSystemHeader = false;  // extra consideration is needed
476    } else {
477      // If this is not an error and we are in a system header, we ignore it.
478      // Check the original Diag ID here, because we also want to ignore
479      // extensions and warnings in -Werror and -pedantic-errors modes, which
480      // *map* warnings/extensions to errors.
481      ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
482
483      DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
484    }
485  }
486
487  if (DiagLevel != Diagnostic::Note) {
488    // Record that a fatal error occurred only when we see a second
489    // non-note diagnostic. This allows notes to be attached to the
490    // fatal error, but suppresses any diagnostics that follow those
491    // notes.
492    if (LastDiagLevel == Diagnostic::Fatal)
493      FatalErrorOccurred = true;
494
495    LastDiagLevel = DiagLevel;
496  }
497
498  // If a fatal error has already been emitted, silence all subsequent
499  // diagnostics.
500  if (FatalErrorOccurred)
501    return false;
502
503  // If the client doesn't care about this message, don't issue it.  If this is
504  // a note and the last real diagnostic was ignored, ignore it too.
505  if (DiagLevel == Diagnostic::Ignored ||
506      (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
507    return false;
508
509  // If this diagnostic is in a system header and is not a clang error, suppress
510  // it.
511  if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
512      Info.getLocation().isValid() &&
513      Info.getLocation().getSpellingLoc().isInSystemHeader() &&
514      (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
515    LastDiagLevel = Diagnostic::Ignored;
516    return false;
517  }
518
519  if (DiagLevel >= Diagnostic::Error) {
520    ErrorOccurred = true;
521    ++NumErrors;
522  }
523
524  // Finally, report it.
525  Client->HandleDiagnostic(DiagLevel, Info);
526  if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
527
528  CurDiagID = ~0U;
529
530  return true;
531}
532
533
534DiagnosticClient::~DiagnosticClient() {}
535
536
537/// ModifierIs - Return true if the specified modifier matches specified string.
538template <std::size_t StrLen>
539static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
540                       const char (&Str)[StrLen]) {
541  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
542}
543
544/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
545/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
546/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
547/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
548/// This is very useful for certain classes of variant diagnostics.
549static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
550                                 const char *Argument, unsigned ArgumentLen,
551                                 llvm::SmallVectorImpl<char> &OutStr) {
552  const char *ArgumentEnd = Argument+ArgumentLen;
553
554  // Skip over 'ValNo' |'s.
555  while (ValNo) {
556    const char *NextVal = std::find(Argument, ArgumentEnd, '|');
557    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
558           " larger than the number of options in the diagnostic string!");
559    Argument = NextVal+1;  // Skip this string.
560    --ValNo;
561  }
562
563  // Get the end of the value.  This is either the } or the |.
564  const char *EndPtr = std::find(Argument, ArgumentEnd, '|');
565
566  // Recursively format the result of the select clause into the output string.
567  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
568}
569
570/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
571/// letter 's' to the string if the value is not 1.  This is used in cases like
572/// this:  "you idiot, you have %4 parameter%s4!".
573static void HandleIntegerSModifier(unsigned ValNo,
574                                   llvm::SmallVectorImpl<char> &OutStr) {
575  if (ValNo != 1)
576    OutStr.push_back('s');
577}
578
579
580/// PluralNumber - Parse an unsigned integer and advance Start.
581static unsigned PluralNumber(const char *&Start, const char *End) {
582  // Programming 101: Parse a decimal number :-)
583  unsigned Val = 0;
584  while (Start != End && *Start >= '0' && *Start <= '9') {
585    Val *= 10;
586    Val += *Start - '0';
587    ++Start;
588  }
589  return Val;
590}
591
592/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
593static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
594  if (*Start != '[') {
595    unsigned Ref = PluralNumber(Start, End);
596    return Ref == Val;
597  }
598
599  ++Start;
600  unsigned Low = PluralNumber(Start, End);
601  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
602  ++Start;
603  unsigned High = PluralNumber(Start, End);
604  assert(*Start == ']' && "Bad plural expression syntax: expected )");
605  ++Start;
606  return Low <= Val && Val <= High;
607}
608
609/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
610static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
611  // Empty condition?
612  if (*Start == ':')
613    return true;
614
615  while (1) {
616    char C = *Start;
617    if (C == '%') {
618      // Modulo expression
619      ++Start;
620      unsigned Arg = PluralNumber(Start, End);
621      assert(*Start == '=' && "Bad plural expression syntax: expected =");
622      ++Start;
623      unsigned ValMod = ValNo % Arg;
624      if (TestPluralRange(ValMod, Start, End))
625        return true;
626    } else {
627      assert((C == '[' || (C >= '0' && C <= '9')) &&
628             "Bad plural expression syntax: unexpected character");
629      // Range expression
630      if (TestPluralRange(ValNo, Start, End))
631        return true;
632    }
633
634    // Scan for next or-expr part.
635    Start = std::find(Start, End, ',');
636    if (Start == End)
637      break;
638    ++Start;
639  }
640  return false;
641}
642
643/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
644/// for complex plural forms, or in languages where all plurals are complex.
645/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
646/// conditions that are tested in order, the form corresponding to the first
647/// that applies being emitted. The empty condition is always true, making the
648/// last form a default case.
649/// Conditions are simple boolean expressions, where n is the number argument.
650/// Here are the rules.
651/// condition  := expression | empty
652/// empty      :=                             -> always true
653/// expression := numeric [',' expression]    -> logical or
654/// numeric    := range                       -> true if n in range
655///             | '%' number '=' range        -> true if n % number in range
656/// range      := number
657///             | '[' number ',' number ']'   -> ranges are inclusive both ends
658///
659/// Here are some examples from the GNU gettext manual written in this form:
660/// English:
661/// {1:form0|:form1}
662/// Latvian:
663/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
664/// Gaeilge:
665/// {1:form0|2:form1|:form2}
666/// Romanian:
667/// {1:form0|0,%100=[1,19]:form1|:form2}
668/// Lithuanian:
669/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
670/// Russian (requires repeated form):
671/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
672/// Slovak
673/// {1:form0|[2,4]:form1|:form2}
674/// Polish (requires repeated form):
675/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
676static void HandlePluralModifier(unsigned ValNo,
677                                 const char *Argument, unsigned ArgumentLen,
678                                 llvm::SmallVectorImpl<char> &OutStr) {
679  const char *ArgumentEnd = Argument + ArgumentLen;
680  while (1) {
681    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
682    const char *ExprEnd = Argument;
683    while (*ExprEnd != ':') {
684      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
685      ++ExprEnd;
686    }
687    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
688      Argument = ExprEnd + 1;
689      ExprEnd = std::find(Argument, ArgumentEnd, '|');
690      OutStr.append(Argument, ExprEnd);
691      return;
692    }
693    Argument = std::find(Argument, ArgumentEnd - 1, '|') + 1;
694  }
695}
696
697
698/// FormatDiagnostic - Format this diagnostic into a string, substituting the
699/// formal arguments into the %0 slots.  The result is appended onto the Str
700/// array.
701void DiagnosticInfo::
702FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
703  const char *DiagStr = getDiags()->getDescription(getID());
704  const char *DiagEnd = DiagStr+strlen(DiagStr);
705
706  FormatDiagnostic(DiagStr, DiagEnd, OutStr);
707}
708
709void DiagnosticInfo::
710FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
711                 llvm::SmallVectorImpl<char> &OutStr) const {
712
713  /// FormattedArgs - Keep track of all of the arguments formatted by
714  /// ConvertArgToString and pass them into subsequent calls to
715  /// ConvertArgToString, allowing the implementation to avoid redundancies in
716  /// obvious cases.
717  llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
718
719  while (DiagStr != DiagEnd) {
720    if (DiagStr[0] != '%') {
721      // Append non-%0 substrings to Str if we have one.
722      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
723      OutStr.append(DiagStr, StrEnd);
724      DiagStr = StrEnd;
725      continue;
726    } else if (DiagStr[1] == '%') {
727      OutStr.push_back('%');  // %% -> %.
728      DiagStr += 2;
729      continue;
730    }
731
732    // Skip the %.
733    ++DiagStr;
734
735    // This must be a placeholder for a diagnostic argument.  The format for a
736    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
737    // The digit is a number from 0-9 indicating which argument this comes from.
738    // The modifier is a string of digits from the set [-a-z]+, arguments is a
739    // brace enclosed string.
740    const char *Modifier = 0, *Argument = 0;
741    unsigned ModifierLen = 0, ArgumentLen = 0;
742
743    // Check to see if we have a modifier.  If so eat it.
744    if (!isdigit(DiagStr[0])) {
745      Modifier = DiagStr;
746      while (DiagStr[0] == '-' ||
747             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
748        ++DiagStr;
749      ModifierLen = DiagStr-Modifier;
750
751      // If we have an argument, get it next.
752      if (DiagStr[0] == '{') {
753        ++DiagStr; // Skip {.
754        Argument = DiagStr;
755
756        for (; DiagStr[0] != '}'; ++DiagStr)
757          assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!");
758        ArgumentLen = DiagStr-Argument;
759        ++DiagStr;  // Skip }.
760      }
761    }
762
763    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
764    unsigned ArgNo = *DiagStr++ - '0';
765
766    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
767
768    switch (Kind) {
769    // ---- STRINGS ----
770    case Diagnostic::ak_std_string: {
771      const std::string &S = getArgStdStr(ArgNo);
772      assert(ModifierLen == 0 && "No modifiers for strings yet");
773      OutStr.append(S.begin(), S.end());
774      break;
775    }
776    case Diagnostic::ak_c_string: {
777      const char *S = getArgCStr(ArgNo);
778      assert(ModifierLen == 0 && "No modifiers for strings yet");
779
780      // Don't crash if get passed a null pointer by accident.
781      if (!S)
782        S = "(null)";
783
784      OutStr.append(S, S + strlen(S));
785      break;
786    }
787    // ---- INTEGERS ----
788    case Diagnostic::ak_sint: {
789      int Val = getArgSInt(ArgNo);
790
791      if (ModifierIs(Modifier, ModifierLen, "select")) {
792        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
793      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
794        HandleIntegerSModifier(Val, OutStr);
795      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
796        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
797      } else {
798        assert(ModifierLen == 0 && "Unknown integer modifier");
799        llvm::raw_svector_ostream(OutStr) << Val;
800      }
801      break;
802    }
803    case Diagnostic::ak_uint: {
804      unsigned Val = getArgUInt(ArgNo);
805
806      if (ModifierIs(Modifier, ModifierLen, "select")) {
807        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
808      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
809        HandleIntegerSModifier(Val, OutStr);
810      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
811        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
812      } else {
813        assert(ModifierLen == 0 && "Unknown integer modifier");
814        llvm::raw_svector_ostream(OutStr) << Val;
815      }
816      break;
817    }
818    // ---- NAMES and TYPES ----
819    case Diagnostic::ak_identifierinfo: {
820      const IdentifierInfo *II = getArgIdentifier(ArgNo);
821      assert(ModifierLen == 0 && "No modifiers for strings yet");
822
823      // Don't crash if get passed a null pointer by accident.
824      if (!II) {
825        const char *S = "(null)";
826        OutStr.append(S, S + strlen(S));
827        continue;
828      }
829
830      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
831      break;
832    }
833    case Diagnostic::ak_qualtype:
834    case Diagnostic::ak_declarationname:
835    case Diagnostic::ak_nameddecl:
836    case Diagnostic::ak_nestednamespec:
837    case Diagnostic::ak_declcontext:
838      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
839                                     Modifier, ModifierLen,
840                                     Argument, ArgumentLen,
841                                     FormattedArgs.data(), FormattedArgs.size(),
842                                     OutStr);
843      break;
844    }
845
846    // Remember this argument info for subsequent formatting operations.  Turn
847    // std::strings into a null terminated string to make it be the same case as
848    // all the other ones.
849    if (Kind != Diagnostic::ak_std_string)
850      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
851    else
852      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
853                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
854
855  }
856}
857
858/// IncludeInDiagnosticCounts - This method (whose default implementation
859///  returns true) indicates whether the diagnostics handled by this
860///  DiagnosticClient should be included in the number of diagnostics
861///  reported by Diagnostic.
862bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
863