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/CharInfo.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/PartialDiagnostic.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace clang;
25 
26 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
27                                const char *Modifier, unsigned ML,
28                                const char *Argument, unsigned ArgLen,
29                                const DiagnosticsEngine::ArgumentValue *PrevArgs,
30                                unsigned NumPrevArgs,
31                                SmallVectorImpl<char> &Output,
32                                void *Cookie,
33                                ArrayRef<intptr_t> QualTypeVals) {
34   const char *Str = "<can't format argument>";
35   Output.append(Str, Str+strlen(Str));
36 }
37 
38 
39 DiagnosticsEngine::DiagnosticsEngine(
40                        const IntrusiveRefCntPtr<DiagnosticIDs> &diags,
41                        DiagnosticOptions *DiagOpts,
42                        DiagnosticConsumer *client, bool ShouldOwnClient)
43   : Diags(diags), DiagOpts(DiagOpts), Client(client),
44     OwnsDiagClient(ShouldOwnClient), SourceMgr(0) {
45   ArgToStringFn = DummyArgToStringFn;
46   ArgToStringCookie = 0;
47 
48   AllExtensionsSilenced = 0;
49   IgnoreAllWarnings = false;
50   WarningsAsErrors = false;
51   EnableAllWarnings = false;
52   ErrorsAsFatal = false;
53   SuppressSystemWarnings = false;
54   SuppressAllDiagnostics = false;
55   ElideType = true;
56   PrintTemplateTree = false;
57   ShowColors = false;
58   ShowOverloads = Ovl_All;
59   ExtBehavior = Ext_Ignore;
60 
61   ErrorLimit = 0;
62   TemplateBacktraceLimit = 0;
63   ConstexprBacktraceLimit = 0;
64 
65   Reset();
66 }
67 
68 DiagnosticsEngine::~DiagnosticsEngine() {
69   if (OwnsDiagClient)
70     delete Client;
71 }
72 
73 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
74                                   bool ShouldOwnClient) {
75   if (OwnsDiagClient && Client)
76     delete Client;
77 
78   Client = client;
79   OwnsDiagClient = ShouldOwnClient;
80 }
81 
82 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
83   DiagStateOnPushStack.push_back(GetCurDiagState());
84 }
85 
86 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
87   if (DiagStateOnPushStack.empty())
88     return false;
89 
90   if (DiagStateOnPushStack.back() != GetCurDiagState()) {
91     // State changed at some point between push/pop.
92     PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
93   }
94   DiagStateOnPushStack.pop_back();
95   return true;
96 }
97 
98 void DiagnosticsEngine::Reset() {
99   ErrorOccurred = false;
100   UncompilableErrorOccurred = false;
101   FatalErrorOccurred = false;
102   UnrecoverableErrorOccurred = false;
103 
104   NumWarnings = 0;
105   NumErrors = 0;
106   NumErrorsSuppressed = 0;
107   TrapNumErrorsOccurred = 0;
108   TrapNumUnrecoverableErrorsOccurred = 0;
109 
110   CurDiagID = ~0U;
111   LastDiagLevel = DiagnosticIDs::Ignored;
112   DelayedDiagID = 0;
113 
114   // Clear state related to #pragma diagnostic.
115   DiagStates.clear();
116   DiagStatePoints.clear();
117   DiagStateOnPushStack.clear();
118 
119   // Create a DiagState and DiagStatePoint representing diagnostic changes
120   // through command-line.
121   DiagStates.push_back(DiagState());
122   DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc()));
123 }
124 
125 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
126                                              StringRef Arg2) {
127   if (DelayedDiagID)
128     return;
129 
130   DelayedDiagID = DiagID;
131   DelayedDiagArg1 = Arg1.str();
132   DelayedDiagArg2 = Arg2.str();
133 }
134 
135 void DiagnosticsEngine::ReportDelayed() {
136   Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
137   DelayedDiagID = 0;
138   DelayedDiagArg1.clear();
139   DelayedDiagArg2.clear();
140 }
141 
142 DiagnosticsEngine::DiagStatePointsTy::iterator
143 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
144   assert(!DiagStatePoints.empty());
145   assert(DiagStatePoints.front().Loc.isInvalid() &&
146          "Should have created a DiagStatePoint for command-line");
147 
148   if (!SourceMgr)
149     return DiagStatePoints.end() - 1;
150 
151   FullSourceLoc Loc(L, *SourceMgr);
152   if (Loc.isInvalid())
153     return DiagStatePoints.end() - 1;
154 
155   DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
156   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
157   if (LastStateChangePos.isValid() &&
158       Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
159     Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
160                            DiagStatePoint(0, Loc));
161   --Pos;
162   return Pos;
163 }
164 
165 void DiagnosticsEngine::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
166                                              SourceLocation L) {
167   assert(Diag < diag::DIAG_UPPER_LIMIT &&
168          "Can only map builtin diagnostics");
169   assert((Diags->isBuiltinWarningOrExtension(Diag) ||
170           (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
171          "Cannot map errors into warnings!");
172   assert(!DiagStatePoints.empty());
173   assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
174 
175   FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc();
176   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
177   // Don't allow a mapping to a warning override an error/fatal mapping.
178   if (Map == diag::MAP_WARNING) {
179     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
180     if (Info.getMapping() == diag::MAP_ERROR ||
181         Info.getMapping() == diag::MAP_FATAL)
182       Map = Info.getMapping();
183   }
184   DiagnosticMappingInfo MappingInfo = makeMappingInfo(Map, L);
185 
186   // Common case; setting all the diagnostics of a group in one place.
187   if (Loc.isInvalid() || Loc == LastStateChangePos) {
188     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
189     return;
190   }
191 
192   // Another common case; modifying diagnostic state in a source location
193   // after the previous one.
194   if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
195       LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
196     // A diagnostic pragma occurred, create a new DiagState initialized with
197     // the current one and a new DiagStatePoint to record at which location
198     // the new state became active.
199     DiagStates.push_back(*GetCurDiagState());
200     PushDiagStatePoint(&DiagStates.back(), Loc);
201     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
202     return;
203   }
204 
205   // We allow setting the diagnostic state in random source order for
206   // completeness but it should not be actually happening in normal practice.
207 
208   DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
209   assert(Pos != DiagStatePoints.end());
210 
211   // Update all diagnostic states that are active after the given location.
212   for (DiagStatePointsTy::iterator
213          I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
214     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
215   }
216 
217   // If the location corresponds to an existing point, just update its state.
218   if (Pos->Loc == Loc) {
219     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
220     return;
221   }
222 
223   // Create a new state/point and fit it into the vector of DiagStatePoints
224   // so that the vector is always ordered according to location.
225   Pos->Loc.isBeforeInTranslationUnitThan(Loc);
226   DiagStates.push_back(*Pos->State);
227   DiagState *NewState = &DiagStates.back();
228   GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
229   DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
230                                                FullSourceLoc(Loc, *SourceMgr)));
231 }
232 
233 bool DiagnosticsEngine::setDiagnosticGroupMapping(
234   StringRef Group, diag::Mapping Map, SourceLocation Loc)
235 {
236   // Get the diagnostics in this group.
237   SmallVector<diag::kind, 8> GroupDiags;
238   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
239     return true;
240 
241   // Set the mapping.
242   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i)
243     setDiagnosticMapping(GroupDiags[i], Map, Loc);
244 
245   return false;
246 }
247 
248 void DiagnosticsEngine::setDiagnosticWarningAsError(diag::kind Diag,
249                                                     bool Enabled) {
250   // If we are enabling this feature, just set the diagnostic mappings to map to
251   // errors.
252   if (Enabled)
253     setDiagnosticMapping(Diag, diag::MAP_ERROR, SourceLocation());
254 
255   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
256   // potentially downgrade anything already mapped to be a warning.
257   DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
258 
259   if (Info.getMapping() == diag::MAP_ERROR ||
260       Info.getMapping() == diag::MAP_FATAL)
261     Info.setMapping(diag::MAP_WARNING);
262 
263   Info.setNoWarningAsError(true);
264 }
265 
266 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
267                                                          bool Enabled) {
268   // If we are enabling this feature, just set the diagnostic mappings to map to
269   // errors.
270   if (Enabled)
271     return setDiagnosticGroupMapping(Group, diag::MAP_ERROR);
272 
273   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
274   // potentially downgrade anything already mapped to be a warning.
275 
276   // Get the diagnostics in this group.
277   SmallVector<diag::kind, 8> GroupDiags;
278   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
279     return true;
280 
281   // Perform the mapping change.
282   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
283     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
284       GroupDiags[i]);
285 
286     if (Info.getMapping() == diag::MAP_ERROR ||
287         Info.getMapping() == diag::MAP_FATAL)
288       Info.setMapping(diag::MAP_WARNING);
289 
290     Info.setNoWarningAsError(true);
291   }
292 
293   return false;
294 }
295 
296 void DiagnosticsEngine::setDiagnosticErrorAsFatal(diag::kind Diag,
297                                                   bool Enabled) {
298   // If we are enabling this feature, just set the diagnostic mappings to map to
299   // errors.
300   if (Enabled)
301     setDiagnosticMapping(Diag, diag::MAP_FATAL, SourceLocation());
302 
303   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
304   // potentially downgrade anything already mapped to be a warning.
305   DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
306 
307   if (Info.getMapping() == diag::MAP_FATAL)
308     Info.setMapping(diag::MAP_ERROR);
309 
310   Info.setNoErrorAsFatal(true);
311 }
312 
313 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
314                                                        bool Enabled) {
315   // If we are enabling this feature, just set the diagnostic mappings to map to
316   // fatal errors.
317   if (Enabled)
318     return setDiagnosticGroupMapping(Group, diag::MAP_FATAL);
319 
320   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
321   // potentially downgrade anything already mapped to be an error.
322 
323   // Get the diagnostics in this group.
324   SmallVector<diag::kind, 8> GroupDiags;
325   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
326     return true;
327 
328   // Perform the mapping change.
329   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
330     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
331       GroupDiags[i]);
332 
333     if (Info.getMapping() == diag::MAP_FATAL)
334       Info.setMapping(diag::MAP_ERROR);
335 
336     Info.setNoErrorAsFatal(true);
337   }
338 
339   return false;
340 }
341 
342 void DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map,
343                                                    SourceLocation Loc) {
344   // Get all the diagnostics.
345   SmallVector<diag::kind, 64> AllDiags;
346   Diags->getAllDiagnostics(AllDiags);
347 
348   // Set the mapping.
349   for (unsigned i = 0, e = AllDiags.size(); i != e; ++i)
350     if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
351       setDiagnosticMapping(AllDiags[i], Map, Loc);
352 }
353 
354 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
355   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
356 
357   CurDiagLoc = storedDiag.getLocation();
358   CurDiagID = storedDiag.getID();
359   NumDiagArgs = 0;
360 
361   NumDiagRanges = storedDiag.range_size();
362   assert(NumDiagRanges < DiagnosticsEngine::MaxRanges &&
363          "Too many arguments to diagnostic!");
364   unsigned i = 0;
365   for (StoredDiagnostic::range_iterator
366          RI = storedDiag.range_begin(),
367          RE = storedDiag.range_end(); RI != RE; ++RI)
368     DiagRanges[i++] = *RI;
369 
370   assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints &&
371          "Too many arguments to diagnostic!");
372   NumDiagFixItHints = 0;
373   for (StoredDiagnostic::fixit_iterator
374          FI = storedDiag.fixit_begin(),
375          FE = storedDiag.fixit_end(); FI != FE; ++FI)
376     DiagFixItHints[NumDiagFixItHints++] = *FI;
377 
378   assert(Client && "DiagnosticConsumer not set!");
379   Level DiagLevel = storedDiag.getLevel();
380   Diagnostic Info(this, storedDiag.getMessage());
381   Client->HandleDiagnostic(DiagLevel, Info);
382   if (Client->IncludeInDiagnosticCounts()) {
383     if (DiagLevel == DiagnosticsEngine::Warning)
384       ++NumWarnings;
385   }
386 
387   CurDiagID = ~0U;
388 }
389 
390 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
391   assert(getClient() && "DiagnosticClient not set!");
392 
393   bool Emitted;
394   if (Force) {
395     Diagnostic Info(this);
396 
397     // Figure out the diagnostic level of this message.
398     DiagnosticIDs::Level DiagLevel
399       = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
400 
401     Emitted = (DiagLevel != DiagnosticIDs::Ignored);
402     if (Emitted) {
403       // Emit the diagnostic regardless of suppression level.
404       Diags->EmitDiag(*this, DiagLevel);
405     }
406   } else {
407     // Process the diagnostic, sending the accumulated information to the
408     // DiagnosticConsumer.
409     Emitted = ProcessDiag();
410   }
411 
412   // Clear out the current diagnostic object.
413   unsigned DiagID = CurDiagID;
414   Clear();
415 
416   // If there was a delayed diagnostic, emit it now.
417   if (!Force && DelayedDiagID && DelayedDiagID != DiagID)
418     ReportDelayed();
419 
420   return Emitted;
421 }
422 
423 
424 DiagnosticConsumer::~DiagnosticConsumer() {}
425 
426 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
427                                         const Diagnostic &Info) {
428   if (!IncludeInDiagnosticCounts())
429     return;
430 
431   if (DiagLevel == DiagnosticsEngine::Warning)
432     ++NumWarnings;
433   else if (DiagLevel >= DiagnosticsEngine::Error)
434     ++NumErrors;
435 }
436 
437 /// ModifierIs - Return true if the specified modifier matches specified string.
438 template <std::size_t StrLen>
439 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
440                        const char (&Str)[StrLen]) {
441   return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
442 }
443 
444 /// ScanForward - Scans forward, looking for the given character, skipping
445 /// nested clauses and escaped characters.
446 static const char *ScanFormat(const char *I, const char *E, char Target) {
447   unsigned Depth = 0;
448 
449   for ( ; I != E; ++I) {
450     if (Depth == 0 && *I == Target) return I;
451     if (Depth != 0 && *I == '}') Depth--;
452 
453     if (*I == '%') {
454       I++;
455       if (I == E) break;
456 
457       // Escaped characters get implicitly skipped here.
458 
459       // Format specifier.
460       if (!isDigit(*I) && !isPunctuation(*I)) {
461         for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
462         if (I == E) break;
463         if (*I == '{')
464           Depth++;
465       }
466     }
467   }
468   return E;
469 }
470 
471 /// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
472 /// like this:  %select{foo|bar|baz}2.  This means that the integer argument
473 /// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
474 /// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
475 /// This is very useful for certain classes of variant diagnostics.
476 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
477                                  const char *Argument, unsigned ArgumentLen,
478                                  SmallVectorImpl<char> &OutStr) {
479   const char *ArgumentEnd = Argument+ArgumentLen;
480 
481   // Skip over 'ValNo' |'s.
482   while (ValNo) {
483     const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
484     assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
485            " larger than the number of options in the diagnostic string!");
486     Argument = NextVal+1;  // Skip this string.
487     --ValNo;
488   }
489 
490   // Get the end of the value.  This is either the } or the |.
491   const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
492 
493   // Recursively format the result of the select clause into the output string.
494   DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
495 }
496 
497 /// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
498 /// letter 's' to the string if the value is not 1.  This is used in cases like
499 /// this:  "you idiot, you have %4 parameter%s4!".
500 static void HandleIntegerSModifier(unsigned ValNo,
501                                    SmallVectorImpl<char> &OutStr) {
502   if (ValNo != 1)
503     OutStr.push_back('s');
504 }
505 
506 /// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
507 /// prints the ordinal form of the given integer, with 1 corresponding
508 /// to the first ordinal.  Currently this is hard-coded to use the
509 /// English form.
510 static void HandleOrdinalModifier(unsigned ValNo,
511                                   SmallVectorImpl<char> &OutStr) {
512   assert(ValNo != 0 && "ValNo must be strictly positive!");
513 
514   llvm::raw_svector_ostream Out(OutStr);
515 
516   // We could use text forms for the first N ordinals, but the numeric
517   // forms are actually nicer in diagnostics because they stand out.
518   Out << ValNo << llvm::getOrdinalSuffix(ValNo);
519 }
520 
521 
522 /// PluralNumber - Parse an unsigned integer and advance Start.
523 static unsigned PluralNumber(const char *&Start, const char *End) {
524   // Programming 101: Parse a decimal number :-)
525   unsigned Val = 0;
526   while (Start != End && *Start >= '0' && *Start <= '9') {
527     Val *= 10;
528     Val += *Start - '0';
529     ++Start;
530   }
531   return Val;
532 }
533 
534 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
535 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
536   if (*Start != '[') {
537     unsigned Ref = PluralNumber(Start, End);
538     return Ref == Val;
539   }
540 
541   ++Start;
542   unsigned Low = PluralNumber(Start, End);
543   assert(*Start == ',' && "Bad plural expression syntax: expected ,");
544   ++Start;
545   unsigned High = PluralNumber(Start, End);
546   assert(*Start == ']' && "Bad plural expression syntax: expected )");
547   ++Start;
548   return Low <= Val && Val <= High;
549 }
550 
551 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
552 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
553   // Empty condition?
554   if (*Start == ':')
555     return true;
556 
557   while (1) {
558     char C = *Start;
559     if (C == '%') {
560       // Modulo expression
561       ++Start;
562       unsigned Arg = PluralNumber(Start, End);
563       assert(*Start == '=' && "Bad plural expression syntax: expected =");
564       ++Start;
565       unsigned ValMod = ValNo % Arg;
566       if (TestPluralRange(ValMod, Start, End))
567         return true;
568     } else {
569       assert((C == '[' || (C >= '0' && C <= '9')) &&
570              "Bad plural expression syntax: unexpected character");
571       // Range expression
572       if (TestPluralRange(ValNo, Start, End))
573         return true;
574     }
575 
576     // Scan for next or-expr part.
577     Start = std::find(Start, End, ',');
578     if (Start == End)
579       break;
580     ++Start;
581   }
582   return false;
583 }
584 
585 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
586 /// for complex plural forms, or in languages where all plurals are complex.
587 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
588 /// conditions that are tested in order, the form corresponding to the first
589 /// that applies being emitted. The empty condition is always true, making the
590 /// last form a default case.
591 /// Conditions are simple boolean expressions, where n is the number argument.
592 /// Here are the rules.
593 /// condition  := expression | empty
594 /// empty      :=                             -> always true
595 /// expression := numeric [',' expression]    -> logical or
596 /// numeric    := range                       -> true if n in range
597 ///             | '%' number '=' range        -> true if n % number in range
598 /// range      := number
599 ///             | '[' number ',' number ']'   -> ranges are inclusive both ends
600 ///
601 /// Here are some examples from the GNU gettext manual written in this form:
602 /// English:
603 /// {1:form0|:form1}
604 /// Latvian:
605 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
606 /// Gaeilge:
607 /// {1:form0|2:form1|:form2}
608 /// Romanian:
609 /// {1:form0|0,%100=[1,19]:form1|:form2}
610 /// Lithuanian:
611 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
612 /// Russian (requires repeated form):
613 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
614 /// Slovak
615 /// {1:form0|[2,4]:form1|:form2}
616 /// Polish (requires repeated form):
617 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
618 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
619                                  const char *Argument, unsigned ArgumentLen,
620                                  SmallVectorImpl<char> &OutStr) {
621   const char *ArgumentEnd = Argument + ArgumentLen;
622   while (1) {
623     assert(Argument < ArgumentEnd && "Plural expression didn't match.");
624     const char *ExprEnd = Argument;
625     while (*ExprEnd != ':') {
626       assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
627       ++ExprEnd;
628     }
629     if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
630       Argument = ExprEnd + 1;
631       ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
632 
633       // Recursively format the result of the plural clause into the
634       // output string.
635       DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
636       return;
637     }
638     Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
639   }
640 }
641 
642 /// \brief Returns the friendly description for a token kind that will appear
643 /// without quotes in diagnostic messages. These strings may be translatable in
644 /// future.
645 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
646   switch (Kind) {
647   case tok::identifier:
648     return "identifier";
649   default:
650     return 0;
651   }
652 }
653 
654 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
655 /// formal arguments into the %0 slots.  The result is appended onto the Str
656 /// array.
657 void Diagnostic::
658 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
659   if (!StoredDiagMessage.empty()) {
660     OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
661     return;
662   }
663 
664   StringRef Diag =
665     getDiags()->getDiagnosticIDs()->getDescription(getID());
666 
667   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
668 }
669 
670 void Diagnostic::
671 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
672                  SmallVectorImpl<char> &OutStr) const {
673 
674   /// FormattedArgs - Keep track of all of the arguments formatted by
675   /// ConvertArgToString and pass them into subsequent calls to
676   /// ConvertArgToString, allowing the implementation to avoid redundancies in
677   /// obvious cases.
678   SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
679 
680   /// QualTypeVals - Pass a vector of arrays so that QualType names can be
681   /// compared to see if more information is needed to be printed.
682   SmallVector<intptr_t, 2> QualTypeVals;
683   SmallVector<char, 64> Tree;
684 
685   for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
686     if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
687       QualTypeVals.push_back(getRawArg(i));
688 
689   while (DiagStr != DiagEnd) {
690     if (DiagStr[0] != '%') {
691       // Append non-%0 substrings to Str if we have one.
692       const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
693       OutStr.append(DiagStr, StrEnd);
694       DiagStr = StrEnd;
695       continue;
696     } else if (isPunctuation(DiagStr[1])) {
697       OutStr.push_back(DiagStr[1]);  // %% -> %.
698       DiagStr += 2;
699       continue;
700     }
701 
702     // Skip the %.
703     ++DiagStr;
704 
705     // This must be a placeholder for a diagnostic argument.  The format for a
706     // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
707     // The digit is a number from 0-9 indicating which argument this comes from.
708     // The modifier is a string of digits from the set [-a-z]+, arguments is a
709     // brace enclosed string.
710     const char *Modifier = 0, *Argument = 0;
711     unsigned ModifierLen = 0, ArgumentLen = 0;
712 
713     // Check to see if we have a modifier.  If so eat it.
714     if (!isDigit(DiagStr[0])) {
715       Modifier = DiagStr;
716       while (DiagStr[0] == '-' ||
717              (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
718         ++DiagStr;
719       ModifierLen = DiagStr-Modifier;
720 
721       // If we have an argument, get it next.
722       if (DiagStr[0] == '{') {
723         ++DiagStr; // Skip {.
724         Argument = DiagStr;
725 
726         DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
727         assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
728         ArgumentLen = DiagStr-Argument;
729         ++DiagStr;  // Skip }.
730       }
731     }
732 
733     assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
734     unsigned ArgNo = *DiagStr++ - '0';
735 
736     // Only used for type diffing.
737     unsigned ArgNo2 = ArgNo;
738 
739     DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
740     if (ModifierIs(Modifier, ModifierLen, "diff")) {
741       assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
742              "Invalid format for diff modifier");
743       ++DiagStr;  // Comma.
744       ArgNo2 = *DiagStr++ - '0';
745       DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
746       if (Kind == DiagnosticsEngine::ak_qualtype &&
747           Kind2 == DiagnosticsEngine::ak_qualtype)
748         Kind = DiagnosticsEngine::ak_qualtype_pair;
749       else {
750         // %diff only supports QualTypes.  For other kinds of arguments,
751         // use the default printing.  For example, if the modifier is:
752         //   "%diff{compare $ to $|other text}1,2"
753         // treat it as:
754         //   "compare %1 to %2"
755         const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|');
756         const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
757         const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
758         const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
759         const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
760         FormatDiagnostic(Argument, FirstDollar, OutStr);
761         FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
762         FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
763         FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
764         FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
765         continue;
766       }
767     }
768 
769     switch (Kind) {
770     // ---- STRINGS ----
771     case DiagnosticsEngine::ak_std_string: {
772       const std::string &S = getArgStdStr(ArgNo);
773       assert(ModifierLen == 0 && "No modifiers for strings yet");
774       OutStr.append(S.begin(), S.end());
775       break;
776     }
777     case DiagnosticsEngine::ak_c_string: {
778       const char *S = getArgCStr(ArgNo);
779       assert(ModifierLen == 0 && "No modifiers for strings yet");
780 
781       // Don't crash if get passed a null pointer by accident.
782       if (!S)
783         S = "(null)";
784 
785       OutStr.append(S, S + strlen(S));
786       break;
787     }
788     // ---- INTEGERS ----
789     case DiagnosticsEngine::ak_sint: {
790       int Val = getArgSInt(ArgNo);
791 
792       if (ModifierIs(Modifier, ModifierLen, "select")) {
793         HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
794                              OutStr);
795       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
796         HandleIntegerSModifier(Val, OutStr);
797       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
798         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
799                              OutStr);
800       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
801         HandleOrdinalModifier((unsigned)Val, OutStr);
802       } else {
803         assert(ModifierLen == 0 && "Unknown integer modifier");
804         llvm::raw_svector_ostream(OutStr) << Val;
805       }
806       break;
807     }
808     case DiagnosticsEngine::ak_uint: {
809       unsigned Val = getArgUInt(ArgNo);
810 
811       if (ModifierIs(Modifier, ModifierLen, "select")) {
812         HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
813       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
814         HandleIntegerSModifier(Val, OutStr);
815       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
816         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
817                              OutStr);
818       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
819         HandleOrdinalModifier(Val, OutStr);
820       } else {
821         assert(ModifierLen == 0 && "Unknown integer modifier");
822         llvm::raw_svector_ostream(OutStr) << Val;
823       }
824       break;
825     }
826     // ---- TOKEN SPELLINGS ----
827     case DiagnosticsEngine::ak_tokenkind: {
828       tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
829       assert(ModifierLen == 0 && "No modifiers for token kinds yet");
830 
831       llvm::raw_svector_ostream Out(OutStr);
832       if (const char *S = tok::getPunctuatorSpelling(Kind))
833         // Quoted token spelling for punctuators.
834         Out << '\'' << S << '\'';
835       else if (const char *S = tok::getKeywordSpelling(Kind))
836         // Unquoted token spelling for keywords.
837         Out << S;
838       else if (const char *S = getTokenDescForDiagnostic(Kind))
839         // Unquoted translatable token name.
840         Out << S;
841       else if (const char *S = tok::getTokenName(Kind))
842         // Debug name, shouldn't appear in user-facing diagnostics.
843         Out << '<' << S << '>';
844       else
845         Out << "(null)";
846       break;
847     }
848     // ---- NAMES and TYPES ----
849     case DiagnosticsEngine::ak_identifierinfo: {
850       const IdentifierInfo *II = getArgIdentifier(ArgNo);
851       assert(ModifierLen == 0 && "No modifiers for strings yet");
852 
853       // Don't crash if get passed a null pointer by accident.
854       if (!II) {
855         const char *S = "(null)";
856         OutStr.append(S, S + strlen(S));
857         continue;
858       }
859 
860       llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
861       break;
862     }
863     case DiagnosticsEngine::ak_qualtype:
864     case DiagnosticsEngine::ak_declarationname:
865     case DiagnosticsEngine::ak_nameddecl:
866     case DiagnosticsEngine::ak_nestednamespec:
867     case DiagnosticsEngine::ak_declcontext:
868     case DiagnosticsEngine::ak_attr:
869       getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
870                                      Modifier, ModifierLen,
871                                      Argument, ArgumentLen,
872                                      FormattedArgs.data(), FormattedArgs.size(),
873                                      OutStr, QualTypeVals);
874       break;
875     case DiagnosticsEngine::ak_qualtype_pair:
876       // Create a struct with all the info needed for printing.
877       TemplateDiffTypes TDT;
878       TDT.FromType = getRawArg(ArgNo);
879       TDT.ToType = getRawArg(ArgNo2);
880       TDT.ElideType = getDiags()->ElideType;
881       TDT.ShowColors = getDiags()->ShowColors;
882       TDT.TemplateDiffUsed = false;
883       intptr_t val = reinterpret_cast<intptr_t>(&TDT);
884 
885       const char *ArgumentEnd = Argument + ArgumentLen;
886       const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
887 
888       // Print the tree.  If this diagnostic already has a tree, skip the
889       // second tree.
890       if (getDiags()->PrintTemplateTree && Tree.empty()) {
891         TDT.PrintFromType = true;
892         TDT.PrintTree = true;
893         getDiags()->ConvertArgToString(Kind, val,
894                                        Modifier, ModifierLen,
895                                        Argument, ArgumentLen,
896                                        FormattedArgs.data(),
897                                        FormattedArgs.size(),
898                                        Tree, QualTypeVals);
899         // If there is no tree information, fall back to regular printing.
900         if (!Tree.empty()) {
901           FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
902           break;
903         }
904       }
905 
906       // Non-tree printing, also the fall-back when tree printing fails.
907       // The fall-back is triggered when the types compared are not templates.
908       const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
909       const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
910 
911       // Append before text
912       FormatDiagnostic(Argument, FirstDollar, OutStr);
913 
914       // Append first type
915       TDT.PrintTree = false;
916       TDT.PrintFromType = true;
917       getDiags()->ConvertArgToString(Kind, val,
918                                      Modifier, ModifierLen,
919                                      Argument, ArgumentLen,
920                                      FormattedArgs.data(), FormattedArgs.size(),
921                                      OutStr, QualTypeVals);
922       if (!TDT.TemplateDiffUsed)
923         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
924                                                TDT.FromType));
925 
926       // Append middle text
927       FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
928 
929       // Append second type
930       TDT.PrintFromType = false;
931       getDiags()->ConvertArgToString(Kind, val,
932                                      Modifier, ModifierLen,
933                                      Argument, ArgumentLen,
934                                      FormattedArgs.data(), FormattedArgs.size(),
935                                      OutStr, QualTypeVals);
936       if (!TDT.TemplateDiffUsed)
937         FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
938                                                TDT.ToType));
939 
940       // Append end text
941       FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
942       break;
943     }
944 
945     // Remember this argument info for subsequent formatting operations.  Turn
946     // std::strings into a null terminated string to make it be the same case as
947     // all the other ones.
948     if (Kind == DiagnosticsEngine::ak_qualtype_pair)
949       continue;
950     else if (Kind != DiagnosticsEngine::ak_std_string)
951       FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
952     else
953       FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
954                                         (intptr_t)getArgStdStr(ArgNo).c_str()));
955 
956   }
957 
958   // Append the type tree to the end of the diagnostics.
959   OutStr.append(Tree.begin(), Tree.end());
960 }
961 
962 StoredDiagnostic::StoredDiagnostic() { }
963 
964 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
965                                    StringRef Message)
966   : ID(ID), Level(Level), Loc(), Message(Message) { }
967 
968 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
969                                    const Diagnostic &Info)
970   : ID(Info.getID()), Level(Level)
971 {
972   assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
973        "Valid source location without setting a source manager for diagnostic");
974   if (Info.getLocation().isValid())
975     Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
976   SmallString<64> Message;
977   Info.FormatDiagnostic(Message);
978   this->Message.assign(Message.begin(), Message.end());
979 
980   Ranges.reserve(Info.getNumRanges());
981   for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
982     Ranges.push_back(Info.getRange(I));
983 
984   FixIts.reserve(Info.getNumFixItHints());
985   for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
986     FixIts.push_back(Info.getFixItHint(I));
987 }
988 
989 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
990                                    StringRef Message, FullSourceLoc Loc,
991                                    ArrayRef<CharSourceRange> Ranges,
992                                    ArrayRef<FixItHint> FixIts)
993   : ID(ID), Level(Level), Loc(Loc), Message(Message),
994     Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
995 {
996 }
997 
998 StoredDiagnostic::~StoredDiagnostic() { }
999 
1000 /// IncludeInDiagnosticCounts - This method (whose default implementation
1001 ///  returns true) indicates whether the diagnostics handled by this
1002 ///  DiagnosticConsumer should be included in the number of diagnostics
1003 ///  reported by DiagnosticsEngine.
1004 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1005 
1006 void IgnoringDiagConsumer::anchor() { }
1007 
1008 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
1009 
1010 void ForwardingDiagnosticConsumer::HandleDiagnostic(
1011        DiagnosticsEngine::Level DiagLevel,
1012        const Diagnostic &Info) {
1013   Target.HandleDiagnostic(DiagLevel, Info);
1014 }
1015 
1016 void ForwardingDiagnosticConsumer::clear() {
1017   DiagnosticConsumer::clear();
1018   Target.clear();
1019 }
1020 
1021 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1022   return Target.IncludeInDiagnosticCounts();
1023 }
1024 
1025 PartialDiagnostic::StorageAllocator::StorageAllocator() {
1026   for (unsigned I = 0; I != NumCached; ++I)
1027     FreeList[I] = Cached + I;
1028   NumFreeListEntries = NumCached;
1029 }
1030 
1031 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1032   // Don't assert if we are in a CrashRecovery context, as this invariant may
1033   // be invalidated during a crash.
1034   assert((NumFreeListEntries == NumCached ||
1035           llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1036          "A partial is on the lamb");
1037 }
1038