clang 20.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
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/FunctionExtras.h"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/Support/Compiler.h"
28#include <cassert>
29#include <cstdint>
30#include <limits>
31#include <list>
32#include <map>
33#include <memory>
34#include <optional>
35#include <string>
36#include <type_traits>
37#include <utility>
38#include <vector>
39
40namespace llvm {
41class Error;
42class raw_ostream;
43class MemoryBuffer;
44namespace vfs {
45class FileSystem;
46} // namespace vfs
47} // namespace llvm
48
49namespace clang {
50
51class DeclContext;
52class DiagnosticBuilder;
53class DiagnosticConsumer;
54class IdentifierInfo;
55class LangOptions;
56class Preprocessor;
57class SourceManager;
58class StoredDiagnostic;
59
60namespace tok {
61
62enum TokenKind : unsigned short;
63
64} // namespace tok
65
66/// Annotates a diagnostic with some code that should be
67/// inserted, removed, or replaced to fix the problem.
68///
69/// This kind of hint should be used when we are certain that the
70/// introduction, removal, or modification of a particular (small!)
71/// amount of code will correct a compilation error. The compiler
72/// should also provide full recovery from such errors, such that
73/// suppressing the diagnostic output can still result in successful
74/// compilation.
75class FixItHint {
76public:
77 /// Code that should be replaced to correct the error. Empty for an
78 /// insertion hint.
80
81 /// Code in the specific range that should be inserted in the insertion
82 /// location.
84
85 /// The actual code to insert at the insertion location, as a
86 /// string.
87 std::string CodeToInsert;
88
90
91 /// Empty code modification hint, indicating that no code
92 /// modification is known.
93 FixItHint() = default;
94
95 bool isNull() const {
96 return !RemoveRange.isValid();
97 }
98
99 /// Create a code modification hint that inserts the given
100 /// code string at a specific location.
102 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.
115 CharSourceRange FromRange,
116 bool BeforePreviousInsertions = false) {
117 FixItHint Hint;
118 Hint.RemoveRange =
119 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
120 Hint.InsertFromRange = FromRange;
122 return Hint;
123 }
124
125 /// Create a code modification hint that removes the given
126 /// source range.
128 FixItHint Hint;
130 return Hint;
131 }
134 }
135
136 /// Create a code modification hint that replaces the given
137 /// source range with the given code string.
139 StringRef Code) {
140 FixItHint Hint;
142 Hint.CodeToInsert = std::string(Code);
143 return Hint;
144 }
145
147 StringRef Code) {
149 }
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.
159 MaxArguments = 10
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/// Concrete class used by the front-end to report problems and issues.
226///
227/// This massages the diagnostics (e.g. handling things like "report warnings
228/// as errors" and passes them off to the DiagnosticConsumer for reporting to
229/// the user. DiagnosticsEngine is tied to one translation unit and one
230/// SourceManager.
231class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
232public:
233 /// The level of the diagnostic, after it has been through mapping.
234 enum Level {
241 };
242
244 /// std::string
246
247 /// const char *
249
250 /// int
252
253 /// unsigned
255
256 /// enum TokenKind : unsigned
258
259 /// IdentifierInfo
261
262 /// address space
264
265 /// Qualifiers
267
268 /// QualType
270
271 /// DeclarationName
273
274 /// NamedDecl *
276
277 /// NestedNameSpecifier *
279
280 /// DeclContext *
282
283 /// pair<QualType, QualType>
285
286 /// Attr *
287 ak_attr
288 };
289
290 /// Represents on argument value, which is a union discriminated
291 /// by ArgumentKind, with a value.
292 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
293
294private:
295 // Used by __extension__
296 unsigned char AllExtensionsSilenced = 0;
297
298 // Treat fatal errors like errors.
299 bool FatalsAsError = false;
300
301 // Suppress all diagnostics.
302 bool SuppressAllDiagnostics = false;
303
304 // Elide common types of templates.
305 bool ElideType = true;
306
307 // Print a tree when comparing templates.
308 bool PrintTemplateTree = false;
309
310 // Color printing is enabled.
311 bool ShowColors = false;
312
313 // Which overload candidates to show.
314 OverloadsShown ShowOverloads = Ovl_All;
315
316 // With Ovl_Best, the number of overload candidates to show when we encounter
317 // an error.
318 //
319 // The value here is the number of candidates to show in the first nontrivial
320 // error. Future errors may show a different number of candidates.
321 unsigned NumOverloadsToShow = 32;
322
323 // Cap of # errors emitted, 0 -> no limit.
324 unsigned ErrorLimit = 0;
325
326 // Cap on depth of template backtrace stack, 0 -> no limit.
327 unsigned TemplateBacktraceLimit = 0;
328
329 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
330 unsigned ConstexprBacktraceLimit = 0;
331
334 DiagnosticConsumer *Client = nullptr;
335 std::unique_ptr<DiagnosticConsumer> Owner;
336 SourceManager *SourceMgr = nullptr;
337
338 /// Mapping information for diagnostics.
339 ///
340 /// Mapping info is packed into four bits per diagnostic. The low three
341 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
342 /// The high bit is set when the mapping was established as a user mapping.
343 /// If the high bit is clear, then the low bits are set to the default
344 /// value, and should be mapped with -pedantic, -Werror, etc.
345 ///
346 /// A new DiagState is created and kept around when diagnostic pragmas modify
347 /// the state so that we know what is the diagnostic state at any given
348 /// source location.
349 class DiagState {
350 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
351
352 public:
353 // "Global" configuration state that can actually vary between modules.
354
355 // Ignore all warnings: -w
356 LLVM_PREFERRED_TYPE(bool)
357 unsigned IgnoreAllWarnings : 1;
358
359 // Enable all warnings.
360 LLVM_PREFERRED_TYPE(bool)
361 unsigned EnableAllWarnings : 1;
362
363 // Treat warnings like errors.
364 LLVM_PREFERRED_TYPE(bool)
365 unsigned WarningsAsErrors : 1;
366
367 // Treat errors like fatal errors.
368 LLVM_PREFERRED_TYPE(bool)
369 unsigned ErrorsAsFatal : 1;
370
371 // Suppress warnings in system headers.
372 LLVM_PREFERRED_TYPE(bool)
373 unsigned SuppressSystemWarnings : 1;
374
375 // Map extensions to warnings or errors?
377
378 DiagState()
379 : IgnoreAllWarnings(false), EnableAllWarnings(false),
380 WarningsAsErrors(false), ErrorsAsFatal(false),
381 SuppressSystemWarnings(false) {}
382
383 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
384 using const_iterator =
385 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
386
387 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
388 DiagMap[Diag] = Info;
389 }
390
391 DiagnosticMapping lookupMapping(diag::kind Diag) const {
392 return DiagMap.lookup(Diag);
393 }
394
395 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
396
397 const_iterator begin() const { return DiagMap.begin(); }
398 const_iterator end() const { return DiagMap.end(); }
399 };
400
401 /// Keeps and automatically disposes all DiagStates that we create.
402 std::list<DiagState> DiagStates;
403
404 /// A mapping from files to the diagnostic states for those files. Lazily
405 /// built on demand for files in which the diagnostic state has not changed.
406 class DiagStateMap {
407 public:
408 /// Add an initial diagnostic state.
409 void appendFirst(DiagState *State);
410
411 /// Add a new latest state point.
412 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
413
414 /// Look up the diagnostic state at a given source location.
415 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
416
417 /// Determine whether this map is empty.
418 bool empty() const { return Files.empty(); }
419
420 /// Clear out this map.
421 void clear() {
422 Files.clear();
423 FirstDiagState = CurDiagState = nullptr;
424 CurDiagStateLoc = SourceLocation();
425 }
426
427 /// Produce a debugging dump of the diagnostic state.
428 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
429 StringRef DiagName = StringRef()) const;
430
431 /// Grab the most-recently-added state point.
432 DiagState *getCurDiagState() const { return CurDiagState; }
433
434 /// Get the location at which a diagnostic state was last added.
435 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
436
437 private:
438 friend class ASTReader;
439 friend class ASTWriter;
440
441 /// Represents a point in source where the diagnostic state was
442 /// modified because of a pragma.
443 ///
444 /// 'Loc' can be null if the point represents the diagnostic state
445 /// modifications done through the command-line.
446 struct DiagStatePoint {
447 DiagState *State;
448 unsigned Offset;
449
450 DiagStatePoint(DiagState *State, unsigned Offset)
451 : State(State), Offset(Offset) {}
452 };
453
454 /// Description of the diagnostic states and state transitions for a
455 /// particular FileID.
456 struct File {
457 /// The diagnostic state for the parent file. This is strictly redundant,
458 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
459 /// map would give us this, but we cache it here for performance.
460 File *Parent = nullptr;
461
462 /// The offset of this file within its parent.
463 unsigned ParentOffset = 0;
464
465 /// Whether this file has any local (not imported from an AST file)
466 /// diagnostic state transitions.
467 bool HasLocalTransitions = false;
468
469 /// The points within the file where the state changes. There will always
470 /// be at least one of these (the state on entry to the file).
472
473 DiagState *lookup(unsigned Offset) const;
474 };
475
476 /// The diagnostic states for each file.
477 mutable std::map<FileID, File> Files;
478
479 /// The initial diagnostic state.
480 DiagState *FirstDiagState;
481
482 /// The current diagnostic state.
483 DiagState *CurDiagState;
484
485 /// The location at which the current diagnostic state was established.
486 SourceLocation CurDiagStateLoc;
487
488 /// Get the diagnostic state information for a file.
489 File *getFile(SourceManager &SrcMgr, FileID ID) const;
490 };
491
492 DiagStateMap DiagStatesByLoc;
493
494 /// Keeps the DiagState that was active during each diagnostic 'push'
495 /// so we can get back at it when we 'pop'.
496 std::vector<DiagState *> DiagStateOnPushStack;
497
498 DiagState *GetCurDiagState() const {
499 return DiagStatesByLoc.getCurDiagState();
500 }
501
502 void PushDiagStatePoint(DiagState *State, SourceLocation L);
503
504 /// Finds the DiagStatePoint that contains the diagnostic state of
505 /// the given source location.
506 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
507 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
508 : DiagStatesByLoc.getCurDiagState();
509 }
510
511 /// Sticky flag set to \c true when an error is emitted.
512 bool ErrorOccurred;
513
514 /// Sticky flag set to \c true when an "uncompilable error" occurs.
515 /// I.e. an error that was not upgraded from a warning by -Werror.
516 bool UncompilableErrorOccurred;
517
518 /// Sticky flag set to \c true when a fatal error is emitted.
519 bool FatalErrorOccurred;
520
521 /// Indicates that an unrecoverable error has occurred.
522 bool UnrecoverableErrorOccurred;
523
524 /// Counts for DiagnosticErrorTrap to check whether an error occurred
525 /// during a parsing section, e.g. during parsing a function.
526 unsigned TrapNumErrorsOccurred;
527 unsigned TrapNumUnrecoverableErrorsOccurred;
528
529 /// The level of the last diagnostic emitted.
530 ///
531 /// This is used to emit continuation diagnostics with the same level as the
532 /// diagnostic that they follow.
533 DiagnosticIDs::Level LastDiagLevel;
534
535 /// Number of warnings reported
536 unsigned NumWarnings;
537
538 /// Number of errors reported
539 unsigned NumErrors;
540
541 /// A function pointer that converts an opaque diagnostic
542 /// argument to a strings.
543 ///
544 /// This takes the modifiers and argument that was present in the diagnostic.
545 ///
546 /// The PrevArgs array indicates the previous arguments formatted for this
547 /// diagnostic. Implementations of this function can use this information to
548 /// avoid redundancy across arguments.
549 ///
550 /// This is a hack to avoid a layering violation between libbasic and libsema.
551 using ArgToStringFnTy = void (*)(
553 StringRef Modifier, StringRef Argument,
554 ArrayRef<ArgumentValue> PrevArgs,
555 SmallVectorImpl<char> &Output,
556 void *Cookie,
557 ArrayRef<intptr_t> QualTypeVals);
558
559 void *ArgToStringCookie = nullptr;
560 ArgToStringFnTy ArgToStringFn;
561
562 /// Whether the diagnostic should be suppressed in FilePath.
563 llvm::unique_function<bool(diag::kind, SourceLocation /*DiagLoc*/,
564 const SourceManager &) const>
565 DiagSuppressionMapping;
566
567public:
568 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
569 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
570 DiagnosticConsumer *client = nullptr,
571 bool ShouldOwnClient = true);
575
577 LLVM_DUMP_METHOD void dump() const;
578 LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
579
581 return Diags;
582 }
583
584 /// Retrieve the diagnostic options.
585 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
586
587 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
588
589 /// Get the current set of diagnostic mappings.
591 const DiagState &DS = *GetCurDiagState();
592 return diag_mapping_range(DS.begin(), DS.end());
593 }
594
595 DiagnosticConsumer *getClient() { return Client; }
596 const DiagnosticConsumer *getClient() const { return Client; }
597
598 /// Determine whether this \c DiagnosticsEngine object own its client.
599 bool ownsClient() const { return Owner != nullptr; }
600
601 /// Return the current diagnostic client along with ownership of that
602 /// client.
603 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
604
605 bool hasSourceManager() const { return SourceMgr != nullptr; }
606
608 assert(SourceMgr && "SourceManager not set!");
609 return *SourceMgr;
610 }
611
613 assert(DiagStatesByLoc.empty() &&
614 "Leftover diag state from a different SourceManager.");
615 SourceMgr = SrcMgr;
616 }
617
618 //===--------------------------------------------------------------------===//
619 // DiagnosticsEngine characterization methods, used by a client to customize
620 // how diagnostics are emitted.
621 //
622
623 /// Copies the current DiagMappings and pushes the new copy
624 /// onto the top of the stack.
626
627 /// Pops the current DiagMappings off the top of the stack,
628 /// causing the new top of the stack to be the active mappings.
629 ///
630 /// \returns \c true if the pop happens, \c false if there is only one
631 /// DiagMapping on the stack.
633
634 /// Set the diagnostic client associated with this diagnostic object.
635 ///
636 /// \param ShouldOwnClient true if the diagnostic object should take
637 /// ownership of \c client.
638 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
639
640 /// Specify a limit for the number of errors we should
641 /// emit before giving up.
642 ///
643 /// Zero disables the limit.
644 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
645
646 /// Specify the maximum number of template instantiation
647 /// notes to emit along with a given diagnostic.
648 void setTemplateBacktraceLimit(unsigned Limit) {
649 TemplateBacktraceLimit = Limit;
650 }
651
652 /// Retrieve the maximum number of template instantiation
653 /// notes to emit along with a given diagnostic.
654 unsigned getTemplateBacktraceLimit() const {
655 return TemplateBacktraceLimit;
656 }
657
658 /// Specify the maximum number of constexpr evaluation
659 /// notes to emit along with a given diagnostic.
660 void setConstexprBacktraceLimit(unsigned Limit) {
661 ConstexprBacktraceLimit = Limit;
662 }
663
664 /// Retrieve the maximum number of constexpr evaluation
665 /// notes to emit along with a given diagnostic.
666 unsigned getConstexprBacktraceLimit() const {
667 return ConstexprBacktraceLimit;
668 }
669
670 /// When set to true, any unmapped warnings are ignored.
671 ///
672 /// If this and WarningsAsErrors are both set, then this one wins.
673 void setIgnoreAllWarnings(bool Val) {
674 GetCurDiagState()->IgnoreAllWarnings = Val;
675 }
676 bool getIgnoreAllWarnings() const {
677 return GetCurDiagState()->IgnoreAllWarnings;
678 }
679
680 /// When set to true, any unmapped ignored warnings are no longer
681 /// ignored.
682 ///
683 /// If this and IgnoreAllWarnings are both set, then that one wins.
684 void setEnableAllWarnings(bool Val) {
685 GetCurDiagState()->EnableAllWarnings = Val;
686 }
687 bool getEnableAllWarnings() const {
688 return GetCurDiagState()->EnableAllWarnings;
689 }
690
691 /// When set to true, any warnings reported are issued as errors.
692 void setWarningsAsErrors(bool Val) {
693 GetCurDiagState()->WarningsAsErrors = Val;
694 }
695 bool getWarningsAsErrors() const {
696 return GetCurDiagState()->WarningsAsErrors;
697 }
698
699 /// When set to true, any error reported is made a fatal error.
700 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
701 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
702
703 /// \brief When set to true, any fatal error reported is made an error.
704 ///
705 /// This setting takes precedence over the setErrorsAsFatal setting above.
706 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
707 bool getFatalsAsError() const { return FatalsAsError; }
708
709 /// When set to true mask warnings that come from system headers.
711 GetCurDiagState()->SuppressSystemWarnings = Val;
712 }
714 return GetCurDiagState()->SuppressSystemWarnings;
715 }
716
717 /// Suppress all diagnostics, to silence the front end when we
718 /// know that we don't want any more diagnostics to be passed along to the
719 /// client
720 void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
721 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
722
723 /// Set type eliding, to skip outputting same types occurring in
724 /// template types.
725 void setElideType(bool Val) { ElideType = Val; }
726 bool getElideType() { return ElideType; }
727
728 /// Set tree printing, to outputting the template difference in a
729 /// tree format.
730 void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
731 bool getPrintTemplateTree() { return PrintTemplateTree; }
732
733 /// Set color printing, so the type diffing will inject color markers
734 /// into the output.
735 void setShowColors(bool Val) { ShowColors = Val; }
736 bool getShowColors() { return ShowColors; }
737
738 /// Specify which overload candidates to show when overload resolution
739 /// fails.
740 ///
741 /// By default, we show all candidates.
743 ShowOverloads = Val;
744 }
745 OverloadsShown getShowOverloads() const { return ShowOverloads; }
746
747 /// When a call or operator fails, print out up to this many candidate
748 /// overloads as suggestions.
749 ///
750 /// With Ovl_Best, we set a high limit for the first nontrivial overload set
751 /// we print, and a lower limit for later sets. This way the user has a
752 /// chance of diagnosing at least one callsite in their program without
753 /// having to recompile with -fshow-overloads=all.
755 switch (getShowOverloads()) {
756 case Ovl_All:
757 // INT_MAX rather than UINT_MAX so that we don't have to think about the
758 // effect of implicit conversions on this value. In practice we'll never
759 // hit 2^31 candidates anyway.
760 return std::numeric_limits<int>::max();
761 case Ovl_Best:
762 return NumOverloadsToShow;
763 }
764 llvm_unreachable("invalid OverloadsShown kind");
765 }
766
767 /// Call this after showing N overload candidates. This influences the value
768 /// returned by later calls to getNumOverloadCandidatesToShow().
769 void overloadCandidatesShown(unsigned N) {
770 // Current heuristic: Start out with a large value for NumOverloadsToShow,
771 // and then once we print one nontrivially-large overload set, decrease it
772 // for future calls.
773 if (N > 4) {
774 NumOverloadsToShow = 4;
775 }
776 }
777
778 /// Pretend that the last diagnostic issued was ignored, so any
779 /// subsequent notes will be suppressed, or restore a prior ignoring
780 /// state after ignoring some diagnostics and their notes, possibly in
781 /// the middle of another diagnostic.
782 ///
783 /// This can be used by clients who suppress diagnostics themselves.
785 if (LastDiagLevel == DiagnosticIDs::Fatal)
786 FatalErrorOccurred = true;
788 }
789
790 /// Determine whether the previous diagnostic was ignored. This can
791 /// be used by clients that want to determine whether notes attached to a
792 /// diagnostic will be suppressed.
794 return LastDiagLevel == DiagnosticIDs::Ignored;
795 }
796
797 /// Controls whether otherwise-unmapped extension diagnostics are
798 /// mapped onto ignore/warning/error.
799 ///
800 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
802 GetCurDiagState()->ExtBehavior = H;
803 }
805 return GetCurDiagState()->ExtBehavior;
806 }
807
808 /// Counter bumped when an __extension__ block is/ encountered.
809 ///
810 /// When non-zero, all extension diagnostics are entirely silenced, no
811 /// matter how they are mapped.
812 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
813 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
814 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
815
816 /// This allows the client to specify that certain warnings are
817 /// ignored.
818 ///
819 /// Notes can never be mapped, errors can only be mapped to fatal, and
820 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
821 ///
822 /// \param Loc The source location that this change of diagnostic state should
823 /// take affect. It can be null if we are setting the latest state.
825
826 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
827 /// have the specified mapping.
828 ///
829 /// \returns true (and ignores the request) if "Group" was unknown, false
830 /// otherwise.
831 ///
832 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
833 /// state of the -Wfoo group and vice versa.
834 ///
835 /// \param Loc The source location that this change of diagnostic state should
836 /// take affect. It can be null if we are setting the state from command-line.
837 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
838 diag::Severity Map,
841 diag::Severity Map,
843
844 /// Set the warning-as-error flag for the given diagnostic group.
845 ///
846 /// This function always only operates on the current diagnostic state.
847 ///
848 /// \returns True if the given group is unknown, false otherwise.
849 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
850
851 /// Set the error-as-fatal flag for the given diagnostic group.
852 ///
853 /// This function always only operates on the current diagnostic state.
854 ///
855 /// \returns True if the given group is unknown, false otherwise.
856 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
857
858 /// Add the specified mapping to all diagnostics of the specified
859 /// flavor.
860 ///
861 /// Mainly to be used by -Wno-everything to disable all warnings but allow
862 /// subsequent -W options to enable specific warnings.
865
866 bool hasErrorOccurred() const { return ErrorOccurred; }
867
868 /// Errors that actually prevent compilation, not those that are
869 /// upgraded from a warning by -Werror.
871 return UncompilableErrorOccurred;
872 }
873 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
874
875 /// Determine whether any kind of unrecoverable error has occurred.
877 return FatalErrorOccurred || UnrecoverableErrorOccurred;
878 }
879
880 unsigned getNumErrors() const { return NumErrors; }
881 unsigned getNumWarnings() const { return NumWarnings; }
882
883 void setNumWarnings(unsigned NumWarnings) {
884 this->NumWarnings = NumWarnings;
885 }
886
887 /// Return an ID for a diagnostic with the specified format string and
888 /// level.
889 ///
890 /// If this is the first request for this diagnostic, it is registered and
891 /// created, otherwise the existing ID is returned.
892 ///
893 /// \param FormatString A fixed diagnostic format string that will be hashed
894 /// and mapped to a unique DiagID.
895 template <unsigned N>
896 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
897 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
898 StringRef(FormatString, N - 1));
899 }
900
901 /// Converts a diagnostic argument (as an intptr_t) into the string
902 /// that represents it.
904 StringRef Modifier, StringRef Argument,
906 SmallVectorImpl<char> &Output,
907 ArrayRef<intptr_t> QualTypeVals) const {
908 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
909 ArgToStringCookie, QualTypeVals);
910 }
911
912 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
913 ArgToStringFn = Fn;
914 ArgToStringCookie = Cookie;
915 }
916
917 /// Note that the prior diagnostic was emitted by some other
918 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
920 LastDiagLevel = Other.LastDiagLevel;
921 }
922
923 /// Reset the state of the diagnostic object to its initial configuration.
924 /// \param[in] soft - if true, doesn't reset the diagnostic mappings and state
925 void Reset(bool soft = false);
926
927 //===--------------------------------------------------------------------===//
928 // DiagnosticsEngine classification and reporting interfaces.
929 //
930
931 /// Determine whether the diagnostic is known to be ignored.
932 ///
933 /// This can be used to opportunistically avoid expensive checks when it's
934 /// known for certain that the diagnostic has been suppressed at the
935 /// specified location \p Loc.
936 ///
937 /// \param Loc The source location we are interested in finding out the
938 /// diagnostic state. Can be null in order to query the latest state.
939 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
940 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
942 }
943
944 /// Based on the way the client configured the DiagnosticsEngine
945 /// object, classify the specified diagnostic ID into a Level, consumable by
946 /// the DiagnosticConsumer.
947 ///
948 /// To preserve invariant assumptions, this function should not be used to
949 /// influence parse or semantic analysis actions. Instead consider using
950 /// \c isIgnored().
951 ///
952 /// \param Loc The source location we are interested in finding out the
953 /// diagnostic state. Can be null in order to query the latest state.
954 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
955 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
956 }
957
958 /// Diagnostic suppression mappings can be used to suppress specific
959 /// diagnostics in specific files.
960 /// Mapping file is expected to be a special case list with sections denoting
961 /// diagnostic groups and `src` entries for globs to suppress. `emit` category
962 /// can be used to disable suppression. Longest glob that matches a filepath
963 /// takes precedence. For example:
964 /// [unused]
965 /// src:clang/*
966 /// src:clang/foo/*=emit
967 /// src:clang/foo/bar/*
968 ///
969 /// Such a mappings file suppress all diagnostics produced by -Wunused in all
970 /// sources under `clang/` directory apart from `clang/foo/`. Diagnostics
971 /// under `clang/foo/bar/` will also be suppressed. Note that the FilePath is
972 /// matched against the globs as-is.
973 /// These take presumed locations into account, and can still be overriden by
974 /// clang-diagnostics pragmas.
975 void setDiagSuppressionMapping(llvm::MemoryBuffer &Input);
976 bool isSuppressedViaMapping(diag::kind DiagId, SourceLocation DiagLoc) const;
977
978 /// Issue the message to the client.
979 ///
980 /// This actually returns an instance of DiagnosticBuilder which emits the
981 /// diagnostics (through @c ProcessDiag) when it is destroyed.
982 ///
983 /// \param DiagID A member of the @c diag::kind enum.
984 /// \param Loc Represents the source location associated with the diagnostic,
985 /// which can be an invalid location if no position information is available.
986 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
987 inline DiagnosticBuilder Report(unsigned DiagID);
988
989 void Report(const StoredDiagnostic &storedDiag);
990
991private:
992 // This is private state used by DiagnosticBuilder. We put it here instead of
993 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
994 // object. This implementation choice means that we can only have a few
995 // diagnostics "in flight" at a time, but this seems to be a reasonable
996 // tradeoff to keep these objects small.
997 friend class Diagnostic;
998 friend class DiagnosticBuilder;
1000 friend class DiagnosticIDs;
1001 friend class PartialDiagnostic;
1002
1003 enum {
1004 /// The maximum number of arguments we can hold.
1005 ///
1006 /// We currently only support up to 10 arguments (%0-%9). A single
1007 /// diagnostic with more than that almost certainly has to be simplified
1008 /// anyway.
1009 MaxArguments = DiagnosticStorage::MaxArguments,
1010 };
1011
1012 DiagStorageAllocator DiagAllocator;
1013
1014 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
1015 bool isPragma = L.isValid();
1016 DiagnosticMapping Mapping =
1017 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
1018
1019 // If this is a pragma mapping, then set the diagnostic mapping flags so
1020 // that we override command line options.
1021 if (isPragma) {
1022 Mapping.setNoWarningAsError(true);
1023 Mapping.setNoErrorAsFatal(true);
1024 }
1025
1026 return Mapping;
1027 }
1028
1029 /// Used to report a diagnostic that is finally fully formed.
1030 ///
1031 /// \returns true if the diagnostic was emitted, false if it was suppressed.
1032 bool ProcessDiag(const DiagnosticBuilder &DiagBuilder) {
1033 return Diags->ProcessDiag(*this, DiagBuilder);
1034 }
1035
1036 /// @name Diagnostic Emission
1037 /// @{
1038protected:
1039 friend class ASTReader;
1040 friend class ASTWriter;
1041
1042 // Sema requires access to the following functions because the current design
1043 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1044 // access us directly to ensure we minimize the emitted code for the common
1045 // Sema::Diag() patterns.
1046 friend class Sema;
1047
1048 /// Emit the diagnostic
1049 ///
1050 /// \param Force Emit the diagnostic regardless of suppression settings.
1051 bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force = false);
1052
1053 /// @}
1054};
1055
1056/// RAII class that determines when any errors have occurred
1057/// between the time the instance was created and the time it was
1058/// queried.
1059///
1060/// Note that you almost certainly do not want to use this. It's usually
1061/// meaningless to ask whether a particular scope triggered an error message,
1062/// because error messages outside that scope can mark things invalid (or cause
1063/// us to reach an error limit), which can suppress errors within that scope.
1065 DiagnosticsEngine &Diag;
1066 unsigned NumErrors;
1067 unsigned NumUnrecoverableErrors;
1068
1069public:
1071 : Diag(Diag) { reset(); }
1072
1073 /// Determine whether any errors have occurred since this
1074 /// object instance was created.
1075 bool hasErrorOccurred() const {
1076 return Diag.TrapNumErrorsOccurred > NumErrors;
1077 }
1078
1079 /// Determine whether any unrecoverable errors have occurred since this
1080 /// object instance was created.
1082 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1083 }
1084
1085 /// Set to initial state of "no errors occurred".
1086 void reset() {
1087 NumErrors = Diag.TrapNumErrorsOccurred;
1088 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1089 }
1090};
1091
1092/// The streaming interface shared between DiagnosticBuilder and
1093/// PartialDiagnostic. This class is not intended to be constructed directly
1094/// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1095///
1096/// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1097/// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1098///
1099/// const StreamingDiagnostic&
1100/// operator<<(const StreamingDiagnostic&, NewArgType);
1101///
1103public:
1105
1106protected:
1107 mutable DiagnosticStorage *DiagStorage = nullptr;
1108
1109 /// Allocator used to allocate storage for this diagnostic.
1111
1112public:
1113 /// Retrieve storage for this particular diagnostic.
1115 if (DiagStorage)
1116 return DiagStorage;
1117
1118 assert(Allocator);
1120 return DiagStorage;
1121 }
1122
1124 if (!DiagStorage)
1125 return;
1126
1127 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1128 // (typically so we have the flexibility of passing a more complex
1129 // diagnostic into the callee, but that does not commonly occur).
1130 //
1131 // Split this out into a slow function for silly compilers (*cough*) which
1132 // can't do decent partial inlining.
1134 }
1135
1137 if (!Allocator)
1138 return;
1140 DiagStorage = nullptr;
1141 }
1142
1144 if (!DiagStorage)
1146
1148 "Too many arguments to diagnostic!");
1151 }
1152
1153 void AddString(StringRef V) const {
1154 if (!DiagStorage)
1156
1158 "Too many arguments to diagnostic!");
1162 }
1163
1164 void AddSourceRange(const CharSourceRange &R) const {
1165 if (!DiagStorage)
1167
1168 DiagStorage->DiagRanges.push_back(R);
1169 }
1170
1171 void AddFixItHint(const FixItHint &Hint) const {
1172 if (Hint.isNull())
1173 return;
1174
1175 if (!DiagStorage)
1177
1178 DiagStorage->FixItHints.push_back(Hint);
1179 }
1180
1181 /// Conversion of StreamingDiagnostic to bool always returns \c true.
1182 ///
1183 /// This allows is to be used in boolean error contexts (where \c true is
1184 /// used to indicate that an error has occurred), like:
1185 /// \code
1186 /// return Diag(...);
1187 /// \endcode
1188 operator bool() const { return true; }
1189
1190protected:
1192
1193 /// Construct with a storage allocator which will manage the storage. The
1194 /// allocator is not a null pointer in this case.
1196 : Allocator(&Alloc) {}
1197
1200
1202};
1203
1204//===----------------------------------------------------------------------===//
1205// DiagnosticBuilder
1206//===----------------------------------------------------------------------===//
1207
1208/// A little helper class used to produce diagnostics.
1209///
1210/// This is constructed by the DiagnosticsEngine::Report method, and
1211/// allows insertion of extra information (arguments and source ranges) into
1212/// the currently "in flight" diagnostic. When the temporary for the builder
1213/// is destroyed, the diagnostic is issued.
1214///
1215/// Note that many of these will be created as temporary objects (many call
1216/// sites), so we want them to be small and we never want their address taken.
1217/// This ensures that compilers with somewhat reasonable optimizers will promote
1218/// the common fields to registers, eliminating increments of the NumArgs field,
1219/// for example.
1221 friend class DiagnosticsEngine;
1222 friend class PartialDiagnostic;
1223 friend class Diagnostic;
1224
1225 mutable DiagnosticsEngine *DiagObj = nullptr;
1226
1227 SourceLocation DiagLoc;
1228 unsigned DiagID;
1229
1230 /// Optional flag value.
1231 ///
1232 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
1233 /// -Rpass=<value>. The content of this string is emitted after the flag name
1234 /// and '='.
1235 mutable std::string FlagValue;
1236
1237 /// Status variable indicating if this diagnostic is still active.
1238 ///
1239 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1240 // but LLVM is not currently smart enough to eliminate the null check that
1241 // Emit() would end up with if we used that as our status variable.
1242 mutable bool IsActive = false;
1243
1244 /// Flag indicating that this diagnostic is being emitted via a
1245 /// call to ForceEmit.
1246 mutable bool IsForceEmit = false;
1247
1248 DiagnosticBuilder() = default;
1249
1251 unsigned DiagID);
1252
1253protected:
1254 /// Clear out the current diagnostic.
1255 void Clear() const {
1256 DiagObj = nullptr;
1257 IsActive = false;
1258 IsForceEmit = false;
1259 }
1260
1261 /// Determine whether this diagnostic is still active.
1262 bool isActive() const { return IsActive; }
1263
1264 /// Force the diagnostic builder to emit the diagnostic now.
1265 ///
1266 /// Once this function has been called, the DiagnosticBuilder object
1267 /// should not be used again before it is destroyed.
1268 ///
1269 /// \returns true if a diagnostic was emitted, false if the
1270 /// diagnostic was suppressed.
1271 bool Emit() {
1272 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1273 // (or by a subclass, as in SemaDiagnosticBuilder).
1274 if (!isActive()) return false;
1275
1276 // Process the diagnostic.
1277 bool Result = DiagObj->EmitDiagnostic(*this, IsForceEmit);
1278
1279 // This diagnostic is dead.
1280 Clear();
1281
1282 return Result;
1283 }
1284
1285public:
1286 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1287 /// input and neuters it.
1289
1290 template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1291 assert(isActive() && "Clients must not add to cleared diagnostic!");
1292 const StreamingDiagnostic &DB = *this;
1293 DB << V;
1294 return *this;
1295 }
1296
1297 // It is necessary to limit this to rvalue reference to avoid calling this
1298 // function with a bitfield lvalue argument since non-const reference to
1299 // bitfield is not allowed.
1300 template <typename T,
1301 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1303 assert(isActive() && "Clients must not add to cleared diagnostic!");
1304 const StreamingDiagnostic &DB = *this;
1305 DB << std::move(V);
1306 return *this;
1307 }
1308
1310
1311 /// Emits the diagnostic.
1313
1314 /// Forces the diagnostic to be emitted.
1316 IsForceEmit = true;
1317 return *this;
1318 }
1319
1320 void addFlagValue(StringRef V) const { FlagValue = std::string(V); }
1321};
1322
1324 StringRef Val;
1325
1326 explicit AddFlagValue(StringRef V) : Val(V) {}
1327};
1328
1329/// Register a value for the flag in the current diagnostic. This
1330/// value will be shown as the suffix "=value" after the flag name. It is
1331/// useful in cases where the diagnostic flag accepts values (e.g.,
1332/// -Rpass or -Wframe-larger-than).
1334 const AddFlagValue V) {
1335 DB.addFlagValue(V.Val);
1336 return DB;
1337}
1338
1340 StringRef S) {
1341 DB.AddString(S);
1342 return DB;
1343}
1344
1346 const char *Str) {
1347 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1349 return DB;
1350}
1351
1353 int I) {
1355 return DB;
1356}
1357
1359 long I) {
1361 return DB;
1362}
1363
1365 long long I) {
1367 return DB;
1368}
1369
1370// We use enable_if here to prevent that this overload is selected for
1371// pointers or other arguments that are implicitly convertible to bool.
1372template <typename T>
1373inline std::enable_if_t<std::is_same<T, bool>::value,
1374 const StreamingDiagnostic &>
1375operator<<(const StreamingDiagnostic &DB, T I) {
1377 return DB;
1378}
1379
1381 unsigned I) {
1383 return DB;
1384}
1385
1387 unsigned long I) {
1389 return DB;
1390}
1391
1393 unsigned long long I) {
1395 return DB;
1396}
1397
1399 tok::TokenKind I) {
1400 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1401 return DB;
1402}
1403
1405 const IdentifierInfo *II) {
1406 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1408 return DB;
1409}
1410
1411// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1412// so that we only match those arguments that are (statically) DeclContexts;
1413// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1414// match.
1415template <typename T>
1416inline std::enable_if_t<
1417 std::is_same<std::remove_const_t<T>, DeclContext>::value,
1418 const StreamingDiagnostic &>
1419operator<<(const StreamingDiagnostic &DB, T *DC) {
1420 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1422 return DB;
1423}
1424
1426 SourceLocation L) {
1428 return DB;
1429}
1430
1432 SourceRange R) {
1434 return DB;
1435}
1436
1438 ArrayRef<SourceRange> Ranges) {
1439 for (SourceRange R : Ranges)
1441 return DB;
1442}
1443
1445 const CharSourceRange &R) {
1446 DB.AddSourceRange(R);
1447 return DB;
1448}
1449
1451 const FixItHint &Hint) {
1452 DB.AddFixItHint(Hint);
1453 return DB;
1454}
1455
1457 ArrayRef<FixItHint> Hints) {
1458 for (const FixItHint &Hint : Hints)
1459 DB.AddFixItHint(Hint);
1460 return DB;
1461}
1462
1465 const std::optional<SourceRange> &Opt) {
1466 if (Opt)
1467 DB << *Opt;
1468 return DB;
1469}
1470
1473 const std::optional<CharSourceRange> &Opt) {
1474 if (Opt)
1475 DB << *Opt;
1476 return DB;
1477}
1478
1480operator<<(const StreamingDiagnostic &DB, const std::optional<FixItHint> &Opt) {
1481 if (Opt)
1482 DB << *Opt;
1483 return DB;
1484}
1485
1486/// A nullability kind paired with a bit indicating whether it used a
1487/// context-sensitive keyword.
1488using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1489
1491 DiagNullabilityKind nullability);
1492
1494 unsigned DiagID) {
1495 return DiagnosticBuilder(this, Loc, DiagID);
1496}
1497
1499 llvm::Error &&E);
1500
1502 return Report(SourceLocation(), DiagID);
1503}
1504
1505//===----------------------------------------------------------------------===//
1506// Diagnostic
1507//===----------------------------------------------------------------------===//
1508
1509/// A little helper class (which is basically a smart pointer that forwards
1510/// info from DiagnosticsEngine and DiagnosticStorage) that allows clients to
1511/// enquire about the diagnostic.
1513 const DiagnosticsEngine *DiagObj;
1514 SourceLocation DiagLoc;
1515 unsigned DiagID;
1516 std::string FlagValue;
1517 const DiagnosticStorage &DiagStorage;
1518 std::optional<StringRef> StoredDiagMessage;
1519
1520public:
1521 Diagnostic(const DiagnosticsEngine *DO, const DiagnosticBuilder &DiagBuilder);
1522 Diagnostic(const DiagnosticsEngine *DO, SourceLocation DiagLoc,
1523 unsigned DiagID, const DiagnosticStorage &DiagStorage,
1524 StringRef StoredDiagMessage);
1525
1526 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1527 unsigned getID() const { return DiagID; }
1528 const SourceLocation &getLocation() const { return DiagLoc; }
1529 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1530 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1531
1532 unsigned getNumArgs() const { return DiagStorage.NumDiagArgs; }
1533
1534 /// Return the kind of the specified index.
1535 ///
1536 /// Based on the kind of argument, the accessors below can be used to get
1537 /// the value.
1538 ///
1539 /// \pre Idx < getNumArgs()
1541 assert(Idx < getNumArgs() && "Argument index out of range!");
1542 return (DiagnosticsEngine::ArgumentKind)DiagStorage.DiagArgumentsKind[Idx];
1543 }
1544
1545 /// Return the provided argument string specified by \p Idx.
1546 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1547 const std::string &getArgStdStr(unsigned Idx) const {
1549 "invalid argument accessor!");
1550 return DiagStorage.DiagArgumentsStr[Idx];
1551 }
1552
1553 /// Return the specified C string argument.
1554 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1555 const char *getArgCStr(unsigned Idx) const {
1557 "invalid argument accessor!");
1558 return reinterpret_cast<const char *>(DiagStorage.DiagArgumentsVal[Idx]);
1559 }
1560
1561 /// Return the specified signed integer argument.
1562 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1563 int64_t getArgSInt(unsigned Idx) const {
1564 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1565 "invalid argument accessor!");
1566 return (int64_t)DiagStorage.DiagArgumentsVal[Idx];
1567 }
1568
1569 /// Return the specified unsigned integer argument.
1570 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1571 uint64_t getArgUInt(unsigned Idx) const {
1572 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1573 "invalid argument accessor!");
1574 return DiagStorage.DiagArgumentsVal[Idx];
1575 }
1576
1577 /// Return the specified IdentifierInfo argument.
1578 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1579 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1581 "invalid argument accessor!");
1582 return reinterpret_cast<IdentifierInfo *>(
1583 DiagStorage.DiagArgumentsVal[Idx]);
1584 }
1585
1586 /// Return the specified non-string argument in an opaque form.
1587 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1588 uint64_t getRawArg(unsigned Idx) const {
1590 "invalid argument accessor!");
1591 return DiagStorage.DiagArgumentsVal[Idx];
1592 }
1593
1594 /// Return the number of source ranges associated with this diagnostic.
1595 unsigned getNumRanges() const { return DiagStorage.DiagRanges.size(); }
1596
1597 /// \pre Idx < getNumRanges()
1598 const CharSourceRange &getRange(unsigned Idx) const {
1599 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1600 return DiagStorage.DiagRanges[Idx];
1601 }
1602
1603 /// Return an array reference for this diagnostic's ranges.
1604 ArrayRef<CharSourceRange> getRanges() const { return DiagStorage.DiagRanges; }
1605
1606 unsigned getNumFixItHints() const { return DiagStorage.FixItHints.size(); }
1607
1608 const FixItHint &getFixItHint(unsigned Idx) const {
1609 assert(Idx < getNumFixItHints() && "Invalid index!");
1610 return DiagStorage.FixItHints[Idx];
1611 }
1612
1613 ArrayRef<FixItHint> getFixItHints() const { return DiagStorage.FixItHints; }
1614
1615 /// Return the value associated with this diagnostic flag.
1616 StringRef getFlagValue() const { return FlagValue; }
1617
1618 /// Format this diagnostic into a string, substituting the
1619 /// formal arguments into the %0 slots.
1620 ///
1621 /// The result is appended onto the \p OutStr array.
1622 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1623
1624 /// Format the given format-string into the output buffer using the
1625 /// arguments stored in this diagnostic.
1626 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1627 SmallVectorImpl<char> &OutStr) const;
1628};
1629
1630/**
1631 * Represents a diagnostic in a form that can be retained until its
1632 * corresponding source manager is destroyed.
1633 */
1635 unsigned ID;
1638 std::string Message;
1639 std::vector<CharSourceRange> Ranges;
1640 std::vector<FixItHint> FixIts;
1641
1642public:
1643 StoredDiagnostic() = default;
1645 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1646 StringRef Message);
1647 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1648 StringRef Message, FullSourceLoc Loc,
1650 ArrayRef<FixItHint> Fixits);
1651
1652 /// Evaluates true when this object stores a diagnostic.
1653 explicit operator bool() const { return !Message.empty(); }
1654
1655 unsigned getID() const { return ID; }
1656 DiagnosticsEngine::Level getLevel() const { return Level; }
1657 const FullSourceLoc &getLocation() const { return Loc; }
1658 StringRef getMessage() const { return Message; }
1659
1660 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1661
1662 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1663
1664 range_iterator range_begin() const { return Ranges.begin(); }
1665 range_iterator range_end() const { return Ranges.end(); }
1666 unsigned range_size() const { return Ranges.size(); }
1667
1669
1670 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1671
1672 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1673 fixit_iterator fixit_end() const { return FixIts.end(); }
1674 unsigned fixit_size() const { return FixIts.size(); }
1675
1677};
1678
1679// Simple debug printing of StoredDiagnostic.
1680llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const StoredDiagnostic &);
1681
1682/// Abstract interface, implemented by clients of the front-end, which
1683/// formats and prints fully processed diagnostics.
1685protected:
1686 unsigned NumWarnings = 0; ///< Number of warnings reported
1687 unsigned NumErrors = 0; ///< Number of errors reported
1688
1689public:
1692
1693 unsigned getNumErrors() const { return NumErrors; }
1694 unsigned getNumWarnings() const { return NumWarnings; }
1695 virtual void clear() { NumWarnings = NumErrors = 0; }
1696
1697 /// Callback to inform the diagnostic client that processing
1698 /// of a source file is beginning.
1699 ///
1700 /// Note that diagnostics may be emitted outside the processing of a source
1701 /// file, for example during the parsing of command line options. However,
1702 /// diagnostics with source range information are required to only be emitted
1703 /// in between BeginSourceFile() and EndSourceFile().
1704 ///
1705 /// \param LangOpts The language options for the source file being processed.
1706 /// \param PP The preprocessor object being used for the source; this is
1707 /// optional, e.g., it may not be present when processing AST source files.
1708 virtual void BeginSourceFile(const LangOptions &LangOpts,
1709 const Preprocessor *PP = nullptr) {}
1710
1711 /// Callback to inform the diagnostic client that processing
1712 /// of a source file has ended.
1713 ///
1714 /// The diagnostic client should assume that any objects made available via
1715 /// BeginSourceFile() are inaccessible.
1716 virtual void EndSourceFile() {}
1717
1718 /// Callback to inform the diagnostic client that processing of all
1719 /// source files has ended.
1720 virtual void finish() {}
1721
1722 /// Indicates whether the diagnostics handled by this
1723 /// DiagnosticConsumer should be included in the number of diagnostics
1724 /// reported by DiagnosticsEngine.
1725 ///
1726 /// The default implementation returns true.
1727 virtual bool IncludeInDiagnosticCounts() const;
1728
1729 /// Handle this diagnostic, reporting it to the user or
1730 /// capturing it to a log as needed.
1731 ///
1732 /// The default implementation just keeps track of the total number of
1733 /// warnings and errors.
1734 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1735 const Diagnostic &Info);
1736};
1737
1738/// A diagnostic client that ignores all diagnostics.
1740 virtual void anchor();
1741
1742 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1743 const Diagnostic &Info) override {
1744 // Just ignore it.
1745 }
1746};
1747
1748/// Diagnostic consumer that forwards diagnostics along to an
1749/// existing, already-initialized diagnostic consumer.
1750///
1753
1754public:
1757
1759 const Diagnostic &Info) override;
1760 void clear() override;
1761
1762 bool IncludeInDiagnosticCounts() const override;
1763};
1764
1765// Struct used for sending info about how a type should be printed.
1769 LLVM_PREFERRED_TYPE(bool)
1771 LLVM_PREFERRED_TYPE(bool)
1772 unsigned PrintFromType : 1;
1773 LLVM_PREFERRED_TYPE(bool)
1774 unsigned ElideType : 1;
1775 LLVM_PREFERRED_TYPE(bool)
1776 unsigned ShowColors : 1;
1777
1778 // The printer sets this variable to true if the template diff was used.
1779 LLVM_PREFERRED_TYPE(bool)
1780 unsigned TemplateDiffUsed : 1;
1781};
1782
1783/// Special character that the diagnostic printer will use to toggle the bold
1784/// attribute. The character itself will be not be printed.
1785const char ToggleHighlight = 127;
1786
1787/// ProcessWarningOptions - Initialize the diagnostic client and process the
1788/// warning options specified on the command line.
1790 const DiagnosticOptions &Opts,
1791 llvm::vfs::FileSystem &VFS, bool ReportDiags = true);
1792void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl<char> &OutStr);
1793} // namespace clang
1794
1795#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H
#define V(N, I)
Definition: ASTContext.h:3443
NodeId Parent
Definition: ASTDiff.cpp:191
static char ID
Definition: Arena.cpp:183
const Decl * D
Expr * E
enum clang::sema::@1712::IndirectLocalPathEntry::EntryKind Kind
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.
bool ShowColors
Definition: Logger.cpp:29
llvm::MachO::Target Target
Definition: MachO.h:51
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
#define bool
Definition: amdgpuintrin.h:20
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:383
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:89
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
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.
Definition: Diagnostic.h:1220
DiagnosticBuilder & operator=(const DiagnosticBuilder &)=delete
const DiagnosticBuilder & setForceEmit() const
Forces the diagnostic to be emitted.
Definition: Diagnostic.h:1315
void Clear() const
Clear out the current diagnostic.
Definition: Diagnostic.h:1255
void addFlagValue(StringRef V) const
Definition: Diagnostic.h:1320
bool isActive() const
Determine whether this diagnostic is still active.
Definition: Diagnostic.h:1262
const DiagnosticBuilder & operator<<(const T &V) const
Definition: Diagnostic.h:1290
bool Emit()
Force the diagnostic builder to emit the diagnostic now.
Definition: Diagnostic.h:1271
~DiagnosticBuilder()
Emits the diagnostic.
Definition: Diagnostic.h:1312
const DiagnosticBuilder & operator<<(T &&V) const
Definition: Diagnostic.h:1302
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1684
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: Diagnostic.h:1716
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.
Definition: Diagnostic.cpp:711
unsigned getNumErrors() const
Definition: Diagnostic.h:1693
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
Definition: Diagnostic.h:1720
unsigned NumErrors
Number of errors reported.
Definition: Diagnostic.h:1687
unsigned getNumWarnings() const
Definition: Diagnostic.h:1694
unsigned NumWarnings
Number of warnings reported.
Definition: Diagnostic.h:1686
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.
Definition: Diagnostic.h:1708
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1064
void reset()
Set to initial state of "no errors occurred".
Definition: Diagnostic.h:1086
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Definition: Diagnostic.h:1081
DiagnosticErrorTrap(DiagnosticsEngine &Diag)
Definition: Diagnostic.h:1070
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1075
Used for handling and querying diagnostic IDs.
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...
Definition: Diagnostic.h:1512
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1528
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
Definition: Diagnostic.h:1547
void FormatDiagnostic(SmallVectorImpl< char > &OutStr) const
Format this diagnostic into a string, substituting the formal arguments into the %0 slots.
Definition: Diagnostic.cpp:971
uint64_t getRawArg(unsigned Idx) const
Return the specified non-string argument in an opaque form.
Definition: Diagnostic.h:1588
unsigned getNumFixItHints() const
Definition: Diagnostic.h:1606
StringRef getFlagValue() const
Return the value associated with this diagnostic flag.
Definition: Diagnostic.h:1616
unsigned getNumRanges() const
Return the number of source ranges associated with this diagnostic.
Definition: Diagnostic.h:1595
const char * getArgCStr(unsigned Idx) const
Return the specified C string argument.
Definition: Diagnostic.h:1555
const IdentifierInfo * getArgIdentifier(unsigned Idx) const
Return the specified IdentifierInfo argument.
Definition: Diagnostic.h:1579
const CharSourceRange & getRange(unsigned Idx) const
Definition: Diagnostic.h:1598
SourceManager & getSourceManager() const
Definition: Diagnostic.h:1530
ArrayRef< FixItHint > getFixItHints() const
Definition: Diagnostic.h:1613
unsigned getNumArgs() const
Definition: Diagnostic.h:1532
bool hasSourceManager() const
Definition: Diagnostic.h:1529
unsigned getID() const
Definition: Diagnostic.h:1527
DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const
Return the kind of the specified index.
Definition: Diagnostic.h:1540
int64_t getArgSInt(unsigned Idx) const
Return the specified signed integer argument.
Definition: Diagnostic.h:1563
uint64_t getArgUInt(unsigned Idx) const
Return the specified unsigned integer argument.
Definition: Diagnostic.h:1571
const FixItHint & getFixItHint(unsigned Idx) const
Definition: Diagnostic.h:1608
ArrayRef< CharSourceRange > getRanges() const
Return an array reference for this diagnostic's ranges.
Definition: Diagnostic.h:1604
const DiagnosticsEngine * getDiags() const
Definition: Diagnostic.h:1526
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
void setErrorsAsFatal(bool Val)
When set to true, any error reported is made a fatal error.
Definition: Diagnostic.h:700
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition: Diagnostic.h:912
bool hasSourceManager() const
Definition: Diagnostic.h:605
bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force=false)
Emit the diagnostic.
Definition: Diagnostic.cpp:650
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
void setDiagSuppressionMapping(llvm::MemoryBuffer &Input)
Diagnostic suppression mappings can be used to suppress specific diagnostics in specific files.
Definition: Diagnostic.cpp:564
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:793
bool hasErrorOccurred() const
Definition: Diagnostic.h:866
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:769
void setPrintTemplateTree(bool Val)
Set tree printing, to outputting the template difference in a tree format.
Definition: Diagnostic.h:730
void setSuppressSystemWarnings(bool Val)
When set to true mask warnings that come from system headers.
Definition: Diagnostic.h:710
void setNumWarnings(unsigned NumWarnings)
Definition: Diagnostic.h:883
bool getErrorsAsFatal() const
Definition: Diagnostic.h:701
DiagnosticsEngine(const DiagnosticsEngine &)=delete
bool isSuppressedViaMapping(diag::kind DiagId, SourceLocation DiagLoc) const
Definition: Diagnostic.cpp:624
void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map, SourceLocation Loc=SourceLocation())
Add the specified mapping to all diagnostics of the specified flavor.
Definition: Diagnostic.cpp:476
void setIgnoreAllWarnings(bool Val)
When set to true, any unmapped warnings are ignored.
Definition: Diagnostic.h:673
bool getSuppressAllDiagnostics() const
Definition: Diagnostic.h:721
bool getIgnoreAllWarnings() const
Definition: Diagnostic.h:676
void setSourceManager(SourceManager *SrcMgr)
Definition: Diagnostic.h:612
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:919
friend void DiagnosticsTestHelper(DiagnosticsEngine &)
void setLastDiagnosticIgnored(bool Ignored)
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed,...
Definition: Diagnostic.h:784
void setExtensionHandlingBehavior(diag::Severity H)
Controls whether otherwise-unmapped extension diagnostics are mapped onto ignore/warning/error.
Definition: Diagnostic.h:801
LLVM_DUMP_METHOD void dump() const
Definition: Diagnostic.cpp:97
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:754
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:585
void setTemplateBacktraceLimit(unsigned Limit)
Specify the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:648
void DecrementAllExtensionsSilenced()
Definition: Diagnostic.h:813
bool hasUnrecoverableErrorOccurred() const
Determine whether any kind of unrecoverable error has occurred.
Definition: Diagnostic.h:876
void setFatalsAsError(bool Val)
When set to true, any fatal error reported is made an error.
Definition: Diagnostic.h:706
diag_mapping_range getDiagnosticMappings() const
Get the current set of diagnostic mappings.
Definition: Diagnostic.h:590
void setErrorLimit(unsigned Limit)
Specify a limit for the number of errors we should emit before giving up.
Definition: Diagnostic.h:644
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition: Diagnostic.h:692
bool getEnableAllWarnings() const
Definition: Diagnostic.h:687
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:105
void setShowOverloads(OverloadsShown Val)
Specify which overload candidates to show when overload resolution fails.
Definition: Diagnostic.h:742
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:603
llvm::iterator_range< DiagState::const_iterator > diag_mapping_range
Definition: Diagnostic.h:587
SourceManager & getSourceManager() const
Definition: Diagnostic.h:607
void pushMappings(SourceLocation Loc)
Copies the current DiagMappings and pushes the new copy onto the top of the stack.
Definition: Diagnostic.cpp:111
const DiagnosticConsumer * getClient() const
Definition: Diagnostic.h:596
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
Definition: Diagnostic.cpp:344
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:666
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:234
void setEnableAllWarnings(bool Val)
When set to true, any unmapped ignored warnings are no longer ignored.
Definition: Diagnostic.h:684
friend class DiagnosticBuilder
Definition: Diagnostic.h:998
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:595
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:873
std::pair< ArgumentKind, intptr_t > ArgumentValue
Represents on argument value, which is a union discriminated by ArgumentKind, with a value.
Definition: Diagnostic.h:292
@ ak_nameddecl
NamedDecl *.
Definition: Diagnostic.h:275
@ ak_declcontext
DeclContext *.
Definition: Diagnostic.h:281
@ ak_addrspace
address space
Definition: Diagnostic.h:263
@ ak_identifierinfo
IdentifierInfo.
Definition: Diagnostic.h:260
@ ak_qualtype_pair
pair<QualType, QualType>
Definition: Diagnostic.h:284
@ ak_c_string
const char *
Definition: Diagnostic.h:248
@ ak_declarationname
DeclarationName.
Definition: Diagnostic.h:272
@ ak_tokenkind
enum TokenKind : unsigned
Definition: Diagnostic.h:257
@ ak_std_string
std::string
Definition: Diagnostic.h:245
@ ak_nestednamespec
NestedNameSpecifier *.
Definition: Diagnostic.h:278
unsigned getNumErrors() const
Definition: Diagnostic.h:880
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition: Diagnostic.h:599
DiagnosticsEngine(IntrusiveRefCntPtr< DiagnosticIDs > Diags, IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, DiagnosticConsumer *client=nullptr, bool ShouldOwnClient=true)
Definition: Diagnostic.cpp:80
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:745
void setConstexprBacktraceLimit(unsigned Limit)
Specify the maximum number of constexpr evaluation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:660
bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled)
Set the error-as-fatal flag for the given diagnostic group.
Definition: Diagnostic.cpp:446
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
bool getFatalsAsError() const
Definition: Diagnostic.h:707
void setShowColors(bool Val)
Set color printing, so the type diffing will inject color markers into the output.
Definition: Diagnostic.h:735
bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled)
Set the warning-as-error flag for the given diagnostic group.
Definition: Diagnostic.cpp:415
bool getWarningsAsErrors() const
Definition: Diagnostic.h:695
void IncrementAllExtensionsSilenced()
Counter bumped when an extension block is/ encountered.
Definition: Diagnostic.h:812
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:903
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:804
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:720
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:654
bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc=SourceLocation())
Change an entire diagnostic group (e.g.
Definition: Diagnostic.cpp:392
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror.
Definition: Diagnostic.h:870
void setElideType(bool Val)
Set type eliding, to skip outputting same types occurring in template types.
Definition: Diagnostic.h:725
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...
Definition: Diagnostic.cpp:115
unsigned getNumWarnings() const
Definition: Diagnostic.h:881
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:580
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Definition: Diagnostic.cpp:127
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:114
static FixItHint CreateRemoval(SourceRange RemoveRange)
Definition: Diagnostic.h:132
FixItHint()=default
Empty code modification hint, indicating that no code modification is known.
bool BeforePreviousInsertions
Definition: Diagnostic.h:89
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition: Diagnostic.h:79
bool isNull() const
Definition: Diagnostic.h:95
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateReplacement(SourceRange RemoveRange, StringRef Code)
Definition: Diagnostic.h:146
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition: Diagnostic.h:83
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition: Diagnostic.h:87
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:101
Diagnostic consumer that forwards diagnostics along to an existing, already-initialized diagnostic co...
Definition: Diagnostic.h:1751
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)
Definition: Diagnostic.h:1755
A SourceLocation and its associated SourceManager.
One of these records is kept for each identifier that is lexed.
A diagnostic client that ignores all diagnostics.
Definition: Diagnostic.h:1739
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
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...
Definition: Diagnostic.h:1634
void setLocation(FullSourceLoc Loc)
Definition: Diagnostic.h:1660
unsigned range_size() const
Definition: Diagnostic.h:1666
unsigned getID() const
Definition: Diagnostic.h:1655
ArrayRef< FixItHint > getFixIts() const
Definition: Diagnostic.h:1676
range_iterator range_begin() const
Definition: Diagnostic.h:1664
ArrayRef< CharSourceRange > getRanges() const
Definition: Diagnostic.h:1668
unsigned fixit_size() const
Definition: Diagnostic.h:1674
DiagnosticsEngine::Level getLevel() const
Definition: Diagnostic.h:1656
fixit_iterator fixit_begin() const
Definition: Diagnostic.h:1672
const FullSourceLoc & getLocation() const
Definition: Diagnostic.h:1657
std::vector< FixItHint >::const_iterator fixit_iterator
Definition: Diagnostic.h:1670
range_iterator range_end() const
Definition: Diagnostic.h:1665
std::vector< CharSourceRange >::const_iterator range_iterator
Definition: Diagnostic.h:1662
StringRef getMessage() const
Definition: Diagnostic.h:1658
fixit_iterator fixit_end() const
Definition: Diagnostic.h:1673
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1102
StreamingDiagnostic(StreamingDiagnostic &&Diag)=default
DiagStorageAllocator * Allocator
Allocator used to allocate storage for this diagnostic.
Definition: Diagnostic.h:1110
StreamingDiagnostic(DiagStorageAllocator &Alloc)
Construct with a storage allocator which will manage the storage.
Definition: Diagnostic.h:1195
DiagnosticStorage * DiagStorage
Definition: Diagnostic.h:1107
void AddString(StringRef V) const
Definition: Diagnostic.h:1153
StreamingDiagnostic(const StreamingDiagnostic &Diag)=default
void AddTaggedVal(uint64_t V, DiagnosticsEngine::ArgumentKind Kind) const
Definition: Diagnostic.h:1143
void AddSourceRange(const CharSourceRange &R) const
Definition: Diagnostic.h:1164
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
Definition: Diagnostic.h:1114
void AddFixItHint(const FixItHint &Hint) const
Definition: Diagnostic.h:1171
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:87
@ Ignored
Do not present this diagnostic, ignore it.
Flavor
Flavors of diagnostics we can emit.
Definition: DiagnosticIDs.h:98
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:70
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_All
Show all overloads.
@ Ovl_Best
Show just the "best" overload candidates.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
@ Result
The result type of a method or function.
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:985
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1488
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:46
const char ToggleHighlight
Special character that the diagnostic printer will use to toggle the bold attribute.
Definition: Diagnostic.h:1785
const FunctionProtoType * T
@ Other
Other implicit parameter.
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,...
#define true
Definition: stdbool.h:25
AddFlagValue(StringRef V)
Definition: Diagnostic.h:1326
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
uint64_t DiagArgumentsVal[MaxArguments]
The values for the various substitution positions.
Definition: Diagnostic.h:174
@ MaxArguments
The maximum number of arguments we can hold.
Definition: Diagnostic.h:159