1 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the Diagnostic-related interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/PartialDiagnostic.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/CrashRecoveryContext.h"
20 
21 using namespace clang;
22 
23 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
24                                const char *Modifier, unsigned ML,
25                                const char *Argument, unsigned ArgLen,
26                                const DiagnosticsEngine::ArgumentValue *PrevArgs,
27                                unsigned NumPrevArgs,
28                                SmallVectorImpl<char> &Output,
29                                void *Cookie,
30                                SmallVectorImpl<intptr_t> &QualTypeVals) {
31   const char *Str = "<can't format argument>";
32   Output.append(Str, Str+strlen(Str));
33 }
34 
35 
36 DiagnosticsEngine::DiagnosticsEngine(
37                        const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
38                        DiagnosticConsumer *client, bool ShouldOwnClient)
39   : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
40     SourceMgr(0) {
41   ArgToStringFn = DummyArgToStringFn;
42   ArgToStringCookie = 0;
43 
44   AllExtensionsSilenced = 0;
45   IgnoreAllWarnings = false;
46   WarningsAsErrors = false;
47   EnableAllWarnings = false;
48   ErrorsAsFatal = false;
49   SuppressSystemWarnings = false;
50   SuppressAllDiagnostics = false;
51   ShowOverloads = Ovl_All;
52   ExtBehavior = Ext_Ignore;
53 
54   ErrorLimit = 0;
55   TemplateBacktraceLimit = 0;
56 
57   Reset();
58 }
59 
60 DiagnosticsEngine::~DiagnosticsEngine() {
61   if (OwnsDiagClient)
62     delete Client;
63 }
64 
65 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
66                                   bool ShouldOwnClient) {
67   if (OwnsDiagClient && Client)
68     delete Client;
69 
70   Client = client;
71   OwnsDiagClient = ShouldOwnClient;
72 }
73 
74 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
75   DiagStateOnPushStack.push_back(GetCurDiagState());
76 }
77 
78 bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
79   if (DiagStateOnPushStack.empty())
80     return false;
81 
82   if (DiagStateOnPushStack.back() != GetCurDiagState()) {
83     // State changed at some point between push/pop.
84     PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
85   }
86   DiagStateOnPushStack.pop_back();
87   return true;
88 }
89 
90 void DiagnosticsEngine::Reset() {
91   ErrorOccurred = false;
92   FatalErrorOccurred = false;
93   UnrecoverableErrorOccurred = false;
94 
95   NumWarnings = 0;
96   NumErrors = 0;
97   NumErrorsSuppressed = 0;
98   TrapNumErrorsOccurred = 0;
99   TrapNumUnrecoverableErrorsOccurred = 0;
100 
101   CurDiagID = ~0U;
102   // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
103   // using a DiagnosticsEngine associated to a translation unit that follow
104   // diagnostics from a DiagnosticsEngine associated to anoter t.u. will not be
105   // displayed.
106   LastDiagLevel = (DiagnosticIDs::Level)-1;
107   DelayedDiagID = 0;
108 
109   // Clear state related to #pragma diagnostic.
110   DiagStates.clear();
111   DiagStatePoints.clear();
112   DiagStateOnPushStack.clear();
113 
114   // Create a DiagState and DiagStatePoint representing diagnostic changes
115   // through command-line.
116   DiagStates.push_back(DiagState());
117   PushDiagStatePoint(&DiagStates.back(), SourceLocation());
118 }
119 
120 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
121                                       StringRef Arg2) {
122   if (DelayedDiagID)
123     return;
124 
125   DelayedDiagID = DiagID;
126   DelayedDiagArg1 = Arg1.str();
127   DelayedDiagArg2 = Arg2.str();
128 }
129 
130 void DiagnosticsEngine::ReportDelayed() {
131   Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
132   DelayedDiagID = 0;
133   DelayedDiagArg1.clear();
134   DelayedDiagArg2.clear();
135 }
136 
137 DiagnosticsEngine::DiagStatePointsTy::iterator
138 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const {
139   assert(!DiagStatePoints.empty());
140   assert(DiagStatePoints.front().Loc.isInvalid() &&
141          "Should have created a DiagStatePoint for command-line");
142 
143   FullSourceLoc Loc(L, *SourceMgr);
144   if (Loc.isInvalid())
145     return DiagStatePoints.end() - 1;
146 
147   DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
148   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
149   if (LastStateChangePos.isValid() &&
150       Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
151     Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
152                            DiagStatePoint(0, Loc));
153   --Pos;
154   return Pos;
155 }
156 
157 /// \brief This allows the client to specify that certain
158 /// warnings are ignored.  Notes can never be mapped, errors can only be
159 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
160 ///
161 /// \param The source location that this change of diagnostic state should
162 /// take affect. It can be null if we are setting the latest state.
163 void DiagnosticsEngine::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
164                                       SourceLocation L) {
165   assert(Diag < diag::DIAG_UPPER_LIMIT &&
166          "Can only map builtin diagnostics");
167   assert((Diags->isBuiltinWarningOrExtension(Diag) ||
168           (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
169          "Cannot map errors into warnings!");
170   assert(!DiagStatePoints.empty());
171 
172   FullSourceLoc Loc(L, *SourceMgr);
173   FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
174   DiagnosticMappingInfo MappingInfo = makeMappingInfo(Map, L);
175 
176   // Common case; setting all the diagnostics of a group in one place.
177   if (Loc.isInvalid() || Loc == LastStateChangePos) {
178     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
179     return;
180   }
181 
182   // Another common case; modifying diagnostic state in a source location
183   // after the previous one.
184   if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
185       LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
186     // A diagnostic pragma occurred, create a new DiagState initialized with
187     // the current one and a new DiagStatePoint to record at which location
188     // the new state became active.
189     DiagStates.push_back(*GetCurDiagState());
190     PushDiagStatePoint(&DiagStates.back(), Loc);
191     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
192     return;
193   }
194 
195   // We allow setting the diagnostic state in random source order for
196   // completeness but it should not be actually happening in normal practice.
197 
198   DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
199   assert(Pos != DiagStatePoints.end());
200 
201   // Update all diagnostic states that are active after the given location.
202   for (DiagStatePointsTy::iterator
203          I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
204     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
205   }
206 
207   // If the location corresponds to an existing point, just update its state.
208   if (Pos->Loc == Loc) {
209     GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
210     return;
211   }
212 
213   // Create a new state/point and fit it into the vector of DiagStatePoints
214   // so that the vector is always ordered according to location.
215   Pos->Loc.isBeforeInTranslationUnitThan(Loc);
216   DiagStates.push_back(*Pos->State);
217   DiagState *NewState = &DiagStates.back();
218   GetCurDiagState()->setMappingInfo(Diag, MappingInfo);
219   DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
220                                                FullSourceLoc(Loc, *SourceMgr)));
221 }
222 
223 bool DiagnosticsEngine::setDiagnosticGroupMapping(
224   StringRef Group, diag::Mapping Map, SourceLocation Loc)
225 {
226   // Get the diagnostics in this group.
227   llvm::SmallVector<diag::kind, 8> GroupDiags;
228   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
229     return true;
230 
231   // Set the mapping.
232   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i)
233     setDiagnosticMapping(GroupDiags[i], Map, Loc);
234 
235   return false;
236 }
237 
238 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
239                                                          bool Enabled) {
240   // If we are enabling this feature, just set the diagnostic mappings to map to
241   // errors.
242   if (Enabled)
243     return setDiagnosticGroupMapping(Group, diag::MAP_ERROR);
244 
245   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
246   // potentially downgrade anything already mapped to be a warning.
247 
248   // Get the diagnostics in this group.
249   llvm::SmallVector<diag::kind, 8> GroupDiags;
250   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
251     return true;
252 
253   // Perform the mapping change.
254   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
255     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
256       GroupDiags[i]);
257 
258     if (Info.getMapping() == diag::MAP_ERROR ||
259         Info.getMapping() == diag::MAP_FATAL)
260       Info.setMapping(diag::MAP_WARNING);
261 
262     Info.setNoWarningAsError(true);
263   }
264 
265   return false;
266 }
267 
268 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
269                                                        bool Enabled) {
270   // If we are enabling this feature, just set the diagnostic mappings to map to
271   // fatal errors.
272   if (Enabled)
273     return setDiagnosticGroupMapping(Group, diag::MAP_FATAL);
274 
275   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
276   // potentially downgrade anything already mapped to be an error.
277 
278   // Get the diagnostics in this group.
279   llvm::SmallVector<diag::kind, 8> GroupDiags;
280   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
281     return true;
282 
283   // Perform the mapping change.
284   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
285     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
286       GroupDiags[i]);
287 
288     if (Info.getMapping() == diag::MAP_FATAL)
289       Info.setMapping(diag::MAP_ERROR);
290 
291     Info.setNoErrorAsFatal(true);
292   }
293 
294   return false;
295 }
296 
297 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
298   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
299 
300   CurDiagLoc = storedDiag.getLocation();
301   CurDiagID = storedDiag.getID();
302   NumDiagArgs = 0;
303 
304   NumDiagRanges = storedDiag.range_size();
305   assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
306          "Too many arguments to diagnostic!");
307   unsigned i = 0;
308   for (StoredDiagnostic::range_iterator
309          RI = storedDiag.range_begin(),
310          RE = storedDiag.range_end(); RI != RE; ++RI)
311     DiagRanges[i++] = *RI;
312 
313   NumFixItHints = storedDiag.fixit_size();
314   assert(NumFixItHints < DiagnosticsEngine::MaxFixItHints &&
315       "Too many fix-it hints!");
316   i = 0;
317   for (StoredDiagnostic::fixit_iterator
318          FI = storedDiag.fixit_begin(),
319          FE = storedDiag.fixit_end(); FI != FE; ++FI)
320     FixItHints[i++] = *FI;
321 
322   assert(Client && "DiagnosticConsumer not set!");
323   Level DiagLevel = storedDiag.getLevel();
324   Diagnostic Info(this, storedDiag.getMessage());
325   Client->HandleDiagnostic(DiagLevel, Info);
326   if (Client->IncludeInDiagnosticCounts()) {
327     if (DiagLevel == DiagnosticsEngine::Warning)
328       ++NumWarnings;
329   }
330 
331   CurDiagID = ~0U;
332 }
333 
334 void DiagnosticBuilder::FlushCounts() {
335   DiagObj->NumDiagArgs = NumArgs;
336   DiagObj->NumDiagRanges = NumRanges;
337   DiagObj->NumFixItHints = NumFixItHints;
338 }
339 
340 bool DiagnosticBuilder::Emit() {
341   // If DiagObj is null, then its soul was stolen by the copy ctor
342   // or the user called Emit().
343   if (DiagObj == 0) return false;
344 
345   // When emitting diagnostics, we set the final argument count into
346   // the DiagnosticsEngine object.
347   FlushCounts();
348 
349   // Process the diagnostic, sending the accumulated information to the
350   // DiagnosticConsumer.
351   bool Emitted = DiagObj->ProcessDiag();
352 
353   // Clear out the current diagnostic object.
354   unsigned DiagID = DiagObj->CurDiagID;
355   DiagObj->Clear();
356 
357   // If there was a delayed diagnostic, emit it now.
358   if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
359     DiagObj->ReportDelayed();
360 
361   // This diagnostic is dead.
362   DiagObj = 0;
363 
364   return Emitted;
365 }
366 
367 
368 DiagnosticConsumer::~DiagnosticConsumer() {}
369 
370 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
371                                         const Diagnostic &Info) {
372   if (!IncludeInDiagnosticCounts())
373     return;
374 
375   if (DiagLevel == DiagnosticsEngine::Warning)
376     ++NumWarnings;
377   else if (DiagLevel >= DiagnosticsEngine::Error)
378     ++NumErrors;
379 }
380 
381 /// ModifierIs - Return true if the specified modifier matches specified string.
382 template <std::size_t StrLen>
383 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
384                        const char (&Str)[StrLen]) {
385   return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
386 }
387 
388 /// ScanForward - Scans forward, looking for the given character, skipping
389 /// nested clauses and escaped characters.
390 static const char *ScanFormat(const char *I, const char *E, char Target) {
391   unsigned Depth = 0;
392 
393   for ( ; I != E; ++I) {
394     if (Depth == 0 && *I == Target) return I;
395     if (Depth != 0 && *I == '}') Depth--;
396 
397     if (*I == '%') {
398       I++;
399       if (I == E) break;
400 
401       // Escaped characters get implicitly skipped here.
402 
403       // Format specifier.
404       if (!isdigit(*I) && !ispunct(*I)) {
405         for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
406         if (I == E) break;
407         if (*I == '{')
408           Depth++;
409       }
410     }
411   }
412   return E;
413 }
414 
415 /// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
416 /// like this:  %select{foo|bar|baz}2.  This means that the integer argument
417 /// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
418 /// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
419 /// This is very useful for certain classes of variant diagnostics.
420 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
421                                  const char *Argument, unsigned ArgumentLen,
422                                  SmallVectorImpl<char> &OutStr) {
423   const char *ArgumentEnd = Argument+ArgumentLen;
424 
425   // Skip over 'ValNo' |'s.
426   while (ValNo) {
427     const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
428     assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
429            " larger than the number of options in the diagnostic string!");
430     Argument = NextVal+1;  // Skip this string.
431     --ValNo;
432   }
433 
434   // Get the end of the value.  This is either the } or the |.
435   const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
436 
437   // Recursively format the result of the select clause into the output string.
438   DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
439 }
440 
441 /// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
442 /// letter 's' to the string if the value is not 1.  This is used in cases like
443 /// this:  "you idiot, you have %4 parameter%s4!".
444 static void HandleIntegerSModifier(unsigned ValNo,
445                                    SmallVectorImpl<char> &OutStr) {
446   if (ValNo != 1)
447     OutStr.push_back('s');
448 }
449 
450 /// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
451 /// prints the ordinal form of the given integer, with 1 corresponding
452 /// to the first ordinal.  Currently this is hard-coded to use the
453 /// English form.
454 static void HandleOrdinalModifier(unsigned ValNo,
455                                   SmallVectorImpl<char> &OutStr) {
456   assert(ValNo != 0 && "ValNo must be strictly positive!");
457 
458   llvm::raw_svector_ostream Out(OutStr);
459 
460   // We could use text forms for the first N ordinals, but the numeric
461   // forms are actually nicer in diagnostics because they stand out.
462   Out << ValNo;
463 
464   // It is critically important that we do this perfectly for
465   // user-written sequences with over 100 elements.
466   switch (ValNo % 100) {
467   case 11:
468   case 12:
469   case 13:
470     Out << "th"; return;
471   default:
472     switch (ValNo % 10) {
473     case 1: Out << "st"; return;
474     case 2: Out << "nd"; return;
475     case 3: Out << "rd"; return;
476     default: Out << "th"; return;
477     }
478   }
479 }
480 
481 
482 /// PluralNumber - Parse an unsigned integer and advance Start.
483 static unsigned PluralNumber(const char *&Start, const char *End) {
484   // Programming 101: Parse a decimal number :-)
485   unsigned Val = 0;
486   while (Start != End && *Start >= '0' && *Start <= '9') {
487     Val *= 10;
488     Val += *Start - '0';
489     ++Start;
490   }
491   return Val;
492 }
493 
494 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
495 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
496   if (*Start != '[') {
497     unsigned Ref = PluralNumber(Start, End);
498     return Ref == Val;
499   }
500 
501   ++Start;
502   unsigned Low = PluralNumber(Start, End);
503   assert(*Start == ',' && "Bad plural expression syntax: expected ,");
504   ++Start;
505   unsigned High = PluralNumber(Start, End);
506   assert(*Start == ']' && "Bad plural expression syntax: expected )");
507   ++Start;
508   return Low <= Val && Val <= High;
509 }
510 
511 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
512 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
513   // Empty condition?
514   if (*Start == ':')
515     return true;
516 
517   while (1) {
518     char C = *Start;
519     if (C == '%') {
520       // Modulo expression
521       ++Start;
522       unsigned Arg = PluralNumber(Start, End);
523       assert(*Start == '=' && "Bad plural expression syntax: expected =");
524       ++Start;
525       unsigned ValMod = ValNo % Arg;
526       if (TestPluralRange(ValMod, Start, End))
527         return true;
528     } else {
529       assert((C == '[' || (C >= '0' && C <= '9')) &&
530              "Bad plural expression syntax: unexpected character");
531       // Range expression
532       if (TestPluralRange(ValNo, Start, End))
533         return true;
534     }
535 
536     // Scan for next or-expr part.
537     Start = std::find(Start, End, ',');
538     if (Start == End)
539       break;
540     ++Start;
541   }
542   return false;
543 }
544 
545 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
546 /// for complex plural forms, or in languages where all plurals are complex.
547 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
548 /// conditions that are tested in order, the form corresponding to the first
549 /// that applies being emitted. The empty condition is always true, making the
550 /// last form a default case.
551 /// Conditions are simple boolean expressions, where n is the number argument.
552 /// Here are the rules.
553 /// condition  := expression | empty
554 /// empty      :=                             -> always true
555 /// expression := numeric [',' expression]    -> logical or
556 /// numeric    := range                       -> true if n in range
557 ///             | '%' number '=' range        -> true if n % number in range
558 /// range      := number
559 ///             | '[' number ',' number ']'   -> ranges are inclusive both ends
560 ///
561 /// Here are some examples from the GNU gettext manual written in this form:
562 /// English:
563 /// {1:form0|:form1}
564 /// Latvian:
565 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
566 /// Gaeilge:
567 /// {1:form0|2:form1|:form2}
568 /// Romanian:
569 /// {1:form0|0,%100=[1,19]:form1|:form2}
570 /// Lithuanian:
571 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
572 /// Russian (requires repeated form):
573 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
574 /// Slovak
575 /// {1:form0|[2,4]:form1|:form2}
576 /// Polish (requires repeated form):
577 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
578 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
579                                  const char *Argument, unsigned ArgumentLen,
580                                  SmallVectorImpl<char> &OutStr) {
581   const char *ArgumentEnd = Argument + ArgumentLen;
582   while (1) {
583     assert(Argument < ArgumentEnd && "Plural expression didn't match.");
584     const char *ExprEnd = Argument;
585     while (*ExprEnd != ':') {
586       assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
587       ++ExprEnd;
588     }
589     if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
590       Argument = ExprEnd + 1;
591       ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
592 
593       // Recursively format the result of the plural clause into the
594       // output string.
595       DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
596       return;
597     }
598     Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
599   }
600 }
601 
602 
603 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
604 /// formal arguments into the %0 slots.  The result is appended onto the Str
605 /// array.
606 void Diagnostic::
607 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
608   if (!StoredDiagMessage.empty()) {
609     OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
610     return;
611   }
612 
613   StringRef Diag =
614     getDiags()->getDiagnosticIDs()->getDescription(getID());
615 
616   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
617 }
618 
619 void Diagnostic::
620 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
621                  SmallVectorImpl<char> &OutStr) const {
622 
623   /// FormattedArgs - Keep track of all of the arguments formatted by
624   /// ConvertArgToString and pass them into subsequent calls to
625   /// ConvertArgToString, allowing the implementation to avoid redundancies in
626   /// obvious cases.
627   SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
628 
629   /// QualTypeVals - Pass a vector of arrays so that QualType names can be
630   /// compared to see if more information is needed to be printed.
631   SmallVector<intptr_t, 2> QualTypeVals;
632   for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
633     if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
634       QualTypeVals.push_back(getRawArg(i));
635 
636   while (DiagStr != DiagEnd) {
637     if (DiagStr[0] != '%') {
638       // Append non-%0 substrings to Str if we have one.
639       const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
640       OutStr.append(DiagStr, StrEnd);
641       DiagStr = StrEnd;
642       continue;
643     } else if (ispunct(DiagStr[1])) {
644       OutStr.push_back(DiagStr[1]);  // %% -> %.
645       DiagStr += 2;
646       continue;
647     }
648 
649     // Skip the %.
650     ++DiagStr;
651 
652     // This must be a placeholder for a diagnostic argument.  The format for a
653     // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
654     // The digit is a number from 0-9 indicating which argument this comes from.
655     // The modifier is a string of digits from the set [-a-z]+, arguments is a
656     // brace enclosed string.
657     const char *Modifier = 0, *Argument = 0;
658     unsigned ModifierLen = 0, ArgumentLen = 0;
659 
660     // Check to see if we have a modifier.  If so eat it.
661     if (!isdigit(DiagStr[0])) {
662       Modifier = DiagStr;
663       while (DiagStr[0] == '-' ||
664              (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
665         ++DiagStr;
666       ModifierLen = DiagStr-Modifier;
667 
668       // If we have an argument, get it next.
669       if (DiagStr[0] == '{') {
670         ++DiagStr; // Skip {.
671         Argument = DiagStr;
672 
673         DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
674         assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
675         ArgumentLen = DiagStr-Argument;
676         ++DiagStr;  // Skip }.
677       }
678     }
679 
680     assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
681     unsigned ArgNo = *DiagStr++ - '0';
682 
683     DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
684 
685     switch (Kind) {
686     // ---- STRINGS ----
687     case DiagnosticsEngine::ak_std_string: {
688       const std::string &S = getArgStdStr(ArgNo);
689       assert(ModifierLen == 0 && "No modifiers for strings yet");
690       OutStr.append(S.begin(), S.end());
691       break;
692     }
693     case DiagnosticsEngine::ak_c_string: {
694       const char *S = getArgCStr(ArgNo);
695       assert(ModifierLen == 0 && "No modifiers for strings yet");
696 
697       // Don't crash if get passed a null pointer by accident.
698       if (!S)
699         S = "(null)";
700 
701       OutStr.append(S, S + strlen(S));
702       break;
703     }
704     // ---- INTEGERS ----
705     case DiagnosticsEngine::ak_sint: {
706       int Val = getArgSInt(ArgNo);
707 
708       if (ModifierIs(Modifier, ModifierLen, "select")) {
709         HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
710                              OutStr);
711       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
712         HandleIntegerSModifier(Val, OutStr);
713       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
714         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
715                              OutStr);
716       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
717         HandleOrdinalModifier((unsigned)Val, OutStr);
718       } else {
719         assert(ModifierLen == 0 && "Unknown integer modifier");
720         llvm::raw_svector_ostream(OutStr) << Val;
721       }
722       break;
723     }
724     case DiagnosticsEngine::ak_uint: {
725       unsigned Val = getArgUInt(ArgNo);
726 
727       if (ModifierIs(Modifier, ModifierLen, "select")) {
728         HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
729       } else if (ModifierIs(Modifier, ModifierLen, "s")) {
730         HandleIntegerSModifier(Val, OutStr);
731       } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
732         HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
733                              OutStr);
734       } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
735         HandleOrdinalModifier(Val, OutStr);
736       } else {
737         assert(ModifierLen == 0 && "Unknown integer modifier");
738         llvm::raw_svector_ostream(OutStr) << Val;
739       }
740       break;
741     }
742     // ---- NAMES and TYPES ----
743     case DiagnosticsEngine::ak_identifierinfo: {
744       const IdentifierInfo *II = getArgIdentifier(ArgNo);
745       assert(ModifierLen == 0 && "No modifiers for strings yet");
746 
747       // Don't crash if get passed a null pointer by accident.
748       if (!II) {
749         const char *S = "(null)";
750         OutStr.append(S, S + strlen(S));
751         continue;
752       }
753 
754       llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
755       break;
756     }
757     case DiagnosticsEngine::ak_qualtype:
758     case DiagnosticsEngine::ak_declarationname:
759     case DiagnosticsEngine::ak_nameddecl:
760     case DiagnosticsEngine::ak_nestednamespec:
761     case DiagnosticsEngine::ak_declcontext:
762       getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
763                                      Modifier, ModifierLen,
764                                      Argument, ArgumentLen,
765                                      FormattedArgs.data(), FormattedArgs.size(),
766                                      OutStr, QualTypeVals);
767       break;
768     }
769 
770     // Remember this argument info for subsequent formatting operations.  Turn
771     // std::strings into a null terminated string to make it be the same case as
772     // all the other ones.
773     if (Kind != DiagnosticsEngine::ak_std_string)
774       FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
775     else
776       FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
777                                         (intptr_t)getArgStdStr(ArgNo).c_str()));
778 
779   }
780 }
781 
782 StoredDiagnostic::StoredDiagnostic() { }
783 
784 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
785                                    StringRef Message)
786   : ID(ID), Level(Level), Loc(), Message(Message) { }
787 
788 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
789                                    const Diagnostic &Info)
790   : ID(Info.getID()), Level(Level)
791 {
792   assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
793        "Valid source location without setting a source manager for diagnostic");
794   if (Info.getLocation().isValid())
795     Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
796   llvm::SmallString<64> Message;
797   Info.FormatDiagnostic(Message);
798   this->Message.assign(Message.begin(), Message.end());
799 
800   Ranges.reserve(Info.getNumRanges());
801   for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
802     Ranges.push_back(Info.getRange(I));
803 
804   FixIts.reserve(Info.getNumFixItHints());
805   for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
806     FixIts.push_back(Info.getFixItHint(I));
807 }
808 
809 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
810                                    StringRef Message, FullSourceLoc Loc,
811                                    ArrayRef<CharSourceRange> Ranges,
812                                    ArrayRef<FixItHint> Fixits)
813   : ID(ID), Level(Level), Loc(Loc), Message(Message)
814 {
815   this->Ranges.assign(Ranges.begin(), Ranges.end());
816   this->FixIts.assign(FixIts.begin(), FixIts.end());
817 }
818 
819 StoredDiagnostic::~StoredDiagnostic() { }
820 
821 /// IncludeInDiagnosticCounts - This method (whose default implementation
822 ///  returns true) indicates whether the diagnostics handled by this
823 ///  DiagnosticConsumer should be included in the number of diagnostics
824 ///  reported by DiagnosticsEngine.
825 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
826 
827 PartialDiagnostic::StorageAllocator::StorageAllocator() {
828   for (unsigned I = 0; I != NumCached; ++I)
829     FreeList[I] = Cached + I;
830   NumFreeListEntries = NumCached;
831 }
832 
833 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
834   // Don't assert if we are in a CrashRecovery context, as this
835   // invariant may be invalidated during a crash.
836   assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
837 }
838