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