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