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