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