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