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