clang 24.0.0git
Diagnostic.cpp
Go to the documentation of this file.
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
25#include "llvm/ADT/IntrusiveRefCntPtr.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Support/ConvertUTF.h"
32#include "llvm/Support/CrashRecoveryContext.h"
33#include "llvm/Support/Error.h"
34#include "llvm/Support/FormatVariadic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/SpecialCaseList.h"
37#include "llvm/Support/Unicode.h"
38#include "llvm/Support/VirtualFileSystem.h"
39#include "llvm/Support/raw_ostream.h"
40#include <algorithm>
41#include <cassert>
42#include <cstddef>
43#include <cstdint>
44#include <cstring>
45#include <memory>
46#include <string>
47#include <utility>
48#include <vector>
49
50using namespace clang;
51
53 DiagNullabilityKind nullability) {
54 DB.AddString(
55 ("'" +
56 getNullabilitySpelling(nullability.first,
57 /*isContextSensitive=*/nullability.second) +
58 "'")
59 .str());
60 return DB;
61}
62
64 llvm::Error &&E) {
65 DB.AddString(toString(std::move(E)));
66 return DB;
67}
68
69static void
71 StringRef Modifier, StringRef Argument,
73 SmallVectorImpl<char> &Output, void *Cookie,
74 ArrayRef<intptr_t> QualTypeVals) {
75 StringRef Str = "<can't format argument>";
76 Output.append(Str.begin(), Str.end());
77}
78
79// FIXME: We should isolate the parser from SpecialCaseList and just use it
80// here.
82 : public llvm::SpecialCaseList {
83public:
84 static std::unique_ptr<WarningsSpecialCaseList>
85 create(const llvm::MemoryBuffer &Input, std::string &Err);
86
87 // Section names refer to diagnostic groups, which cover multiple individual
88 // diagnostics. Expand diagnostic groups here to individual diagnostics.
89 // A diagnostic can have multiple diagnostic groups associated with it, we let
90 // the last section take precedence in such cases.
92
93 bool isDiagSuppressed(diag::kind DiagId, SourceLocation DiagLoc,
94 const SourceManager &SM) const;
95
96 /// Whether a section applies to \p DiagId.
97 bool hasSection(diag::kind DiagId) const {
98 return DiagToSection.contains(DiagId);
99 }
100
101private:
102 llvm::DenseMap<diag::kind, const Section *> DiagToSection;
103};
104
106 DiagnosticOptions &DiagOpts,
107 DiagnosticConsumer *client,
108 bool ShouldOwnClient)
109 : Diags(std::move(diags)), DiagOpts(DiagOpts) {
110 setClient(client, ShouldOwnClient);
111 ArgToStringFn = DummyArgToStringFn;
112
113 Reset();
114}
115
117 // If we own the diagnostic client, destroy it first so that it can access the
118 // engine from its destructor.
119 setClient(nullptr);
120}
121
122void DiagnosticsEngine::dump() const { DiagStatesByLoc.dump(*SourceMgr); }
123
124void DiagnosticsEngine::dump(StringRef DiagName) const {
125 DiagStatesByLoc.dump(*SourceMgr, DiagName);
126}
127
129 bool ShouldOwnClient) {
130 Owner.reset(ShouldOwnClient ? client : nullptr);
131 Client = client;
132}
133
135 DiagStateOnPushStack.push_back(GetCurDiagState());
136}
137
139 if (DiagStateOnPushStack.empty())
140 return false;
141
142 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
143 // State changed at some point between push/pop.
144 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
145 }
146 DiagStateOnPushStack.pop_back();
147 return true;
148}
149
150void DiagnosticsEngine::ResetPragmas() { DiagStatesByLoc.clear(/*Soft=*/true); }
151
152void DiagnosticsEngine::Reset(bool soft /*=false*/) {
153 ErrorOccurred = false;
154 UncompilableErrorOccurred = false;
155 FatalErrorOccurred = false;
156 UnrecoverableErrorOccurred = false;
157
158 NumWarnings = 0;
159 NumErrors = 0;
160 TrapNumErrorsOccurred = 0;
161 TrapNumUnrecoverableErrorsOccurred = 0;
162
163 LastDiagLevel = Ignored;
164
165 if (!soft) {
166 // Clear state related to #pragma diagnostic.
167 DiagStates.clear();
168 DiagStatesByLoc.clear(false);
169 DiagStateOnPushStack.clear();
170
171 // Create a DiagState and DiagStatePoint representing diagnostic changes
172 // through command-line.
173 DiagStates.emplace_back(*Diags);
174 DiagStatesByLoc.appendFirst(&DiagStates.back());
175 }
176}
177
179DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) {
180 std::pair<iterator, bool> Result = DiagMap.try_emplace(Diag);
181
182 // Initialize the entry if we added it.
183 if (Result.second) {
184 Result.first->second = DiagIDs.getDefaultMapping(Diag);
186 DiagIDs.initCustomDiagMapping(Result.first->second, Diag);
187 }
188
189 return Result.first->second;
190}
191
192void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
193 assert(Files.empty() && "not first");
194 FirstDiagState = CurDiagState = State;
195 CurDiagStateLoc = SourceLocation();
196}
197
198void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
199 SourceLocation Loc,
200 DiagState *State) {
201 CurDiagState = State;
202 CurDiagStateLoc = Loc;
203
204 FileIDAndOffset Decomp = SrcMgr.getDecomposedLoc(Loc);
205 unsigned Offset = Decomp.second;
206 for (File *F = getFile(SrcMgr, Decomp.first); F;
207 Offset = F->ParentOffset, F = F->Parent) {
208 F->HasLocalTransitions = true;
209 auto &Last = F->StateTransitions.back();
210 assert(Last.Offset <= Offset && "state transitions added out of order");
211
212 if (Last.Offset == Offset) {
213 if (Last.State == State)
214 break;
215 Last.State = State;
216 continue;
217 }
218
219 F->StateTransitions.push_back({State, Offset});
220 }
221}
222
223DiagnosticsEngine::DiagState *
224DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
225 SourceLocation Loc) const {
226 // Common case: we have not seen any diagnostic pragmas.
227 if (Files.empty())
228 return FirstDiagState;
229
230 FileIDAndOffset Decomp = SrcMgr.getDecomposedLoc(Loc);
231 const File *F = getFile(SrcMgr, Decomp.first);
232 return F->lookup(Decomp.second);
233}
234
235DiagnosticsEngine::DiagState *
236DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
237 auto OnePastIt =
238 llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
239 return P.Offset <= Offset;
240 });
241 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
242 return OnePastIt[-1].State;
243}
244
245DiagnosticsEngine::DiagStateMap::File *
246DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
247 FileID ID) const {
248 assert(ID != FileID::getSentinel());
249 if (LastLookupFileID != ID) {
250 // getFileUncached() can recurse into getFile(), so update the cache after.
251 LastLookupFile = getFileUncached(SrcMgr, ID);
252 LastLookupFileID = ID;
253 }
254 return LastLookupFile;
255}
256
257DiagnosticsEngine::DiagStateMap::File *
258DiagnosticsEngine::DiagStateMap::getFileUncached(SourceManager &SrcMgr,
259 FileID ID) const {
260 // Get or insert the File for this ID.
261 auto [FilePtr, Inserted] = getOrInsertFile(ID);
262 if (!Inserted)
263 return FilePtr;
264 auto &F = *FilePtr;
265
266 // We created a new File; look up the diagnostic state at the start of it and
267 // initialize it.
268 if (ID.isValid()) {
269 FileIDAndOffset Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
270 F.Parent = getFile(SrcMgr, Decomp.first);
271 F.ParentOffset = Decomp.second;
272 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
273 } else {
274 // This is the (imaginary) root file into which we pretend all top-level
275 // files are included; it descends from the initial state.
276 //
277 // FIXME: This doesn't guarantee that we use the same ordering as
278 // isBeforeInTranslationUnit in the cases where someone invented another
279 // top-level file and added diagnostic pragmas to it. See the code at the
280 // end of isBeforeInTranslationUnit for the quirks it deals with.
281 F.StateTransitions.push_back({FirstDiagState, 0});
282 }
283 return &F;
284}
285
286void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
287 StringRef DiagName) const {
288 llvm::errs() << "diagnostic state at ";
289 CurDiagStateLoc.print(llvm::errs(), SrcMgr);
290 llvm::errs() << ": " << CurDiagState << "\n";
291
292 SmallVector<std::pair<FileID, File *>, 16> SortedFiles;
293 for (const auto &[ID, FilePtr] : Files)
294 SortedFiles.emplace_back(ID, FilePtr.get());
295 llvm::sort(SortedFiles, llvm::less_first());
296
297 for (auto &F : SortedFiles) {
298 FileID ID = F.first;
299 File &File = *F.second;
300
301 bool PrintedOuterHeading = false;
302 auto PrintOuterHeading = [&] {
303 if (PrintedOuterHeading)
304 return;
305 PrintedOuterHeading = true;
306
307 llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
308 << ">: " << SrcMgr.getBufferOrFake(ID).getBufferIdentifier();
309
310 if (File.Parent) {
311 FileIDAndOffset Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
312 assert(File.ParentOffset == Decomp.second);
313 llvm::errs() << " parent " << File.Parent << " <FileID "
314 << Decomp.first.getHashValue() << "> ";
315 SrcMgr.getLocForStartOfFile(Decomp.first)
316 .getLocWithOffset(Decomp.second)
317 .print(llvm::errs(), SrcMgr);
318 }
319 if (File.HasLocalTransitions)
320 llvm::errs() << " has_local_transitions";
321 llvm::errs() << "\n";
322 };
323
324 if (DiagName.empty())
325 PrintOuterHeading();
326
327 for (DiagStatePoint &Transition : File.StateTransitions) {
328 bool PrintedInnerHeading = false;
329 auto PrintInnerHeading = [&] {
330 if (PrintedInnerHeading)
331 return;
332 PrintedInnerHeading = true;
333
334 PrintOuterHeading();
335 llvm::errs() << " ";
336 SrcMgr.getLocForStartOfFile(ID)
337 .getLocWithOffset(Transition.Offset)
338 .print(llvm::errs(), SrcMgr);
339 llvm::errs() << ": state " << Transition.State << ":\n";
340 };
341
342 if (DiagName.empty())
343 PrintInnerHeading();
344
345 for (auto &Mapping : *Transition.State) {
346 StringRef Option =
347 SrcMgr.getDiagnostics().Diags->getWarningOptionForDiag(
348 Mapping.first);
349 if (!DiagName.empty() && DiagName != Option)
350 continue;
351
352 PrintInnerHeading();
353 llvm::errs() << " ";
354 if (Option.empty())
355 llvm::errs() << "<unknown " << Mapping.first << ">";
356 else
357 llvm::errs() << Option;
358 llvm::errs() << ": ";
359
360 switch (Mapping.second.getSeverity()) {
362 llvm::errs() << "ignored";
363 break;
365 llvm::errs() << "remark";
366 break;
368 llvm::errs() << "warning";
369 break;
371 llvm::errs() << "error";
372 break;
374 llvm::errs() << "fatal";
375 break;
376 }
377
378 if (!Mapping.second.isUser())
379 llvm::errs() << " default";
380 if (Mapping.second.isPragma())
381 llvm::errs() << " pragma";
382 if (Mapping.second.hasNoWarningAsError())
383 llvm::errs() << " no-error";
384 if (Mapping.second.hasNoErrorAsFatal())
385 llvm::errs() << " no-fatal";
386 if (Mapping.second.wasUpgradedFromWarning())
387 llvm::errs() << " overruled";
388 llvm::errs() << "\n";
389 }
390 }
391 }
392}
393
394void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
395 SourceLocation Loc) {
396 assert(Loc.isValid() && "Adding invalid loc point");
397 DiagStatesByLoc.append(*SourceMgr, Loc, State);
398}
399
401 SourceLocation L) {
402 assert((Diags->isWarningOrExtension(Diag) ||
403 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
404 "Cannot map errors into warnings!");
405 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
406
407 // A command line -Wfoo has an invalid L and cannot override error/fatal
408 // mapping, while a warning pragma can.
409 bool WasUpgradedFromWarning = false;
410 if (Map == diag::Severity::Warning && L.isInvalid()) {
411 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
412 if (Info.getSeverity() == diag::Severity::Error ||
414 Map = Info.getSeverity();
415 WasUpgradedFromWarning = true;
416 }
417 }
418 DiagnosticMapping Mapping = makeUserMapping(Map, L);
419 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
420
421 // Make sure we propagate the NoWarningAsError flag from an existing
422 // mapping (which may be the default mapping).
423 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
425 Mapping.hasNoWarningAsError());
426
427 // Common case; setting all the diagnostics of a group in one place.
428 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
429 DiagStatesByLoc.getCurDiagState()) {
430 // FIXME: This is theoretically wrong: if the current state is shared with
431 // some other location (via push/pop) we will change the state for that
432 // other location as well. This cannot currently happen, as we can't update
433 // the diagnostic state at the same location at which we pop.
434 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
435 return;
436 }
437
438 // A diagnostic pragma occurred, create a new DiagState initialized with
439 // the current one and a new DiagStatePoint to record at which location
440 // the new state became active.
441 DiagStates.push_back(*GetCurDiagState());
442 DiagStates.back().setMapping(Diag, Mapping);
443 PushDiagStatePoint(&DiagStates.back(), L);
444}
445
447 StringRef Group, diag::Severity Map,
448 SourceLocation Loc) {
449 // Get the diagnostics in this group.
451 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
452 return true;
453
454 Diags->setGroupSeverity(Group, Map);
455
456 // Set the mapping.
457 for (diag::kind Diag : GroupDiags)
458 setSeverity(Diag, Map, Loc);
459
460 return false;
461}
462
464 diag::Group Group,
465 diag::Severity Map,
466 SourceLocation Loc) {
467 return setSeverityForGroup(Flavor, Diags->getWarningOptionForGroup(Group),
468 Map, Loc);
469}
470
472 bool Enabled) {
473 // If we are enabling this feature, just set the diagnostic mappings to map to
474 // errors.
475 if (Enabled)
478 Diags->setGroupSeverity(Group, diag::Severity::Warning);
479
480 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
481 // potentially downgrade anything already mapped to be a warning.
482
483 // Get the diagnostics in this group.
485 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
486 GroupDiags))
487 return true;
488
489 // Perform the mapping change.
490 for (diag::kind Diag : GroupDiags) {
491 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
492
493 if (Info.getSeverity() == diag::Severity::Error ||
496
497 Info.setNoWarningAsError(true);
498 }
499
500 return false;
501}
502
504 bool Enabled) {
505 // If we are enabling this feature, just set the diagnostic mappings to map to
506 // fatal errors.
507 if (Enabled)
510 Diags->setGroupSeverity(Group, diag::Severity::Error);
511
512 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
513 // and potentially downgrade anything already mapped to be a fatal error.
514
515 // Get the diagnostics in this group.
517 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
518 GroupDiags))
519 return true;
520
521 // Perform the mapping change.
522 for (diag::kind Diag : GroupDiags) {
523 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
524
527
528 Info.setNoErrorAsFatal(true);
529 }
530
531 return false;
532}
533
535 diag::Severity Map,
536 SourceLocation Loc) {
537 // Get all the diagnostics.
538 std::vector<diag::kind> AllDiags;
539 DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
540
541 // Set the mapping.
542 for (diag::kind Diag : AllDiags)
543 if (Diags->isWarningOrExtension(Diag))
544 setSeverity(Diag, Map, Loc);
545}
546
547std::unique_ptr<DiagnosticsEngine::WarningsSpecialCaseList>
549 const llvm::MemoryBuffer &Input, std::string &Err) {
550 auto WarningSuppressionList = std::make_unique<WarningsSpecialCaseList>();
551 if (!WarningSuppressionList->createInternal(&Input, Err))
552 return nullptr;
553 return WarningSuppressionList;
554}
555
557 DiagnosticsEngine &Diags) {
558 static constexpr auto WarningFlavor = clang::diag::Flavor::WarningOrError;
559 for (const auto &SectionEntry : sections()) {
560 StringRef DiagGroup = SectionEntry.name();
561 if (DiagGroup == "*") {
562 // Drop the default section introduced by special case list, we only
563 // support exact diagnostic group names.
564 // FIXME: We should make this configurable in the parser instead.
565 continue;
566 }
567 SmallVector<diag::kind> GroupDiags;
568 if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
569 WarningFlavor, DiagGroup, GroupDiags)) {
570 StringRef Suggestion =
571 DiagnosticIDs::getNearestOption(WarningFlavor, DiagGroup);
572 Diags.Report(diag::warn_unknown_diag_option)
573 << static_cast<unsigned>(WarningFlavor) << DiagGroup
574 << !Suggestion.empty() << Suggestion;
575 continue;
576 }
577 for (diag::kind Diag : GroupDiags)
578 // We're intentionally overwriting any previous mappings here to make sure
579 // latest one takes precedence.
580 DiagToSection[Diag] = &SectionEntry;
581 }
582}
583
584void DiagnosticsEngine::setDiagSuppressionMapping(llvm::MemoryBuffer &Input) {
585 std::string Error;
586 auto WarningSuppressionList = WarningsSpecialCaseList::create(Input, Error);
587 if (!WarningSuppressionList) {
588 // FIXME: Use a `%select` statement instead of printing `Error` as-is. This
589 // should help localization.
590 Report(diag::err_drv_malformed_warning_suppression_mapping)
591 << Input.getBufferIdentifier() << Error;
592 return;
593 }
594 WarningSuppressionList->processSections(*this);
595 DiagSuppressionMapping = std::move(WarningSuppressionList);
596}
597
599 diag::kind DiagId, SourceLocation DiagLoc, const SourceManager &SM) const {
600 const Section *DiagSection = DiagToSection.lookup(DiagId);
601 if (!DiagSection)
602 return false;
603 PresumedLoc PLoc = SM.getPresumedLoc(DiagLoc);
604 if (!PLoc.isValid())
605 return false;
606
607 StringRef F = llvm::sys::path::remove_leading_dotslash(PLoc.getFilename());
608
609 unsigned LastSup = DiagSection->getLastMatch("src", F, "");
610 if (LastSup == 0)
611 return false;
612
613 unsigned LastEmit = DiagSection->getLastMatch("src", F, "emit");
614 return LastSup > LastEmit;
615}
616
619 const SourceManager &SM = getSourceManager();
620 unsigned Class = 0;
621 if (SM.isInSystemHeader(SM.getExpansionLoc(Loc)))
622 Class |= static_cast<unsigned>(DiagStateSystemClass::SystemHeader);
623 if (SM.isInSystemMacro(Loc))
624 Class |= static_cast<unsigned>(DiagStateSystemClass::SystemMacro);
625 return static_cast<DiagStateSystemClass>(Class);
626}
627
629 SourceLocation DiagLoc) const {
630 if (!hasSourceManager() || !DiagSuppressionMapping)
631 return false;
632 return DiagSuppressionMapping->isDiagSuppressed(DiagId, DiagLoc,
634}
635
637 return DiagSuppressionMapping && DiagSuppressionMapping->hasSection(DiagId);
638}
639
641 DiagnosticStorage DiagStorage;
642 DiagStorage.DiagRanges.append(storedDiag.range_begin(),
643 storedDiag.range_end());
644
645 DiagStorage.FixItHints.append(storedDiag.fixit_begin(),
646 storedDiag.fixit_end());
647
648 assert(Client && "DiagnosticConsumer not set!");
649 Level DiagLevel = storedDiag.getLevel();
650 Diagnostic Info(this, storedDiag.getLocation(), storedDiag.getID(),
651 DiagStorage, storedDiag.getMessage());
652 Report(DiagLevel, Info);
653}
654
655void DiagnosticsEngine::Report(Level DiagLevel, const Diagnostic &Info) {
656 assert(DiagLevel != Ignored && "Cannot emit ignored diagnostics!");
657 assert(!getDiagnosticIDs()->isTrapDiag(Info.getID()) &&
658 "Trap diagnostics should not be consumed by the DiagnosticsEngine");
659 Client->HandleDiagnostic(DiagLevel, Info);
660 if (Client->IncludeInDiagnosticCounts()) {
661 if (DiagLevel == Warning)
662 ++NumWarnings;
663 }
664}
665
666/// ProcessDiag - This is the method used to report a diagnostic that is
667/// finally fully formed.
668bool DiagnosticsEngine::ProcessDiag(const DiagnosticBuilder &DiagBuilder) {
669 Diagnostic Info(this, DiagBuilder);
670
671 assert(getClient() && "DiagnosticClient not set!");
672
673 // Figure out the diagnostic level of this message.
674 unsigned DiagID = Info.getID();
675 Level DiagLevel = getDiagnosticLevel(DiagID, Info.getLocation());
676
677 // Update counts for DiagnosticErrorTrap even if a fatal error occurred
678 // or diagnostics are suppressed.
679 if (DiagLevel >= Error) {
680 ++TrapNumErrorsOccurred;
681 if (Diags->isUnrecoverable(DiagID))
682 ++TrapNumUnrecoverableErrorsOccurred;
683 }
684
685 if (SuppressAllDiagnostics)
686 return false;
687
688 if (DiagLevel != Note) {
689 // Record that a fatal error occurred only when we see a second
690 // non-note diagnostic. This allows notes to be attached to the
691 // fatal error, but suppresses any diagnostics that follow those
692 // notes.
693 if (LastDiagLevel == Fatal)
694 FatalErrorOccurred = true;
695
696 LastDiagLevel = DiagLevel;
697 }
698
699 // If a fatal error has already been emitted, silence all subsequent
700 // diagnostics.
701 if (FatalErrorOccurred) {
702 if (DiagLevel >= Error && Client->IncludeInDiagnosticCounts())
703 ++NumErrors;
704
705 return false;
706 }
707
708 // If the client doesn't care about this message, don't issue it. If this is
709 // a note and the last real diagnostic was ignored, ignore it too.
710 if (DiagLevel == Ignored || (DiagLevel == Note && LastDiagLevel == Ignored))
711 return false;
712
713 if (DiagLevel >= Error) {
714 if (Diags->isUnrecoverable(DiagID))
715 UnrecoverableErrorOccurred = true;
716
717 // Warnings which have been upgraded to errors do not prevent compilation.
718 if (Diags->isDefaultMappingAsError(DiagID))
719 UncompilableErrorOccurred = true;
720
721 ErrorOccurred = true;
722 if (Client->IncludeInDiagnosticCounts())
723 ++NumErrors;
724
725 // If we've emitted a lot of errors, emit a fatal error instead of it to
726 // stop a flood of bogus errors.
727 if (ErrorLimit && NumErrors > ErrorLimit && DiagLevel == Error) {
728 Report(diag::fatal_too_many_errors);
729 return false;
730 }
731 }
732
733 // Make sure we set FatalErrorOccurred to ensure that the notes from the
734 // diagnostic that caused `fatal_too_many_errors` won't be emitted.
735 if (Info.getID() == diag::fatal_too_many_errors)
736 FatalErrorOccurred = true;
737
738 // Finally, report it.
739 Report(DiagLevel, Info);
740 return true;
741}
742
744 bool Force) {
745 assert(getClient() && "DiagnosticClient not set!");
746
747 bool Emitted;
748 if (Force) {
749 Diagnostic Info(this, DB);
750
751 // Figure out the diagnostic level of this message.
752 Level DiagLevel = getDiagnosticLevel(Info.getID(), Info.getLocation());
753
754 // Emit the diagnostic regardless of suppression level.
755 Emitted = DiagLevel != Ignored;
756 if (Emitted)
757 Report(DiagLevel, Info);
758 } else {
759 // Process the diagnostic, sending the accumulated information to the
760 // DiagnosticConsumer.
761 Emitted = ProcessDiag(DB);
762 }
763
764 return Emitted;
765}
766
767DiagnosticBuilder::DiagnosticBuilder(DiagnosticsEngine *DiagObj,
768 SourceLocation DiagLoc, unsigned DiagID)
769 : StreamingDiagnostic(DiagObj->DiagAllocator), DiagObj(DiagObj),
770 DiagLoc(DiagLoc), DiagID(DiagID), IsActive(true) {
771 assert(DiagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
772}
773
774DiagnosticBuilder::DiagnosticBuilder(const DiagnosticBuilder &D)
776 DiagLoc = D.DiagLoc;
777 DiagID = D.DiagID;
778 FlagValue = D.FlagValue;
779 DiagObj = D.DiagObj;
781 D.DiagStorage = nullptr;
783 IsActive = D.IsActive;
784 IsForceEmit = D.IsForceEmit;
785 D.Clear();
786}
787
789 const DiagnosticBuilder &DiagBuilder)
790 : DiagObj(DO), DiagLoc(DiagBuilder.DiagLoc), DiagID(DiagBuilder.DiagID),
791 FlagValue(DiagBuilder.FlagValue), DiagStorage(*DiagBuilder.getStorage()) {
792}
793
795 unsigned DiagID, const DiagnosticStorage &DiagStorage,
796 StringRef StoredDiagMessage)
797 : DiagObj(DO), DiagLoc(DiagLoc), DiagID(DiagID), DiagStorage(DiagStorage),
798 StoredDiagMessage(StoredDiagMessage) {}
799
801
803 const Diagnostic &Info) {
805 return;
806
807 if (DiagLevel == DiagnosticsEngine::Warning)
808 ++NumWarnings;
809 else if (DiagLevel >= DiagnosticsEngine::Error)
810 ++NumErrors;
811}
812
813/// ModifierIs - Return true if the specified modifier matches specified string.
814template <std::size_t StrLen>
815static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
816 const char (&Str)[StrLen]) {
817 return StrLen - 1 == ModifierLen && memcmp(Modifier, Str, StrLen - 1) == 0;
818}
819
820/// ScanForward - Scans forward, looking for the given character, skipping
821/// nested clauses and escaped characters.
822static const char *ScanFormat(const char *I, const char *E, char Target) {
823 unsigned Depth = 0;
824
825 for (; I != E; ++I) {
826 if (Depth == 0 && *I == Target)
827 return I;
828 if (Depth != 0 && *I == '}')
829 Depth--;
830
831 if (*I == '%') {
832 I++;
833 if (I == E)
834 break;
835
836 // Escaped characters get implicitly skipped here.
837
838 // Format specifier.
839 if (!isDigit(*I) && !isPunctuation(*I)) {
840 for (I++; I != E && !isDigit(*I) && *I != '{'; I++)
841 ;
842 if (I == E)
843 break;
844 if (*I == '{')
845 Depth++;
846 }
847 }
848 }
849 return E;
850}
851
852/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
853/// like this: %select{foo|bar|baz}2. This means that the integer argument
854/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
855/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
856/// This is very useful for certain classes of variant diagnostics.
857static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
858 const char *Argument, unsigned ArgumentLen,
859 SmallVectorImpl<char> &OutStr) {
860 const char *ArgumentEnd = Argument + ArgumentLen;
861
862 // Skip over 'ValNo' |'s.
863 while (ValNo) {
864 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
865 assert(NextVal != ArgumentEnd &&
866 "Value for integer select modifier was"
867 " larger than the number of options in the diagnostic string!");
868 Argument = NextVal + 1; // Skip this string.
869 --ValNo;
870 }
871
872 // Get the end of the value. This is either the } or the |.
873 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
874
875 // Recursively format the result of the select clause into the output string.
876 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
877}
878
879/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
880/// letter 's' to the string if the value is not 1. This is used in cases like
881/// this: "you idiot, you have %4 parameter%s4!".
882static void HandleIntegerSModifier(unsigned ValNo,
883 SmallVectorImpl<char> &OutStr) {
884 if (ValNo != 1)
885 OutStr.push_back('s');
886}
887
888/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
889/// prints the ordinal form of the given integer, with 1 corresponding
890/// to the first ordinal. Currently this is hard-coded to use the
891/// English form.
892static void HandleOrdinalModifier(unsigned ValNo,
893 SmallVectorImpl<char> &OutStr) {
894 assert(ValNo != 0 && "ValNo must be strictly positive!");
895
896 llvm::raw_svector_ostream Out(OutStr);
897
898 // We could use text forms for the first N ordinals, but the numeric
899 // forms are actually nicer in diagnostics because they stand out.
900 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
901}
902
903// 123 -> "123".
904// 1234 -> "1.23k".
905// 123456 -> "123.46k".
906// 1234567 -> "1.23M".
907// 1234567890 -> "1.23G".
908// 1234567890123 -> "1.23T".
910 SmallVectorImpl<char> &OutStr) {
911 static constexpr std::array<std::pair<int64_t, char>, 4> Units = {
912 {{1'000'000'000'000L, 'T'},
913 {1'000'000'000L, 'G'},
914 {1'000'000L, 'M'},
915 {1'000L, 'k'}}};
916
917 llvm::raw_svector_ostream Out(OutStr);
918 if (ValNo < 0) {
919 Out << "-";
920 ValNo = -ValNo;
921 }
922 for (const auto &[UnitSize, UnitSign] : Units) {
923 if (ValNo >= UnitSize) {
924 Out << llvm::format("%0.2f%c", ValNo / static_cast<double>(UnitSize),
925 UnitSign);
926 return;
927 }
928 }
929 Out << ValNo;
930}
931
932/// PluralNumber - Parse an unsigned integer and advance Start.
933static unsigned PluralNumber(const char *&Start, const char *End) {
934 // Programming 101: Parse a decimal number :-)
935 unsigned Val = 0;
936 while (Start != End && *Start >= '0' && *Start <= '9') {
937 Val *= 10;
938 Val += *Start - '0';
939 ++Start;
940 }
941 return Val;
942}
943
944/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
945static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
946 if (*Start != '[') {
947 unsigned Ref = PluralNumber(Start, End);
948 return Ref == Val;
949 }
950
951 ++Start;
952 unsigned Low = PluralNumber(Start, End);
953 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
954 ++Start;
955 unsigned High = PluralNumber(Start, End);
956 assert(*Start == ']' && "Bad plural expression syntax: expected )");
957 ++Start;
958 return Low <= Val && Val <= High;
959}
960
961/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
962static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
963 // Empty condition?
964 if (*Start == ':')
965 return true;
966
967 while (true) {
968 char C = *Start;
969 if (C == '%') {
970 // Modulo expression
971 ++Start;
972 unsigned Arg = PluralNumber(Start, End);
973 assert(*Start == '=' && "Bad plural expression syntax: expected =");
974 ++Start;
975 unsigned ValMod = ValNo % Arg;
976 if (TestPluralRange(ValMod, Start, End))
977 return true;
978 } else {
979 assert((C == '[' || (C >= '0' && C <= '9')) &&
980 "Bad plural expression syntax: unexpected character");
981 // Range expression
982 if (TestPluralRange(ValNo, Start, End))
983 return true;
984 }
985
986 // Scan for next or-expr part.
987 Start = std::find(Start, End, ',');
988 if (Start == End)
989 break;
990 ++Start;
991 }
992 return false;
993}
994
995/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
996/// for complex plural forms, or in languages where all plurals are complex.
997/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
998/// conditions that are tested in order, the form corresponding to the first
999/// that applies being emitted. The empty condition is always true, making the
1000/// last form a default case.
1001/// Conditions are simple boolean expressions, where n is the number argument.
1002/// Here are the rules.
1003/// condition := expression | empty
1004/// empty := -> always true
1005/// expression := numeric [',' expression] -> logical or
1006/// numeric := range -> true if n in range
1007/// | '%' number '=' range -> true if n % number in range
1008/// range := number
1009/// | '[' number ',' number ']' -> ranges are inclusive both ends
1010///
1011/// Here are some examples from the GNU gettext manual written in this form:
1012/// English:
1013/// {1:form0|:form1}
1014/// Latvian:
1015/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
1016/// Gaeilge:
1017/// {1:form0|2:form1|:form2}
1018/// Romanian:
1019/// {1:form0|0,%100=[1,19]:form1|:form2}
1020/// Lithuanian:
1021/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
1022/// Russian (requires repeated form):
1023/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
1024/// Slovak
1025/// {1:form0|[2,4]:form1|:form2}
1026/// Polish (requires repeated form):
1027/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
1028static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
1029 const char *Argument, unsigned ArgumentLen,
1030 SmallVectorImpl<char> &OutStr) {
1031 const char *ArgumentEnd = Argument + ArgumentLen;
1032 while (true) {
1033 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
1034 const char *ExprEnd = Argument;
1035 while (*ExprEnd != ':') {
1036 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
1037 ++ExprEnd;
1038 }
1039 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
1040 Argument = ExprEnd + 1;
1041 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
1042
1043 // Recursively format the result of the plural clause into the
1044 // output string.
1045 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
1046 return;
1047 }
1048 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
1049 }
1050}
1051
1052/// Returns the friendly description for a token kind that will appear
1053/// without quotes in diagnostic messages. These strings may be translatable in
1054/// future.
1056 switch (Kind) {
1057 case tok::identifier:
1058 return "identifier";
1059 default:
1060 return nullptr;
1061 }
1062}
1063
1064/// FormatDiagnostic - Format this diagnostic into a string, substituting the
1065/// formal arguments into the %0 slots. The result is appended onto the Str
1066/// array.
1068 if (StoredDiagMessage.has_value()) {
1069 OutStr.append(StoredDiagMessage->begin(), StoredDiagMessage->end());
1070 return;
1071 }
1072
1073 StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID());
1074
1075 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
1076}
1077
1078/// EscapeStringForDiagnostic - Append Str to the diagnostic buffer,
1079/// escaping non-printable characters and ill-formed code unit sequences.
1080static void EscapeStringForDiagnostic(StringRef Str,
1081 SmallVectorImpl<char> &OutStr,
1082 bool ForCodepoint) {
1083 OutStr.reserve(OutStr.size() + Str.size());
1084 auto *Begin = reinterpret_cast<const unsigned char *>(Str.data());
1085 llvm::raw_svector_ostream OutStream(OutStr);
1086 unsigned Size = Str.size();
1087 const unsigned char *End = Begin + Size;
1088 if (ForCodepoint) {
1089 unsigned Size = llvm::getUTF8SequenceSize(Begin, End);
1090 if (Size == 0)
1091 Size = llvm::findMaximalSubpartOfIllFormedUTF8Sequence(Begin, End);
1092 End = Begin + Size;
1093 }
1094 while (Begin != End) {
1095 if (!ForCodepoint && (isPrintable(*Begin) || isWhitespace(*Begin))) {
1096 OutStream << *Begin;
1097 ++Begin;
1098 continue;
1099 }
1100 if (ForCodepoint && *Begin < 0x80) {
1101 if (isPrintable(*Begin)) {
1102 OutStream << "'" << *Begin << "'";
1103 ++Begin;
1104 continue;
1105 }
1106 }
1107 if (llvm::isLegalUTF8Sequence(Begin, End)) {
1108 llvm::UTF32 CodepointValue;
1109 llvm::UTF32 *CpPtr = &CodepointValue;
1110 const unsigned char *CodepointBegin = Begin;
1111 const unsigned char *CodepointEnd =
1112 Begin + llvm::getNumBytesForUTF8(*Begin);
1113 llvm::ConversionResult Res = llvm::ConvertUTF8toUTF32(
1114 &Begin, CodepointEnd, &CpPtr, CpPtr + 1, llvm::strictConversion);
1115 (void)Res;
1116 assert(
1117 llvm::conversionOK == Res &&
1118 "the sequence is legal UTF-8 but we couldn't convert it to UTF-32");
1119 assert(Begin == CodepointEnd &&
1120 "we must be further along in the string now");
1121
1122 if (llvm::sys::unicode::isPrintable(CodepointValue) ||
1123 (!ForCodepoint && llvm::sys::unicode::isFormatting(CodepointValue))) {
1124 OutStream << (ForCodepoint ? "'" : "")
1125 << StringRef(reinterpret_cast<const char *>(CodepointBegin),
1126 std::distance(CodepointBegin, CodepointEnd))
1127 << (ForCodepoint ? "' " : "");
1128 if (!ForCodepoint)
1129 continue;
1130 }
1131 // Unprintable code point.
1132 OutStream << (ForCodepoint ? "" : "<") << "U+"
1133 << llvm::format_hex_no_prefix(CodepointValue, 4, true)
1134 << (ForCodepoint ? "" : ">");
1135 continue;
1136 }
1137 // Invalid code unit.
1138 OutStream << "<0x" << llvm::format_hex_no_prefix(*Begin, 2, true) << ">";
1139 ++Begin;
1140 }
1141}
1142
1143/// EscapeStringForDiagnostic - Append Str to the diagnostic buffer,
1144/// escaping non-printable characters and ill-formed code unit sequences.
1146 SmallVectorImpl<char> &OutStr) {
1147 ::EscapeStringForDiagnostic(Str, OutStr, /*ForCodepoint=*/false);
1148}
1149
1150/// Displays a single Unicode codepoint in U+NNNN notation, optionally
1151/// prepending the quoted codepoint itself if printable.
1153 SmallString<16> CP;
1154 ::EscapeStringForDiagnostic(Str, CP, /*ForCodepoint=*/true);
1155 return CP;
1156}
1157
1159 char ResultBuf[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
1160 char *ResultPtr = ResultBuf;
1161 if (!llvm::ConvertCodePointToUTF8(CP, ResultPtr))
1162 return SmallString<16>(llvm::formatv("<{0:X+}>", CP).str());
1164 StringRef(ResultBuf, ResultPtr - ResultBuf));
1165}
1166
1167void Diagnostic::FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1168 SmallVectorImpl<char> &OutStr) const {
1169 // When the diagnostic string is only "%0", the entire string is being given
1170 // by an outside source. Remove unprintable characters from this string
1171 // and skip all the other string processing.
1172 if (DiagEnd - DiagStr == 2 && StringRef(DiagStr, DiagEnd - DiagStr) == "%0" &&
1174 const std::string &S = getArgStdStr(0);
1175 EscapeStringForDiagnostic(S, OutStr);
1176 return;
1177 }
1178
1179 /// FormattedArgs - Keep track of all of the arguments formatted by
1180 /// ConvertArgToString and pass them into subsequent calls to
1181 /// ConvertArgToString, allowing the implementation to avoid redundancies in
1182 /// obvious cases.
1184
1185 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
1186 /// compared to see if more information is needed to be printed.
1187 SmallVector<intptr_t, 2> QualTypeVals;
1188 SmallString<64> Tree;
1189
1190 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
1192 QualTypeVals.push_back(getRawArg(i));
1193
1194 while (DiagStr != DiagEnd) {
1195 if (DiagStr[0] != '%') {
1196 // Append non-%0 substrings to Str if we have one.
1197 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
1198 OutStr.append(DiagStr, StrEnd);
1199 DiagStr = StrEnd;
1200 continue;
1201 } else if (isPunctuation(DiagStr[1])) {
1202 OutStr.push_back(DiagStr[1]); // %% -> %.
1203 DiagStr += 2;
1204 continue;
1205 }
1206
1207 // Skip the %.
1208 ++DiagStr;
1209
1210 // This must be a placeholder for a diagnostic argument. The format for a
1211 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
1212 // The digit is a number from 0-9 indicating which argument this comes from.
1213 // The modifier is a string of digits from the set [-a-z]+, arguments is a
1214 // brace enclosed string.
1215 const char *Modifier = nullptr, *Argument = nullptr;
1216 unsigned ModifierLen = 0, ArgumentLen = 0;
1217
1218 // Check to see if we have a modifier. If so eat it.
1219 if (!isDigit(DiagStr[0])) {
1220 Modifier = DiagStr;
1221 while (DiagStr[0] == '-' || (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
1222 ++DiagStr;
1223 ModifierLen = DiagStr - Modifier;
1224
1225 // If we have an argument, get it next.
1226 if (DiagStr[0] == '{') {
1227 ++DiagStr; // Skip {.
1228 Argument = DiagStr;
1229
1230 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
1231 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
1232 ArgumentLen = DiagStr - Argument;
1233 ++DiagStr; // Skip }.
1234 }
1235 }
1236
1237 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
1238 unsigned ArgNo = *DiagStr++ - '0';
1239
1240 // Only used for type diffing.
1241 unsigned ArgNo2 = ArgNo;
1242
1244 if (ModifierIs(Modifier, ModifierLen, "diff")) {
1245 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
1246 "Invalid format for diff modifier");
1247 ++DiagStr; // Comma.
1248 ArgNo2 = *DiagStr++ - '0';
1250 if (Kind == DiagnosticsEngine::ak_qualtype &&
1253 else {
1254 // %diff only supports QualTypes. For other kinds of arguments,
1255 // use the default printing. For example, if the modifier is:
1256 // "%diff{compare $ to $|other text}1,2"
1257 // treat it as:
1258 // "compare %1 to %2"
1259 const char *ArgumentEnd = Argument + ArgumentLen;
1260 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1261 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
1262 "Found too many '|'s in a %diff modifier!");
1263 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
1264 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
1265 const char ArgStr1[] = {'%', static_cast<char>('0' + ArgNo)};
1266 const char ArgStr2[] = {'%', static_cast<char>('0' + ArgNo2)};
1267 FormatDiagnostic(Argument, FirstDollar, OutStr);
1268 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
1269 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1270 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
1271 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1272 continue;
1273 }
1274 }
1275
1276 switch (Kind) {
1277 // ---- STRINGS ----
1280 StringRef S = [&]() -> StringRef {
1282 return getArgStdStr(ArgNo);
1283 const char *SZ = getArgCStr(ArgNo);
1284 // Don't crash if get passed a null pointer by accident.
1285 return SZ ? SZ : "(null)";
1286 }();
1287 bool Quoted = false;
1288 if (ModifierIs(Modifier, ModifierLen, "quoted")) {
1289 Quoted = true;
1290 OutStr.push_back('\'');
1291 } else {
1292 assert(ModifierLen == 0 && "unknown modifier for string");
1293 }
1294 EscapeStringForDiagnostic(S, OutStr);
1295 if (Quoted)
1296 OutStr.push_back('\'');
1297 break;
1298 }
1299 // ---- INTEGERS ----
1301 int64_t Val = getArgSInt(ArgNo);
1302
1303 if (ModifierIs(Modifier, ModifierLen, "select")) {
1304 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
1305 OutStr);
1306 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
1307 HandleIntegerSModifier(Val, OutStr);
1308 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
1309 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
1310 OutStr);
1311 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
1312 HandleOrdinalModifier((unsigned)Val, OutStr);
1313 } else if (ModifierIs(Modifier, ModifierLen, "human")) {
1314 HandleIntegerHumanModifier(Val, OutStr);
1315 } else {
1316 assert(ModifierLen == 0 && "Unknown integer modifier");
1317 llvm::raw_svector_ostream(OutStr) << Val;
1318 }
1319 break;
1320 }
1322 uint64_t Val = getArgUInt(ArgNo);
1323
1324 if (ModifierIs(Modifier, ModifierLen, "select")) {
1325 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
1326 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
1327 HandleIntegerSModifier(Val, OutStr);
1328 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
1329 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
1330 OutStr);
1331 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
1332 HandleOrdinalModifier(Val, OutStr);
1333 } else if (ModifierIs(Modifier, ModifierLen, "human")) {
1334 HandleIntegerHumanModifier(Val, OutStr);
1335 } else {
1336 assert(ModifierLen == 0 && "Unknown integer modifier");
1337 llvm::raw_svector_ostream(OutStr) << Val;
1338 }
1339 break;
1340 }
1341 // ---- TOKEN SPELLINGS ----
1343 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
1344 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
1345
1346 llvm::raw_svector_ostream Out(OutStr);
1347 if (const char *S = tok::getPunctuatorSpelling(Kind))
1348 // Quoted token spelling for punctuators.
1349 Out << '\'' << S << '\'';
1350 else if ((S = tok::getKeywordSpelling(Kind)))
1351 // Unquoted token spelling for keywords.
1352 Out << S;
1353 else if ((S = getTokenDescForDiagnostic(Kind)))
1354 // Unquoted translatable token name.
1355 Out << S;
1356 else if ((S = tok::getTokenName(Kind)))
1357 // Debug name, shouldn't appear in user-facing diagnostics.
1358 Out << '<' << S << '>';
1359 else
1360 Out << "(null)";
1361 break;
1362 }
1363 // ---- NAMES and TYPES ----
1365 const IdentifierInfo *II = getArgIdentifier(ArgNo);
1366 assert(ModifierLen == 0 && "No modifiers for strings yet");
1367
1368 // Don't crash if get passed a null pointer by accident.
1369 if (!II) {
1370 const char *S = "(null)";
1371 OutStr.append(S, S + strlen(S));
1372 continue;
1373 }
1374
1375 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
1376 break;
1377 }
1388 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
1389 StringRef(Modifier, ModifierLen),
1390 StringRef(Argument, ArgumentLen),
1391 FormattedArgs, OutStr, QualTypeVals);
1392 break;
1394 // Create a struct with all the info needed for printing.
1396 TDT.FromType = getRawArg(ArgNo);
1397 TDT.ToType = getRawArg(ArgNo2);
1398 TDT.ElideType = getDiags()->ElideType;
1399 TDT.ShowColors = getDiags()->ShowColors;
1400 TDT.TemplateDiffUsed = false;
1401 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1402
1403 const char *ArgumentEnd = Argument + ArgumentLen;
1404 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1405
1406 // Print the tree. If this diagnostic already has a tree, skip the
1407 // second tree.
1408 if (getDiags()->PrintTemplateTree && Tree.empty()) {
1409 TDT.PrintFromType = true;
1410 TDT.PrintTree = true;
1411 getDiags()->ConvertArgToString(Kind, val,
1412 StringRef(Modifier, ModifierLen),
1413 StringRef(Argument, ArgumentLen),
1414 FormattedArgs, Tree, QualTypeVals);
1415 // If there is no tree information, fall back to regular printing.
1416 if (!Tree.empty()) {
1417 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1418 break;
1419 }
1420 }
1421
1422 // Non-tree printing, also the fall-back when tree printing fails.
1423 // The fall-back is triggered when the types compared are not templates.
1424 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1425 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1426
1427 // Append before text
1428 FormatDiagnostic(Argument, FirstDollar, OutStr);
1429
1430 // Append first type
1431 TDT.PrintTree = false;
1432 TDT.PrintFromType = true;
1433 getDiags()->ConvertArgToString(Kind, val,
1434 StringRef(Modifier, ModifierLen),
1435 StringRef(Argument, ArgumentLen),
1436 FormattedArgs, OutStr, QualTypeVals);
1437 if (!TDT.TemplateDiffUsed)
1438 FormattedArgs.push_back(
1439 std::make_pair(DiagnosticsEngine::ak_qualtype, TDT.FromType));
1440
1441 // Append middle text
1442 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1443
1444 // Append second type
1445 TDT.PrintFromType = false;
1446 getDiags()->ConvertArgToString(Kind, val,
1447 StringRef(Modifier, ModifierLen),
1448 StringRef(Argument, ArgumentLen),
1449 FormattedArgs, OutStr, QualTypeVals);
1450 if (!TDT.TemplateDiffUsed)
1451 FormattedArgs.push_back(
1452 std::make_pair(DiagnosticsEngine::ak_qualtype, TDT.ToType));
1453
1454 // Append end text
1455 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1456 break;
1457 }
1458 }
1459
1460 // Remember this argument info for subsequent formatting operations. Turn
1461 // std::strings into a null terminated string to make it be the same case as
1462 // all the other ones.
1464 continue;
1465 else if (Kind != DiagnosticsEngine::ak_std_string)
1466 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1467 else
1468 FormattedArgs.push_back(
1469 std::make_pair(DiagnosticsEngine::ak_c_string,
1470 (intptr_t)getArgStdStr(ArgNo).c_str()));
1471 }
1472
1473 // Append the type tree to the end of the diagnostics.
1474 OutStr.append(Tree.begin(), Tree.end());
1475}
1476
1478 StringRef Message)
1479 : ID(ID), Level(Level), Message(Message) {}
1480
1482 const Diagnostic &Info)
1483 : ID(Info.getID()), Level(Level) {
1484 assert(
1485 (Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1486 "Valid source location without setting a source manager for diagnostic");
1487 if (Info.getLocation().isValid())
1488 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1489 SmallString<64> Message;
1490 Info.FormatDiagnostic(Message);
1491 this->Message.assign(Message.begin(), Message.end());
1492 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1493 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1494}
1495
1497 StringRef Message, FullSourceLoc Loc,
1499 ArrayRef<FixItHint> FixIts)
1500 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1501 Ranges(Ranges.begin(), Ranges.end()),
1502 FixIts(FixIts.begin(), FixIts.end()) {}
1503
1504llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
1505 const StoredDiagnostic &SD) {
1506 if (SD.getLocation().hasManager())
1507 OS << SD.getLocation().printToString(SD.getLocation().getManager()) << ": ";
1508 OS << SD.getMessage();
1509 return OS;
1510}
1511
1512/// IncludeInDiagnosticCounts - This method (whose default implementation
1513/// returns true) indicates whether the diagnostics handled by this
1514/// DiagnosticConsumer should be included in the number of diagnostics
1515/// reported by DiagnosticsEngine.
1517
1518void IgnoringDiagConsumer::anchor() {}
1519
1521
1523 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
1524 Target.HandleDiagnostic(DiagLevel, Info);
1525}
1526
1529 Target.clear();
1530}
1531
1533 return Target.IncludeInDiagnosticCounts();
1534}
1535
1537 for (unsigned I = 0; I != NumCached; ++I)
1538 FreeList[I] = Cached + I;
1539 NumFreeListEntries = NumCached;
1540}
1541
1543 // Don't assert if we are in a CrashRecovery context, as this invariant may
1544 // be invalidated during a crash.
1545 assert((NumFreeListEntries == NumCached ||
1546 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1547 "A partial is on the lam");
1548}
1549
static const char * ScanFormat(const char *I, const char *E, char Target)
ScanForward - Scans forward, looking for the given character, skipping nested clauses and escaped cha...
static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl< char > &OutStr)
HandlePluralModifier - Handle the integer 'plural' modifier.
static void HandleIntegerSModifier(unsigned ValNo, SmallVectorImpl< char > &OutStr)
HandleIntegerSModifier - Handle the integer 's' modifier.
static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End)
EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
static void HandleIntegerHumanModifier(int64_t ValNo, SmallVectorImpl< char > &OutStr)
static unsigned PluralNumber(const char *&Start, const char *End)
PluralNumber - Parse an unsigned integer and advance Start.
static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl< char > &OutStr)
HandleSelectModifier - Handle the integer 'select' modifier.
static bool ModifierIs(const char *Modifier, unsigned ModifierLen, const char(&Str)[StrLen])
ModifierIs - Return true if the specified modifier matches specified string.
static bool TestPluralRange(unsigned Val, const char *&Start, const char *End)
TestPluralRange - Test if Val is in the parsed range. Modifies Start.
static void HandleOrdinalModifier(unsigned ValNo, SmallVectorImpl< char > &OutStr)
HandleOrdinalModifier - Handle the integer 'ord' modifier.
static const char * getTokenDescForDiagnostic(tok::TokenKind Kind)
Returns the friendly description for a token kind that will appear without quotes in diagnostic messa...
Defines the Diagnostic-related interfaces.
static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM, StringRef Name)
Defines the Diagnostic IDs-related interfaces.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TokenKind enum and support functions.
bool isDiagSuppressed(diag::kind DiagId, SourceLocation DiagLoc, const SourceManager &SM) const
bool hasSection(diag::kind DiagId) const
Whether a section applies to DiagId.
void processSections(DiagnosticsEngine &Diags)
static std::unique_ptr< WarningsSpecialCaseList > create(const llvm::MemoryBuffer &Input, std::string &Err)
A little helper class used to produce diagnostics.
void Clear() const
Clear out the current diagnostic.
friend class DiagnosticsEngine
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
unsigned NumErrors
Number of errors reported.
unsigned NumWarnings
Number of warnings reported.
virtual bool IncludeInDiagnosticCounts() const
Indicates whether the diagnostics handled by this DiagnosticConsumer should be included in the number...
void initCustomDiagMapping(DiagnosticMapping &, unsigned DiagID)
static StringRef getNearestOption(diag::Flavor Flavor, StringRef Group)
Get the diagnostic option with the closest edit distance to the given group name.
DiagnosticMapping getDefaultMapping(unsigned DiagID) const
Get the default mapping for this diagnostic.
static bool IsCustomDiag(diag::kind Diag)
static void getAllDiagnostics(diag::Flavor Flavor, std::vector< diag::kind > &Diags)
Get the set of all diagnostic IDs.
void setNoWarningAsError(bool Value)
void setSeverity(diag::Severity Value)
diag::Severity getSeverity() const
void setUpgradedFromWarning(bool Value)
void setNoErrorAsFatal(bool Value)
bool hasNoWarningAsError() const
Options for controlling the compiler diagnostics engine.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Diagnostic(const DiagnosticsEngine *DO, const DiagnosticBuilder &DiagBuilder)
const SourceLocation & getLocation() const
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
void FormatDiagnostic(SmallVectorImpl< char > &OutStr) const
Format this diagnostic into a string, substituting the formal arguments into the %0 slots.
uint64_t getRawArg(unsigned Idx) const
Return the specified non-string argument in an opaque form.
const char * getArgCStr(unsigned Idx) const
Return the specified C string argument.
const IdentifierInfo * getArgIdentifier(unsigned Idx) const
Return the specified IdentifierInfo argument.
SourceManager & getSourceManager() const
ArrayRef< FixItHint > getFixItHints() const
unsigned getNumArgs() const
bool hasSourceManager() const
unsigned getID() const
DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const
Return the kind of the specified index.
int64_t getArgSInt(unsigned Idx) const
Return the specified signed integer argument.
uint64_t getArgUInt(unsigned Idx) const
Return the specified unsigned integer argument.
ArrayRef< CharSourceRange > getRanges() const
Return an array reference for this diagnostic's ranges.
const DiagnosticsEngine * getDiags() const
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasSourceManager() const
Definition Diagnostic.h:665
bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force=false)
Emit the diagnostic.
void setDiagSuppressionMapping(llvm::MemoryBuffer &Input)
Diagnostic suppression mappings can be used to suppress specific diagnostics in specific files.
DiagnosticsEngine(IntrusiveRefCntPtr< DiagnosticIDs > Diags, DiagnosticOptions &DiagOpts, DiagnosticConsumer *client=nullptr, bool ShouldOwnClient=true)
DiagStateSystemClass getDiagStateSystemClassForLoc(SourceLocation Loc) const
Returns whether Loc is in a system header and/or a system macro.
bool isSuppressedViaMapping(diag::kind DiagId, SourceLocation DiagLoc) const
void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map, SourceLocation Loc=SourceLocation())
Add the specified mapping to all diagnostics of the specified flavor.
LLVM_DUMP_METHOD void dump() const
void ResetPragmas()
We keep a cache of FileIDs for diagnostics mapped by pragmas.
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
bool hasDiagSuppressionMappingFor(diag::kind DiagId) const
True if an active diagnostic suppression mapping has a section for DiagId, so that its severity can d...
SourceManager & getSourceManager() const
Definition Diagnostic.h:667
void pushMappings(SourceLocation Loc)
Copies the current DiagMappings and pushes the new copy onto the top of the stack.
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:245
friend class DiagnosticBuilder
DiagnosticConsumer * getClient()
Definition Diagnostic.h:655
@ ak_nameddecl
NamedDecl *.
Definition Diagnostic.h:286
@ ak_declcontext
DeclContext *.
Definition Diagnostic.h:292
@ ak_addrspace
address space
Definition Diagnostic.h:274
@ ak_identifierinfo
IdentifierInfo.
Definition Diagnostic.h:271
@ ak_qualtype_pair
pair<QualType, QualType>
Definition Diagnostic.h:295
@ ak_attr_info
AttributeCommonInfo *.
Definition Diagnostic.h:304
@ ak_c_string
const char *
Definition Diagnostic.h:259
@ ak_declarationname
DeclarationName.
Definition Diagnostic.h:283
@ ak_tokenkind
enum TokenKind : unsigned
Definition Diagnostic.h:268
@ ak_std_string
std::string
Definition Diagnostic.h:256
@ ak_nestednamespec
NestedNameSpecifier *.
Definition Diagnostic.h:289
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled)
Set the error-as-fatal flag for the given diagnostic group.
bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled)
Set the warning-as-error flag for the given diagnostic group.
void ConvertArgToString(ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, ArrayRef< intptr_t > QualTypeVals) const
Converts a diagnostic argument (as an intptr_t) into the string that represents it.
Definition Diagnostic.h:963
bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc=SourceLocation())
Change an entire diagnostic group (e.g.
bool popMappings(SourceLocation Loc)
Pops the current DiagMappings off the top of the stack, causing the new top of the stack to be the ac...
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:640
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
static FileID getSentinel()
bool IncludeInDiagnosticCounts() const override
Indicates whether the diagnostics handled by this DiagnosticConsumer should be included in the number...
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
A SourceLocation and its associated SourceManager.
bool hasManager() const
Checks whether the SourceManager is present.
const SourceManager & getManager() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
Encodes a location in the source.
std::string printToString(const SourceManager &SM) const
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
DiagnosticsEngine & getDiagnostics() const
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
llvm::MemoryBufferRef getBufferOrFake(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
FileIDAndOffset getDecomposedIncludedLoc(FileID FID) const
Returns the "included/expanded in" decomposed location of the given FileID.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
unsigned getID() const
range_iterator range_begin() const
DiagnosticsEngine::Level getLevel() const
fixit_iterator fixit_begin() const
const FullSourceLoc & getLocation() const
range_iterator range_end() const
StringRef getMessage() const
fixit_iterator fixit_end() const
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
DiagStorageAllocator * Allocator
Allocator used to allocate storage for this diagnostic.
DiagnosticStorage * DiagStorage
void AddString(StringRef V) const
Flavor
Flavors of diagnostics we can emit.
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
@ Warning
Present this diagnostic as a warning.
@ Fatal
Present this diagnostic as a fatal error.
@ Error
Present this diagnostic as an error.
@ Remark
Present this diagnostic as a remark.
@ Ignored
Do not present this diagnostic, ignore it.
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
Top level wrappers for InstallAPI frontend operations.
LLVM_READONLY bool isPrintable(unsigned char c)
Return true if this character is an ASCII printable character; that is, a character that should take ...
Definition CharInfo.h:160
DiagStateSystemClass
Whether a source location is in a system header and/or a system macro.
Definition Diagnostic.h:226
std::pair< FileID, unsigned > FileIDAndOffset
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition CharInfo.h:114
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
SmallString< 16 > EscapeSingleCodepointForDiagnostic(StringRef Str)
Displays a single Unicode codepoint in U+NNNN notation, optionally prepending the quoted codepoint it...
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
LLVM_READONLY bool isPunctuation(unsigned char c)
Return true if this character is an ASCII punctuation character.
Definition CharInfo.h:152
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
#define true
Definition stdbool.h:25
SmallVector< CharSourceRange, 8 > DiagRanges
The list of ranges added to this diagnostic.
Definition Diagnostic.h:181
SmallVector< FixItHint, 6 > FixItHints
If valid, provides a hint with some code to insert, remove, or modify at a particular position.
Definition Diagnostic.h:185