Diagnostic.cpp revision 23e47c6b6e8ccdd8daa378ab2a879644425c72d8
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, const char *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                               llvm::SmallVectorImpl<char> &Output,
194                               void *Cookie) {
195  const char *Str = "<can't format argument>";
196  Output.append(Str, Str+strlen(Str));
197}
198
199
200Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
201  AllExtensionsSilenced = 0;
202  IgnoreAllWarnings = false;
203  WarningsAsErrors = false;
204  SuppressSystemWarnings = false;
205  SuppressAllDiagnostics = false;
206  ExtBehavior = Ext_Ignore;
207
208  ErrorOccurred = false;
209  FatalErrorOccurred = false;
210  NumDiagnostics = 0;
211
212  NumErrors = 0;
213  CustomDiagInfo = 0;
214  CurDiagID = ~0U;
215  LastDiagLevel = Ignored;
216
217  ArgToStringFn = DummyArgToStringFn;
218  ArgToStringCookie = 0;
219
220  // Set all mappings to 'unset'.
221  DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
222  DiagMappingsStack.push_back(BlankDiags);
223}
224
225Diagnostic::~Diagnostic() {
226  delete CustomDiagInfo;
227}
228
229
230void Diagnostic::pushMappings() {
231  DiagMappingsStack.push_back(DiagMappingsStack.back());
232}
233
234bool Diagnostic::popMappings() {
235  if (DiagMappingsStack.size() == 1)
236    return false;
237
238  DiagMappingsStack.pop_back();
239  return true;
240}
241
242/// getCustomDiagID - Return an ID for a diagnostic with the specified message
243/// and level.  If this is the first request for this diagnosic, it is
244/// registered and created, otherwise the existing ID is returned.
245unsigned Diagnostic::getCustomDiagID(Level L, const char *Message) {
246  if (CustomDiagInfo == 0)
247    CustomDiagInfo = new diag::CustomDiagInfo();
248  return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
249}
250
251
252/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
253/// level of the specified diagnostic ID is a Warning or Extension.
254/// This only works on builtin diagnostics, not custom ones, and is not legal to
255/// call on NOTEs.
256bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
257  return DiagID < diag::DIAG_UPPER_LIMIT &&
258         getBuiltinDiagClass(DiagID) != CLASS_ERROR;
259}
260
261/// \brief Determine whether the given built-in diagnostic ID is a
262/// Note.
263bool Diagnostic::isBuiltinNote(unsigned DiagID) {
264  return DiagID < diag::DIAG_UPPER_LIMIT &&
265    getBuiltinDiagClass(DiagID) == CLASS_NOTE;
266}
267
268/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
269/// ID is for an extension of some sort.
270///
271bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) {
272  return DiagID < diag::DIAG_UPPER_LIMIT &&
273         getBuiltinDiagClass(DiagID) == CLASS_EXTENSION;
274}
275
276
277/// getDescription - Given a diagnostic ID, return a description of the
278/// issue.
279const char *Diagnostic::getDescription(unsigned DiagID) const {
280  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
281    return Info->Description;
282  return CustomDiagInfo->getDescription(DiagID);
283}
284
285/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
286/// object, classify the specified diagnostic ID into a Level, consumable by
287/// the DiagnosticClient.
288Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
289  // Handle custom diagnostics, which cannot be mapped.
290  if (DiagID >= diag::DIAG_UPPER_LIMIT)
291    return CustomDiagInfo->getLevel(DiagID);
292
293  unsigned DiagClass = getBuiltinDiagClass(DiagID);
294  assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
295  return getDiagnosticLevel(DiagID, DiagClass);
296}
297
298/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
299/// object, classify the specified diagnostic ID into a Level, consumable by
300/// the DiagnosticClient.
301Diagnostic::Level
302Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
303  // Specific non-error diagnostics may be mapped to various levels from ignored
304  // to error.  Errors can only be mapped to fatal.
305  Diagnostic::Level Result = Diagnostic::Fatal;
306
307  // Get the mapping information, if unset, compute it lazily.
308  unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
309  if (MappingInfo == 0) {
310    MappingInfo = GetDefaultDiagMapping(DiagID);
311    setDiagnosticMappingInternal(DiagID, MappingInfo, false);
312  }
313
314  switch (MappingInfo & 7) {
315  default: assert(0 && "Unknown mapping!");
316  case diag::MAP_IGNORE:
317    // Ignore this, unless this is an extension diagnostic and we're mapping
318    // them onto warnings or errors.
319    if (!isBuiltinExtensionDiag(DiagID) ||  // Not an extension
320        ExtBehavior == Ext_Ignore ||        // Extensions ignored anyway
321        (MappingInfo & 8) != 0)             // User explicitly mapped it.
322      return Diagnostic::Ignored;
323    Result = Diagnostic::Warning;
324    if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
325    break;
326  case diag::MAP_ERROR:
327    Result = Diagnostic::Error;
328    break;
329  case diag::MAP_FATAL:
330    Result = Diagnostic::Fatal;
331    break;
332  case diag::MAP_WARNING:
333    // If warnings are globally mapped to ignore or error, do it.
334    if (IgnoreAllWarnings)
335      return Diagnostic::Ignored;
336
337    Result = Diagnostic::Warning;
338
339    // If this is an extension diagnostic and we're in -pedantic-error mode, and
340    // if the user didn't explicitly map it, upgrade to an error.
341    if (ExtBehavior == Ext_Error &&
342        (MappingInfo & 8) == 0 &&
343        isBuiltinExtensionDiag(DiagID))
344      Result = Diagnostic::Error;
345
346    if (WarningsAsErrors)
347      Result = Diagnostic::Error;
348    break;
349
350  case diag::MAP_WARNING_NO_WERROR:
351    // Diagnostics specified with -Wno-error=foo should be set to warnings, but
352    // not be adjusted by -Werror or -pedantic-errors.
353    Result = Diagnostic::Warning;
354
355    // If warnings are globally mapped to ignore or error, do it.
356    if (IgnoreAllWarnings)
357      return Diagnostic::Ignored;
358
359    break;
360  }
361
362  // Okay, we're about to return this as a "diagnostic to emit" one last check:
363  // if this is any sort of extension warning, and if we're in an __extension__
364  // block, silence it.
365  if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
366    return Diagnostic::Ignored;
367
368  return Result;
369}
370
371struct WarningOption {
372  const char  *Name;
373  const short *Members;
374  const char  *SubGroups;
375};
376
377#define GET_DIAG_ARRAYS
378#include "clang/Basic/DiagnosticGroups.inc"
379#undef GET_DIAG_ARRAYS
380
381// Second the table of options, sorted by name for fast binary lookup.
382static const WarningOption OptionTable[] = {
383#define GET_DIAG_TABLE
384#include "clang/Basic/DiagnosticGroups.inc"
385#undef GET_DIAG_TABLE
386};
387static const size_t OptionTableSize =
388sizeof(OptionTable) / sizeof(OptionTable[0]);
389
390static bool WarningOptionCompare(const WarningOption &LHS,
391                                 const WarningOption &RHS) {
392  return strcmp(LHS.Name, RHS.Name) < 0;
393}
394
395static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
396                            Diagnostic &Diags) {
397  // Option exists, poke all the members of its diagnostic set.
398  if (const short *Member = Group->Members) {
399    for (; *Member != -1; ++Member)
400      Diags.setDiagnosticMapping(*Member, Mapping);
401  }
402
403  // Enable/disable all subgroups along with this one.
404  if (const char *SubGroups = Group->SubGroups) {
405    for (; *SubGroups != (char)-1; ++SubGroups)
406      MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
407  }
408}
409
410/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
411/// "unknown-pragmas" to have the specified mapping.  This returns true and
412/// ignores the request if "Group" was unknown, false otherwise.
413bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
414                                           diag::Mapping Map) {
415
416  WarningOption Key = { Group, 0, 0 };
417  const WarningOption *Found =
418  std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
419                   WarningOptionCompare);
420  if (Found == OptionTable + OptionTableSize ||
421      strcmp(Found->Name, Group) != 0)
422    return true;  // Option not found.
423
424  MapGroupMembers(Found, Map, *this);
425  return false;
426}
427
428
429/// ProcessDiag - This is the method used to report a diagnostic that is
430/// finally fully formed.
431bool Diagnostic::ProcessDiag() {
432  DiagnosticInfo Info(this);
433
434  if (SuppressAllDiagnostics)
435    return false;
436
437  // Figure out the diagnostic level of this message.
438  Diagnostic::Level DiagLevel;
439  unsigned DiagID = Info.getID();
440
441  // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
442  // in a system header.
443  bool ShouldEmitInSystemHeader;
444
445  if (DiagID >= diag::DIAG_UPPER_LIMIT) {
446    // Handle custom diagnostics, which cannot be mapped.
447    DiagLevel = CustomDiagInfo->getLevel(DiagID);
448
449    // Custom diagnostics always are emitted in system headers.
450    ShouldEmitInSystemHeader = true;
451  } else {
452    // Get the class of the diagnostic.  If this is a NOTE, map it onto whatever
453    // the diagnostic level was for the previous diagnostic so that it is
454    // filtered the same as the previous diagnostic.
455    unsigned DiagClass = getBuiltinDiagClass(DiagID);
456    if (DiagClass == CLASS_NOTE) {
457      DiagLevel = Diagnostic::Note;
458      ShouldEmitInSystemHeader = false;  // extra consideration is needed
459    } else {
460      // If this is not an error and we are in a system header, we ignore it.
461      // Check the original Diag ID here, because we also want to ignore
462      // extensions and warnings in -Werror and -pedantic-errors modes, which
463      // *map* warnings/extensions to errors.
464      ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
465
466      DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
467    }
468  }
469
470  if (DiagLevel != Diagnostic::Note) {
471    // Record that a fatal error occurred only when we see a second
472    // non-note diagnostic. This allows notes to be attached to the
473    // fatal error, but suppresses any diagnostics that follow those
474    // notes.
475    if (LastDiagLevel == Diagnostic::Fatal)
476      FatalErrorOccurred = true;
477
478    LastDiagLevel = DiagLevel;
479  }
480
481  // If a fatal error has already been emitted, silence all subsequent
482  // diagnostics.
483  if (FatalErrorOccurred)
484    return false;
485
486  // If the client doesn't care about this message, don't issue it.  If this is
487  // a note and the last real diagnostic was ignored, ignore it too.
488  if (DiagLevel == Diagnostic::Ignored ||
489      (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
490    return false;
491
492  // If this diagnostic is in a system header and is not a clang error, suppress
493  // it.
494  if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
495      Info.getLocation().isValid() &&
496      Info.getLocation().getSpellingLoc().isInSystemHeader() &&
497      (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
498    LastDiagLevel = Diagnostic::Ignored;
499    return false;
500  }
501
502  if (DiagLevel >= Diagnostic::Error) {
503    ErrorOccurred = true;
504    ++NumErrors;
505  }
506
507  // Finally, report it.
508  Client->HandleDiagnostic(DiagLevel, Info);
509  if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
510
511  CurDiagID = ~0U;
512
513  return true;
514}
515
516
517DiagnosticClient::~DiagnosticClient() {}
518
519
520/// ModifierIs - Return true if the specified modifier matches specified string.
521template <std::size_t StrLen>
522static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
523                       const char (&Str)[StrLen]) {
524  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
525}
526
527/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
528/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
529/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
530/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
531/// This is very useful for certain classes of variant diagnostics.
532static void HandleSelectModifier(unsigned ValNo,
533                                 const char *Argument, unsigned ArgumentLen,
534                                 llvm::SmallVectorImpl<char> &OutStr) {
535  const char *ArgumentEnd = Argument+ArgumentLen;
536
537  // Skip over 'ValNo' |'s.
538  while (ValNo) {
539    const char *NextVal = std::find(Argument, ArgumentEnd, '|');
540    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
541           " larger than the number of options in the diagnostic string!");
542    Argument = NextVal+1;  // Skip this string.
543    --ValNo;
544  }
545
546  // Get the end of the value.  This is either the } or the |.
547  const char *EndPtr = std::find(Argument, ArgumentEnd, '|');
548  // Add the value to the output string.
549  OutStr.append(Argument, EndPtr);
550}
551
552/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
553/// letter 's' to the string if the value is not 1.  This is used in cases like
554/// this:  "you idiot, you have %4 parameter%s4!".
555static void HandleIntegerSModifier(unsigned ValNo,
556                                   llvm::SmallVectorImpl<char> &OutStr) {
557  if (ValNo != 1)
558    OutStr.push_back('s');
559}
560
561
562/// PluralNumber - Parse an unsigned integer and advance Start.
563static unsigned PluralNumber(const char *&Start, const char *End) {
564  // Programming 101: Parse a decimal number :-)
565  unsigned Val = 0;
566  while (Start != End && *Start >= '0' && *Start <= '9') {
567    Val *= 10;
568    Val += *Start - '0';
569    ++Start;
570  }
571  return Val;
572}
573
574/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
575static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
576  if (*Start != '[') {
577    unsigned Ref = PluralNumber(Start, End);
578    return Ref == Val;
579  }
580
581  ++Start;
582  unsigned Low = PluralNumber(Start, End);
583  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
584  ++Start;
585  unsigned High = PluralNumber(Start, End);
586  assert(*Start == ']' && "Bad plural expression syntax: expected )");
587  ++Start;
588  return Low <= Val && Val <= High;
589}
590
591/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
592static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
593  // Empty condition?
594  if (*Start == ':')
595    return true;
596
597  while (1) {
598    char C = *Start;
599    if (C == '%') {
600      // Modulo expression
601      ++Start;
602      unsigned Arg = PluralNumber(Start, End);
603      assert(*Start == '=' && "Bad plural expression syntax: expected =");
604      ++Start;
605      unsigned ValMod = ValNo % Arg;
606      if (TestPluralRange(ValMod, Start, End))
607        return true;
608    } else {
609      assert((C == '[' || (C >= '0' && C <= '9')) &&
610             "Bad plural expression syntax: unexpected character");
611      // Range expression
612      if (TestPluralRange(ValNo, Start, End))
613        return true;
614    }
615
616    // Scan for next or-expr part.
617    Start = std::find(Start, End, ',');
618    if (Start == End)
619      break;
620    ++Start;
621  }
622  return false;
623}
624
625/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
626/// for complex plural forms, or in languages where all plurals are complex.
627/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
628/// conditions that are tested in order, the form corresponding to the first
629/// that applies being emitted. The empty condition is always true, making the
630/// last form a default case.
631/// Conditions are simple boolean expressions, where n is the number argument.
632/// Here are the rules.
633/// condition  := expression | empty
634/// empty      :=                             -> always true
635/// expression := numeric [',' expression]    -> logical or
636/// numeric    := range                       -> true if n in range
637///             | '%' number '=' range        -> true if n % number in range
638/// range      := number
639///             | '[' number ',' number ']'   -> ranges are inclusive both ends
640///
641/// Here are some examples from the GNU gettext manual written in this form:
642/// English:
643/// {1:form0|:form1}
644/// Latvian:
645/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
646/// Gaeilge:
647/// {1:form0|2:form1|:form2}
648/// Romanian:
649/// {1:form0|0,%100=[1,19]:form1|:form2}
650/// Lithuanian:
651/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
652/// Russian (requires repeated form):
653/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
654/// Slovak
655/// {1:form0|[2,4]:form1|:form2}
656/// Polish (requires repeated form):
657/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
658static void HandlePluralModifier(unsigned ValNo,
659                                 const char *Argument, unsigned ArgumentLen,
660                                 llvm::SmallVectorImpl<char> &OutStr) {
661  const char *ArgumentEnd = Argument + ArgumentLen;
662  while (1) {
663    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
664    const char *ExprEnd = Argument;
665    while (*ExprEnd != ':') {
666      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
667      ++ExprEnd;
668    }
669    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
670      Argument = ExprEnd + 1;
671      ExprEnd = std::find(Argument, ArgumentEnd, '|');
672      OutStr.append(Argument, ExprEnd);
673      return;
674    }
675    Argument = std::find(Argument, ArgumentEnd - 1, '|') + 1;
676  }
677}
678
679
680/// FormatDiagnostic - Format this diagnostic into a string, substituting the
681/// formal arguments into the %0 slots.  The result is appended onto the Str
682/// array.
683void DiagnosticInfo::
684FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
685  const char *DiagStr = getDiags()->getDescription(getID());
686  const char *DiagEnd = DiagStr+strlen(DiagStr);
687
688  while (DiagStr != DiagEnd) {
689    if (DiagStr[0] != '%') {
690      // Append non-%0 substrings to Str if we have one.
691      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
692      OutStr.append(DiagStr, StrEnd);
693      DiagStr = StrEnd;
694      continue;
695    } else if (DiagStr[1] == '%') {
696      OutStr.push_back('%');  // %% -> %.
697      DiagStr += 2;
698      continue;
699    }
700
701    // Skip the %.
702    ++DiagStr;
703
704    // This must be a placeholder for a diagnostic argument.  The format for a
705    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
706    // The digit is a number from 0-9 indicating which argument this comes from.
707    // The modifier is a string of digits from the set [-a-z]+, arguments is a
708    // brace enclosed string.
709    const char *Modifier = 0, *Argument = 0;
710    unsigned ModifierLen = 0, ArgumentLen = 0;
711
712    // Check to see if we have a modifier.  If so eat it.
713    if (!isdigit(DiagStr[0])) {
714      Modifier = DiagStr;
715      while (DiagStr[0] == '-' ||
716             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
717        ++DiagStr;
718      ModifierLen = DiagStr-Modifier;
719
720      // If we have an argument, get it next.
721      if (DiagStr[0] == '{') {
722        ++DiagStr; // Skip {.
723        Argument = DiagStr;
724
725        for (; DiagStr[0] != '}'; ++DiagStr)
726          assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!");
727        ArgumentLen = DiagStr-Argument;
728        ++DiagStr;  // Skip }.
729      }
730    }
731
732    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
733    unsigned ArgNo = *DiagStr++ - '0';
734
735    switch (getArgKind(ArgNo)) {
736    // ---- STRINGS ----
737    case Diagnostic::ak_std_string: {
738      const std::string &S = getArgStdStr(ArgNo);
739      assert(ModifierLen == 0 && "No modifiers for strings yet");
740      OutStr.append(S.begin(), S.end());
741      break;
742    }
743    case Diagnostic::ak_c_string: {
744      const char *S = getArgCStr(ArgNo);
745      assert(ModifierLen == 0 && "No modifiers for strings yet");
746
747      // Don't crash if get passed a null pointer by accident.
748      if (!S)
749        S = "(null)";
750
751      OutStr.append(S, S + strlen(S));
752      break;
753    }
754    // ---- INTEGERS ----
755    case Diagnostic::ak_sint: {
756      int Val = getArgSInt(ArgNo);
757
758      if (ModifierIs(Modifier, ModifierLen, "select")) {
759        HandleSelectModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
760      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
761        HandleIntegerSModifier(Val, OutStr);
762      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
763        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
764      } else {
765        assert(ModifierLen == 0 && "Unknown integer modifier");
766        llvm::raw_svector_ostream(OutStr) << Val;
767      }
768      break;
769    }
770    case Diagnostic::ak_uint: {
771      unsigned Val = getArgUInt(ArgNo);
772
773      if (ModifierIs(Modifier, ModifierLen, "select")) {
774        HandleSelectModifier(Val, Argument, ArgumentLen, OutStr);
775      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
776        HandleIntegerSModifier(Val, OutStr);
777      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
778        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
779      } else {
780        assert(ModifierLen == 0 && "Unknown integer modifier");
781        llvm::raw_svector_ostream(OutStr) << Val;
782      }
783      break;
784    }
785    // ---- NAMES and TYPES ----
786    case Diagnostic::ak_identifierinfo: {
787      const IdentifierInfo *II = getArgIdentifier(ArgNo);
788      assert(ModifierLen == 0 && "No modifiers for strings yet");
789
790      // Don't crash if get passed a null pointer by accident.
791      if (!II) {
792        const char *S = "(null)";
793        OutStr.append(S, S + strlen(S));
794        continue;
795      }
796
797      llvm::raw_svector_ostream(OutStr) << '\'' << II->getNameStr() << '\'';
798      break;
799    }
800    case Diagnostic::ak_qualtype:
801    case Diagnostic::ak_declarationname:
802    case Diagnostic::ak_nameddecl:
803    case Diagnostic::ak_nestednamespec:
804    case Diagnostic::ak_declcontext:
805      getDiags()->ConvertArgToString(getArgKind(ArgNo), getRawArg(ArgNo),
806                                     Modifier, ModifierLen,
807                                     Argument, ArgumentLen, OutStr);
808      break;
809    }
810  }
811}
812
813/// IncludeInDiagnosticCounts - This method (whose default implementation
814///  returns true) indicates whether the diagnostics handled by this
815///  DiagnosticClient should be included in the number of diagnostics
816///  reported by Diagnostic.
817bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
818