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