clang 24.0.0git
Diagnostic.h
Go to the documentation of this file.
1//===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
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/// \file
10/// Defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15#define LLVM_CLANG_BASIC_DIAGNOSTIC_H
16
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/FunctionExtras.h"
25#include "llvm/ADT/IntrusiveRefCntPtr.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/iterator_range.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/ConvertUTF.h"
32#include "llvm/Support/VirtualFileSystemFwd.h"
33#include <cassert>
34#include <cstdint>
35#include <limits>
36#include <list>
37#include <memory>
38#include <optional>
39#include <string>
40#include <string_view>
41#include <type_traits>
42#include <utility>
43#include <vector>
44
45namespace llvm {
46class Error;
47class raw_ostream;
48class MemoryBuffer;
49} // namespace llvm
50
51namespace clang {
52
53class DeclContext;
54class Diagnostic;
57class IdentifierInfo;
58class LangOptions;
59class Preprocessor;
60class SourceManager;
62
63namespace tok {
64
65enum TokenKind : unsigned short;
66
67} // namespace tok
68
69/// Annotates a diagnostic with some code that should be
70/// inserted, removed, or replaced to fix the problem.
71///
72/// This kind of hint should be used when we are certain that the
73/// introduction, removal, or modification of a particular (small!)
74/// amount of code will correct a compilation error. The compiler
75/// should also provide full recovery from such errors, such that
76/// suppressing the diagnostic output can still result in successful
77/// compilation.
78class FixItHint {
79public:
80 /// Code that should be replaced to correct the error. Empty for an
81 /// insertion hint.
83
84 /// Code in the specific range that should be inserted in the insertion
85 /// location.
87
88 /// The actual code to insert at the insertion location, as a
89 /// string.
90 std::string CodeToInsert;
91
93
94 /// Empty code modification hint, indicating that no code
95 /// modification is known.
96 FixItHint() = default;
97
98 bool isNull() const { return !RemoveRange.isValid(); }
99
100 /// Create a code modification hint that inserts the given
101 /// code string at a specific location.
102 static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code,
103 bool BeforePreviousInsertions = false) {
104 FixItHint Hint;
105 Hint.RemoveRange =
106 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
107 Hint.CodeToInsert = std::string(Code);
109 return Hint;
110 }
111
112 /// Create a code modification hint that inserts the given
113 /// code from \p FromRange at a specific location.
114 static FixItHint
116 CharSourceRange FromRange,
117 bool BeforePreviousInsertions = false) {
118 FixItHint Hint;
119 Hint.RemoveRange =
120 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
121 Hint.InsertFromRange = FromRange;
123 return Hint;
124 }
125
126 /// Create a code modification hint that removes the given
127 /// source range.
129 FixItHint Hint;
131 return Hint;
132 }
136
137 /// Create a code modification hint that replaces the given
138 /// source range with the given code string.
140 StringRef Code) {
141 FixItHint Hint;
143 Hint.CodeToInsert = std::string(Code);
144 return Hint;
145 }
146
150};
151
153 enum {
154 /// The maximum number of arguments we can hold. We
155 /// currently only support up to 10 arguments (%0-%9).
156 ///
157 /// A single diagnostic with more than that almost certainly has to
158 /// be simplified anyway.
160 };
161
162 /// The number of entries in Arguments.
163 unsigned char NumDiagArgs = 0;
164
165 /// Specifies for each argument whether it is in DiagArgumentsStr
166 /// or in DiagArguments.
168
169 /// The values for the various substitution positions.
170 ///
171 /// This is used when the argument is not an std::string. The specific value
172 /// is mangled into an uint64_t and the interpretation depends on exactly
173 /// what sort of argument kind it is.
175
176 /// The values for the various substitution positions that have
177 /// string arguments.
179
180 /// The list of ranges added to this diagnostic.
182
183 /// If valid, provides a hint with some code to insert, remove, or
184 /// modify at a particular position.
186
187 DiagnosticStorage() = default;
188};
189
190/// An allocator for DiagnosticStorage objects, which uses a small cache to
191/// objects, used to reduce malloc()/free() traffic for partial diagnostics.
193 static const unsigned NumCached = 16;
194 DiagnosticStorage Cached[NumCached];
195 DiagnosticStorage *FreeList[NumCached];
196 unsigned NumFreeListEntries;
197
198public:
201
202 /// Allocate new storage.
204 if (NumFreeListEntries == 0)
205 return new DiagnosticStorage;
206
207 DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
208 Result->NumDiagArgs = 0;
209 Result->DiagRanges.clear();
210 Result->FixItHints.clear();
211 return Result;
212 }
213
214 /// Free the given storage object.
216 if (S >= Cached && S <= Cached + NumCached) {
217 FreeList[NumFreeListEntries++] = S;
218 return;
219 }
220
221 delete S;
222 }
223};
224
225/// Whether a source location is in a system header and/or a system macro.
233
234/// Concrete class used by the front-end to report problems and issues.
235///
236/// This massages the diagnostics (e.g. handling things like "report warnings
237/// as errors" and passes them off to the DiagnosticConsumer for reporting to
238/// the user. DiagnosticsEngine is tied to one translation unit and one
239/// SourceManager.
240class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
241public:
242 /// The level of the diagnostic, after it has been through mapping.
243 // FIXME: Make this an alias for DiagnosticIDs::Level as soon as
244 // we can use 'using enum'.
253
255 /// std::string
257
258 /// const char *
260
261 /// int
263
264 /// unsigned
266
267 /// enum TokenKind : unsigned
269
270 /// IdentifierInfo
272
273 /// address space
275
276 /// Qualifiers
278
279 /// QualType
281
282 /// DeclarationName
284
285 /// NamedDecl *
287
288 /// NestedNameSpecifier *
290
291 /// DeclContext *
293
294 /// pair<QualType, QualType>
296
297 /// Attr *
299
300 /// Expr *
302
303 /// AttributeCommonInfo *
305 };
306
307 /// Represents on argument value, which is a union discriminated
308 /// by ArgumentKind, with a value.
309 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
310
311private:
312 // Used by __extension__
313 unsigned char AllExtensionsSilenced = 0;
314
315 // Treat fatal errors like errors.
316 bool FatalsAsError = false;
317
318 // Suppress all diagnostics.
319 bool SuppressAllDiagnostics = false;
320
321 // Force system warnings to be shown, regardless of the current
322 // diagnostic state. This is used for temporary overrides and is not
323 // stored as location-specific state in modules.
324 bool ForceSystemWarnings = false;
325
326 // Elide common types of templates.
327 bool ElideType = true;
328
329 // Print a tree when comparing templates.
330 bool PrintTemplateTree = false;
331
332 // Color printing is enabled.
333 bool ShowColors = false;
334
335 // Which overload candidates to show.
336 OverloadsShown ShowOverloads = Ovl_All;
337
338 // With Ovl_Best, the number of overload candidates to show when we encounter
339 // an error.
340 //
341 // The value here is the number of candidates to show in the first nontrivial
342 // error. Future errors may show a different number of candidates.
343 unsigned NumOverloadsToShow = 32;
344
345 // Cap of # errors emitted, 0 -> no limit.
346 unsigned ErrorLimit = 0;
347
348 // Cap on depth of template backtrace stack, 0 -> no limit.
349 unsigned TemplateBacktraceLimit = 0;
350
351 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
352 unsigned ConstexprBacktraceLimit = 0;
353
355 DiagnosticOptions &DiagOpts;
356 DiagnosticConsumer *Client = nullptr;
357 std::unique_ptr<DiagnosticConsumer> Owner;
358 SourceManager *SourceMgr = nullptr;
359
360 /// Mapping information for diagnostics.
361 ///
362 /// Mapping info is packed into four bits per diagnostic. The low three
363 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
364 /// The high bit is set when the mapping was established as a user mapping.
365 /// If the high bit is clear, then the low bits are set to the default
366 /// value, and should be mapped with -pedantic, -Werror, etc.
367 ///
368 /// A new DiagState is created and kept around when diagnostic pragmas modify
369 /// the state so that we know what is the diagnostic state at any given
370 /// source location.
371 class DiagState {
372 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
373
374 public:
375 // "Global" configuration state that can actually vary between modules.
376
377 // Ignore all warnings: -w
378 LLVM_PREFERRED_TYPE(bool)
379 unsigned IgnoreAllWarnings : 1;
380
381 // Enable all warnings.
382 LLVM_PREFERRED_TYPE(bool)
383 unsigned EnableAllWarnings : 1;
384
385 // Treat warnings like errors.
386 LLVM_PREFERRED_TYPE(bool)
387 unsigned WarningsAsErrors : 1;
388
389 // Treat errors like fatal errors.
390 LLVM_PREFERRED_TYPE(bool)
391 unsigned ErrorsAsFatal : 1;
392
393 // Suppress warnings in system headers.
394 LLVM_PREFERRED_TYPE(bool)
395 unsigned SuppressSystemWarnings : 1;
396
397 // Map extensions to warnings or errors?
399
400 DiagnosticIDs &DiagIDs;
401
402 DiagState(DiagnosticIDs &DiagIDs)
403 : IgnoreAllWarnings(false), EnableAllWarnings(false),
404 WarningsAsErrors(false), ErrorsAsFatal(false),
405 SuppressSystemWarnings(false), DiagIDs(DiagIDs) {}
406
407 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
408 using const_iterator =
409 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
410
411 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
412 DiagMap[Diag] = Info;
413 }
414
415 DiagnosticMapping lookupMapping(diag::kind Diag) const {
416 return DiagMap.lookup(Diag);
417 }
418
419 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
420
421 const_iterator begin() const { return DiagMap.begin(); }
422 const_iterator end() const { return DiagMap.end(); }
423 };
424
425 /// Keeps and automatically disposes all DiagStates that we create.
426 std::list<DiagState> DiagStates;
427
428 /// A mapping from files to the diagnostic states for those files. Lazily
429 /// built on demand for files in which the diagnostic state has not changed.
430 class DiagStateMap {
431 public:
432 /// Add an initial diagnostic state.
433 void appendFirst(DiagState *State);
434
435 /// Add a new latest state point.
436 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
437
438 /// Look up the diagnostic state at a given source location.
439 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
440
441 /// Determine whether this map is empty.
442 bool empty() const { return Files.empty(); }
443
444 /// Clear out this map.
445 void clear(bool Soft) {
446 // Just clear the cache when in soft mode.
447 Files.clear();
448 LastLookupFileID = FileID::getSentinel();
449 if (!Soft) {
450 FirstDiagState = CurDiagState = nullptr;
451 CurDiagStateLoc = SourceLocation();
452 }
453 }
454
455 /// Produce a debugging dump of the diagnostic state.
456 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
457 StringRef DiagName = StringRef()) const;
458
459 /// Grab the most-recently-added state point.
460 DiagState *getCurDiagState() const { return CurDiagState; }
461
462 /// Get the location at which a diagnostic state was last added.
463 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
464
465 private:
466 friend class ASTReader;
467 friend class ASTWriter;
468
469 /// Represents a point in source where the diagnostic state was
470 /// modified because of a pragma.
471 ///
472 /// 'Loc' can be null if the point represents the diagnostic state
473 /// modifications done through the command-line.
474 struct DiagStatePoint {
475 DiagState *State;
476 unsigned Offset;
477
478 DiagStatePoint(DiagState *State, unsigned Offset)
479 : State(State), Offset(Offset) {}
480 };
481
482 /// Description of the diagnostic states and state transitions for a
483 /// particular FileID.
484 struct File {
485 /// The diagnostic state for the parent file. This is strictly redundant,
486 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
487 /// map would give us this, but we cache it here for performance.
488 File *Parent = nullptr;
489
490 /// The offset of this file within its parent.
491 unsigned ParentOffset = 0;
492
493 /// Whether this file has any local (not imported from an AST file)
494 /// diagnostic state transitions.
495 bool HasLocalTransitions = false;
496
497 /// The points within the file where the state changes. There will always
498 /// be at least one of these (the state on entry to the file).
499 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
500
501 DiagState *lookup(unsigned Offset) const;
502 };
503
504 /// The diagnostic states for each file.
505 mutable llvm::DenseMap<FileID, std::unique_ptr<File>> Files;
506
507 std::pair<File *, bool> getOrInsertFile(FileID ID) const {
508 auto [It, Inserted] = Files.try_emplace(ID);
509 if (Inserted)
510 It->second = std::make_unique<File>();
511 return {It->second.get(), Inserted};
512 }
513
514 /// One-entry cache for getFile(): Files gets large, and most
515 /// lookups are for the same FileID as the previous one.
516 mutable FileID LastLookupFileID = FileID::getSentinel();
517 mutable File *LastLookupFile = nullptr;
518
519 /// The initial diagnostic state.
520 DiagState *FirstDiagState;
521
522 /// The current diagnostic state.
523 DiagState *CurDiagState;
524
525 /// The location at which the current diagnostic state was established.
526 SourceLocation CurDiagStateLoc;
527
528 /// Get the diagnostic state information for a file.
529 File *getFile(SourceManager &SrcMgr, FileID ID) const;
530 File *getFileUncached(SourceManager &SrcMgr, FileID ID) const;
531 };
532
533 DiagStateMap DiagStatesByLoc;
534
535 /// Keeps the DiagState that was active during each diagnostic 'push'
536 /// so we can get back at it when we 'pop'.
537 std::vector<DiagState *> DiagStateOnPushStack;
538
539 DiagState *GetCurDiagState() const {
540 return DiagStatesByLoc.getCurDiagState();
541 }
542
543 void PushDiagStatePoint(DiagState *State, SourceLocation L);
544
545 /// Finds the DiagStatePoint that contains the diagnostic state of
546 /// the given source location.
547 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
548 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
549 : DiagStatesByLoc.getCurDiagState();
550 }
551
552 /// Sticky flag set to \c true when an error is emitted.
553 bool ErrorOccurred;
554
555 /// Sticky flag set to \c true when an "uncompilable error" occurs.
556 /// I.e. an error that was not upgraded from a warning by -Werror.
557 bool UncompilableErrorOccurred;
558
559 /// Sticky flag set to \c true when a fatal error is emitted.
560 bool FatalErrorOccurred;
561
562 /// Indicates that an unrecoverable error has occurred.
563 bool UnrecoverableErrorOccurred;
564
565 /// Counts for DiagnosticErrorTrap to check whether an error occurred
566 /// during a parsing section, e.g. during parsing a function.
567 unsigned TrapNumErrorsOccurred;
568 unsigned TrapNumUnrecoverableErrorsOccurred;
569
570 /// The level of the last diagnostic emitted.
571 ///
572 /// This is used to emit continuation diagnostics with the same level as the
573 /// diagnostic that they follow.
574 Level LastDiagLevel;
575
576 /// Number of warnings reported
577 unsigned NumWarnings;
578
579 /// Number of errors reported
580 unsigned NumErrors;
581
582 /// A function pointer that converts an opaque diagnostic
583 /// argument to a strings.
584 ///
585 /// This takes the modifiers and argument that was present in the diagnostic.
586 ///
587 /// The PrevArgs array indicates the previous arguments formatted for this
588 /// diagnostic. Implementations of this function can use this information to
589 /// avoid redundancy across arguments.
590 ///
591 /// This is a hack to avoid a layering violation between libbasic and libsema.
592 using ArgToStringFnTy = void (*)(ArgumentKind Kind, intptr_t Val,
593 StringRef Modifier, StringRef Argument,
594 ArrayRef<ArgumentValue> PrevArgs,
595 SmallVectorImpl<char> &Output, void *Cookie,
596 ArrayRef<intptr_t> QualTypeVals);
597
598 void *ArgToStringCookie = nullptr;
599 ArgToStringFnTy ArgToStringFn;
600
601 /// Whether the diagnostic should be suppressed in FilePath.
602 llvm::unique_function<bool(diag::kind, SourceLocation /*DiagLoc*/,
603 const SourceManager &) const>
604 DiagSuppressionMapping;
605
606public:
607 /// Returns a cache key representing the diagnostic state at \p Loc.
608 const void *getDiagStateKeyForLoc(SourceLocation Loc) const {
609 return GetDiagStateForLoc(Loc);
610 }
611
612 /// Returns whether \p Loc is in a system header and/or a system macro.
613 /// Severity depends on this through
614 /// DiagnosticIDs::shouldSuppressAsSystemWarning(), so a cache keyed on
615 /// getDiagStateKeyForLoc() must take it into account as well.
617
618 /// True if an active diagnostic suppression mapping makes severity dependent
619 /// on the file path.
621 return static_cast<bool>(DiagSuppressionMapping);
622 }
623
625 DiagnosticOptions &DiagOpts,
626 DiagnosticConsumer *client = nullptr,
627 bool ShouldOwnClient = true);
631
633 LLVM_DUMP_METHOD void dump() const;
634 LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
635
637 return Diags;
638 }
639
640 /// Retrieve the diagnostic options.
641 DiagnosticOptions &getDiagnosticOptions() const { return DiagOpts; }
642
643 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
644
645 /// Get the current set of diagnostic mappings.
647 const DiagState &DS = *GetCurDiagState();
648 return diag_mapping_range(DS.begin(), DS.end());
649 }
650
651 DiagnosticConsumer *getClient() { return Client; }
652 const DiagnosticConsumer *getClient() const { return Client; }
653
654 /// Determine whether this \c DiagnosticsEngine object own its client.
655 bool ownsClient() const { return Owner != nullptr; }
656
657 /// Return the current diagnostic client along with ownership of that
658 /// client.
659 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
660
661 bool hasSourceManager() const { return SourceMgr != nullptr; }
662
664 assert(SourceMgr && "SourceManager not set!");
665 return *SourceMgr;
666 }
667
669 assert(DiagStatesByLoc.empty() &&
670 "Leftover diag state from a different SourceManager.");
671 SourceMgr = SrcMgr;
672 }
673
674 //===--------------------------------------------------------------------===//
675 // DiagnosticsEngine characterization methods, used by a client to customize
676 // how diagnostics are emitted.
677 //
678
679 /// Copies the current DiagMappings and pushes the new copy
680 /// onto the top of the stack.
682
683 /// Pops the current DiagMappings off the top of the stack,
684 /// causing the new top of the stack to be the active mappings.
685 ///
686 /// \returns \c true if the pop happens, \c false if there is only one
687 /// DiagMapping on the stack.
688 bool popMappings(SourceLocation Loc);
689
690 /// Set the diagnostic client associated with this diagnostic object.
691 ///
692 /// \param ShouldOwnClient true if the diagnostic object should take
693 /// ownership of \c client.
694 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
695
696 /// Specify a limit for the number of errors we should
697 /// emit before giving up.
698 ///
699 /// Zero disables the limit.
700 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
701
702 /// Specify the maximum number of template instantiation
703 /// notes to emit along with a given diagnostic.
704 void setTemplateBacktraceLimit(unsigned Limit) {
705 TemplateBacktraceLimit = Limit;
706 }
707
708 /// Retrieve the maximum number of template instantiation
709 /// notes to emit along with a given diagnostic.
710 unsigned getTemplateBacktraceLimit() const { return TemplateBacktraceLimit; }
711
712 /// Specify the maximum number of constexpr evaluation
713 /// notes to emit along with a given diagnostic.
714 void setConstexprBacktraceLimit(unsigned Limit) {
715 ConstexprBacktraceLimit = Limit;
716 }
717
718 /// Retrieve the maximum number of constexpr evaluation
719 /// notes to emit along with a given diagnostic.
720 unsigned getConstexprBacktraceLimit() const {
721 return ConstexprBacktraceLimit;
722 }
723
724 /// When set to true, any unmapped warnings are ignored.
725 ///
726 /// If this and WarningsAsErrors are both set, then this one wins.
727 void setIgnoreAllWarnings(bool Val) {
728 GetCurDiagState()->IgnoreAllWarnings = Val;
729 }
730 bool getIgnoreAllWarnings() const {
731 return GetCurDiagState()->IgnoreAllWarnings;
732 }
733
734 /// When set to true, any unmapped ignored warnings are no longer
735 /// ignored.
736 ///
737 /// If this and IgnoreAllWarnings are both set, then that one wins.
738 void setEnableAllWarnings(bool Val) {
739 GetCurDiagState()->EnableAllWarnings = Val;
740 }
741 bool getEnableAllWarnings() const {
742 return GetCurDiagState()->EnableAllWarnings;
743 }
744
745 /// When set to true, any warnings reported are issued as errors.
746 void setWarningsAsErrors(bool Val) {
747 GetCurDiagState()->WarningsAsErrors = Val;
748 }
749 bool getWarningsAsErrors() const {
750 return GetCurDiagState()->WarningsAsErrors;
751 }
752
753 /// When set to true, any error reported is made a fatal error.
754 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
755 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
756
757 /// \brief When set to true, any fatal error reported is made an error.
758 ///
759 /// This setting takes precedence over the setErrorsAsFatal setting above.
760 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
761 bool getFatalsAsError() const { return FatalsAsError; }
762
763 /// When set to true mask warnings that come from system headers.
765 GetCurDiagState()->SuppressSystemWarnings = Val;
766 }
768 return GetCurDiagState()->SuppressSystemWarnings;
769 }
770
771 /// Suppress all diagnostics, to silence the front end when we
772 /// know that we don't want any more diagnostics to be passed along to the
773 /// client
774 void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
775 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
776
777 void setForceSystemWarnings(bool Val) { ForceSystemWarnings = Val; }
778 bool getForceSystemWarnings() const { return ForceSystemWarnings; }
779
780 /// Set type eliding, to skip outputting same types occurring in
781 /// template types.
782 void setElideType(bool Val) { ElideType = Val; }
783 bool getElideType() { return ElideType; }
784
785 /// Set tree printing, to outputting the template difference in a
786 /// tree format.
787 void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
788 bool getPrintTemplateTree() { return PrintTemplateTree; }
789
790 /// Set color printing, so the type diffing will inject color markers
791 /// into the output.
792 void setShowColors(bool Val) { ShowColors = Val; }
793 bool getShowColors() { return ShowColors; }
794
795 /// Specify which overload candidates to show when overload resolution
796 /// fails.
797 ///
798 /// By default, we show all candidates.
799 void setShowOverloads(OverloadsShown Val) { ShowOverloads = Val; }
800 OverloadsShown getShowOverloads() const { return ShowOverloads; }
801
802 /// When a call or operator fails, print out up to this many candidate
803 /// overloads as suggestions.
804 ///
805 /// With Ovl_Best, we set a high limit for the first nontrivial overload set
806 /// we print, and a lower limit for later sets. This way the user has a
807 /// chance of diagnosing at least one callsite in their program without
808 /// having to recompile with -fshow-overloads=all.
810 switch (getShowOverloads()) {
811 case Ovl_All:
812 // INT_MAX rather than UINT_MAX so that we don't have to think about the
813 // effect of implicit conversions on this value. In practice we'll never
814 // hit 2^31 candidates anyway.
815 return std::numeric_limits<int>::max();
816 case Ovl_Best:
817 return NumOverloadsToShow;
818 }
819 llvm_unreachable("invalid OverloadsShown kind");
820 }
821
822 /// Call this after showing N overload candidates. This influences the value
823 /// returned by later calls to getNumOverloadCandidatesToShow().
824 void overloadCandidatesShown(unsigned N) {
825 // Current heuristic: Start out with a large value for NumOverloadsToShow,
826 // and then once we print one nontrivially-large overload set, decrease it
827 // for future calls.
828 if (N > 4) {
829 NumOverloadsToShow = 4;
830 }
831 }
832
833 /// Pretend that the last diagnostic issued was ignored, so any
834 /// subsequent notes will be suppressed, or restore a prior ignoring
835 /// state after ignoring some diagnostics and their notes, possibly in
836 /// the middle of another diagnostic.
837 ///
838 /// This can be used by clients who suppress diagnostics themselves.
839 void setLastDiagnosticIgnored(bool IsIgnored) {
840 if (LastDiagLevel == Fatal)
841 FatalErrorOccurred = true;
842 LastDiagLevel = IsIgnored ? Ignored : Warning;
843 }
844
845 /// Determine whether the previous diagnostic was ignored. This can
846 /// be used by clients that want to determine whether notes attached to a
847 /// diagnostic will be suppressed.
848 bool isLastDiagnosticIgnored() const { return LastDiagLevel == Ignored; }
849
850 /// Controls whether otherwise-unmapped extension diagnostics are
851 /// mapped onto ignore/warning/error.
852 ///
853 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
855 GetCurDiagState()->ExtBehavior = H;
856 }
858 return GetCurDiagState()->ExtBehavior;
859 }
860
861 /// Counter bumped when an __extension__ block is/ encountered.
862 ///
863 /// When non-zero, all extension diagnostics are entirely silenced, no
864 /// matter how they are mapped.
865 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
866 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
867 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
868
869 /// This allows the client to specify that certain warnings are
870 /// ignored.
871 ///
872 /// Notes can never be mapped, errors can only be mapped to fatal, and
873 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
874 ///
875 /// \param Loc The source location that this change of diagnostic state should
876 /// take affect. It can be null if we are setting the latest state.
878
879 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
880 /// have the specified mapping.
881 ///
882 /// \returns true (and ignores the request) if "Group" was unknown, false
883 /// otherwise.
884 ///
885 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
886 /// state of the -Wfoo group and vice versa.
887 ///
888 /// \param Loc The source location that this change of diagnostic state should
889 /// take affect. It can be null if we are setting the state from command-line.
890 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
891 diag::Severity Map,
894 diag::Severity Map,
896
897 /// Set the warning-as-error flag for the given diagnostic group.
898 ///
899 /// This function always only operates on the current diagnostic state.
900 ///
901 /// \returns True if the given group is unknown, false otherwise.
902 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
903
904 /// Set the error-as-fatal flag for the given diagnostic group.
905 ///
906 /// This function always only operates on the current diagnostic state.
907 ///
908 /// \returns True if the given group is unknown, false otherwise.
909 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
910
911 /// Add the specified mapping to all diagnostics of the specified
912 /// flavor.
913 ///
914 /// Mainly to be used by -Wno-everything to disable all warnings but allow
915 /// subsequent -W options to enable specific warnings.
918
919 bool hasErrorOccurred() const { return ErrorOccurred; }
920
921 /// Errors that actually prevent compilation, not those that are
922 /// upgraded from a warning by -Werror.
924 return UncompilableErrorOccurred;
925 }
926 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
927
928 /// Determine whether any kind of unrecoverable error has occurred.
930 return FatalErrorOccurred || UnrecoverableErrorOccurred;
931 }
932
933 unsigned getNumErrors() const { return NumErrors; }
934 unsigned getNumWarnings() const { return NumWarnings; }
935
936 void setNumWarnings(unsigned NumWarnings) { this->NumWarnings = NumWarnings; }
937
938 /// Return an ID for a diagnostic with the specified format string and
939 /// level.
940 ///
941 /// If this is the first request for this diagnostic, it is registered and
942 /// created, otherwise the existing ID is returned.
943 ///
944 /// \param FormatString A fixed diagnostic format string that will be hashed
945 /// and mapped to a unique DiagID.
946 template <unsigned N>
947 // FIXME: this API should almost never be used; custom diagnostics do not
948 // have an associated diagnostic group and thus cannot be controlled by users
949 // like other diagnostics. The number of times this API is used in Clang
950 // should only ever be reduced, not increased.
951 // [[deprecated("Use a CustomDiagDesc instead of a Level")]]
952 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
953 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
954 StringRef(FormatString, N - 1));
955 }
956
957 /// Converts a diagnostic argument (as an intptr_t) into the string
958 /// that represents it.
959 void ConvertArgToString(ArgumentKind Kind, intptr_t Val, StringRef Modifier,
960 StringRef Argument, ArrayRef<ArgumentValue> PrevArgs,
961 SmallVectorImpl<char> &Output,
962 ArrayRef<intptr_t> QualTypeVals) const {
963 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
964 ArgToStringCookie, QualTypeVals);
965 }
966
967 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
968 ArgToStringFn = Fn;
969 ArgToStringCookie = Cookie;
970 }
971
972 /// Note that the prior diagnostic was emitted by some other
973 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
975 LastDiagLevel = Other.LastDiagLevel;
976 }
977
978 /// Reset the state of the diagnostic object to its initial configuration.
979 /// \param[in] soft - if true, doesn't reset the diagnostic mappings and state
980 void Reset(bool soft = false);
981 /// We keep a cache of FileIDs for diagnostics mapped by pragmas. These might
982 /// get invalidated when diagnostics engine is shared across different
983 /// compilations. Provide users with a way to reset that.
984 void ResetPragmas();
985
986 //===--------------------------------------------------------------------===//
987 // DiagnosticsEngine classification and reporting interfaces.
988 //
989
990 /// Determine whether the diagnostic is known to be ignored.
991 ///
992 /// This can be used to opportunistically avoid expensive checks when it's
993 /// known for certain that the diagnostic has been suppressed at the
994 /// specified location \p Loc.
995 ///
996 /// \param Loc The source location we are interested in finding out the
997 /// diagnostic state. Can be null in order to query the latest state.
998 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
999 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
1001 }
1002
1003 bool areAllIgnored(StringRef Group, SourceLocation Loc) const {
1004 llvm::SmallVector<diag::kind> diagsInGroup;
1005 bool Failed = Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1006 Group, diagsInGroup);
1007 assert(!Failed && "Incorrect group name?");
1008 (void)Failed;
1009 return Diags->getDiagnosticListHighestSeverity(diagsInGroup, Loc, *this) ==
1011 }
1012
1013 /// Based on the way the client configured the DiagnosticsEngine
1014 /// object, classify the specified diagnostic ID into a Level, consumable by
1015 /// the DiagnosticConsumer.
1016 ///
1017 /// To preserve invariant assumptions, this function should not be used to
1018 /// influence parse or semantic analysis actions. Instead consider using
1019 /// \c isIgnored().
1020 ///
1021 /// \param Loc The source location we are interested in finding out the
1022 /// diagnostic state. Can be null in order to query the latest state.
1023 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
1024 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
1025 }
1026
1027 /// Diagnostic suppression mappings can be used to suppress specific
1028 /// diagnostics in specific files.
1029 /// Mapping file is expected to be a special case list with sections denoting
1030 /// diagnostic groups and `src` entries for globs to suppress. `emit` category
1031 /// can be used to disable suppression. The last glob that matches a filepath
1032 /// takes precedence. For example:
1033 /// [unused]
1034 /// src:clang/*
1035 /// src:clang/foo/*=emit
1036 /// src:clang/foo/bar/*
1037 ///
1038 /// Such a mappings file suppress all diagnostics produced by -Wunused in all
1039 /// sources under `clang/` directory apart from `clang/foo/`. Diagnostics
1040 /// under `clang/foo/bar/` will also be suppressed. Note that the FilePath is
1041 /// matched against the globs as-is.
1042 /// These take presumed locations into account, and can still be overriden by
1043 /// clang-diagnostics pragmas.
1044 void setDiagSuppressionMapping(llvm::MemoryBuffer &Input);
1045 bool isSuppressedViaMapping(diag::kind DiagId, SourceLocation DiagLoc) const;
1046
1047 /// Issue the message to the client.
1048 ///
1049 /// This actually returns an instance of DiagnosticBuilder which emits the
1050 /// diagnostics (through @c ProcessDiag) when it is destroyed.
1051 ///
1052 /// \param DiagID A member of the @c diag::kind enum.
1053 /// \param Loc Represents the source location associated with the diagnostic,
1054 /// which can be an invalid location if no position information is available.
1055 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
1056 inline DiagnosticBuilder Report(unsigned DiagID);
1057
1058 void Report(const StoredDiagnostic &storedDiag);
1059
1060private:
1061 // This is private state used by DiagnosticBuilder. We put it here instead of
1062 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
1063 // object. This implementation choice means that we can only have a few
1064 // diagnostics "in flight" at a time, but this seems to be a reasonable
1065 // tradeoff to keep these objects small.
1066 friend class Diagnostic;
1067 friend class DiagnosticBuilder;
1069 friend class DiagnosticIDs;
1070 friend class PartialDiagnostic;
1071
1072 enum {
1073 /// The maximum number of arguments we can hold.
1074 ///
1075 /// We currently only support up to 10 arguments (%0-%9). A single
1076 /// diagnostic with more than that almost certainly has to be simplified
1077 /// anyway.
1078 MaxArguments = DiagnosticStorage::MaxArguments,
1079 };
1080
1081 DiagStorageAllocator DiagAllocator;
1082
1083 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
1084 bool isPragma = L.isValid();
1085 DiagnosticMapping Mapping =
1086 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
1087
1088 // If this is a pragma mapping, then set the diagnostic mapping flags so
1089 // that we override command line options.
1090 if (isPragma) {
1091 Mapping.setNoWarningAsError(true);
1092 Mapping.setNoErrorAsFatal(true);
1093 }
1094
1095 return Mapping;
1096 }
1097
1098 /// Used to report a diagnostic that is finally fully formed.
1099 ///
1100 /// \returns true if the diagnostic was emitted, false if it was suppressed.
1101 bool ProcessDiag(const DiagnosticBuilder &DiagBuilder);
1102
1103 /// Forward a diagnostic to the DiagnosticConsumer.
1104 void Report(Level DiagLevel, const Diagnostic &Info);
1105
1106 /// @name Diagnostic Emission
1107 /// @{
1108protected:
1109 friend class ASTReader;
1110 friend class ASTWriter;
1111
1112 // Sema requires access to the following functions because the current design
1113 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1114 // access us directly to ensure we minimize the emitted code for the common
1115 // Sema::Diag() patterns.
1116 friend class Sema;
1117
1118 /// Emit the diagnostic
1119 ///
1120 /// \param Force Emit the diagnostic regardless of suppression settings.
1121 bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force = false);
1122
1123 /// @}
1124};
1125
1126/// RAII class that determines when any errors have occurred
1127/// between the time the instance was created and the time it was
1128/// queried.
1129///
1130/// Note that you almost certainly do not want to use this. It's usually
1131/// meaningless to ask whether a particular scope triggered an error message,
1132/// because error messages outside that scope can mark things invalid (or cause
1133/// us to reach an error limit), which can suppress errors within that scope.
1135 DiagnosticsEngine &Diag;
1136 unsigned NumErrors;
1137 unsigned NumUnrecoverableErrors;
1138
1139public:
1140 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag) : Diag(Diag) {
1141 reset();
1142 }
1143
1144 /// Determine whether any errors have occurred since this
1145 /// object instance was created.
1146 bool hasErrorOccurred() const {
1147 return Diag.TrapNumErrorsOccurred > NumErrors;
1148 }
1149
1150 /// Determine whether any unrecoverable errors have occurred since this
1151 /// object instance was created.
1153 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1154 }
1155
1156 /// Set to initial state of "no errors occurred".
1157 void reset() {
1158 NumErrors = Diag.TrapNumErrorsOccurred;
1159 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1160 }
1161};
1162
1163/// RAII class that temporarily sets the "ignore all warnings" state on a
1164/// DiagnosticsEngine and restores the previous state on destruction. Use it to
1165/// silence warnings around a self-contained region of diagnostics, such as a
1166/// compiler-synthesized call whose arguments are known to be correct.
1168 DiagnosticsEngine &Diag;
1169 bool OldValue;
1170
1171public:
1173 : Diag(Diag), OldValue(Diag.getIgnoreAllWarnings()) {
1174 Diag.setIgnoreAllWarnings(true);
1175 }
1176 ~IgnoreAllWarningDiagRAII() { Diag.setIgnoreAllWarnings(OldValue); }
1177};
1178
1179/// RAII class that temporarily forces warnings in system headers and system
1180/// macros to be shown on a DiagnosticsEngine and restores the previous state on
1181/// destruction. Use it to ask what a diagnostic's severity would be if the
1182/// location were not in a system header.
1184 DiagnosticsEngine &Diag;
1185 bool OldValue;
1186
1187public:
1188 explicit ForceSystemWarningsRAII(DiagnosticsEngine &Diag, bool Force = true)
1189 : Diag(Diag), OldValue(Diag.getForceSystemWarnings()) {
1190 if (Force)
1191 Diag.setForceSystemWarnings(true);
1192 }
1193 ~ForceSystemWarningsRAII() { Diag.setForceSystemWarnings(OldValue); }
1194};
1195
1196/// The streaming interface shared between DiagnosticBuilder and
1197/// PartialDiagnostic. This class is not intended to be constructed directly
1198/// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1199///
1200/// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1201/// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1202///
1203/// const StreamingDiagnostic&
1204/// operator<<(const StreamingDiagnostic&, NewArgType);
1205///
1207public:
1209
1210protected:
1211 mutable DiagnosticStorage *DiagStorage = nullptr;
1212
1213 /// Allocator used to allocate storage for this diagnostic.
1215
1216public:
1217 /// Retrieve storage for this particular diagnostic.
1219 if (DiagStorage)
1220 return DiagStorage;
1221
1222 assert(Allocator);
1223 DiagStorage = Allocator->Allocate();
1224 return DiagStorage;
1225 }
1226
1228 if (!DiagStorage)
1229 return;
1230
1231 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1232 // (typically so we have the flexibility of passing a more complex
1233 // diagnostic into the callee, but that does not commonly occur).
1234 //
1235 // Split this out into a slow function for silly compilers (*cough*) which
1236 // can't do decent partial inlining.
1238 }
1239
1241 if (!Allocator)
1242 return;
1243 Allocator->Deallocate(DiagStorage);
1244 DiagStorage = nullptr;
1245 }
1246
1248 if (!DiagStorage)
1250
1251 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1252 "Too many arguments to diagnostic!");
1253 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
1254 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
1255 }
1256
1257 void AddString(StringRef V) const {
1258 if (!DiagStorage)
1260
1261 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1262 "Too many arguments to diagnostic!");
1263 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
1265 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
1266 }
1267
1268 void AddSourceRange(const CharSourceRange &R) const {
1269 if (!DiagStorage)
1271
1272 DiagStorage->DiagRanges.push_back(R);
1273 }
1274
1275 void AddFixItHint(const FixItHint &Hint) const {
1276 if (Hint.isNull())
1277 return;
1278
1279 if (!DiagStorage)
1281
1282 DiagStorage->FixItHints.push_back(Hint);
1283 }
1284
1285 /// Conversion of StreamingDiagnostic to bool always returns \c true.
1286 ///
1287 /// This allows is to be used in boolean error contexts (where \c true is
1288 /// used to indicate that an error has occurred), like:
1289 /// \code
1290 /// return Diag(...);
1291 /// \endcode
1292 operator bool() const { return true; }
1293
1294protected:
1296
1297 /// Construct with a storage allocator which will manage the storage. The
1298 /// allocator is not a null pointer in this case.
1300 : Allocator(&Alloc) {}
1301
1304
1306};
1307
1308//===----------------------------------------------------------------------===//
1309// DiagnosticBuilder
1310//===----------------------------------------------------------------------===//
1311
1312/// A little helper class used to produce diagnostics.
1313///
1314/// This is constructed by the DiagnosticsEngine::Report method, and
1315/// allows insertion of extra information (arguments and source ranges) into
1316/// the currently "in flight" diagnostic. When the temporary for the builder
1317/// is destroyed, the diagnostic is issued.
1318///
1319/// Note that many of these will be created as temporary objects (many call
1320/// sites), so we want them to be small and we never want their address taken.
1321/// This ensures that compilers with somewhat reasonable optimizers will promote
1322/// the common fields to registers, eliminating increments of the NumArgs field,
1323/// for example.
1324class DiagnosticBuilder : public StreamingDiagnostic {
1325 friend class DiagnosticsEngine;
1326 friend class PartialDiagnostic;
1327 friend class Diagnostic;
1328
1329 mutable DiagnosticsEngine *DiagObj = nullptr;
1330
1331 SourceLocation DiagLoc;
1332 unsigned DiagID;
1333
1334 /// Optional flag value.
1335 ///
1336 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
1337 /// -Rpass=<value>. The content of this string is emitted after the flag name
1338 /// and '='.
1339 mutable std::string FlagValue;
1340
1341 /// Status variable indicating if this diagnostic is still active.
1342 ///
1343 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1344 // but LLVM is not currently smart enough to eliminate the null check that
1345 // Emit() would end up with if we used that as our status variable.
1346 mutable bool IsActive = false;
1347
1348 /// Flag indicating that this diagnostic is being emitted via a
1349 /// call to ForceEmit.
1350 mutable bool IsForceEmit = false;
1351
1352 DiagnosticBuilder() = default;
1353
1354protected:
1355 DiagnosticBuilder(DiagnosticsEngine *DiagObj, SourceLocation DiagLoc,
1356 unsigned DiagID);
1357
1358 DiagnosticsEngine *getDiagnosticsEngine() const { return DiagObj; }
1359 unsigned getDiagID() const { return DiagID; }
1360
1361 /// Clear out the current diagnostic.
1362 void Clear() const {
1363 DiagObj = nullptr;
1364 IsActive = false;
1365 IsForceEmit = false;
1366 }
1367
1368 /// Determine whether this diagnostic is still active.
1369 bool isActive() const { return IsActive; }
1370
1371 /// Force the diagnostic builder to emit the diagnostic now.
1372 ///
1373 /// Once this function has been called, the DiagnosticBuilder object
1374 /// should not be used again before it is destroyed.
1375 ///
1376 /// \returns true if a diagnostic was emitted, false if the
1377 /// diagnostic was suppressed.
1378 bool Emit() {
1379 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1380 // (or by a subclass, as in SemaDiagnosticBuilder).
1381 if (!isActive())
1382 return false;
1383
1384 // Process the diagnostic.
1385 bool Result = DiagObj->EmitDiagnostic(*this, IsForceEmit);
1386
1387 // This diagnostic is dead.
1388 Clear();
1389
1390 return Result;
1391 }
1392
1393public:
1394 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1395 /// input and neuters it.
1397
1398 template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1399 assert(isActive() && "Clients must not add to cleared diagnostic!");
1400 const StreamingDiagnostic &DB = *this;
1401 DB << V;
1402 return *this;
1403 }
1404
1405 // It is necessary to limit this to rvalue reference to avoid calling this
1406 // function with a bitfield lvalue argument since non-const reference to
1407 // bitfield is not allowed.
1408 template <typename T,
1409 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1410 const DiagnosticBuilder &operator<<(T &&V) const {
1411 assert(isActive() && "Clients must not add to cleared diagnostic!");
1412 const StreamingDiagnostic &DB = *this;
1413 DB << std::move(V);
1414 return *this;
1415 }
1416
1417 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1418
1419 /// Emits the diagnostic.
1421
1422 /// Forces the diagnostic to be emitted.
1423 const DiagnosticBuilder &setForceEmit() const {
1424 IsForceEmit = true;
1425 return *this;
1426 }
1427
1428 void addFlagValue(StringRef V) const { FlagValue = std::string(V); }
1429};
1430
1432 StringRef Val;
1433
1434 explicit AddFlagValue(StringRef V) : Val(V) {}
1435};
1436
1437/// Register a value for the flag in the current diagnostic. This
1438/// value will be shown as the suffix "=value" after the flag name. It is
1439/// useful in cases where the diagnostic flag accepts values (e.g.,
1440/// -Rpass or -Wframe-larger-than).
1442 const AddFlagValue V) {
1443 DB.addFlagValue(V.Val);
1444 return DB;
1445}
1446
1448 StringRef S) {
1449 DB.AddString(S);
1450 return DB;
1451}
1452
1454 const llvm::Twine &S) {
1455 DB.AddString(S.str());
1456 return DB;
1457}
1458
1460 std::string_view S) {
1461 DB.AddString(S);
1462 return DB;
1463}
1464
1466 const std::string &S) {
1467 DB.AddString(S);
1468 return DB;
1469}
1470
1473 const llvm::SmallVectorImpl<char> &S) {
1474 DB.AddString(llvm::StringRef(S.data(), S.size()));
1475 return DB;
1476}
1477
1479 const char *Str) {
1480 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1482 return DB;
1483}
1484
1486 const llvm::APSInt &Int) {
1487 DB.AddString(toString(Int, /*Radix=*/10, Int.isSigned(),
1488 /*formatAsCLiteral=*/false,
1489 /*UpperCase=*/true, /*InsertSeparators=*/true));
1490 return DB;
1491}
1492
1494 const llvm::APInt &Int) {
1495 DB.AddString(toString(Int, /*Radix=*/10, /*Signed=*/false,
1496 /*formatAsCLiteral=*/false,
1497 /*UpperCase=*/true, /*InsertSeparators=*/true));
1498 return DB;
1499}
1500
1502 int I) {
1504 return DB;
1505}
1506
1508 long I) {
1510 return DB;
1511}
1512
1514 long long I) {
1516 return DB;
1517}
1518
1519// We use enable_if here to prevent that this overload is selected for
1520// pointers or other arguments that are implicitly convertible to bool.
1521template <typename T>
1522inline std::enable_if_t<std::is_same<T, bool>::value,
1523 const StreamingDiagnostic &>
1524operator<<(const StreamingDiagnostic &DB, T I) {
1526 return DB;
1527}
1528
1530 unsigned I) {
1532 return DB;
1533}
1534
1536 unsigned long I) {
1538 return DB;
1539}
1540
1542 unsigned long long I) {
1544 return DB;
1545}
1546
1548 tok::TokenKind I) {
1549 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1550 return DB;
1551}
1552
1554 const IdentifierInfo *II) {
1555 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1557 return DB;
1558}
1559
1560// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1561// so that we only match those arguments that are (statically) DeclContexts;
1562// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1563// match.
1564template <typename T>
1565inline std::enable_if_t<
1566 std::is_same<std::remove_const_t<T>, DeclContext>::value,
1567 const StreamingDiagnostic &>
1568operator<<(const StreamingDiagnostic &DB, T *DC) {
1569 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1571 return DB;
1572}
1573
1574// Convert scoped enums to their underlying type, so that we don't have
1575// clutter the emitting code with `llvm::to_underlying()`.
1576// We also need to disable implicit conversion for the first argument,
1577// because classes that derive from StreamingDiagnostic define their own
1578// templated operator<< that accept a wide variety of types, leading
1579// to ambiguity.
1580template <typename T, typename U,
1581 typename UnderlyingU = typename std::enable_if_t<
1582 std::is_enum_v<std::remove_reference_t<U>>,
1583 std::underlying_type<std::remove_reference_t<U>>>::type>
1584inline std::enable_if_t<
1585 std::is_same_v<std::remove_const_t<T>, StreamingDiagnostic> &&
1586 !std::is_convertible_v<U, UnderlyingU>,
1587 const StreamingDiagnostic &>
1588operator<<(const T &DB, U &&SE) {
1589 DB << llvm::to_underlying(SE);
1590 return DB;
1591}
1592
1594 SourceLocation L) {
1596 return DB;
1597}
1598
1600 SourceRange R) {
1602 return DB;
1603}
1604
1606 ArrayRef<SourceRange> Ranges) {
1607 for (SourceRange R : Ranges)
1609 return DB;
1610}
1611
1613 const CharSourceRange &R) {
1614 DB.AddSourceRange(R);
1615 return DB;
1616}
1617
1619 const FixItHint &Hint) {
1620 DB.AddFixItHint(Hint);
1621 return DB;
1622}
1623
1625 ArrayRef<FixItHint> Hints) {
1626 for (const FixItHint &Hint : Hints)
1627 DB.AddFixItHint(Hint);
1628 return DB;
1629}
1630
1633 const std::optional<SourceRange> &Opt) {
1634 if (Opt)
1635 DB << *Opt;
1636 return DB;
1637}
1638
1641 const std::optional<CharSourceRange> &Opt) {
1642 if (Opt)
1643 DB << *Opt;
1644 return DB;
1645}
1646
1648operator<<(const StreamingDiagnostic &DB, const std::optional<FixItHint> &Opt) {
1649 if (Opt)
1650 DB << *Opt;
1651 return DB;
1652}
1653
1654/// A nullability kind paired with a bit indicating whether it used a
1655/// context-sensitive keyword.
1656using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1657
1659 DiagNullabilityKind nullability);
1660
1662 unsigned DiagID) {
1663 return DiagnosticBuilder(this, Loc, DiagID);
1664}
1665
1667 llvm::Error &&E);
1668
1670 return Report(SourceLocation(), DiagID);
1671}
1672
1673//===----------------------------------------------------------------------===//
1674// Diagnostic
1675//===----------------------------------------------------------------------===//
1676
1677/// A little helper class (which is basically a smart pointer that forwards
1678/// info from DiagnosticsEngine and DiagnosticStorage) that allows clients to
1679/// enquire about the diagnostic.
1681 const DiagnosticsEngine *DiagObj;
1682 SourceLocation DiagLoc;
1683 unsigned DiagID;
1684 std::string FlagValue;
1685 const DiagnosticStorage &DiagStorage;
1686 std::optional<StringRef> StoredDiagMessage;
1687
1688public:
1689 Diagnostic(const DiagnosticsEngine *DO, const DiagnosticBuilder &DiagBuilder);
1690 Diagnostic(const DiagnosticsEngine *DO, SourceLocation DiagLoc,
1691 unsigned DiagID, const DiagnosticStorage &DiagStorage,
1692 StringRef StoredDiagMessage);
1693
1694 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1695 unsigned getID() const { return DiagID; }
1696 const SourceLocation &getLocation() const { return DiagLoc; }
1697 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1699 return DiagObj->getSourceManager();
1700 }
1701
1702 unsigned getNumArgs() const { return DiagStorage.NumDiagArgs; }
1703
1704 /// Return the kind of the specified index.
1705 ///
1706 /// Based on the kind of argument, the accessors below can be used to get
1707 /// the value.
1708 ///
1709 /// \pre Idx < getNumArgs()
1711 assert(Idx < getNumArgs() && "Argument index out of range!");
1712 return (DiagnosticsEngine::ArgumentKind)DiagStorage.DiagArgumentsKind[Idx];
1713 }
1714
1715 /// Return the provided argument string specified by \p Idx.
1716 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1717 const std::string &getArgStdStr(unsigned Idx) const {
1719 "invalid argument accessor!");
1720 return DiagStorage.DiagArgumentsStr[Idx];
1721 }
1722
1723 /// Return the specified C string argument.
1724 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1725 const char *getArgCStr(unsigned Idx) const {
1727 "invalid argument accessor!");
1728 return reinterpret_cast<const char *>(DiagStorage.DiagArgumentsVal[Idx]);
1729 }
1730
1731 /// Return the specified signed integer argument.
1732 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1733 int64_t getArgSInt(unsigned Idx) const {
1734 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1735 "invalid argument accessor!");
1736 return (int64_t)DiagStorage.DiagArgumentsVal[Idx];
1737 }
1738
1739 /// Return the specified unsigned integer argument.
1740 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1741 uint64_t getArgUInt(unsigned Idx) const {
1742 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1743 "invalid argument accessor!");
1744 return DiagStorage.DiagArgumentsVal[Idx];
1745 }
1746
1747 /// Return the specified IdentifierInfo argument.
1748 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1749 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1751 "invalid argument accessor!");
1752 return reinterpret_cast<IdentifierInfo *>(
1753 DiagStorage.DiagArgumentsVal[Idx]);
1754 }
1755
1756 /// Return the specified non-string argument in an opaque form.
1757 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1758 uint64_t getRawArg(unsigned Idx) const {
1760 "invalid argument accessor!");
1761 return DiagStorage.DiagArgumentsVal[Idx];
1762 }
1763
1764 /// Return the number of source ranges associated with this diagnostic.
1765 unsigned getNumRanges() const { return DiagStorage.DiagRanges.size(); }
1766
1767 /// \pre Idx < getNumRanges()
1768 const CharSourceRange &getRange(unsigned Idx) const {
1769 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1770 return DiagStorage.DiagRanges[Idx];
1771 }
1772
1773 /// Return an array reference for this diagnostic's ranges.
1774 ArrayRef<CharSourceRange> getRanges() const { return DiagStorage.DiagRanges; }
1775
1776 unsigned getNumFixItHints() const { return DiagStorage.FixItHints.size(); }
1777
1778 const FixItHint &getFixItHint(unsigned Idx) const {
1779 assert(Idx < getNumFixItHints() && "Invalid index!");
1780 return DiagStorage.FixItHints[Idx];
1781 }
1782
1783 ArrayRef<FixItHint> getFixItHints() const { return DiagStorage.FixItHints; }
1784
1785 /// Return the value associated with this diagnostic flag.
1786 StringRef getFlagValue() const { return FlagValue; }
1787
1788 /// Format this diagnostic into a string, substituting the
1789 /// formal arguments into the %0 slots.
1790 ///
1791 /// The result is appended onto the \p OutStr array.
1792 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1793
1794 /// Format the given format-string into the output buffer using the
1795 /// arguments stored in this diagnostic.
1796 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1797 SmallVectorImpl<char> &OutStr) const;
1798};
1799
1800/**
1801 * Represents a diagnostic in a form that can be retained until its
1802 * corresponding source manager is destroyed.
1803 */
1805 unsigned ID;
1807 FullSourceLoc Loc;
1808 std::string Message;
1809 std::vector<CharSourceRange> Ranges;
1810 std::vector<FixItHint> FixIts;
1811
1812public:
1813 StoredDiagnostic() = default;
1815 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1816 StringRef Message);
1817 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1818 StringRef Message, FullSourceLoc Loc,
1820 ArrayRef<FixItHint> Fixits);
1821
1822 /// Evaluates true when this object stores a diagnostic.
1823 explicit operator bool() const { return !Message.empty(); }
1824
1825 unsigned getID() const { return ID; }
1826 DiagnosticsEngine::Level getLevel() const { return Level; }
1827 const FullSourceLoc &getLocation() const { return Loc; }
1828 StringRef getMessage() const { return Message; }
1829
1830 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1831
1832 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1833
1834 range_iterator range_begin() const { return Ranges.begin(); }
1835 range_iterator range_end() const { return Ranges.end(); }
1836 unsigned range_size() const { return Ranges.size(); }
1837
1839
1840 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1841
1842 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1843 fixit_iterator fixit_end() const { return FixIts.end(); }
1844 unsigned fixit_size() const { return FixIts.size(); }
1845
1847};
1848
1849// Simple debug printing of StoredDiagnostic.
1850llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const StoredDiagnostic &);
1851
1852/// Abstract interface, implemented by clients of the front-end, which
1853/// formats and prints fully processed diagnostics. The destructor must be
1854/// called even with -disable-free.
1856protected:
1857 unsigned NumWarnings = 0; ///< Number of warnings reported
1858 unsigned NumErrors = 0; ///< Number of errors reported
1859
1860public:
1863
1864 unsigned getNumErrors() const { return NumErrors; }
1865 unsigned getNumWarnings() const { return NumWarnings; }
1866 virtual void clear() { NumWarnings = NumErrors = 0; }
1867
1868 /// Callback to inform the diagnostic client that processing
1869 /// of a source file is beginning.
1870 ///
1871 /// Note that diagnostics may be emitted outside the processing of a source
1872 /// file, for example during the parsing of command line options. However,
1873 /// diagnostics with source range information are required to only be emitted
1874 /// in between BeginSourceFile() and EndSourceFile().
1875 ///
1876 /// \param LangOpts The language options for the source file being processed.
1877 /// \param PP The preprocessor object being used for the source; this is
1878 /// optional, e.g., it may not be present when processing AST source files.
1879 virtual void BeginSourceFile(const LangOptions &LangOpts,
1880 const Preprocessor *PP = nullptr) {}
1881
1882 /// Callback to inform the diagnostic client that processing
1883 /// of a source file has ended.
1884 ///
1885 /// The diagnostic client should assume that any objects made available via
1886 /// BeginSourceFile() are inaccessible.
1887 virtual void EndSourceFile() {}
1888
1889 /// Indicates whether the diagnostics handled by this
1890 /// DiagnosticConsumer should be included in the number of diagnostics
1891 /// reported by DiagnosticsEngine.
1892 ///
1893 /// The default implementation returns true.
1894 virtual bool IncludeInDiagnosticCounts() const;
1895
1896 /// Handle this diagnostic, reporting it to the user or
1897 /// capturing it to a log as needed.
1898 ///
1899 /// The default implementation just keeps track of the total number of
1900 /// warnings and errors.
1901 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1902 const Diagnostic &Info);
1903};
1904
1905/// A diagnostic client that ignores all diagnostics.
1907 virtual void anchor();
1908
1909 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1910 const Diagnostic &Info) override {
1911 // Just ignore it.
1912 }
1913};
1914
1915/// Diagnostic consumer that forwards diagnostics along to an
1916/// existing, already-initialized diagnostic consumer.
1917///
1919 DiagnosticConsumer &Target;
1920
1921public:
1924
1926 const Diagnostic &Info) override;
1927 void clear() override;
1928
1929 bool IncludeInDiagnosticCounts() const override;
1930};
1931
1932// Struct used for sending info about how a type should be printed.
1936 LLVM_PREFERRED_TYPE(bool)
1938 LLVM_PREFERRED_TYPE(bool)
1939 unsigned PrintFromType : 1;
1940 LLVM_PREFERRED_TYPE(bool)
1941 unsigned ElideType : 1;
1942 LLVM_PREFERRED_TYPE(bool)
1943 unsigned ShowColors : 1;
1944
1945 // The printer sets this variable to true if the template diff was used.
1946 LLVM_PREFERRED_TYPE(bool)
1947 unsigned TemplateDiffUsed : 1;
1948};
1949
1950/// Special character that the diagnostic printer will use to toggle the bold
1951/// attribute. The character itself will be not be printed.
1952const char ToggleHighlight = 127;
1953
1954/// ProcessWarningOptions - Initialize the diagnostic client and process the
1955/// warning options specified on the command line.
1957 const DiagnosticOptions &Opts,
1958 llvm::vfs::FileSystem &VFS, bool ReportDiags = true);
1959void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl<char> &OutStr);
1962} // namespace clang
1963
1964#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H
#define V(N, I)
Defines the Diagnostic IDs-related interfaces.
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.
Defines clang::OptionalUnsigned.
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 various enumerations that describe declaration and type specifiers.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
An allocator for DiagnosticStorage objects, which uses a small cache to objects, used to reduce mallo...
Definition Diagnostic.h:192
void Deallocate(DiagnosticStorage *S)
Free the given storage object.
Definition Diagnostic.h:215
DiagnosticStorage * Allocate()
Allocate new storage.
Definition Diagnostic.h:203
A little helper class used to produce diagnostics.
DiagnosticBuilder & operator=(const DiagnosticBuilder &)=delete
const DiagnosticBuilder & setForceEmit() const
Forces the diagnostic to be emitted.
void Clear() const
Clear out the current diagnostic.
void addFlagValue(StringRef V) const
bool isActive() const
Determine whether this diagnostic is still active.
friend class PartialDiagnostic
const DiagnosticBuilder & operator<<(const T &V) const
DiagnosticsEngine * getDiagnosticsEngine() const
friend class DiagnosticsEngine
bool Emit()
Force the diagnostic builder to emit the diagnostic now.
~DiagnosticBuilder()
Emits the diagnostic.
const DiagnosticBuilder & operator<<(T &&V) const
unsigned getDiagID() const
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
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 getNumErrors() const
unsigned NumErrors
Number of errors reported.
unsigned getNumWarnings() const
unsigned NumWarnings
Number of warnings reported.
virtual bool IncludeInDiagnosticCounts() const
Indicates whether the diagnostics handled by this DiagnosticConsumer should be included in the number...
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
void reset()
Set to initial state of "no errors occurred".
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
DiagnosticErrorTrap(DiagnosticsEngine &Diag)
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Level
The level of the diagnostic, after it has been through mapping.
void setNoWarningAsError(bool Value)
static DiagnosticMapping Make(diag::Severity Severity, bool IsUser, bool IsPragma)
void setNoErrorAsFatal(bool Value)
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.
unsigned getNumFixItHints() const
StringRef getFlagValue() const
Return the value associated with this diagnostic flag.
unsigned getNumRanges() const
Return the number of source ranges associated with this diagnostic.
const char * getArgCStr(unsigned Idx) const
Return the specified C string argument.
const IdentifierInfo * getArgIdentifier(unsigned Idx) const
Return the specified IdentifierInfo argument.
const CharSourceRange & getRange(unsigned Idx) const
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.
const FixItHint & getFixItHint(unsigned Idx) const
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
void setErrorsAsFatal(bool Val)
When set to true, any error reported is made a fatal error.
Definition Diagnostic.h:754
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition Diagnostic.h:967
bool hasSourceManager() const
Definition Diagnostic.h:661
bool hasDiagSuppressionMapping() const
True if an active diagnostic suppression mapping makes severity dependent on the file path.
Definition Diagnostic.h:620
bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force=false)
Emit the diagnostic.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:952
void setDiagSuppressionMapping(llvm::MemoryBuffer &Input)
Diagnostic suppression mappings can be used to suppress specific diagnostics in specific files.
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition Diagnostic.h:848
DiagnosticsEngine(IntrusiveRefCntPtr< DiagnosticIDs > Diags, DiagnosticOptions &DiagOpts, DiagnosticConsumer *client=nullptr, bool ShouldOwnClient=true)
bool hasErrorOccurred() const
Definition Diagnostic.h:919
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:824
void setPrintTemplateTree(bool Val)
Set tree printing, to outputting the template difference in a tree format.
Definition Diagnostic.h:787
void setSuppressSystemWarnings(bool Val)
When set to true mask warnings that come from system headers.
Definition Diagnostic.h:764
void setNumWarnings(unsigned NumWarnings)
Definition Diagnostic.h:936
bool getErrorsAsFatal() const
Definition Diagnostic.h:755
DiagnosticsEngine(const DiagnosticsEngine &)=delete
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.
void setIgnoreAllWarnings(bool Val)
When set to true, any unmapped warnings are ignored.
Definition Diagnostic.h:727
bool getForceSystemWarnings() const
Definition Diagnostic.h:778
bool getSuppressAllDiagnostics() const
Definition Diagnostic.h:775
bool getIgnoreAllWarnings() const
Definition Diagnostic.h:730
void setSourceManager(SourceManager *SrcMgr)
Definition Diagnostic.h:668
void notePriorDiagnosticFrom(const DiagnosticsEngine &Other)
Note that the prior diagnostic was emitted by some other DiagnosticsEngine, and we may be attaching a...
Definition Diagnostic.h:974
friend void DiagnosticsTestHelper(DiagnosticsEngine &)
friend class DiagnosticErrorTrap
void setExtensionHandlingBehavior(diag::Severity H)
Controls whether otherwise-unmapped extension diagnostics are mapped onto ignore/warning/error.
Definition Diagnostic.h:854
LLVM_DUMP_METHOD void dump() const
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:809
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:641
const void * getDiagStateKeyForLoc(SourceLocation Loc) const
Returns a cache key representing the diagnostic state at Loc.
Definition Diagnostic.h:608
friend class PartialDiagnostic
void setTemplateBacktraceLimit(unsigned Limit)
Specify the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition Diagnostic.h:704
void DecrementAllExtensionsSilenced()
Definition Diagnostic.h:866
bool hasUnrecoverableErrorOccurred() const
Determine whether any kind of unrecoverable error has occurred.
Definition Diagnostic.h:929
void ResetPragmas()
We keep a cache of FileIDs for diagnostics mapped by pragmas.
void setFatalsAsError(bool Val)
When set to true, any fatal error reported is made an error.
Definition Diagnostic.h:760
diag_mapping_range getDiagnosticMappings() const
Get the current set of diagnostic mappings.
Definition Diagnostic.h:646
void setErrorLimit(unsigned Limit)
Specify a limit for the number of errors we should emit before giving up.
Definition Diagnostic.h:700
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition Diagnostic.h:746
bool getEnableAllWarnings() const
Definition Diagnostic.h:741
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
void setShowOverloads(OverloadsShown Val)
Specify which overload candidates to show when overload resolution fails.
Definition Diagnostic.h:799
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition Diagnostic.h:659
llvm::iterator_range< DiagState::const_iterator > diag_mapping_range
Definition Diagnostic.h:643
void setLastDiagnosticIgnored(bool IsIgnored)
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed,...
Definition Diagnostic.h:839
SourceManager & getSourceManager() const
Definition Diagnostic.h:663
void pushMappings(SourceLocation Loc)
Copies the current DiagMappings and pushes the new copy onto the top of the stack.
const DiagnosticConsumer * getClient() const
Definition Diagnostic.h:652
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
DiagnosticsEngine & operator=(const DiagnosticsEngine &)=delete
unsigned getConstexprBacktraceLimit() const
Retrieve the maximum number of constexpr evaluation notes to emit along with a given diagnostic.
Definition Diagnostic.h:720
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:245
void setEnableAllWarnings(bool Val)
When set to true, any unmapped ignored warnings are no longer ignored.
Definition Diagnostic.h:738
friend class DiagnosticBuilder
DiagnosticConsumer * getClient()
Definition Diagnostic.h:651
bool hasFatalErrorOccurred() const
Definition Diagnostic.h:926
std::pair< ArgumentKind, intptr_t > ArgumentValue
Represents on argument value, which is a union discriminated by ArgumentKind, with a value.
Definition Diagnostic.h:309
@ 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
unsigned getNumErrors() const
Definition Diagnostic.h:933
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:998
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition Diagnostic.h:655
bool areAllIgnored(StringRef Group, SourceLocation Loc) const
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:800
void setConstexprBacktraceLimit(unsigned Limit)
Specify the maximum number of constexpr evaluation notes to emit along with a given diagnostic.
Definition Diagnostic.h:714
bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled)
Set the error-as-fatal flag for the given diagnostic group.
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:767
bool getFatalsAsError() const
Definition Diagnostic.h:761
void setForceSystemWarnings(bool Val)
Definition Diagnostic.h:777
void setShowColors(bool Val)
Set color printing, so the type diffing will inject color markers into the output.
Definition Diagnostic.h:792
bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled)
Set the warning-as-error flag for the given diagnostic group.
bool getWarningsAsErrors() const
Definition Diagnostic.h:749
void IncrementAllExtensionsSilenced()
Counter bumped when an extension block is/ encountered.
Definition Diagnostic.h:865
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:959
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:857
void setSuppressAllDiagnostics(bool Val)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
Definition Diagnostic.h:774
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition Diagnostic.h:710
bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc=SourceLocation())
Change an entire diagnostic group (e.g.
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror.
Definition Diagnostic.h:923
void setElideType(bool Val)
Set type eliding, to skip outputting same types occurring in template types.
Definition Diagnostic.h:782
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...
unsigned getNumWarnings() const
Definition Diagnostic.h:934
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:636
static FileID getSentinel()
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition Diagnostic.h:115
static FixItHint CreateRemoval(SourceRange RemoveRange)
Definition Diagnostic.h:133
FixItHint()=default
Empty code modification hint, indicating that no code modification is known.
bool BeforePreviousInsertions
Definition Diagnostic.h:92
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition Diagnostic.h:82
bool isNull() const
Definition Diagnostic.h:98
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
static FixItHint CreateReplacement(SourceRange RemoveRange, StringRef Code)
Definition Diagnostic.h:147
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition Diagnostic.h:86
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition Diagnostic.h:90
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
ForceSystemWarningsRAII(DiagnosticsEngine &Diag, bool Force=true)
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.
ForwardingDiagnosticConsumer(DiagnosticConsumer &Target)
A SourceLocation and its associated SourceManager.
One of these records is kept for each identifier that is lexed.
IgnoreAllWarningDiagRAII(DiagnosticsEngine &Diag)
A diagnostic client that ignores all diagnostics.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
void setLocation(FullSourceLoc Loc)
unsigned range_size() const
unsigned getID() const
ArrayRef< FixItHint > getFixIts() const
range_iterator range_begin() const
ArrayRef< CharSourceRange > getRanges() const
unsigned fixit_size() const
DiagnosticsEngine::Level getLevel() const
fixit_iterator fixit_begin() const
const FullSourceLoc & getLocation() const
std::vector< FixItHint >::const_iterator fixit_iterator
range_iterator range_end() const
std::vector< CharSourceRange >::const_iterator range_iterator
StringRef getMessage() const
fixit_iterator fixit_end() const
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StreamingDiagnostic(StreamingDiagnostic &&Diag)=default
DiagStorageAllocator * Allocator
Allocator used to allocate storage for this diagnostic.
clang::DiagStorageAllocator DiagStorageAllocator
StreamingDiagnostic(DiagStorageAllocator &Alloc)
Construct with a storage allocator which will manage the storage.
DiagnosticStorage * DiagStorage
void AddString(StringRef V) const
StreamingDiagnostic(const StreamingDiagnostic &Diag)=default
void AddTaggedVal(uint64_t V, DiagnosticsEngine::ArgumentKind Kind) const
void AddSourceRange(const CharSourceRange &R) const
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
void AddFixItHint(const FixItHint &Hint) const
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
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),...
@ Ignored
Do not present this diagnostic, ignore it.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
DiagStateSystemClass
Whether a source location is in a system header and/or a system macro.
Definition Diagnostic.h:226
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_All
Show all overloads.
@ Ovl_Best
Show just the "best" overload candidates.
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
const FunctionProtoType * T
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:50
const char ToggleHighlight
Special character that the diagnostic printer will use to toggle the bold attribute.
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.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__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 uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define true
Definition stdbool.h:25
AddFlagValue(StringRef V)
unsigned char DiagArgumentsKind[MaxArguments]
Specifies for each argument whether it is in DiagArgumentsStr or in DiagArguments.
Definition Diagnostic.h:167
SmallVector< CharSourceRange, 8 > DiagRanges
The list of ranges added to this diagnostic.
Definition Diagnostic.h:181
unsigned char NumDiagArgs
The number of entries in Arguments.
Definition Diagnostic.h:163
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
std::string DiagArgumentsStr[MaxArguments]
The values for the various substitution positions that have string arguments.
Definition Diagnostic.h:178
@ MaxArguments
The maximum number of arguments we can hold.
Definition Diagnostic.h:159
uint64_t DiagArgumentsVal[MaxArguments]
The values for the various substitution positions.
Definition Diagnostic.h:174